Files
Lark-Snooper/tests/test_summary.py
2026-11-21 00:52:00 +08:00

1462 lines
49 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import argparse
import json
import stat
from datetime import date, datetime
from types import SimpleNamespace
from zoneinfo import ZoneInfo
import pytest
from lark_snooper import cmd_summarize
from snooper_storage import SnifferStorage as Storage
from snooper_summary import (
DEFAULT_MODEL,
MagpieClient,
SummaryError,
chunk_messages,
clean_model_output,
drop_casual_content,
drop_empty_meeting_section,
escape_obsidian_tags,
format_followup_checkboxes,
load_previous_summary,
normalize_heading_breaks,
normalize_self_name,
previous_workday,
require_efund_model,
resolve_day,
sanitize_wikilink_pipes,
shorten_headings,
summarize_messages,
write_summary,
)
class FakeResponse:
def __init__(self, data, status_code=200):
self.data = data
self.status_code = status_code
def json(self):
return self.data
class FakeSession:
def __init__(self, models=None, completions=None):
self.models = models if models is not None else [DEFAULT_MODEL]
self.completions = list(completions or [])
self.get_calls = []
self.post_calls = []
def get(self, url, **kwargs):
self.get_calls.append((url, kwargs))
return FakeResponse({"data": [{"id": model} for model in self.models]})
def post(self, url, **kwargs):
self.post_calls.append((url, kwargs))
if not self.completions:
return FakeResponse({"model": DEFAULT_MODEL, "choices": []})
model, content = self.completions.pop(0)
return FakeResponse({
"model": model,
"choices": [{
"message": {
"content": content
}
}]
})
@pytest.fixture(autouse=True)
def fake_membership_filter(monkeypatch):
"""Keep legacy CLI tests offline; membership behavior has dedicated tests."""
def identity(client, rows):
return rows, {
"included": len(rows),
"excluded_before_join": 0,
"excluded_unknown": 0,
"excluded_chats": 0,
}
monkeypatch.setattr(
"snooper_membership.filter_rows_with_membership", identity
)
def synthetic_row(
msg_id="m1",
content="合成消息",
create_time=1_792_000_000,
chat_id="chat-test",
chat_name="合成群",
chat_type=2,
direction="in",
sender_id="sender-test",
):
return SimpleNamespace(
msg_id=msg_id,
create_time=create_time,
chat_id=chat_id,
chat_name=chat_name,
chat_type=chat_type,
sender_id=sender_id,
sender_name="合成用户",
msg_type_name="TEXT",
direction=direction,
content=content,
)
def test_sanitize_wikilink_pipes_preserves_table_and_other_text():
content = "| [[审核群|指数内容部落]] | 普通|文本 |\n[[人物|称呼]]"
assert sanitize_wikilink_pipes(content) == (
"| [[审核群|指数内容部落]] | 普通|文本 |\n[[人物|称呼]]"
)
def test_clean_model_output_discards_think_draft_and_keeps_final_answer():
content = "<think>草稿\n# 重复日报</think>\n# 最终日报\n正文"
assert clean_model_output(content) == "# 最终日报\n正文"
with pytest.raises(SummaryError):
clean_model_output("<think>未闭合草稿")
def test_system_only_private_chat_does_not_require_a_person_name():
row = synthetic_row(chat_type=1, chat_name="", content="[系统消息]")
row.msg_type = 6
row.msg_type_name = "SYSTEM"
session = FakeSession()
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
MagpieClient(DEFAULT_MODEL, session=session),
[row],
date(2026, 11, 3),
tz,
)
assert "本日未收到消息" in result
assert session.post_calls == []
def test_model_policy_checks_actual_model_after_optional_routing_prefix():
assert require_efund_model(DEFAULT_MODEL) == DEFAULT_MODEL
assert require_efund_model("EFundGPT-other") == "EFundGPT-other"
routed_model = "maqqie/gg-chat/EFundGPT-dsv4pro"
assert require_efund_model(routed_model) == routed_model
for model in (
"",
"deepseek-v4-pro",
"efundgpt-dsv4-pro",
"maqqie/gg-chat/deepseek-v4-pro",
"maqqie/gg-chat/efundgpt-dsv4-pro",
"maqqie/gg-chat/",
" EFundGPT-dsv4-pro",
):
with pytest.raises(SummaryError):
require_efund_model(model)
def test_preflight_requires_exact_model_and_sends_no_chat():
session = FakeSession(models=["maqqie/gg-chat/EFundGPT-dsv4pro"])
client = MagpieClient(DEFAULT_MODEL, session=session)
with pytest.raises(SummaryError, match="已拒绝读取消息"):
client.assert_model_available()
assert len(session.get_calls) == 1
assert session.post_calls == []
def test_non_efund_response_is_not_returned():
session = FakeSession(completions=[("deepseek-v4-pro", "不应返回")])
client = MagpieClient(DEFAULT_MODEL, session=session)
with pytest.raises(SummaryError, match="EFundGPT"):
client.complete("仅含合成数据的测试")
def test_http_error_does_not_expose_response_body():
class ErrorSession(FakeSession):
def post(self, url, **kwargs):
return FakeResponse({"echo": "敏感合成正文"}, status_code=400)
client = MagpieClient(DEFAULT_MODEL, session=ErrorSession())
with pytest.raises(SummaryError) as error:
client.complete("敏感合成正文")
assert "敏感合成正文" not in str(error.value)
def test_chunking_preserves_every_character_and_respects_limit():
original = "甲" * 4700
rows = [
synthetic_row(content=original),
synthetic_row("m2", content="第二条")
]
messages = [{
"msg_id": row.msg_id,
"time": "2026-11-03T10:00:00+08:00",
"chat_id": row.chat_id,
"content": row.content,
} for row in rows]
chunks = chunk_messages(messages, max_chars=2000)
assert len(chunks) > 1
flattened = [message for chunk in chunks for message in chunk]
assert "".join(message["content"] for message in flattened
if message["msg_id"] == "m1") == original
assert [
message["content"] for message in flattened
if message["msg_id"] == "m2"
] == ["第二条"]
for chunk in chunks:
assert sum(
len(json.dumps(item, ensure_ascii=False)) for item in chunk) < 2300
def test_multi_chunk_summary_uses_same_approved_model_for_all_calls():
session = FakeSession(completions=[
(DEFAULT_MODEL, "第一部分"),
(DEFAULT_MODEL, "第二部分"),
(DEFAULT_MODEL, "单对话摘要"),
(DEFAULT_MODEL, "最终总结"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(content="一" * 1200),
synthetic_row("m2", content="二" * 1200)
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(client,
rows,
date(2026, 11, 3),
tz,
max_chars=2000)
assert result == "最终总结"
assert len(session.post_calls) == 4
for _, kwargs in session.post_calls:
assert kwargs["json"]["model"] == DEFAULT_MODEL
assert kwargs["json"]["reasoning_effort"] == "high"
def test_summary_is_per_conversation_before_daily_combination():
session = FakeSession(completions=[
(DEFAULT_MODEL, "私聊摘要"),
(DEFAULT_MODEL, "群聊摘要"),
(DEFAULT_MODEL, "最终日度总结"),
(DEFAULT_MODEL, "同事甲:最终日度总结"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(
"group-message",
content="群聊原始内容",
chat_id="group-a",
chat_name="项目群",
chat_type=2,
),
synthetic_row(
"private-message",
content="私聊原始内容",
chat_id="private-b",
chat_name="同事甲",
chat_type=1,
),
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(client, rows, date(2026, 11, 3), tz)
assert result == "同事甲:最终日度总结"
assert len(session.post_calls) == 4
prompts = [
kwargs["json"]["messages"][1]["content"]
for _, kwargs in session.post_calls
]
assert "私聊原始内容" in prompts[0]
assert "群聊原始内容" not in prompts[0]
assert "群聊原始内容" in prompts[1]
assert "私聊原始内容" not in prompts[1]
assert "群聊摘要" in prompts[2]
assert "私聊摘要" in prompts[2]
assert "群聊原始内容" not in prompts[2]
assert "私聊原始内容" not in prompts[2]
def test_summary_applies_chat_specific_prompts_to_each_relevant_stage():
session = FakeSession(completions=[
(DEFAULT_MODEL, "业务监控摘要"),
(DEFAULT_MODEL, "普通群摘要"),
(DEFAULT_MODEL, "最终日度总结"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(chat_id="monitor", chat_name="监控群"),
synthetic_row("m2", chat_id="regular", chat_name="普通群"),
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
custom_prompt = "放量提醒是业务监控重点,不得省略。"
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
chat_prompts={"monitor": custom_prompt},
)
assert result == "最终日度总结"
prompts = [
kwargs["json"]["messages"][1]["content"]
for _, kwargs in session.post_calls
]
assert custom_prompt in prompts[0]
assert custom_prompt not in prompts[1]
assert custom_prompt in prompts[2]
def test_summary_prioritizes_discussions_with_current_user_messages():
session = FakeSession(completions=[
(DEFAULT_MODEL, "重点讨论摘要"),
(DEFAULT_MODEL, "最终日度总结"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row("incoming", content="同事提出的问题", chat_id="group-a"),
synthetic_row(
"outgoing",
content="我的判断和回复",
chat_id="group-a",
direction="out",
),
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(client, rows, date(2026, 11, 3), tz)
assert result == "最终日度总结"
first_prompt = session.post_calls[0][1]["json"]["messages"][1]["content"]
final_prompt = session.post_calls[1][1]["json"]["messages"][1]["content"]
assert "我的判断和回复" in first_prompt
assert '"direction": "out"' in first_prompt
assert '"user_spoke": true' in first_prompt
assert "重点总结当前用户参与的讨论" in first_prompt
assert '"user_spoke": true' in final_prompt
assert "优先保留当前用户参与讨论" in final_prompt
def test_summary_orders_chats_by_participation_private_human_and_bot():
session = FakeSession(completions=[
(DEFAULT_MODEL, "本人参与群摘要"),
(DEFAULT_MODEL, "私聊摘要"),
(DEFAULT_MODEL, "真人群摘要"),
(DEFAULT_MODEL, "机器人群摘要"),
(DEFAULT_MODEL, "最终日度总结"),
(DEFAULT_MODEL, "私聊:最终日度总结"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row("bot-message",
chat_id="bot-group",
chat_name="机器人群",
sender_id="bot"),
synthetic_row(
"human-message",
chat_id="human-group",
chat_name="真人群",
sender_id="human",
),
synthetic_row(
"private-message",
chat_id="private-chat",
chat_name="私聊",
chat_type=1,
sender_id="human",
),
synthetic_row(
"own-message",
chat_id="own-group",
chat_name="本人参与群",
direction="out",
sender_id="human",
),
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
sender_types={
"human": 1,
"bot": 2
},
)
assert result == "私聊:最终日度总结"
prompts = [
kwargs["json"]["messages"][1]["content"]
for _, kwargs in session.post_calls
]
assert '"chat_id": "own-group"' in prompts[0]
assert '"priority_rank": 1' in prompts[0]
assert '"chat_id": "private-chat"' in prompts[1]
assert '"priority_rank": 2' in prompts[1]
assert '"chat_id": "human-group"' in prompts[2]
assert '"priority_rank": 3' in prompts[2]
assert '"has_human_messages": true' in prompts[2]
assert '"chat_id": "bot-group"' in prompts[3]
assert '"priority_rank": 4' in prompts[3]
assert '"has_bot_messages": true' in prompts[3]
final_prompt = prompts[4]
assert "## 八、运维信息(必须位于全文最后)" in final_prompt
assert "## 四、前日工作延续" in final_prompt
assert "## 二、今日会议" in final_prompt
assert "三级标题保持简短" in final_prompt
assert "> [!note]" in final_prompt
assert "> [!warning]" in final_prompt
assert "仅知情、他人负责、一般通知和机器人监控无需跟进" in final_prompt
assert "今日工作概览只写工作主线、关键进展和结果,不列举人名或群名" in final_prompt
assert final_prompt.index("本人参与群摘要") < final_prompt.index("私聊摘要")
assert final_prompt.index("私聊摘要") < final_prompt.index("真人群摘要")
assert final_prompt.index("真人群摘要") < final_prompt.index("机器人群摘要")
def test_private_chat_labels_keep_only_the_other_party():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "### 排班\n### 模型([[王五]]、[[赵六]])"),
(DEFAULT_MODEL, "| 事项 | 负责人 | 来源 |\n| 排班 | 未明确 | [[王五]] |"),
(DEFAULT_MODEL, "| 事项 | 负责人 | 来源 |\n| 排班 | 未明确 | [[赵六]] |"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(
"incoming",
chat_id="private-chat",
chat_name="赵六",
chat_type=1,
sender_id="other",
),
synthetic_row(
"outgoing",
chat_id="private-chat",
chat_name="赵六",
chat_type=1,
direction="out",
sender_id="me",
),
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={"private-chat": {"me": "王五", "other": "赵六"}},
)
final_prompt = session.post_calls[1][1]["json"]["messages"][1]["content"]
assert "### 排班([[赵六]])" in final_prompt
assert "### 模型([[赵六]])" in final_prompt
assert "私聊:" not in final_prompt
assert "[[王五]] 与 [[赵六]]" not in final_prompt
assert result.endswith("| 排班 | 未明确 | [[赵六]] |")
def test_private_chat_name_is_derived_from_incoming_contact():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "### 排班([[赵六]])"),
(DEFAULT_MODEL, "### 排班([[赵六]])"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(
"incoming",
chat_id="private-chat",
chat_name="",
chat_type=1,
sender_id="other",
),
synthetic_row(
"system",
chat_id="private-chat",
chat_name="",
chat_type=1,
sender_id="1",
),
synthetic_row(
"outgoing",
chat_id="private-chat",
chat_name="",
chat_type=1,
direction="out",
sender_id="me",
),
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={
"private-chat": {
"me": "王五",
"other": "赵六",
"1": "系统消息",
}
},
sender_types={"other": 1, "1": 2},
)
first_prompt = session.post_calls[0][1]["json"]["messages"][1]["content"]
assert '"chat_name": "赵六"' in first_prompt
assert result == "### 排班([[赵六]])"
def test_generic_self_references_use_configured_self_name():
assert normalize_self_name("当前用户与本人;伦伦本人", "Ben", set()) == "Ben与Ben;伦伦本人"
def test_summary_uses_configured_self_name():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "[[王五]] 回复"),
(DEFAULT_MODEL, "[[王五]] 与 [[赵六]] 确认"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(
"incoming",
chat_id="private-chat",
chat_name="赵六",
chat_type=1,
sender_id="other",
),
synthetic_row(
"outgoing",
chat_id="private-chat",
chat_name="赵六",
chat_type=1,
direction="out",
sender_id="me",
),
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={"private-chat": {"me": "王五", "other": "赵六"}},
self_name="Ben",
)
participation = session.post_calls[0][1]["json"]["messages"][1]["content"]
assert '"self_name": "Ben"' in participation
assert result == "[[Ben]] 与 [[赵六]] 确认"
def test_missing_human_private_summary_is_restored_with_chat_name():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "### 排班([[赵六]])"),
(DEFAULT_MODEL, "最终日度总结"),
(DEFAULT_MODEL, "仍遗漏对方"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(
"incoming",
chat_id="private-chat",
chat_name="赵六",
chat_type=1,
sender_id="other",
)
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={"private-chat": {"other": "赵六"}},
sender_types={"other": 1},
)
assert len(session.post_calls) == 3
assert "### 排班([[赵六]])" in result
assert result.count("### 排班([[赵六]])") == 1
def test_multiple_private_sources_are_repaired_from_conversation_summaries():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "[[王五]] 私聊:数据库迁移"),
(DEFAULT_MODEL, "[[王五]] 私聊:模型选型"),
(
DEFAULT_MODEL,
"### 数据库(对方)\n"
"| 事项 | 来源 |\n| 数据库迁移 | [[王五]] |\n| 模型选型 | [[王五]] |",
),
(
DEFAULT_MODEL,
"### 数据库([[周八]])\n"
"| 事项 | 来源 |\n| 数据库迁移 | [[周八]] |\n| 模型选型 | [[孙七]] |",
),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = []
for chat_id, other, topic in (
("private-a", "周八", "数据库"),
("private-b", "孙七", "模型"),
):
rows.append(
synthetic_row(
f"out-{topic}",
content=topic,
chat_id=chat_id,
chat_name=other,
chat_type=1,
direction="out",
sender_id="me",
)
)
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={
"private-a": {"me": "王五", "other": "周八"},
"private-b": {"me": "王五", "other": "孙七"},
},
)
assert len(session.post_calls) == 4
assert "### 数据库([[周八]])" in result
assert "| 数据库迁移 | [[周八]] |" in result
assert "| 模型选型 | [[孙七]] |" in result
def test_person_named_group_links_support_commas_and_nested_wikilinks():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "[[吴九, [[李四]], 王五]]:讨论需求"),
(DEFAULT_MODEL, "[[吴九, [[李四]], 王五]]:已确认需求"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
group_name = "吴九, 李四, 王五"
rows = [synthetic_row(chat_id="group-a", chat_name=group_name)]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={
"group-a": {
"u1": "吴九",
"u2": "李四",
"u3": "王五",
"sender-test": "李四",
}
},
)
assert result == "吴九, 李四, 王五:已确认需求"
assert "[[吴九, [[李四]], 王五]]" not in result
def test_calendar_events_are_included_even_without_messages():
session = FakeSession(completions=[(DEFAULT_MODEL, "会议日报")])
client = MagpieClient(DEFAULT_MODEL, session=session)
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
[],
date(2026, 11, 3),
tz,
calendar_events=[
{
"summary": "合成会议",
"begin": "2026-11-03T09:00:00+08:00",
"end": "2026-11-03T10:00:00+08:00",
"location": "合成会议室",
"cancelled": False,
"url": "",
}
],
)
assert result == "会议日报"
prompt = session.post_calls[0][1]["json"]["messages"][1]["content"]
assert "合成会议" in prompt
assert "合成会议室" in prompt
assert "## 二、今日会议" in prompt
assert "[会议标题](url)" in prompt
def test_summary_applies_heading_normalization_to_model_output():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "单群摘要"),
(DEFAULT_MODEL, "## 一、今日工作概览今日工作围绕合成事项展开。\n### 合成事项- [[张三]] 确认。\n"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client, [synthetic_row()], date(2026, 11, 3), tz
)
assert "## 一、今日工作概览\n今日工作围绕合成事项展开。" in result
assert "### 合成事项\n- 张三 确认。" in result
def test_person_named_group_allows_missing_members_and_count_suffix():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "[[吴九, [[李四]], 王五等8人]]:讨论需求"),
(DEFAULT_MODEL, "[[吴九, [[李四]], 王五等8人]]:已确认需求"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
group_name = "吴九, 李四, 王五等8人"
rows = [synthetic_row(chat_id="group-a", chat_name=group_name)]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={"group-a": {"u1": "吴九", "u2": "李四", "sender-test": "吴九"}},
)
assert result == "吴九, 李四, 王五等8人:已确认需求"
assert "[[吴九, [[李四]], 王五等8人]]" not in result
def test_previous_day_summary_is_used_for_continuity():
session = FakeSession(completions=[
(DEFAULT_MODEL, "今日摘要"),
(DEFAULT_MODEL, "最终日度总结"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
[synthetic_row()],
date(2026, 11, 3),
tz,
previous_summary="# 2026-11-02\n\n前日合成待办",
)
assert result == "最终日度总结"
final_prompt = session.post_calls[1][1]["json"]["messages"][1]["content"]
assert "前日合成待办" in final_prompt
assert "今日继续推进" in final_prompt
assert "今日未见延续" in final_prompt
def test_bare_group_name_heading_becomes_topic_heading():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "### [[项目群]]"),
(DEFAULT_MODEL, "### [[项目群]]"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [synthetic_row(chat_id="group-a", chat_name="项目群")]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(client, rows, date(2026, 11, 3), tz)
assert result == "### 沟通事项:[[项目群]]"
def test_summary_enriches_names_and_requests_obsidian_wikilinks():
session = FakeSession(completions=[
(DEFAULT_MODEL, "张三确认了事项"),
(DEFAULT_MODEL, "# 最终总结\n张三确认了事项"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(
content="三确认一下",
chat_id="group-a",
chat_name="项目群",
chat_type=2,
)
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={"group-a": {
"sender-test": "张三"
}},
)
assert result.startswith("# 最终总结")
system_prompt = session.post_calls[0][1]["json"]["messages"][0]["content"]
first_prompt = session.post_calls[0][1]["json"]["messages"][1]["content"]
final_prompt = session.post_calls[1][1]["json"]["messages"][1]["content"]
assert '"sender_name": "张三"' not in first_prompt
assert '"full_name"' not in first_prompt
assert '"sender_type": 0' in first_prompt
assert "不通过通讯录强行补全本名" in system_prompt
assert "[[会话名]]" in system_prompt
assert "#tag" in system_prompt
assert "[[张三]]确认了事项" in final_prompt
assert "[[张三]]确认了事项" in result
assert "Wikilink" in final_prompt
def test_person_only_group_name_stays_plain_but_people_keep_wikilinks():
session = FakeSession(completions=[
(DEFAULT_MODEL, "[[张三、李四]] 中 [[张三]] 确认了事项"),
(DEFAULT_MODEL, "来源:[[张三]]、[[李四]];[[张三]] 已确认"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(
chat_id="group-a",
chat_name="张三、李四",
chat_type=2,
)
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={
"group-a": {
"sender-a": "张三",
"sender-b": "李四"
},
},
)
chat_summary = session.post_calls[1][1]["json"]["messages"][1]["content"]
assert "[[张三、李四]]" not in chat_summary
assert "张三、李四 中 [[张三]] 确认了事项" in chat_summary
assert result == "来源:张三、李四;[[张三]] 已确认"
def test_summary_normalizes_people_aliases_after_both_model_stages():
session = FakeSession(completions=[
(DEFAULT_MODEL, "四总发送了文件"),
(DEFAULT_MODEL, "[[四总]] 最终确认"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [synthetic_row(chat_id="group-a", chat_name="项目群")]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={"group-a": {
"sender-test": "李四"
}},
people_aliases={"四总": "李四"},
)
final_prompt = session.post_calls[1][1]["json"]["messages"][1]["content"]
assert "四总发送了文件" in final_prompt
assert "[[李四]]" not in final_prompt
assert result == "四总 最终确认"
def test_unconfirmed_person_wikilink_is_removed_but_group_link_is_preserved():
session = FakeSession(completions=[
(DEFAULT_MODEL, "[[张四]] 在 [[项目群]] 发送文件"),
(DEFAULT_MODEL, "[[张四]] 在 [[项目群]] 已确认"),
])
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [synthetic_row(chat_id="group-a", chat_name="项目群")]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(
client,
rows,
date(2026, 11, 3),
tz,
contacts={"group-a": {
"sender-test": "张三"
}},
)
assert result == "张四 在 [[项目群]] 已确认"
assert "[[张四]]" not in result
assert "[[项目群]]" in result
def test_storage_selects_only_received_messages_inside_day_and_chat():
storage = Storage(url="sqlite:///:memory:")
tz = ZoneInfo("Asia/Shanghai")
start = int(datetime(2026, 11, 3, 0, 0, tzinfo=tz).timestamp())
end = int(datetime(2026, 11, 4, 0, 0, tzinfo=tz).timestamp())
base = {
"chat_id": "chat-a",
"chat_type": 2,
"from_id": "sender-a",
"msg_type": 4,
"msg_type_name": "TEXT",
"create_time": start + 100,
}
storage.save_message({
**base, "msg_id": "in-day",
"content": "合成收到"
},
direction="in")
storage.save_message({
**base, "msg_id": "out-day",
"content": "合成发出"
},
direction="out")
storage.save_message(
{
**base, "msg_id": "in-other-chat",
"chat_id": "chat-b",
"content": "其他会话"
},
direction="in",
)
storage.save_message(
{
**base, "msg_id": "before-day",
"create_time": start - 1
},
direction="in")
storage.save_message({
**base, "msg_id": "at-end",
"create_time": end
},
direction="in")
rows = storage.get_received_messages(start, end, chat_ids=["chat-a"])
assert [row.msg_id for row in rows] == ["in-day"]
rows = storage.get_received_messages(start,
end,
chat_ids=["chat-a"],
include_outgoing=True)
assert [row.msg_id for row in rows] == ["in-day", "out-day"]
def test_yaml_config_resolves_dated_output_paths(tmp_path):
from snooper_summary import configured_output_path, load_output_config
config_file = tmp_path / "config.yaml"
config_file.write_text(
"output:\n"
f" summary: '{tmp_path}/summaries/{{date}}.md'\n"
f" dry_run: '{tmp_path}/dry-runs/{{date}}.json'\n",
encoding="utf-8",
)
config = load_output_config(config_file)
target_day = date(2026, 11, 3)
assert configured_output_path(config, "summary",
target_day) == (tmp_path / "summaries" /
"2026-11-03.md")
assert configured_output_path(config, "dry_run",
target_day) == (tmp_path / "dry-runs" /
"2026-11-03.json")
def test_regular_day_loads_previous_two_daily_logs(tmp_path):
config = {"summary": str(tmp_path / "{date}.md")}
(tmp_path / "2026-11-02.md").write_text("前一天合成日志", encoding="utf-8")
(tmp_path / "2026-11-01.md").write_text("前两天合成日志", encoding="utf-8")
content, previous_missing = load_previous_summary(config, date(2026, 11, 3))
assert not previous_missing
assert "【前一天 2026-11-02】\n前一天合成日志" in content
assert "【前两天 2026-11-01】\n前两天合成日志" in content
def test_monday_loads_sunday_and_previous_workday(tmp_path):
config = {"summary": str(tmp_path / "{date}.md")}
(tmp_path / "2026-11-01.md").write_text("周日合成日志", encoding="utf-8")
(tmp_path / "2026-10-30.md").write_text("周五合成日志", encoding="utf-8")
content, previous_missing = load_previous_summary(config, date(2026, 11, 2))
assert not previous_missing
assert "【周日 2026-11-01】\n周日合成日志" in content
assert "【上周最后工作日 2026-10-30】\n周五合成日志" in content
def test_monday_with_workday_log_is_not_missing_without_sunday(tmp_path):
config = {"summary": str(tmp_path / "{date}.md")}
(tmp_path / "2026-10-30.md").write_text("周五合成日志", encoding="utf-8")
content, previous_missing = load_previous_summary(config, date(2026, 11, 2))
assert not previous_missing
assert "【周日 2026-11-01】\n<日志不存在>" in content
assert "周五合成日志" in content
def test_monday_without_sunday_or_workday_log_is_missing(tmp_path):
config = {"summary": str(tmp_path / "{date}.md")}
content, previous_missing = load_previous_summary(config, date(2026, 11, 2))
assert previous_missing
assert "【周日 2026-11-01】\n<日志不存在>" in content
assert "【上周最后工作日 2026-10-30】\n<日志不存在>" in content
def test_previous_workday_skips_custom_holidays_and_weekends():
holidays = {date(2026, 10, 30), date(2026, 11, 1)}
assert previous_workday(
date(2026, 11, 2),
is_workday=lambda day: day.weekday() < 5 and day not in holidays,
) == date(2026, 10, 29)
def test_heading_body_is_separated_before_length_normalization():
content = "### 简短标题([[张三]])- 第一条正文\n- 第二条正文\n"
assert normalize_heading_breaks(content) == (
"### 简短标题([[张三]])\n- 第一条正文\n- 第二条正文\n"
)
assert shorten_headings(content, max_chars=8) == (
"### 简短标题([[张三]])\n- 第一条正文\n- 第二条正文\n"
)
def test_heading_breaks_cover_sections_and_plain_wikilink_bodies():
content = (
"## 一、今日工作概览今日工作围绕数据治理展开。\n"
"### 数据治理[[张三]] 提醒更新数据。\n"
"### 简短标题- [[张三]] 提醒更新数据。\n"
"### 部门扩容[[张三]] 新增集群(无自杀逻辑)。[[李四]]确认。\n"
"### 简短标题([[李四]])\n"
)
assert normalize_heading_breaks(content) == (
"## 一、今日工作概览\n今日工作围绕数据治理展开。\n"
"### 数据治理\n[[张三]] 提醒更新数据。\n"
"### 简短标题\n- [[张三]] 提醒更新数据。\n"
"### 部门扩容\n[[张三]] 新增集群(无自杀逻辑)。[[李四]]确认。\n"
"### 简短标题([[李四]])\n"
)
def test_split_person_heading_is_merged():
assert normalize_heading_breaks("### 与\n[[张三]]\n- 事项\n") == (
"### [[张三]]\n- 事项\n"
)
def test_empty_meeting_section_is_omitted_but_fetch_error_is_kept():
content = (
"## 一、今日工作概览\n工作\n"
"## 二、今日会议\n| 无 | 无 | 无 |\n"
"## 三、关键沟通与结论\n事项\n"
)
assert drop_empty_meeting_section(content, False) == (
"## 一、今日工作概览\n工作\n## 三、关键沟通与结论\n事项\n"
)
assert drop_empty_meeting_section(content, False, "Timeout") == content
def test_casual_sections_and_social_filler_are_removed():
content = (
"### 工作事项\n- 合成工作结论\n"
"### 与赵六的闲聊\n- 寒暄和表情包\n"
"### 其他沟通\n- 礼节性问候,无实质工作内容\n"
"- 另一项工作信息\n"
"## 四、前日工作延续\n"
)
assert drop_casual_content(content) == (
"### 工作事项\n- 合成工作结论\n"
"### 其他沟通\n- 另一项工作信息\n"
"## 四、前日工作延续\n"
)
def test_third_level_headings_are_hard_limited_without_cutting_wikilinks():
content = (
"### 一二三四五六七八九十([[张三]])\n"
"### 一二三四五六七八九十\n"
"## 二级标题不截断\n"
)
assert shorten_headings(content) == content
assert shorten_headings(content, max_chars=8) == (
"### 一二三四五六七…([[张三]])\n"
"### 一二三四五六七…\n"
"## 二级标题不截断\n"
)
def test_followup_heading_is_separated_before_checkbox_conversion():
content = "## 六、明日跟进建议- [ ] 第一项\n2. 第二项\n"
assert format_followup_checkboxes(shorten_headings(content)) == (
"## 六、明日跟进建议\n- [ ] 第一项\n- [ ] 第二项\n"
)
def test_followup_items_are_checkboxes_and_idempotent():
content = ("## 五、明日跟进建议\n"
"1. 第一项\n"
"2) 第二项\n"
"- 第三项\n"
"- [ ] 已有复选框\n"
"## 六、运维信息\n"
"1. 不转换运维编号\n")
expected = ("## 五、明日跟进建议\n"
"- [ ] 第一项\n"
"- [ ] 第二项\n"
"- [ ] 第三项\n"
"- [ ] 已有复选框\n"
"## 六、运维信息\n"
"1. 不转换运维编号\n")
assert format_followup_checkboxes(content) == expected
assert format_followup_checkboxes(expected) == expected
def test_obsidian_tag_escaping_preserves_heading_line_endings():
content = "## 标题\n正文\n### 次标题\r\n- 列表\r\n"
assert escape_obsidian_tags(content) == content
def test_obsidian_tag_escaping_preserves_headings_existing_escapes_and_urls():
content = ("# 日报\\n"
"正文 #ETF放量 与 #123,已有 \\#标签。\\n"
"## 二、标题内的 #重点\\n"
"链接 https://example.com/#section 不变。\\n")
assert escape_obsidian_tags(content) == (
"# 日报\\n"
"正文 \\#ETF放量 与 \\#123,已有 \\#标签。\\n"
"## 二、标题内的 \\#重点\\n"
"链接 https://example.com/#section 不变。\\n")
assert escape_obsidian_tags(
escape_obsidian_tags(content)) == escape_obsidian_tags(content)
def test_summary_file_is_private(tmp_path):
output = write_summary(tmp_path / "private" / "summary.md", "合成总结")
assert output.read_text(encoding="utf-8") == "合成总结\n"
assert stat.S_IMODE(output.stat().st_mode) == 0o600
def test_cli_end_to_end_with_synthetic_db_and_fake_magpie(
tmp_path, monkeypatch, capsys):
database_url = f"sqlite:///{tmp_path / 'synthetic.db'}"
storage = Storage(url=database_url)
_, start, _, _ = resolve_day("2026-11-03", "Asia/Shanghai")
base = {
"chat_id": "chat-synthetic",
"chat_type": 2,
"from_id": "sender-synthetic",
"msg_type": 4,
"msg_type_name": "TEXT",
"create_time": int(start.timestamp()) + 60,
}
storage.save_message({
**base, "msg_id": "incoming",
"content": "合成收到内容"
},
direction="in")
storage.save_message({
**base, "msg_id": "outgoing",
"content": "合成发出内容"
},
direction="out")
monkeypatch.setenv("LARKX_STORAGE_URL", database_url)
routed_model = "maqqie/gg-chat-efund/EFundGPT-dsv4pro"
session = FakeSession(
models=[routed_model],
completions=[
(routed_model, "单对话摘要"),
(
routed_model,
"## 一、今日工作概览今日工作围绕合成事项展开。\n"
"### 合成事项- [[张三]] 确认。\n# 合成总结",
),
],
)
monkeypatch.setattr("snooper_summary.requests.Session", lambda: session)
output = tmp_path / "summary.md"
dry_run = tmp_path / "dry-runs" / "2026-11-03.json"
dry_run.parent.mkdir()
dry_run.write_text("合成 dry-run", encoding="utf-8")
config_file = tmp_path / "config.yaml"
config_file.write_text(
f"output:\n summary: '{tmp_path}/previous/{{date}}.md'\n"
f" dry_run: '{tmp_path}/dry-runs/{{date}}.json'\n",
encoding="utf-8",
)
previous = tmp_path / "previous" / "2026-11-02.md"
previous.parent.mkdir()
previous.write_text(
"---\nmodel: synthetic\n---\n\n# 前日日志\n\n前日合成待办\n",
encoding="utf-8",
)
monkeypatch.setattr("lark_snooper.get_version", lambda: "0.1.0.dev0+test")
args = argparse.Namespace(
date="2026-11-03",
timezone="Asia/Shanghai",
model=routed_model,
base_url="http://127.0.0.1:3425/v1",
timeout=1,
chat=None,
max_chars=80000,
output=output,
config=config_file,
check=False,
dry_run=False,
no_contacts=True,
no_fetch=True,
no_calendar=True,
no_card_images=True,
)
assert cmd_summarize(args) == 0
output_text = output.read_text(encoding="utf-8")
assert "## 一、今日工作概览\n今日工作围绕合成事项展开。" in output_text
assert "### 合成事项\n- 张三 确认。" in output_text
assert not dry_run.exists()
request_text = session.post_calls[0][1]["json"]["messages"][1]["content"]
assert "合成收到内容" in request_text
assert "合成发出内容" in request_text
final_prompt = session.post_calls[1][1]["json"]["messages"][1]["content"]
assert "前日合成待办" in final_prompt
terminal = capsys.readouterr()
assert "合成收到内容" not in terminal.out + terminal.err
def test_cli_dry_run_exports_records_without_calling_model(
tmp_path, monkeypatch, capsys):
database_url = f"sqlite:///{tmp_path / 'synthetic.db'}"
storage = Storage(url=database_url)
_, start, _, _ = resolve_day("2026-11-03", "Asia/Shanghai")
base = {
"chat_id": "chat-synthetic",
"chat_type": 2,
"from_id": "sender-synthetic",
"msg_type": 4,
"msg_type_name": "TEXT",
"create_time": int(start.timestamp()) + 60,
}
storage.save_message({
**base, "msg_id": "incoming",
"content": "合成收到内容"
},
direction="in")
storage.save_message({
**base, "msg_id": "outgoing",
"content": "合成发出内容"
},
direction="out")
monkeypatch.setenv("LARKX_STORAGE_URL", database_url)
session = FakeSession(completions=[(DEFAULT_MODEL, "不应生成")])
monkeypatch.setattr("snooper_summary.requests.Session", lambda: session)
output = tmp_path / "from-yaml" / "2026-11-03.json"
config_file = tmp_path / "config.yaml"
config_file.write_text(
f"output:\n dry_run: '{tmp_path}/from-yaml/{{date}}.json'\n",
encoding="utf-8",
)
args = argparse.Namespace(
date="2026-11-03",
timezone="Asia/Shanghai",
model=DEFAULT_MODEL,
base_url="http://127.0.0.1:3425/v1",
timeout=1,
chat=None,
max_chars=80000,
output=None,
config=config_file,
check=False,
dry_run=True,
no_fetch=True,
)
assert cmd_summarize(args) == 0
assert session.post_calls == []
records = json.loads(output.read_text(encoding="utf-8"))
assert [record["msg_id"] for record in records] == ["incoming", "outgoing"]
assert records[0]["content"] == "合成收到内容"
assert stat.S_IMODE(output.stat().st_mode) == 0o600
terminal = capsys.readouterr()
assert "合成收到内容" not in terminal.out + terminal.err
def test_cli_summarize_prefetches_before_reading(tmp_path, monkeypatch):
from snooper_summary import resolve_day as resolve_summary_day
database_url = f"sqlite:///{tmp_path / 'synthetic.db'}"
monkeypatch.setenv("LARKX_STORAGE_URL", database_url)
session = FakeSession(completions=[(DEFAULT_MODEL,
"单对话摘要"), (DEFAULT_MODEL, "# 合成总结")])
monkeypatch.setattr("snooper_summary.requests.Session", lambda: session)
monkeypatch.setattr("lark_snooper.LarkClient", lambda auth: object())
monkeypatch.setattr("lark_snooper.LarkAuth", lambda: object())
sync_calls = []
def fake_sync(
client,
storage,
target_day,
tz,
batch_size=50,
chat_ids=None,
exclude_chat_ids=None,
force=False,
):
assert len(
session.get_calls) == 1 # EFundGPT preflight still comes first.
_, start, _, _ = resolve_summary_day("2026-11-03", "Asia/Shanghai")
storage.save_message(
{
"msg_id": "prefetched",
"chat_id": "chat-synthetic",
"chat_type": 2,
"from_id": "sender-synthetic",
"msg_type": 4,
"msg_type_name": "TEXT",
"create_time": int(start.timestamp()) + 60,
"content": "合成预取消息",
},
direction="in",
)
storage.save_message(
{
"msg_id": "excluded",
"chat_id": "chat-excluded",
"chat_type": 2,
"from_id": "sender-synthetic",
"msg_type": 4,
"msg_type_name": "TEXT",
"create_time": int(start.timestamp()) + 120,
"content": "不应读取的排除群消息",
},
direction="in",
)
sync_calls.append({
"batch_size": batch_size,
"chat_ids": chat_ids,
"exclude_chat_ids": exclude_chat_ids,
})
return {
"failed": 0,
"matched": 1,
"saved": 1,
"chats": 1,
"requests": 1,
"skipped": 0,
}
monkeypatch.setattr("snooper_history.sync_all_chats_for_day", fake_sync)
output = tmp_path / "summary.md"
config_file = tmp_path / "config.yaml"
config_file.write_text(
f"output:\n summary: '{tmp_path}/summaries/{{date}}.md'\n"
f" dry_run: '{tmp_path}/dry-runs/{{date}}.json'\n"
"chats:\n exclude:\n - 'chat-excluded'\n",
encoding="utf-8",
)
monkeypatch.setattr("lark_snooper.get_version", lambda: "0.1.0.dev0+test")
args = argparse.Namespace(
date="2026-11-03",
timezone="Asia/Shanghai",
model=DEFAULT_MODEL,
base_url="http://127.0.0.1:3425/v1",
timeout=1,
chat=["chat-synthetic"],
config=config_file,
max_chars=80000,
output=output,
check=False,
dry_run=False,
no_contacts=True,
no_fetch=False,
no_calendar=True,
no_card_images=True,
force_fetch=False,
)
assert cmd_summarize(args) == 0
assert sync_calls == [{
"batch_size": 50,
"chat_ids": ["chat-synthetic"],
"exclude_chat_ids": ["chat-excluded"],
}]
assert len(session.post_calls) == 2
request_text = session.post_calls[0][1]["json"]["messages"][1]["content"]
assert "合成预取消息" in request_text
assert "不应读取的排除群消息" not in request_text
assert output.read_text(encoding="utf-8") == (
"---\nversion: 0.1.0.dev0+test\n"
f"model: {DEFAULT_MODEL}\nis_read: false\n"
"tags:\n- no_previous_day_log\n- no_previous_weekly\n---\n\n# 合成总结\n")
def test_cli_model_failure_happens_before_storage_is_opened(monkeypatch):
monkeypatch.setattr(
MagpieClient,
"assert_model_available",
lambda self: (_ for _ in ()).throw(SummaryError("合成模型错误")),
)
def storage_must_not_open():
raise AssertionError("模型检查失败时不应打开消息库")
monkeypatch.setattr("lark_snooper.Storage", storage_must_not_open)
args = argparse.Namespace(
date="2026-11-03",
timezone="Asia/Shanghai",
model=DEFAULT_MODEL,
base_url="http://127.0.0.1:3425/v1",
timeout=1,
chat=None,
max_chars=2000,
output=None,
check=False,
dry_run=False,
no_contacts=True,
no_fetch=True,
)
assert cmd_summarize(args) == 1