Compare commits
14 Commits
6a55c0d140
...
16811d5ec8
| Author | SHA1 | Date | |
|---|---|---|---|
| 16811d5ec8 | |||
| 397ca3db40 | |||
| 313605f01b | |||
| d79be58dfa | |||
| 954bea2249 | |||
| d14f517db2 | |||
| e34402f980 | |||
| adb5c67345 | |||
| cc38e0daa7 | |||
| eafc6f0fe5 | |||
| f48ae4f809 | |||
| 2de88ec003 | |||
| 71fa22d1ba | |||
| 8f6831c3e8 |
10
README.md
10
README.md
@ -110,7 +110,7 @@ VIDEO 消息不设每日数量上限:下载到 `~/.larkx/videos`,每个视
|
|||||||
|
|
||||||
日报在读取本地消息后、媒体和模型分析前,会通过飞书 `joinTimesSec` 校验当前用户的实际入群时间,排除当时尚未入群的群聊历史;私聊不受影响。入群时间缓存到 `~/.larkx/chat-join-times.json`,无法确认入群时间的群默认排除,避免把可见历史误当作当时已参与。
|
日报在读取本地消息后、媒体和模型分析前,会通过飞书 `joinTimesSec` 校验当前用户的实际入群时间,排除当时尚未入群的群聊历史;私聊不受影响。入群时间缓存到 `~/.larkx/chat-join-times.json`,无法确认入群时间的群默认排除,避免把可见历史误当作当时已参与。
|
||||||
|
|
||||||
周记在每周日总结刚结束的上一段周日至周六,文件名按统计周最后一天(周六)使用 `%U` 年周序号(如 `MsgW2024-26.md`),标题使用实际写作日(周日),frontmatter 不设置 `date` 属性;周记使用统计周日报和上周周记生成;下一周日报会读取上周周记作为背景,下一篇周记同样读取上周周记做延续性对照。缺少上周周记时添加 `no_previous_weekly` 标签,不编造历史。批量补日志按“本周日报 → 本周周记 → 下周日报”的顺序执行,未结束的跨月周不提前生成周记。
|
周记在每周日总结当天结束的周一至周日,文件名按统计周最后一天(周日)使用 `%U` 年周序号(如 `MsgW2024-27.md`),标题为 `周记(开始日期 至 结束日期)`,周记前不添加写作日期;frontmatter 不设置 `date` 属性;周记使用统计周日报和上周周记生成;下一周日报会读取上周周记作为背景,下一篇周记同样读取上周周记做延续性对照。缺少上周周记时添加 `no_previous_weekly` 标签,不编造历史。批量补日志按自然月执行“本周日报 → 本周周记 → 下一周”,完成当月各周后生成月记,再进入下个月;未结束的周和月不提前生成周记或月记。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 生成指定日期所在自然周的周记
|
# 生成指定日期所在自然周的周记
|
||||||
@ -118,11 +118,17 @@ VIDEO 消息不设每日数量上限:下载到 `~/.larkx/videos`,每个视
|
|||||||
|
|
||||||
# 明确覆盖已有周记
|
# 明确覆盖已有周记
|
||||||
./lark_snooper.py weekly --week 2024-07-08 --overwrite
|
./lark_snooper.py weekly --week 2024-07-08 --overwrite
|
||||||
|
|
||||||
|
# 根据周记生成指定月份的月记
|
||||||
|
./lark_snooper.py monthly --month 2024-07 --model maqqie/gg-chat-efund/EFundGPT-dsv4pro
|
||||||
```
|
```
|
||||||
|
|
||||||
生成日报时会读取前一天和前两天 Markdown(不包含其 frontmatter),在“前日工作延续”中区分继续推进和今日未见延续。前一天文件不存在或为空时,属性添加 `tags: [no_previous_day_log]`,并明确无法判断延续性。周一同时读取周末最后一天(周日)和上周最后一个工作日的日志,工作日判断包含法定节假日和调休。
|
生成日报时会读取前一天和前两天 Markdown(不包含其 frontmatter),在“前日工作延续”中区分继续推进和今日未见延续。前一天文件不存在或为空时,属性添加 `tags: [no_previous_day_log]`,并明确无法判断延续性。周一同时读取周末最后一天(周日)和上周最后一个工作日的日志,工作日判断包含法定节假日和调休。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# 图片输入使用独立模型,文本总结仍使用主模型
|
||||||
|
./lark_snooper.py summarize --date 2026-10-08 --image-model maqqie/gg-chat-efund/EFundGPT-dsv4-flash-code
|
||||||
|
|
||||||
# 只检查模型,不同步或读取消息
|
# 只检查模型,不同步或读取消息
|
||||||
./lark_snooper.py summarize --check
|
./lark_snooper.py summarize --check
|
||||||
|
|
||||||
@ -219,7 +225,7 @@ chats:
|
|||||||
|
|
||||||
## 版本号
|
## 版本号
|
||||||
|
|
||||||
日报 frontmatter 包含 `version`。版本由 tracked `VERSION`、当前 commit 和工作区状态组成:干净时为 `0.1.0+g<commit>`,有未提交改动时为 `0.1.0.dev0+g<commit>`。不会自动执行 `git clean -fd`。
|
日报 frontmatter 包含 `version`。版本由 tracked `VERSION`、当前 commit 和工作区状态组成:干净时仅显示 `VERSION`(如 `0.2.1`),有未提交改动时为 `0.2.1.dev0+g<commit>`。不会自动执行 `git clean -fd`。
|
||||||
|
|
||||||
每次 commit 前递增 patch 版本,并将 `VERSION` 一并提交:
|
每次 commit 前递增 patch 版本,并将 `VERSION` 一并提交:
|
||||||
|
|
||||||
|
|||||||
@ -6,6 +6,7 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from datetime import date, datetime, timedelta
|
from datetime import date, datetime, timedelta
|
||||||
@ -16,6 +17,7 @@ from larkx.storage.models import Message
|
|||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
|
|
||||||
from snooper_client import SnifferLarkClient as LarkClient
|
from snooper_client import SnifferLarkClient as LarkClient
|
||||||
|
from snooper_history import HistoryError, sync_all_chats_for_day
|
||||||
from snooper_membership import (
|
from snooper_membership import (
|
||||||
MembershipError,
|
MembershipError,
|
||||||
fetch_self_join_times,
|
fetch_self_join_times,
|
||||||
@ -34,25 +36,42 @@ from snooper_summary import (
|
|||||||
resolve_chat_rules,
|
resolve_chat_rules,
|
||||||
resolve_day,
|
resolve_day,
|
||||||
)
|
)
|
||||||
|
from snooper_monthly import month_bounds, monthly_output_path
|
||||||
from snooper_weekly import week_bounds, weekly_output_path
|
from snooper_weekly import week_bounds, weekly_output_path
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent
|
ROOT = Path(__file__).resolve().parent
|
||||||
DEFAULT_STATE_PATH = Path("~/.larkx/backfill-state.json")
|
DEFAULT_STATE_PATH = Path("~/.larkx/backfill-state.json")
|
||||||
|
|
||||||
|
|
||||||
|
def has_missing_report_tag(path: Path) -> bool:
|
||||||
|
"""Return whether frontmatter marks a weekly or monthly background gap."""
|
||||||
|
if not path.exists() or path.stat().st_size == 0:
|
||||||
|
return False
|
||||||
|
frontmatter = path.read_text(encoding="utf-8").split("\n---", 1)[0]
|
||||||
|
return bool(re.search(r"(?m)^- no_previous_(?:weekly|monthly)\s*$", frontmatter))
|
||||||
|
|
||||||
|
|
||||||
def missing_message_dates(
|
def missing_message_dates(
|
||||||
start: date,
|
start: date,
|
||||||
end: date,
|
end: date,
|
||||||
has_messages,
|
has_messages,
|
||||||
output_for_day,
|
output_for_day,
|
||||||
overwrite: bool = False,
|
overwrite: bool = False,
|
||||||
|
refresh_tagged_from: date | None = None,
|
||||||
|
daily_overwrite_from: date | None = None,
|
||||||
):
|
):
|
||||||
"""Yield only days that have messages and lack a nonempty summary."""
|
"""Yield message days that are missing or explicitly tagged for refresh."""
|
||||||
current = start
|
current = start
|
||||||
while current <= end:
|
while current <= end:
|
||||||
output = Path(output_for_day(current))
|
output = Path(output_for_day(current))
|
||||||
exists = output.exists() and output.stat().st_size > 0
|
exists = output.exists() and output.stat().st_size > 0
|
||||||
if (overwrite or not exists) and has_messages(current):
|
refresh = (
|
||||||
|
refresh_tagged_from is not None
|
||||||
|
and current >= refresh_tagged_from
|
||||||
|
and has_missing_report_tag(output)
|
||||||
|
)
|
||||||
|
forced = daily_overwrite_from is not None and current >= daily_overwrite_from
|
||||||
|
if (overwrite or not exists or refresh or forced) and has_messages(current):
|
||||||
yield current
|
yield current
|
||||||
current += timedelta(days=1)
|
current += timedelta(days=1)
|
||||||
|
|
||||||
@ -86,9 +105,14 @@ def main():
|
|||||||
parser.add_argument("--timezone", default=DEFAULT_TIMEZONE)
|
parser.add_argument("--timezone", default=DEFAULT_TIMEZONE)
|
||||||
parser.add_argument("--config", default="config.yaml")
|
parser.add_argument("--config", default="config.yaml")
|
||||||
parser.add_argument("--model", default=os.environ.get("MAGPIE_MODEL", DEFAULT_MODEL))
|
parser.add_argument("--model", default=os.environ.get("MAGPIE_MODEL", DEFAULT_MODEL))
|
||||||
|
parser.add_argument("--image-model", help="图片卡片和视频帧使用的 EFundGPT 模型")
|
||||||
parser.add_argument("--base-url", default=os.environ.get("MAGPIE_BASE_URL", DEFAULT_BASE_URL))
|
parser.add_argument("--base-url", default=os.environ.get("MAGPIE_BASE_URL", DEFAULT_BASE_URL))
|
||||||
parser.add_argument("--timeout", type=int, default=600)
|
parser.add_argument("--timeout", type=int, default=600)
|
||||||
parser.add_argument("--overwrite", action="store_true", help="覆盖已有非空日报")
|
parser.add_argument("--overwrite", action="store_true", help="覆盖已有非空日报、周记和月记")
|
||||||
|
parser.add_argument("--weekly-through", help="先仅补齐此日期前已结束周的周记")
|
||||||
|
parser.add_argument("--refresh-tagged-from", help="重新生成此日期起带缺周报/月报标签的日报")
|
||||||
|
parser.add_argument("--daily-overwrite-from", help="覆盖此日期起的全部已有日报")
|
||||||
|
parser.add_argument("--fetch-missing", action="store_true", help="对本地无消息且从未同步的日期先联网拉取,再判断是否生成")
|
||||||
parser.add_argument("--state", default=str(DEFAULT_STATE_PATH))
|
parser.add_argument("--state", default=str(DEFAULT_STATE_PATH))
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
@ -132,6 +156,19 @@ def main():
|
|||||||
if end < start:
|
if end < start:
|
||||||
print("--end-date 不能早于 --start-date", file=sys.stderr)
|
print("--end-date 不能早于 --start-date", file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
|
weekly_through = (
|
||||||
|
resolve_day(args.weekly_through, args.timezone)[0]
|
||||||
|
if args.weekly_through else None
|
||||||
|
)
|
||||||
|
refresh_tagged_from = (
|
||||||
|
resolve_day(args.refresh_tagged_from, args.timezone)[0]
|
||||||
|
if args.refresh_tagged_from else None
|
||||||
|
)
|
||||||
|
daily_overwrite_from = (
|
||||||
|
resolve_day(args.daily_overwrite_from, args.timezone)[0]
|
||||||
|
if args.daily_overwrite_from else None
|
||||||
|
)
|
||||||
|
daily_start = max(start, refresh_tagged_from) if refresh_tagged_from else start
|
||||||
|
|
||||||
def output_for_day(day: date) -> Path:
|
def output_for_day(day: date) -> Path:
|
||||||
return Path(
|
return Path(
|
||||||
@ -150,6 +187,43 @@ def main():
|
|||||||
filtered, _ = filter_rows_by_membership(rows, join_times)
|
filtered, _ = filter_rows_by_membership(rows, join_times)
|
||||||
return bool(filtered)
|
return bool(filtered)
|
||||||
|
|
||||||
|
def ensure_day_synced(day: date) -> None:
|
||||||
|
"""Fetch a day's messages only when it has neither local data nor a sync mark."""
|
||||||
|
if storage.is_day_synced(day.isoformat()):
|
||||||
|
return
|
||||||
|
_, day_start, day_end, tz = resolve_day(day.isoformat(), args.timezone)
|
||||||
|
rows = storage.get_received_messages(
|
||||||
|
int(day_start.timestamp()),
|
||||||
|
int(day_end.timestamp()),
|
||||||
|
exclude_chat_ids=exclude_chat_ids,
|
||||||
|
include_outgoing=True,
|
||||||
|
)
|
||||||
|
if rows:
|
||||||
|
return
|
||||||
|
import chinese_calendar
|
||||||
|
|
||||||
|
if chinese_calendar.is_holiday(day):
|
||||||
|
storage.mark_day_synced(day.isoformat(), 0)
|
||||||
|
return
|
||||||
|
print(f"===== 联网拉取 {day} =====", flush=True)
|
||||||
|
try:
|
||||||
|
stats = sync_all_chats_for_day(
|
||||||
|
LarkClient(LarkAuth()),
|
||||||
|
storage,
|
||||||
|
day,
|
||||||
|
tz,
|
||||||
|
batch_size=50,
|
||||||
|
exclude_chat_ids=exclude_chat_ids,
|
||||||
|
)
|
||||||
|
except HistoryError as error:
|
||||||
|
print(f"===== 联网拉取 {day} 失败: {error} =====", flush=True)
|
||||||
|
return
|
||||||
|
print(
|
||||||
|
f"===== 联网拉取 {day} 完成:消息 {stats['matched']} 条,"
|
||||||
|
f"失败会话 {stats['failed']} 个 =====",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
state = {
|
state = {
|
||||||
"model": args.model,
|
"model": args.model,
|
||||||
"start_date": start.isoformat(),
|
"start_date": start.isoformat(),
|
||||||
@ -157,15 +231,20 @@ def main():
|
|||||||
"status": "running",
|
"status": "running",
|
||||||
"completed": 0,
|
"completed": 0,
|
||||||
"weekly_completed": 0,
|
"weekly_completed": 0,
|
||||||
|
"monthly_completed": 0,
|
||||||
"failed": 0,
|
"failed": 0,
|
||||||
"last_completed": None,
|
"last_completed": None,
|
||||||
"last_attempted": None,
|
"last_attempted": None,
|
||||||
}
|
}
|
||||||
state_path = Path(args.state).expanduser()
|
state_path = Path(args.state).expanduser()
|
||||||
write_state(state_path, state)
|
write_state(state_path, state)
|
||||||
print(f"补日志范围: {start} 至 {end};已有非空日报和无消息日自动跳过", flush=True)
|
print(
|
||||||
|
f"补日志范围: {daily_start} 至 {end};"
|
||||||
|
"缺失报告及指定范围内带缺背景标签的日报将重新生成",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
def run_step(command, output, label, weekly=False):
|
def run_step(command, output, label, kind="daily"):
|
||||||
state["last_attempted"] = label
|
state["last_attempted"] = label
|
||||||
write_state(state_path, state)
|
write_state(state_path, state)
|
||||||
print(f"===== {label} 开始 =====", flush=True)
|
print(f"===== {label} 开始 =====", flush=True)
|
||||||
@ -176,61 +255,126 @@ def main():
|
|||||||
write_state(state_path, state)
|
write_state(state_path, state)
|
||||||
print(f"补日志在 {label} 停止;修复后重跑会继续", flush=True)
|
print(f"补日志在 {label} 停止;修复后重跑会继续", flush=True)
|
||||||
return result.returncode or 1
|
return result.returncode or 1
|
||||||
key = "weekly_completed" if weekly else "completed"
|
key = {"daily": "completed", "weekly": "weekly_completed", "monthly": "monthly_completed"}[kind]
|
||||||
state[key] += 1
|
state[key] += 1
|
||||||
state["last_weekly_completed" if weekly else "last_completed"] = label
|
state_key = {"daily": "last_completed", "weekly": "last_weekly_completed", "monthly": "last_monthly_completed"}[kind]
|
||||||
|
state[state_key] = label
|
||||||
write_state(state_path, state)
|
write_state(state_path, state)
|
||||||
print(f"===== {label} 完成 =====", flush=True)
|
print(f"===== {label} 完成 =====", flush=True)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
current_week, _ = week_bounds(start)
|
def run_weekly(current_week, label_prefix="周记"):
|
||||||
while current_week <= end:
|
|
||||||
_, natural_week_end = week_bounds(current_week)
|
_, natural_week_end = week_bounds(current_week)
|
||||||
day_start = max(start, current_week)
|
weekly_path = weekly_output_path(config["output"], current_week)
|
||||||
day_end = min(end, natural_week_end)
|
has_daily_note = any(
|
||||||
for day in missing_message_dates(
|
output_for_day(current_week + timedelta(days=offset)).exists()
|
||||||
day_start, day_end, has_messages, output_for_day, args.overwrite
|
for offset in range(7)
|
||||||
):
|
)
|
||||||
command = [
|
weekly_exists = weekly_path.exists() and weekly_path.stat().st_size > 0
|
||||||
sys.executable, str(ROOT / "lark_snooper.py"), "summarize",
|
if natural_week_end > end or not has_daily_note:
|
||||||
"--date", day.isoformat(), "--timezone", args.timezone,
|
return 0
|
||||||
"--config", args.config, "--model", args.model,
|
if weekly_exists and not args.overwrite:
|
||||||
"--base-url", args.base_url, "--timeout", str(args.timeout),
|
return 0
|
||||||
"--no-fetch",
|
command = [
|
||||||
]
|
sys.executable, str(ROOT / "lark_snooper.py"), "weekly",
|
||||||
result = run_step(command, output_for_day(day), f"补日志 {day}")
|
"--week", current_week.isoformat(), "--config", args.config,
|
||||||
|
"--model", args.model, "--base-url", args.base_url,
|
||||||
|
"--timeout", str(args.timeout),
|
||||||
|
]
|
||||||
|
if args.overwrite:
|
||||||
|
command.append("--overwrite")
|
||||||
|
return run_step(
|
||||||
|
command, weekly_path, f"{label_prefix} {current_week}", kind="weekly"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Phase 1: establish weekly continuity before refreshing dependent daily notes.
|
||||||
|
if weekly_through:
|
||||||
|
current_week, _ = week_bounds(start)
|
||||||
|
while current_week <= weekly_through:
|
||||||
|
result = run_weekly(current_week, "预补周记")
|
||||||
if result:
|
if result:
|
||||||
return result
|
return result
|
||||||
|
current_week += timedelta(days=7)
|
||||||
|
|
||||||
# Only completed weeks get a weekly note; a month-ending partial week waits.
|
# Phase 2: process one calendar month at a time; each month ends with its note.
|
||||||
if natural_week_end <= end:
|
month_start = daily_start.replace(day=1)
|
||||||
weekly_path = weekly_output_path(config["output"], current_week)
|
while month_start <= end:
|
||||||
has_daily_note = any(
|
_, natural_month_end = month_bounds(month_start.year, month_start.month)
|
||||||
output_for_day(day_start + timedelta(days=offset)).exists()
|
month_end = min(end, natural_month_end)
|
||||||
for offset in range((day_end - day_start).days + 1)
|
print(f"##### 处理自然月 {month_start:%Y-%m} #####", flush=True)
|
||||||
)
|
current_week, _ = week_bounds(month_start)
|
||||||
weekly_exists = weekly_path.exists() and weekly_path.stat().st_size > 0
|
while current_week <= month_end:
|
||||||
if has_daily_note and (args.overwrite or not weekly_exists):
|
_, natural_week_end = week_bounds(current_week)
|
||||||
|
day_start = max(daily_start, month_start, current_week)
|
||||||
|
day_end = min(month_end, natural_week_end)
|
||||||
|
|
||||||
|
def has_messages_or_fetch(day: date) -> bool:
|
||||||
|
if args.fetch_missing:
|
||||||
|
ensure_day_synced(day)
|
||||||
|
return has_messages(day)
|
||||||
|
|
||||||
|
for day in missing_message_dates(
|
||||||
|
day_start,
|
||||||
|
day_end,
|
||||||
|
has_messages_or_fetch,
|
||||||
|
output_for_day,
|
||||||
|
args.overwrite,
|
||||||
|
refresh_tagged_from,
|
||||||
|
daily_overwrite_from,
|
||||||
|
):
|
||||||
command = [
|
command = [
|
||||||
sys.executable, str(ROOT / "lark_snooper.py"), "weekly",
|
sys.executable, str(ROOT / "lark_snooper.py"), "summarize",
|
||||||
"--week", current_week.isoformat(), "--config", args.config,
|
"--date", day.isoformat(), "--timezone", args.timezone,
|
||||||
|
"--config", args.config, "--model", args.model,
|
||||||
|
"--base-url", args.base_url, "--timeout", str(args.timeout),
|
||||||
|
"--no-fetch",
|
||||||
|
]
|
||||||
|
if args.image_model:
|
||||||
|
command.extend(["--image-model", args.image_model])
|
||||||
|
output = output_for_day(day)
|
||||||
|
if (
|
||||||
|
args.overwrite
|
||||||
|
or has_missing_report_tag(output)
|
||||||
|
or (daily_overwrite_from and day >= daily_overwrite_from)
|
||||||
|
):
|
||||||
|
command.append("--overwrite")
|
||||||
|
result = run_step(command, output, f"补日志 {day}")
|
||||||
|
if result:
|
||||||
|
return result
|
||||||
|
|
||||||
|
result = run_weekly(current_week)
|
||||||
|
if result:
|
||||||
|
return result
|
||||||
|
current_week += timedelta(days=7)
|
||||||
|
|
||||||
|
if natural_month_end <= end:
|
||||||
|
monthly_path = monthly_output_path(config["output"], month_start)
|
||||||
|
monthly_exists = monthly_path.exists() and monthly_path.stat().st_size > 0
|
||||||
|
if args.overwrite or not monthly_exists:
|
||||||
|
command = [
|
||||||
|
sys.executable, str(ROOT / "lark_snooper.py"), "monthly",
|
||||||
|
"--month", f"{month_start:%Y-%m}", "--config", args.config,
|
||||||
"--model", args.model, "--base-url", args.base_url,
|
"--model", args.model, "--base-url", args.base_url,
|
||||||
"--timeout", str(args.timeout),
|
"--timeout", str(args.timeout),
|
||||||
]
|
]
|
||||||
if args.overwrite:
|
if args.overwrite:
|
||||||
command.append("--overwrite")
|
command.append("--overwrite")
|
||||||
result = run_step(
|
result = run_step(
|
||||||
command, weekly_path, f"周记 {current_week}", weekly=True
|
command, monthly_path, f"月记 {month_start:%Y-%m}", kind="monthly"
|
||||||
)
|
)
|
||||||
if result:
|
if result:
|
||||||
return result
|
return result
|
||||||
current_week += timedelta(days=7)
|
month_start = date(
|
||||||
|
month_start.year + (month_start.month == 12),
|
||||||
|
month_start.month % 12 + 1,
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
|
||||||
state["status"] = "completed"
|
state["status"] = "completed"
|
||||||
write_state(state_path, state)
|
write_state(state_path, state)
|
||||||
print(
|
print(
|
||||||
f"补日志完成: 新生成 {state['completed']} 天,"
|
f"补日志完成: 新生成 {state['completed']} 天,"
|
||||||
f"周记 {state['weekly_completed']} 篇",
|
f"周记 {state['weekly_completed']} 篇,月记 {state['monthly_completed']} 篇",
|
||||||
flush=True,
|
flush=True,
|
||||||
)
|
)
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@ -223,8 +223,20 @@ def cmd_summarize(args):
|
|||||||
)
|
)
|
||||||
# The EFundGPT preflight must pass before history sync or storage access.
|
# The EFundGPT preflight must pass before history sync or storage access.
|
||||||
client.assert_model_available()
|
client.assert_model_available()
|
||||||
|
image_client = client
|
||||||
|
image_model = getattr(args, "image_model", None)
|
||||||
|
if image_model and image_model != model:
|
||||||
|
image_client = MagpieClient(
|
||||||
|
model=image_model,
|
||||||
|
base_url=base_url,
|
||||||
|
api_key=os.environ.get("MAGPIE_API_KEY"),
|
||||||
|
timeout=args.timeout,
|
||||||
|
)
|
||||||
|
image_client.assert_model_available()
|
||||||
if args.check:
|
if args.check:
|
||||||
print(f"OK Magpie 可用模型: {model}(未读取消息)")
|
print(f"OK Magpie 可用模型: {model}(未读取消息)")
|
||||||
|
if image_client is not client:
|
||||||
|
print(f"OK Magpie 可用图片模型: {image_model}")
|
||||||
return 0
|
return 0
|
||||||
config = load_config(getattr(args, "config", None))
|
config = load_config(getattr(args, "config", None))
|
||||||
output_config = {} if args.output else config["output"]
|
output_config = {} if args.output else config["output"]
|
||||||
@ -318,7 +330,7 @@ def cmd_summarize(args):
|
|||||||
from snooper_card_images import enrich_card_images
|
from snooper_card_images import enrich_card_images
|
||||||
|
|
||||||
image_stats = enrich_card_images(
|
image_stats = enrich_card_images(
|
||||||
LarkClient(LarkAuth()), client, rows, max_images=3
|
LarkClient(LarkAuth()), image_client, rows, max_images=3
|
||||||
)
|
)
|
||||||
if image_stats["candidates"]:
|
if image_stats["candidates"]:
|
||||||
print(
|
print(
|
||||||
@ -330,7 +342,7 @@ def cmd_summarize(args):
|
|||||||
|
|
||||||
video_stats = enrich_videos(
|
video_stats = enrich_videos(
|
||||||
LarkClient(LarkAuth()),
|
LarkClient(LarkAuth()),
|
||||||
client,
|
image_client,
|
||||||
rows,
|
rows,
|
||||||
max_frames=getattr(args, "video_frames", 12),
|
max_frames=getattr(args, "video_frames", 12),
|
||||||
transcribe_audio=not getattr(args, "no_video_audio", False),
|
transcribe_audio=not getattr(args, "no_video_audio", False),
|
||||||
@ -441,6 +453,8 @@ def cmd_summarize(args):
|
|||||||
missing_background_tags.append("no_previous_day_log")
|
missing_background_tags.append("no_previous_day_log")
|
||||||
if previous_weekly_missing:
|
if previous_weekly_missing:
|
||||||
missing_background_tags.append("no_previous_weekly")
|
missing_background_tags.append("no_previous_weekly")
|
||||||
|
if previous_monthly_missing:
|
||||||
|
missing_background_tags.append("no_previous_monthly")
|
||||||
if missing_background_tags:
|
if missing_background_tags:
|
||||||
properties["tags"] = missing_background_tags
|
properties["tags"] = missing_background_tags
|
||||||
content = add_obsidian_properties(content, properties)
|
content = add_obsidian_properties(content, properties)
|
||||||
@ -497,6 +511,31 @@ def cmd_weekly(args):
|
|||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_monthly(args):
|
||||||
|
from snooper_monthly import MonthlyError, generate_monthly
|
||||||
|
from snooper_summary import SummaryError
|
||||||
|
|
||||||
|
try:
|
||||||
|
generate_monthly(
|
||||||
|
month=args.month,
|
||||||
|
model=args.model or os.environ.get("MAGPIE_MODEL", "EFundGPT-dsv4-pro"),
|
||||||
|
base_url=args.base_url
|
||||||
|
or os.environ.get("MAGPIE_BASE_URL", "http://127.0.0.1:3425/v1"),
|
||||||
|
api_key=os.environ.get("MAGPIE_API_KEY"),
|
||||||
|
timeout=args.timeout,
|
||||||
|
config_path=args.config,
|
||||||
|
output=args.output,
|
||||||
|
overwrite=args.overwrite,
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
except (MonthlyError, SummaryError) as error:
|
||||||
|
print(f"月记生成失败: {error}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
except OSError as error:
|
||||||
|
print(f"月记写入失败: {type(error).__name__}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
prog="lark_snooper.py", description="LarkAgentX 历史同步与 EFundGPT 日度总结"
|
prog="lark_snooper.py", description="LarkAgentX 历史同步与 EFundGPT 日度总结"
|
||||||
@ -513,6 +552,16 @@ def main():
|
|||||||
weekly.add_argument("--overwrite", action="store_true", help="覆盖已有周记")
|
weekly.add_argument("--overwrite", action="store_true", help="覆盖已有周记")
|
||||||
weekly.set_defaults(fn=cmd_weekly)
|
weekly.set_defaults(fn=cmd_weekly)
|
||||||
|
|
||||||
|
monthly = subparsers.add_parser("monthly", help="根据周记生成月记并读取上月月记")
|
||||||
|
monthly.add_argument("--month", required=True, help="月份 YYYY-MM")
|
||||||
|
monthly.add_argument("--model", help="实际模型段必须以 EFundGPT 开头")
|
||||||
|
monthly.add_argument("--base-url", help="Magpie OpenAI 兼容地址")
|
||||||
|
monthly.add_argument("--timeout", type=int, default=600)
|
||||||
|
monthly.add_argument("--config", help="YAML 配置路径;默认读取当前目录 config.yaml")
|
||||||
|
monthly.add_argument("-o", "--output", help="覆盖月记输出路径")
|
||||||
|
monthly.add_argument("--overwrite", action="store_true", help="覆盖已有月记")
|
||||||
|
monthly.set_defaults(fn=cmd_monthly)
|
||||||
|
|
||||||
web = subparsers.add_parser("web", help="打开本机会话搜索与忽略列表管理页")
|
web = subparsers.add_parser("web", help="打开本机会话搜索与忽略列表管理页")
|
||||||
web.add_argument("--port", type=int, default=8765, help="本机监听端口,默认 8765")
|
web.add_argument("--port", type=int, default=8765, help="本机监听端口,默认 8765")
|
||||||
web.add_argument("--config", default="config.yaml", help="要维护的 YAML 配置路径")
|
web.add_argument("--config", default="config.yaml", help="要维护的 YAML 配置路径")
|
||||||
@ -537,6 +586,7 @@ def main():
|
|||||||
summarize.add_argument("--timezone", default="Asia/Shanghai", help="统计日边界时区")
|
summarize.add_argument("--timezone", default="Asia/Shanghai", help="统计日边界时区")
|
||||||
summarize.add_argument("--chat", action="append", help="只汇总指定 chat_id;可重复")
|
summarize.add_argument("--chat", action="append", help="只汇总指定 chat_id;可重复")
|
||||||
summarize.add_argument("--model", help="实际模型段必须以 EFundGPT 开头;也可设 MAGPIE_MODEL")
|
summarize.add_argument("--model", help="实际模型段必须以 EFundGPT 开头;也可设 MAGPIE_MODEL")
|
||||||
|
summarize.add_argument("--image-model", help="图片卡片和视频帧使用的 EFundGPT 模型;默认同主模型")
|
||||||
summarize.add_argument("--base-url", help="Magpie OpenAI 兼容地址")
|
summarize.add_argument("--base-url", help="Magpie OpenAI 兼容地址")
|
||||||
summarize.add_argument("--timeout", type=int, default=180, help="单次 Magpie 请求超时秒数")
|
summarize.add_argument("--timeout", type=int, default=180, help="单次 Magpie 请求超时秒数")
|
||||||
summarize.add_argument("--max-chars", type=int, default=80000, help="每个对话内每块消息最大字符数")
|
summarize.add_argument("--max-chars", type=int, default=80000, help="每个对话内每块消息最大字符数")
|
||||||
@ -550,6 +600,7 @@ def main():
|
|||||||
summarize.add_argument("--force-fetch", action="store_true", help="即使本地已有数据也强制重新拉取")
|
summarize.add_argument("--force-fetch", action="store_true", help="即使本地已有数据也强制重新拉取")
|
||||||
summarize.add_argument("--config", help="YAML 配置路径;默认读取当前目录 config.yaml")
|
summarize.add_argument("--config", help="YAML 配置路径;默认读取当前目录 config.yaml")
|
||||||
summarize.add_argument("-o", "--output", help="输出路径,优先级高于 YAML")
|
summarize.add_argument("-o", "--output", help="输出路径,优先级高于 YAML")
|
||||||
|
summarize.add_argument("--overwrite", action="store_true", help="覆盖已有非空日报")
|
||||||
mode = summarize.add_mutually_exclusive_group()
|
mode = summarize.add_mutually_exclusive_group()
|
||||||
mode.add_argument("--check", action="store_true", help="只检查模型,不同步或读取消息")
|
mode.add_argument("--check", action="store_true", help="只检查模型,不同步或读取消息")
|
||||||
mode.add_argument("--dry-run", action="store_true", help="只导出消息 JSON,不发送给模型")
|
mode.add_argument("--dry-run", action="store_true", help="只导出消息 JSON,不发送给模型")
|
||||||
|
|||||||
@ -14,8 +14,10 @@ class CalendarError(RuntimeError):
|
|||||||
|
|
||||||
AI_NOTES_CHAT_ID = "7391681490647744513"
|
AI_NOTES_CHAT_ID = "7391681490647744513"
|
||||||
AI_NOTES_URL_RE = re.compile(
|
AI_NOTES_URL_RE = re.compile(
|
||||||
r"https://[A-Za-z0-9.-]+\.feishu\.cn/(?:docx|minutes)/[A-Za-z0-9]+(?:\?[^\s\x00-\x1f]*)?"
|
r"https://[A-Za-z0-9.-]+\.feishu\.cn/(?:docx|minutes)/[A-Za-z0-9]+"
|
||||||
|
r"(?:[?][^\s\x00-\x1f\"<>]+)?"
|
||||||
)
|
)
|
||||||
|
TOPIC_RE = re.compile(r"Topic:\s*([^\n]+?)(?=Owner:|\Z)")
|
||||||
|
|
||||||
|
|
||||||
def resolve_calendar_links(config: dict[str, Any]) -> dict[str, str]:
|
def resolve_calendar_links(config: dict[str, Any]) -> dict[str, str]:
|
||||||
@ -35,6 +37,12 @@ def resolve_calendar_links(config: dict[str, Any]) -> dict[str, str]:
|
|||||||
return resolved
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_topic(text: str) -> str:
|
||||||
|
"""Extract a meeting topic from card text like 'Topic: 标题Owner: ...'."""
|
||||||
|
match = TOPIC_RE.search(text or "")
|
||||||
|
return match.group(1).strip() if match else ""
|
||||||
|
|
||||||
|
|
||||||
def fetch_ai_notes_links(
|
def fetch_ai_notes_links(
|
||||||
client: Any,
|
client: Any,
|
||||||
target_day: date,
|
target_day: date,
|
||||||
@ -69,13 +77,15 @@ def fetch_ai_notes_links(
|
|||||||
{"chat_id": chat_id, "start": start_ts, "end": end_ts},
|
{"chat_id": chat_id, "start": start_ts, "end": end_ts},
|
||||||
)
|
)
|
||||||
for content, content_data, ts in result:
|
for content, content_data, ts in result:
|
||||||
# Search content and content_data separately to avoid mixing with JSON
|
text = str(content or "")
|
||||||
for text_to_search in (str(content or ""), str(content_data or "")):
|
data_text = str(content_data or "")
|
||||||
|
topic = _extract_topic(text) or _extract_topic(data_text)
|
||||||
|
for text_to_search in (text, data_text):
|
||||||
for match in AI_NOTES_URL_RE.finditer(text_to_search):
|
for match in AI_NOTES_URL_RE.finditer(text_to_search):
|
||||||
url = match.group(0)
|
url = match.group(0)
|
||||||
if url not in seen_urls:
|
if url not in seen_urls:
|
||||||
seen_urls.add(url)
|
seen_urls.add(url)
|
||||||
links.append({"url": url, "create_time": int(ts), "topic": ""})
|
links.append({"url": url, "create_time": int(ts), "topic": topic})
|
||||||
except Exception:
|
except Exception:
|
||||||
pass # Fall back to network if storage read fails
|
pass # Fall back to network if storage read fails
|
||||||
|
|
||||||
@ -133,7 +143,10 @@ def _fetch_ai_notes_links_from_network(
|
|||||||
if ts:
|
if ts:
|
||||||
batch_min_time = ts if batch_min_time is None else min(batch_min_time, ts)
|
batch_min_time = ts if batch_min_time is None else min(batch_min_time, ts)
|
||||||
if start_ts <= ts < end_ts:
|
if start_ts <= ts < end_ts:
|
||||||
|
content = str(msg.get("content") or "")
|
||||||
content_data = msg.get("content_data")
|
content_data = msg.get("content_data")
|
||||||
|
content_data_str = str(content_data or "")
|
||||||
|
topic = _extract_topic(content) or _extract_topic(content_data_str)
|
||||||
if content_data and storage is not None:
|
if content_data and storage is not None:
|
||||||
# Extract URLs with topics from raw content_data
|
# Extract URLs with topics from raw content_data
|
||||||
extracted = storage._extract_links_with_topics(content_data)
|
extracted = storage._extract_links_with_topics(content_data)
|
||||||
@ -141,17 +154,15 @@ def _fetch_ai_notes_links_from_network(
|
|||||||
url = item["url"]
|
url = item["url"]
|
||||||
if url not in seen_urls:
|
if url not in seen_urls:
|
||||||
seen_urls.add(url)
|
seen_urls.add(url)
|
||||||
links.append({"url": url, "create_time": ts, "topic": item.get("topic", "")})
|
links.append({"url": url, "create_time": ts, "topic": topic or item.get("topic", "")})
|
||||||
else:
|
else:
|
||||||
# Fallback to plain text search
|
# Fallback to plain text search
|
||||||
content = str(msg.get("content") or "")
|
|
||||||
content_data_str = str(content_data or "")
|
|
||||||
text_to_search = content + content_data_str
|
text_to_search = content + content_data_str
|
||||||
for match in AI_NOTES_URL_RE.finditer(text_to_search):
|
for match in AI_NOTES_URL_RE.finditer(text_to_search):
|
||||||
url = match.group(0)
|
url = match.group(0)
|
||||||
if url not in seen_urls:
|
if url not in seen_urls:
|
||||||
seen_urls.add(url)
|
seen_urls.add(url)
|
||||||
links.append({"url": url, "create_time": ts, "topic": ""})
|
links.append({"url": url, "create_time": ts, "topic": topic})
|
||||||
if batch_min_time and batch_min_time < start_ts:
|
if batch_min_time and batch_min_time < start_ts:
|
||||||
break
|
break
|
||||||
upper = lower - 1
|
upper = lower - 1
|
||||||
@ -241,6 +252,7 @@ def fetch_calendar_events(
|
|||||||
event_map = response.get("events") or {}
|
event_map = response.get("events") or {}
|
||||||
events = []
|
events = []
|
||||||
used_urls: set[str] = set()
|
used_urls: set[str] = set()
|
||||||
|
event_end_times: list[tuple[int, str]] = []
|
||||||
for instance in response.get("calendarEventInstance") or []:
|
for instance in response.get("calendarEventInstance") or []:
|
||||||
event = event_map.get(str(instance.get("eventRefId") or ""), {})
|
event = event_map.get(str(instance.get("eventRefId") or ""), {})
|
||||||
locations = event.get("locations") or []
|
locations = event.get("locations") or []
|
||||||
@ -270,9 +282,23 @@ def fetch_calendar_events(
|
|||||||
"url": ai_notes_url or native_url or manual_url,
|
"url": ai_notes_url or native_url or manual_url,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
event_end_times.append((event_end_ts, summary))
|
||||||
events.sort(key=lambda event: (event["begin"], event["summary"]))
|
events.sort(key=lambda event: (event["begin"], event["summary"]))
|
||||||
# Collect unmatched links for separate display
|
# Collect unmatched links for separate display
|
||||||
unmatched_links = [
|
unmatched_links = [
|
||||||
link for link in ai_notes_links if link["url"] not in used_urls
|
link for link in ai_notes_links if link["url"] not in used_urls
|
||||||
]
|
]
|
||||||
|
# Fall back to the nearest meeting name for untitled links (e.g. docx notices).
|
||||||
|
for link in unmatched_links:
|
||||||
|
if link.get("topic"):
|
||||||
|
continue
|
||||||
|
best_delta = None
|
||||||
|
best_summary = ""
|
||||||
|
for end_ts, summary in event_end_times:
|
||||||
|
delta = link["create_time"] - end_ts
|
||||||
|
if abs(delta) <= 21600 and (best_delta is None or abs(delta) < abs(best_delta)):
|
||||||
|
best_delta = delta
|
||||||
|
best_summary = summary
|
||||||
|
if best_summary:
|
||||||
|
link["topic"] = best_summary
|
||||||
return events, unmatched_links
|
return events, unmatched_links
|
||||||
|
|||||||
@ -214,4 +214,6 @@ def sync_all_chats_for_day(
|
|||||||
"error_type": type(error).__name__,
|
"error_type": type(error).__name__,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
if not stats["failed"] and hasattr(storage, "mark_day_synced"):
|
||||||
|
storage.mark_day_synced(target_day.isoformat(), stats["matched"])
|
||||||
return stats
|
return stats
|
||||||
|
|||||||
@ -102,7 +102,7 @@ def load_previous_monthly_background(
|
|||||||
workdays += 1
|
workdays += 1
|
||||||
current += timedelta(days=1)
|
current += timedelta(days=1)
|
||||||
if workdays > 5:
|
if workdays > 5:
|
||||||
return None, True
|
return None, False
|
||||||
|
|
||||||
# Load previous month's note
|
# Load previous month's note
|
||||||
if target_day.month == 1:
|
if target_day.month == 1:
|
||||||
@ -203,7 +203,6 @@ def generate_monthly(
|
|||||||
properties = {
|
properties = {
|
||||||
"version": get_version(),
|
"version": get_version(),
|
||||||
"model": model.rsplit("/", 1)[-1],
|
"model": model.rsplit("/", 1)[-1],
|
||||||
"type": "monthly",
|
|
||||||
"is_read": False,
|
"is_read": False,
|
||||||
}
|
}
|
||||||
result = write_summary(output_path, add_obsidian_properties(content, properties))
|
result = write_summary(output_path, add_obsidian_properties(content, properties))
|
||||||
|
|||||||
@ -26,6 +26,17 @@ class SyncProgress(Base):
|
|||||||
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
||||||
|
|
||||||
|
|
||||||
|
class DaySyncState(Base):
|
||||||
|
"""Whether a calendar day has been fully synced, regardless of message count."""
|
||||||
|
|
||||||
|
__tablename__ = "day_sync_state"
|
||||||
|
|
||||||
|
sync_date = Column(String(10), primary_key=True)
|
||||||
|
completed = Column(Integer, default=0)
|
||||||
|
message_count = Column(Integer, default=0)
|
||||||
|
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
||||||
|
|
||||||
|
|
||||||
class SnifferStorage(Storage):
|
class SnifferStorage(Storage):
|
||||||
def __init__(self, url: str | None = None):
|
def __init__(self, url: str | None = None):
|
||||||
if url is None and not os.environ.get("LARKX_STORAGE_URL"):
|
if url is None and not os.environ.get("LARKX_STORAGE_URL"):
|
||||||
@ -247,3 +258,33 @@ class SnifferStorage(Storage):
|
|||||||
session.commit()
|
session.commit()
|
||||||
finally:
|
finally:
|
||||||
session.close()
|
session.close()
|
||||||
|
|
||||||
|
def mark_day_synced(self, sync_date: str, message_count: int) -> None:
|
||||||
|
"""Record that a calendar day has been fully synced (even with 0 messages)."""
|
||||||
|
session = self.Session()
|
||||||
|
try:
|
||||||
|
row = (
|
||||||
|
session.query(DaySyncState)
|
||||||
|
.filter_by(sync_date=sync_date)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if not row:
|
||||||
|
row = DaySyncState(sync_date=sync_date)
|
||||||
|
session.add(row)
|
||||||
|
row.completed = 1
|
||||||
|
row.message_count = int(message_count)
|
||||||
|
session.commit()
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|
||||||
|
def is_day_synced(self, sync_date: str) -> bool:
|
||||||
|
session = self.Session()
|
||||||
|
try:
|
||||||
|
row = (
|
||||||
|
session.query(DaySyncState)
|
||||||
|
.filter_by(sync_date=sync_date)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
return bool(row and row.completed)
|
||||||
|
finally:
|
||||||
|
session.close()
|
||||||
|
|||||||
@ -181,6 +181,23 @@ def require_efund_model(model: str) -> str:
|
|||||||
return model
|
return model
|
||||||
|
|
||||||
|
|
||||||
|
def require_matching_efund_model(returned_model: str, requested_model: str) -> str:
|
||||||
|
"""Accept only the gateway's case/auto- alias of the requested EFundGPT model."""
|
||||||
|
require_efund_model(requested_model)
|
||||||
|
if not isinstance(returned_model, str):
|
||||||
|
raise SummaryError("模型名必须是字符串。")
|
||||||
|
returned = returned_model.rsplit("/", 1)[-1].lower()
|
||||||
|
requested = requested_model.rsplit("/", 1)[-1].lower()
|
||||||
|
if returned.startswith("auto-"):
|
||||||
|
returned = returned[5:]
|
||||||
|
if returned != requested:
|
||||||
|
raise SummaryError(
|
||||||
|
"隐私保护已阻止请求:响应模型与请求的 EFundGPT 模型不一致;"
|
||||||
|
"不会回退到其他模型。"
|
||||||
|
)
|
||||||
|
return returned_model
|
||||||
|
|
||||||
|
|
||||||
def clean_model_output(content: str) -> str:
|
def clean_model_output(content: str) -> str:
|
||||||
"""Keep only the final answer after a model reasoning block."""
|
"""Keep only the final answer after a model reasoning block."""
|
||||||
if "<think>" in content and "</think>" not in content:
|
if "<think>" in content and "</think>" not in content:
|
||||||
@ -583,7 +600,7 @@ class MagpieClient:
|
|||||||
)
|
)
|
||||||
returned_model = data.get("model")
|
returned_model = data.get("model")
|
||||||
if returned_model is not None:
|
if returned_model is not None:
|
||||||
require_efund_model(returned_model)
|
require_matching_efund_model(returned_model, self.model)
|
||||||
choices = data.get("choices")
|
choices = data.get("choices")
|
||||||
if not isinstance(choices, list) or not choices:
|
if not isinstance(choices, list) or not choices:
|
||||||
raise SummaryError("Magpie 没有返回图片读取结果。")
|
raise SummaryError("Magpie 没有返回图片读取结果。")
|
||||||
@ -616,7 +633,7 @@ class MagpieClient:
|
|||||||
)
|
)
|
||||||
returned_model = data.get("model")
|
returned_model = data.get("model")
|
||||||
if returned_model is not None:
|
if returned_model is not None:
|
||||||
require_efund_model(returned_model)
|
require_matching_efund_model(returned_model, self.model)
|
||||||
choices = data.get("choices")
|
choices = data.get("choices")
|
||||||
if not isinstance(choices, list) or not choices:
|
if not isinstance(choices, list) or not choices:
|
||||||
raise SummaryError("Magpie 没有返回总结内容。")
|
raise SummaryError("Magpie 没有返回总结内容。")
|
||||||
@ -1066,7 +1083,10 @@ def summarize_messages(
|
|||||||
]
|
]
|
||||||
day_context = _day_context(target_day)
|
day_context = _day_context(target_day)
|
||||||
if not rows and not calendar_events:
|
if not rows and not calendar_events:
|
||||||
return f"# {target_day.isoformat()} 工作总结({day_context})\n\n本日未收到消息。\n"
|
return (
|
||||||
|
f"# {target_day.isoformat()} 工作总结\n\n"
|
||||||
|
f"> {day_context}\n\n本日未收到消息。\n"
|
||||||
|
)
|
||||||
messages = [serialize_message(row, tz) for row in rows]
|
messages = [serialize_message(row, tz) for row in rows]
|
||||||
groups: dict[str, list[dict[str, Any]]] = {}
|
groups: dict[str, list[dict[str, Any]]] = {}
|
||||||
for message in messages:
|
for message in messages:
|
||||||
@ -1278,13 +1298,17 @@ def summarize_messages(
|
|||||||
content = sanitize_wikilink_pipes(
|
content = sanitize_wikilink_pipes(
|
||||||
drop_casual_content(format_followup_checkboxes(shorten_headings(content)))
|
drop_casual_content(format_followup_checkboxes(shorten_headings(content)))
|
||||||
)
|
)
|
||||||
# Prepend day context to the title
|
# Keep day context out of the heading so calendar metadata is easy to hide.
|
||||||
if content.startswith("# "):
|
if content.startswith(f"# {target_day.isoformat()}"):
|
||||||
content = content.replace(
|
lines = content.splitlines()
|
||||||
|
lines[0] = re.sub(
|
||||||
|
rf"^# {re.escape(target_day.isoformat())}([^)]*)",
|
||||||
f"# {target_day.isoformat()}",
|
f"# {target_day.isoformat()}",
|
||||||
f"# {target_day.isoformat()}({day_context})",
|
lines[0],
|
||||||
1,
|
|
||||||
)
|
)
|
||||||
|
lines.insert(1, "")
|
||||||
|
lines.insert(2, f"> {day_context}")
|
||||||
|
content = "\n".join(lines) + ("\n" if content.endswith("\n") else "")
|
||||||
return content
|
return content
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -10,8 +10,8 @@ VERSION_FILE = PROJECT_ROOT / "VERSION"
|
|||||||
|
|
||||||
|
|
||||||
def format_version(base_version: str, commit: str, dirty: bool) -> str:
|
def format_version(base_version: str, commit: str, dirty: bool) -> str:
|
||||||
base = f"{base_version.strip()}.dev0" if dirty else base_version.strip()
|
base = base_version.strip()
|
||||||
return f"{base}+g{commit}"
|
return f"{base}.dev0+g{commit}" if dirty else base
|
||||||
|
|
||||||
|
|
||||||
def get_version(root: Path | None = None) -> str:
|
def get_version(root: Path | None = None) -> str:
|
||||||
|
|||||||
@ -43,8 +43,8 @@ WEEKLY_FINAL_PROMPT = """请根据 {week_start} 至 {week_end} 的日报提取
|
|||||||
3. 对照上周周记,区分本周继续推进和本周未见延续;上周周记为空时明确写无法判断,不得编造。
|
3. 对照上周周记,区分本周继续推进和本周未见延续;上周周记为空时明确写无法判断,不得编造。
|
||||||
4. 下周跟进建议只保留当前用户明确负责或需要回复、决策、协作推进的事项,每项使用 - [ ] checkbox。
|
4. 下周跟进建议只保留当前用户明确负责或需要回复、决策、协作推进的事项,每项使用 - [ ] checkbox。
|
||||||
5. 运维信息统一放在全文最后,不在前文重复。
|
5. 运维信息统一放在全文最后,不在前文重复。
|
||||||
6. 使用以下结构:
|
6. 使用以下结构,标题中的“周记”前不得添加日期:
|
||||||
# {weekly_date} 周记({week_start} 至 {week_end})
|
# 周记({week_start} 至 {week_end})
|
||||||
## 一、本周工作概览
|
## 一、本周工作概览
|
||||||
## 二、关键进展与结论
|
## 二、关键进展与结论
|
||||||
## 三、上周工作延续
|
## 三、上周工作延续
|
||||||
@ -66,8 +66,8 @@ class WeeklyError(RuntimeError):
|
|||||||
|
|
||||||
|
|
||||||
def week_bounds(day: date) -> tuple[date, date]:
|
def week_bounds(day: date) -> tuple[date, date]:
|
||||||
"""Return the Sunday–Saturday reporting week containing day."""
|
"""Return the Monday–Sunday reporting week containing day."""
|
||||||
start = day - timedelta(days=(day.weekday() + 1) % 7)
|
start = day - timedelta(days=day.weekday())
|
||||||
return start, start + timedelta(days=6)
|
return start, start + timedelta(days=6)
|
||||||
|
|
||||||
|
|
||||||
@ -196,7 +196,7 @@ def generate_weekly(
|
|||||||
WEEKLY_FINAL_PROMPT.format(
|
WEEKLY_FINAL_PROMPT.format(
|
||||||
week_start=week_start.isoformat(),
|
week_start=week_start.isoformat(),
|
||||||
week_end=week_end.isoformat(),
|
week_end=week_end.isoformat(),
|
||||||
weekly_date=(week_end + timedelta(days=1)).isoformat(),
|
weekly_date=week_end.isoformat(),
|
||||||
weekly_parts=json.dumps(weekly_parts, ensure_ascii=False, indent=2),
|
weekly_parts=json.dumps(weekly_parts, ensure_ascii=False, indent=2),
|
||||||
previous_weekly=previous_weekly or "<上周周记不存在>",
|
previous_weekly=previous_weekly or "<上周周记不存在>",
|
||||||
)
|
)
|
||||||
@ -207,7 +207,6 @@ def generate_weekly(
|
|||||||
properties = {
|
properties = {
|
||||||
"version": get_version(),
|
"version": get_version(),
|
||||||
"model": model.rsplit("/", 1)[-1],
|
"model": model.rsplit("/", 1)[-1],
|
||||||
"type": "weekly",
|
|
||||||
"is_read": False,
|
"is_read": False,
|
||||||
}
|
}
|
||||||
if previous_weekly is None:
|
if previous_weekly is None:
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
from backfill_summaries import missing_message_dates
|
from backfill_summaries import has_missing_report_tag, missing_message_dates
|
||||||
|
|
||||||
|
|
||||||
def test_backfill_skips_empty_days_and_existing_nonempty_summaries(tmp_path):
|
def test_backfill_skips_empty_days_and_existing_nonempty_summaries(tmp_path):
|
||||||
@ -33,3 +33,67 @@ def test_backfill_overwrite_still_skips_days_without_messages(tmp_path):
|
|||||||
))
|
))
|
||||||
|
|
||||||
assert days == [date(2024, 6, 2)]
|
assert days == [date(2024, 6, 2)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_backfill_refreshes_only_tagged_reports_from_requested_date(tmp_path):
|
||||||
|
tagged = tmp_path / "2024-11-27.md"
|
||||||
|
tagged.write_text(
|
||||||
|
"---\ntags:\n- no_previous_weekly\n---\n旧日报", encoding="utf-8"
|
||||||
|
)
|
||||||
|
later = tmp_path / "2024-11-28.md"
|
||||||
|
later.write_text("---\ntags:\n- no_previous_monthly\n---\n旧日报", encoding="utf-8")
|
||||||
|
ordinary = tmp_path / "2024-11-29.md"
|
||||||
|
ordinary.write_text("已有日报", encoding="utf-8")
|
||||||
|
|
||||||
|
days = list(missing_message_dates(
|
||||||
|
date(2024, 11, 27),
|
||||||
|
date(2024, 11, 29),
|
||||||
|
lambda day: True,
|
||||||
|
lambda day: tmp_path / f"{day.isoformat()}.md",
|
||||||
|
refresh_tagged_from=date(2024, 11, 28),
|
||||||
|
))
|
||||||
|
|
||||||
|
assert days == [date(2024, 11, 28)]
|
||||||
|
assert has_missing_report_tag(tagged)
|
||||||
|
assert has_missing_report_tag(later)
|
||||||
|
assert not has_missing_report_tag(ordinary)
|
||||||
|
|
||||||
|
|
||||||
|
def test_backfill_force_refreshes_all_daily_notes_from_requested_date(tmp_path):
|
||||||
|
before = tmp_path / "2026-10-07.md"
|
||||||
|
before.write_text("保留日报", encoding="utf-8")
|
||||||
|
first = tmp_path / "2026-10-08.md"
|
||||||
|
first.write_text("旧日报", encoding="utf-8")
|
||||||
|
second = tmp_path / "2026-10-09.md"
|
||||||
|
second.write_text("旧日报", encoding="utf-8")
|
||||||
|
|
||||||
|
days = list(missing_message_dates(
|
||||||
|
date(2026, 10, 7),
|
||||||
|
date(2026, 10, 9),
|
||||||
|
lambda day: True,
|
||||||
|
lambda day: tmp_path / f"{day.isoformat()}.md",
|
||||||
|
daily_overwrite_from=date(2026, 10, 8),
|
||||||
|
))
|
||||||
|
|
||||||
|
assert days == [date(2026, 10, 8), date(2026, 10, 9)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_backfill_does_not_probe_days_that_do_not_need_regeneration(tmp_path):
|
||||||
|
probes = []
|
||||||
|
|
||||||
|
def has_messages(day):
|
||||||
|
probes.append(day)
|
||||||
|
return True
|
||||||
|
|
||||||
|
for day in (date(2026, 2, 17), date(2026, 2, 18)):
|
||||||
|
(tmp_path / f"{day.isoformat()}.md").write_text("已有日报", encoding="utf-8")
|
||||||
|
|
||||||
|
days = list(missing_message_dates(
|
||||||
|
date(2026, 2, 17),
|
||||||
|
date(2026, 2, 18),
|
||||||
|
has_messages,
|
||||||
|
lambda day: tmp_path / f"{day.isoformat()}.md",
|
||||||
|
))
|
||||||
|
|
||||||
|
assert days == []
|
||||||
|
assert probes == [] # 已存在且无需重生成的日子不应触发拉取判断
|
||||||
|
|||||||
@ -1,7 +1,60 @@
|
|||||||
from datetime import date
|
from datetime import date, datetime
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
from snooper_calendar import fetch_calendar_events
|
from snooper_calendar import (
|
||||||
|
AI_NOTES_CHAT_ID,
|
||||||
|
_extract_topic,
|
||||||
|
fetch_ai_notes_links,
|
||||||
|
fetch_calendar_events,
|
||||||
|
)
|
||||||
|
from snooper_storage import SnifferStorage
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_topic_from_card_text():
|
||||||
|
text = (
|
||||||
|
"[卡片]\nMeeting recording completed"
|
||||||
|
"Topic: 指数-金科定期AI业务讨论会Owner: 万轶伦"
|
||||||
|
)
|
||||||
|
assert _extract_topic(text) == "指数-金科定期AI业务讨论会"
|
||||||
|
assert _extract_topic("https://efund.feishu.cn/docx/abc") == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_ai_notes_url_regex_stops_before_json_quote():
|
||||||
|
from snooper_calendar import AI_NOTES_URL_RE
|
||||||
|
|
||||||
|
json_text = (
|
||||||
|
'{"text": "https://efund.feishu.cn/docx/abc123?dcuId=7&from=vc#doxcnX", '
|
||||||
|
'"richText": {}}'
|
||||||
|
)
|
||||||
|
urls = AI_NOTES_URL_RE.findall(json_text)
|
||||||
|
assert urls == ["https://efund.feishu.cn/docx/abc123?dcuId=7&from=vc#doxcnX"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_ai_notes_links_reads_topic_from_local_content():
|
||||||
|
tz = ZoneInfo("Asia/Shanghai")
|
||||||
|
storage = SnifferStorage(url="sqlite:///:memory:")
|
||||||
|
ts = int(datetime(2026, 11, 17, 14, 0, tzinfo=tz).timestamp())
|
||||||
|
storage.save_message({
|
||||||
|
"msg_id": "minutes-1",
|
||||||
|
"chat_id": AI_NOTES_CHAT_ID,
|
||||||
|
"chat_type": 2,
|
||||||
|
"from_id": "bot",
|
||||||
|
"msg_type": 14,
|
||||||
|
"create_time": ts,
|
||||||
|
"content": (
|
||||||
|
"[卡片]\nMeeting recording completed"
|
||||||
|
"Topic: 指数-金科定期AI业务讨论会Owner: 万轶伦\n"
|
||||||
|
"https://efund.feishu.cn/minutes/abc123"
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
links = fetch_ai_notes_links(
|
||||||
|
object(), date(2026, 11, 17), tz, storage=storage
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(links) == 1
|
||||||
|
assert links[0]["url"].startswith("https://efund.feishu.cn/minutes/abc123")
|
||||||
|
assert links[0]["topic"] == "指数-金科定期AI业务讨论会"
|
||||||
|
|
||||||
|
|
||||||
class FakeCalendarClient:
|
class FakeCalendarClient:
|
||||||
@ -81,3 +134,60 @@ def test_fetch_calendar_events_normalizes_and_sorts_daily_instances():
|
|||||||
assert request["calendarIds"] == ["calendar-synthetic"]
|
assert request["calendarIds"] == ["calendar-synthetic"]
|
||||||
assert request["needsBriefEvents"] is True
|
assert request["needsBriefEvents"] is True
|
||||||
assert request["endTime"] - request["startTime"] == 86_400
|
assert request["endTime"] - request["startTime"] == 86_400
|
||||||
|
|
||||||
|
|
||||||
|
class FakeMeetingCalendarClient:
|
||||||
|
def __init__(self, begin_ts, end_ts):
|
||||||
|
self.begin_ts = begin_ts
|
||||||
|
self.end_ts = end_ts
|
||||||
|
|
||||||
|
def api(self, name, data):
|
||||||
|
if name == "calendars.GetUserPrimaryCalendarRequest":
|
||||||
|
return {"calendar": {"id": "calendar-synthetic"}}
|
||||||
|
assert name == "calendarevents.QueryInstanceRequest"
|
||||||
|
return {
|
||||||
|
"calendarEventInstance": [
|
||||||
|
{"eventRefId": "event-a", "beginTime": self.begin_ts, "endTime": self.end_ts}
|
||||||
|
],
|
||||||
|
"events": {
|
||||||
|
"event-a": {
|
||||||
|
"summary": "指数-金科定期AI业务讨论会",
|
||||||
|
"locations": [],
|
||||||
|
"isDeleted": False,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_untitled_ai_notes_link_falls_back_to_nearest_meeting_name():
|
||||||
|
tz = ZoneInfo("Asia/Shanghai")
|
||||||
|
begin = int(datetime(2026, 11, 17, 14, 0, tzinfo=tz).timestamp())
|
||||||
|
end = int(datetime(2026, 11, 17, 15, 0, tzinfo=tz).timestamp())
|
||||||
|
minutes_ts = int(datetime(2026, 11, 17, 15, 15, tzinfo=tz).timestamp())
|
||||||
|
docx_ts = int(datetime(2026, 11, 17, 17, 38, tzinfo=tz).timestamp())
|
||||||
|
|
||||||
|
storage = SnifferStorage(url="sqlite:///:memory:")
|
||||||
|
storage.save_message({
|
||||||
|
"msg_id": "minutes-1", "chat_id": AI_NOTES_CHAT_ID, "chat_type": 2,
|
||||||
|
"from_id": "bot", "msg_type": 14, "create_time": minutes_ts,
|
||||||
|
"content": (
|
||||||
|
"[卡片]\nMeeting recording completed"
|
||||||
|
"Topic: 指数-金科定期AI业务讨论会Owner: 万轶伦\n"
|
||||||
|
"https://efund.feishu.cn/minutes/m1"
|
||||||
|
),
|
||||||
|
})
|
||||||
|
storage.save_message({
|
||||||
|
"msg_id": "docx-1", "chat_id": AI_NOTES_CHAT_ID, "chat_type": 2,
|
||||||
|
"from_id": "bot", "msg_type": 4, "create_time": docx_ts,
|
||||||
|
"content": "https://efund.feishu.cn/docx/d1",
|
||||||
|
})
|
||||||
|
|
||||||
|
client = FakeMeetingCalendarClient(begin, end)
|
||||||
|
events, unmatched = fetch_calendar_events(
|
||||||
|
client, date(2026, 11, 17), tz, storage=storage
|
||||||
|
)
|
||||||
|
|
||||||
|
assert events[0]["url"].startswith("https://efund.feishu.cn/minutes/m1")
|
||||||
|
assert any(link["url"].startswith("https://efund.feishu.cn/docx/d1") for link in unmatched)
|
||||||
|
docx = next(link for link in unmatched if "docx/d1" in link["url"])
|
||||||
|
assert docx["topic"] == "指数-金科定期AI业务讨论会"
|
||||||
|
|||||||
@ -138,6 +138,57 @@ def test_sync_all_chats_for_day_excludes_configured_chat_before_history_pull():
|
|||||||
assert storage.get_messages("private-b") == []
|
assert storage.get_messages("private-b") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_marks_day_synced_when_no_failures():
|
||||||
|
from snooper_history import sync_all_chats_for_day
|
||||||
|
|
||||||
|
tz = ZoneInfo("Asia/Shanghai")
|
||||||
|
start_ts = 1_792_000_000
|
||||||
|
client = FakeClient(start_ts)
|
||||||
|
client.auth = type("Auth", (), {"user_id": "self"})()
|
||||||
|
storage = Storage(url="sqlite:///:memory:")
|
||||||
|
|
||||||
|
stats = sync_all_chats_for_day(
|
||||||
|
client,
|
||||||
|
storage,
|
||||||
|
date(2026, 11, 3),
|
||||||
|
tz,
|
||||||
|
batch_size=2,
|
||||||
|
start_ts=start_ts,
|
||||||
|
end_ts=start_ts + 86_400,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert stats["failed"] == 0
|
||||||
|
assert storage.is_day_synced("2026-11-03") is True
|
||||||
|
assert storage.is_day_synced("2026-11-04") is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_does_not_mark_day_synced_when_failures():
|
||||||
|
from snooper_history import sync_all_chats_for_day
|
||||||
|
|
||||||
|
class FailingClient(FakeClient):
|
||||||
|
def pull_history(self, chat_id, positions, **kwargs):
|
||||||
|
raise RuntimeError("合成失败")
|
||||||
|
|
||||||
|
tz = ZoneInfo("Asia/Shanghai")
|
||||||
|
start_ts = 1_792_000_000
|
||||||
|
client = FailingClient(start_ts)
|
||||||
|
client.auth = type("Auth", (), {"user_id": "self"})()
|
||||||
|
storage = Storage(url="sqlite:///:memory:")
|
||||||
|
|
||||||
|
stats = sync_all_chats_for_day(
|
||||||
|
client,
|
||||||
|
storage,
|
||||||
|
date(2026, 11, 3),
|
||||||
|
tz,
|
||||||
|
batch_size=2,
|
||||||
|
start_ts=start_ts,
|
||||||
|
end_ts=start_ts + 86_400,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert stats["failed"] >= 1
|
||||||
|
assert storage.is_day_synced("2026-11-03") is False
|
||||||
|
|
||||||
|
|
||||||
def test_history_failure_log_identifies_chat_without_sensitive_error_body(tmp_path):
|
def test_history_failure_log_identifies_chat_without_sensitive_error_body(tmp_path):
|
||||||
from snooper_history import (
|
from snooper_history import (
|
||||||
format_history_failures,
|
format_history_failures,
|
||||||
|
|||||||
15
tests/test_monthly.py
Normal file
15
tests/test_monthly.py
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from snooper_monthly import load_previous_monthly_background
|
||||||
|
|
||||||
|
|
||||||
|
def test_previous_monthly_missing_only_applies_to_first_five_workdays(tmp_path):
|
||||||
|
output = {"monthly": str(tmp_path / "Monthly" / "MsgMYYYY-MM.md")}
|
||||||
|
|
||||||
|
content, missing = load_previous_monthly_background(output, date(2024, 11, 1))
|
||||||
|
assert content is None
|
||||||
|
assert missing is True
|
||||||
|
|
||||||
|
content, missing = load_previous_monthly_background(output, date(2024, 11, 27))
|
||||||
|
assert content is None
|
||||||
|
assert missing is False
|
||||||
@ -24,6 +24,7 @@ from snooper_summary import (
|
|||||||
normalize_self_name,
|
normalize_self_name,
|
||||||
previous_workday,
|
previous_workday,
|
||||||
require_efund_model,
|
require_efund_model,
|
||||||
|
require_matching_efund_model,
|
||||||
resolve_day,
|
resolve_day,
|
||||||
sanitize_wikilink_pipes,
|
sanitize_wikilink_pipes,
|
||||||
shorten_headings,
|
shorten_headings,
|
||||||
@ -140,9 +141,19 @@ def test_system_only_private_chat_does_not_require_a_person_name():
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert "本日未收到消息" in result
|
assert "本日未收到消息" in result
|
||||||
|
assert result.startswith("# 2026-11-03 工作总结\n\n> 周二,工作日,交易日\n")
|
||||||
|
assert "工作总结(" not in result
|
||||||
assert session.post_calls == []
|
assert session.post_calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_model_response_accepts_only_matching_gateway_alias():
|
||||||
|
requested = "auto/EFundGPT-dsv4-flash-code"
|
||||||
|
returned = "group/auto-efundgpt-dsv4-flash-code"
|
||||||
|
assert require_matching_efund_model(returned, requested) == returned
|
||||||
|
with pytest.raises(SummaryError, match="响应模型与请求"):
|
||||||
|
require_matching_efund_model("group/auto-other-model", requested)
|
||||||
|
|
||||||
|
|
||||||
def test_model_policy_checks_actual_model_after_optional_routing_prefix():
|
def test_model_policy_checks_actual_model_after_optional_routing_prefix():
|
||||||
assert require_efund_model(DEFAULT_MODEL) == DEFAULT_MODEL
|
assert require_efund_model(DEFAULT_MODEL) == DEFAULT_MODEL
|
||||||
assert require_efund_model("EFundGPT-other") == "EFundGPT-other"
|
assert require_efund_model("EFundGPT-other") == "EFundGPT-other"
|
||||||
@ -1430,7 +1441,7 @@ def test_cli_summarize_prefetches_before_reading(tmp_path, monkeypatch):
|
|||||||
assert output.read_text(encoding="utf-8") == (
|
assert output.read_text(encoding="utf-8") == (
|
||||||
"---\nversion: 0.1.0.dev0+test\n"
|
"---\nversion: 0.1.0.dev0+test\n"
|
||||||
f"model: {DEFAULT_MODEL}\nis_read: false\n"
|
f"model: {DEFAULT_MODEL}\nis_read: false\n"
|
||||||
"tags:\n- no_previous_day_log\n- no_previous_weekly\n---\n\n# 合成总结\n")
|
"tags:\n- no_previous_day_log\n- no_previous_weekly\n- no_previous_monthly\n---\n\n# 合成总结\n")
|
||||||
|
|
||||||
|
|
||||||
def test_cli_model_failure_happens_before_storage_is_opened(monkeypatch):
|
def test_cli_model_failure_happens_before_storage_is_opened(monkeypatch):
|
||||||
|
|||||||
@ -2,7 +2,7 @@ from snooper_version import bump_patch, format_version
|
|||||||
|
|
||||||
|
|
||||||
def test_version_marks_dirty_worktree_as_dev():
|
def test_version_marks_dirty_worktree_as_dev():
|
||||||
assert format_version("0.1.0", "abc1234", False) == "0.1.0+gabc1234"
|
assert format_version("0.1.0", "abc1234", False) == "0.1.0"
|
||||||
assert format_version("0.1.0", "abc1234", True) == "0.1.0.dev0+gabc1234"
|
assert format_version("0.1.0", "abc1234", True) == "0.1.0.dev0+gabc1234"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -17,10 +17,11 @@ from snooper_weekly import (
|
|||||||
|
|
||||||
def test_week_bounds_use_monday_and_sunday():
|
def test_week_bounds_use_monday_and_sunday():
|
||||||
assert week_bounds(date(2024, 7, 4)) == (
|
assert week_bounds(date(2024, 7, 4)) == (
|
||||||
date(2024, 6, 30), date(2024, 7, 6)
|
date(2024, 7, 1), date(2024, 7, 7)
|
||||||
)
|
)
|
||||||
assert iso_week_label(date(2024, 6, 30)) == "2024-W26"
|
assert iso_week_label(date(2024, 7, 1)) == "2024-W27"
|
||||||
assert "# {weekly_date} 周记" in WEEKLY_FINAL_PROMPT
|
assert "# 周记({week_start} 至 {week_end})" in WEEKLY_FINAL_PROMPT
|
||||||
|
assert "# {weekly_date} 周记" not in WEEKLY_FINAL_PROMPT
|
||||||
|
|
||||||
|
|
||||||
def test_previous_weekly_background_uses_previous_monday(tmp_path):
|
def test_previous_weekly_background_uses_previous_monday(tmp_path):
|
||||||
@ -28,7 +29,7 @@ def test_previous_weekly_background_uses_previous_monday(tmp_path):
|
|||||||
"summary": str(tmp_path / "Daily" / "MsgYYYY-MM-DD.md"),
|
"summary": str(tmp_path / "Daily" / "MsgYYYY-MM-DD.md"),
|
||||||
"weekly": str(tmp_path / "Weekly" / "MsgWYYYY-WW.md"),
|
"weekly": str(tmp_path / "Weekly" / "MsgWYYYY-WW.md"),
|
||||||
}
|
}
|
||||||
weekly = tmp_path / "Weekly" / "MsgW2024-26.md"
|
weekly = tmp_path / "Weekly" / "MsgW2024-27.md"
|
||||||
weekly.parent.mkdir(parents=True)
|
weekly.parent.mkdir(parents=True)
|
||||||
weekly.write_text("---\ntype: weekly\n---\n\n上周合成周记", encoding="utf-8")
|
weekly.write_text("---\ntype: weekly\n---\n\n上周合成周记", encoding="utf-8")
|
||||||
|
|
||||||
@ -49,7 +50,7 @@ def test_generate_weekly_reads_previous_week_and_sanitizes_links(
|
|||||||
(daily / f"Msg{day}.md").write_text(
|
(daily / f"Msg{day}.md").write_text(
|
||||||
f"---\nmodel: synthetic\n---\n\n# {day}\n合成进展", encoding="utf-8"
|
f"---\nmodel: synthetic\n---\n\n# {day}\n合成进展", encoding="utf-8"
|
||||||
)
|
)
|
||||||
(weekly / "MsgW2024-26.md").write_text("上周合成周记", encoding="utf-8")
|
(weekly / "MsgW2024-27.md").write_text("上周合成周记", encoding="utf-8")
|
||||||
config = tmp_path / "config.yaml"
|
config = tmp_path / "config.yaml"
|
||||||
config.write_text(
|
config.write_text(
|
||||||
f"output:\n summary: '{daily}/MsgYYYY-MM-DD.md'\n"
|
f"output:\n summary: '{daily}/MsgYYYY-MM-DD.md'\n"
|
||||||
@ -79,7 +80,7 @@ def test_generate_weekly_reads_previous_week_and_sanitizes_links(
|
|||||||
|
|
||||||
text = output.read_text(encoding="utf-8")
|
text = output.read_text(encoding="utf-8")
|
||||||
assert "[[审核群|指数内容部落]]" in text
|
assert "[[审核群|指数内容部落]]" in text
|
||||||
assert "type: weekly" in text
|
assert "type: weekly" not in text
|
||||||
assert "date:" not in text
|
assert "date:" not in text
|
||||||
assert "上周合成周记" in clients[0].prompts[-1]
|
assert "上周合成周记" in clients[0].prompts[-1]
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user