feat: 按自然月回补日报周报和月报

This commit is contained in:
Benature
2026-11-22 20:52:23 +08:00
parent 8f6831c3e8
commit 71fa22d1ba
8 changed files with 204 additions and 42 deletions

View File

@ -110,7 +110,7 @@ VIDEO 消息不设每日数量上限:下载到 `~/.larkx/videos`,每个视
日报在读取本地消息后、媒体和模型分析前,会通过飞书 `joinTimesSec` 校验当前用户的实际入群时间,排除当时尚未入群的群聊历史;私聊不受影响。入群时间缓存到 `~/.larkx/chat-join-times.json`,无法确认入群时间的群默认排除,避免把可见历史误当作当时已参与。
周记在每周日总结当天结束的周一至周日,文件名按统计周最后一天(周日)使用 `%U` 年周序号(如 `MsgW2024-27.md`),标题为 `周记(开始日期 至 结束日期)`,周记前不添加写作日期;frontmatter 不设置 `date` 属性;周记使用统计周日报和上周周记生成;下一周日报会读取上周周记作为背景,下一篇周记同样读取上周周记做延续性对照。缺少上周周记时添加 `no_previous_weekly` 标签,不编造历史。批量补日志按“本周日报 → 本周周记 → 下周日报”的顺序执行,未结束的跨月周不提前生成周记。
周记在每周日总结当天结束的周一至周日,文件名按统计周最后一天(周日)使用 `%U` 年周序号(如 `MsgW2024-27.md`),标题为 `周记(开始日期 至 结束日期)`,周记前不添加写作日期;frontmatter 不设置 `date` 属性;周记使用统计周日报和上周周记生成;下一周日报会读取上周周记作为背景,下一篇周记同样读取上周周记做延续性对照。缺少上周周记时添加 `no_previous_weekly` 标签,不编造历史。批量补日志按自然月执行“本周日报 → 本周周记 → 下一周”,完成当月各周后生成月记,再进入下个月;未结束的周和月不提前生成周记或月记。
```bash
# 生成指定日期所在自然周的周记
@ -118,6 +118,9 @@ VIDEO 消息不设每日数量上限:下载到 `~/.larkx/videos`,每个视
# 明确覆盖已有周记
./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]`,并明确无法判断延续性。周一同时读取周末最后一天(周日)和上周最后一个工作日的日志,工作日判断包含法定节假日和调休。

View File

@ -1 +1 @@
0.2.1
0.2.2

View File

@ -6,6 +6,7 @@ from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
from datetime import date, datetime, timedelta
@ -34,25 +35,40 @@ from snooper_summary import (
resolve_chat_rules,
resolve_day,
)
from snooper_monthly import month_bounds, monthly_output_path
from snooper_weekly import week_bounds, weekly_output_path
ROOT = Path(__file__).resolve().parent
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(
start: date,
end: date,
has_messages,
output_for_day,
overwrite: bool = False,
refresh_tagged_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
while current <= end:
output = Path(output_for_day(current))
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)
)
if (overwrite or not exists or refresh) and has_messages(current):
yield current
current += timedelta(days=1)
@ -88,7 +104,9 @@ def main():
parser.add_argument("--model", default=os.environ.get("MAGPIE_MODEL", DEFAULT_MODEL))
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("--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("--state", default=str(DEFAULT_STATE_PATH))
args = parser.parse_args()
@ -132,6 +150,15 @@ def main():
if end < start:
print("--end-date 不能早于 --start-date", file=sys.stderr)
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_start = max(start, refresh_tagged_from) if refresh_tagged_from else start
def output_for_day(day: date) -> Path:
return Path(
@ -157,15 +184,20 @@ def main():
"status": "running",
"completed": 0,
"weekly_completed": 0,
"monthly_completed": 0,
"failed": 0,
"last_completed": None,
"last_attempted": None,
}
state_path = Path(args.state).expanduser()
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
write_state(state_path, state)
print(f"===== {label} 开始 =====", flush=True)
@ -176,61 +208,113 @@ def main():
write_state(state_path, state)
print(f"补日志在 {label} 停止;修复后重跑会继续", flush=True)
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["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)
print(f"===== {label} 完成 =====", flush=True)
return 0
current_week, _ = week_bounds(start)
while current_week <= end:
def run_weekly(current_week, label_prefix="周记"):
_, natural_week_end = week_bounds(current_week)
day_start = max(start, current_week)
day_end = min(end, natural_week_end)
for day in missing_message_dates(
day_start, day_end, has_messages, output_for_day, args.overwrite
):
command = [
sys.executable, str(ROOT / "lark_snooper.py"), "summarize",
"--date", day.isoformat(), "--timezone", args.timezone,
"--config", args.config, "--model", args.model,
"--base-url", args.base_url, "--timeout", str(args.timeout),
"--no-fetch",
]
result = run_step(command, output_for_day(day), f"补日志 {day}")
weekly_path = weekly_output_path(config["output"], current_week)
has_daily_note = any(
output_for_day(current_week + timedelta(days=offset)).exists()
for offset in range(7)
)
weekly_exists = weekly_path.exists() and weekly_path.stat().st_size > 0
if natural_week_end > end or not has_daily_note:
return 0
if weekly_exists and not args.overwrite:
return 0
command = [
sys.executable, str(ROOT / "lark_snooper.py"), "weekly",
"--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:
return result
current_week += timedelta(days=7)
# Only completed weeks get a weekly note; a month-ending partial week waits.
if natural_week_end <= end:
weekly_path = weekly_output_path(config["output"], current_week)
has_daily_note = any(
output_for_day(day_start + timedelta(days=offset)).exists()
for offset in range((day_end - day_start).days + 1)
)
weekly_exists = weekly_path.exists() and weekly_path.stat().st_size > 0
if has_daily_note and (args.overwrite or not weekly_exists):
# Phase 2: process one calendar month at a time; each month ends with its note.
month_start = daily_start.replace(day=1)
while month_start <= end:
_, natural_month_end = month_bounds(month_start.year, month_start.month)
month_end = min(end, natural_month_end)
print(f"##### 处理自然月 {month_start:%Y-%m} #####", flush=True)
current_week, _ = week_bounds(month_start)
while current_week <= month_end:
_, natural_week_end = week_bounds(current_week)
day_start = max(daily_start, month_start, current_week)
day_end = min(month_end, natural_week_end)
for day in missing_message_dates(
day_start,
day_end,
has_messages,
output_for_day,
args.overwrite,
refresh_tagged_from,
):
command = [
sys.executable, str(ROOT / "lark_snooper.py"), "weekly",
"--week", current_week.isoformat(), "--config", args.config,
sys.executable, str(ROOT / "lark_snooper.py"), "summarize",
"--date", day.isoformat(), "--timezone", args.timezone,
"--config", args.config, "--model", args.model,
"--base-url", args.base_url, "--timeout", str(args.timeout),
"--no-fetch",
]
output = output_for_day(day)
if args.overwrite or has_missing_report_tag(output):
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,
"--timeout", str(args.timeout),
]
if args.overwrite:
command.append("--overwrite")
result = run_step(
command, weekly_path, f"周记 {current_week}", weekly=True
command, monthly_path, f"月记 {month_start:%Y-%m}", kind="monthly"
)
if 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"
write_state(state_path, state)
print(
f"补日志完成: 新生成 {state['completed']} 天,"
f"周记 {state['weekly_completed']} 篇",
f"周记 {state['weekly_completed']} 篇,月记 {state['monthly_completed']} 篇",
flush=True,
)
return 0

View File

@ -441,6 +441,8 @@ def cmd_summarize(args):
missing_background_tags.append("no_previous_day_log")
if previous_weekly_missing:
missing_background_tags.append("no_previous_weekly")
if previous_monthly_missing:
missing_background_tags.append("no_previous_monthly")
if missing_background_tags:
properties["tags"] = missing_background_tags
content = add_obsidian_properties(content, properties)
@ -497,6 +499,31 @@ def cmd_weekly(args):
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():
parser = argparse.ArgumentParser(
prog="lark_snooper.py", description="LarkAgentX 历史同步与 EFundGPT 日度总结"
@ -513,6 +540,16 @@ def main():
weekly.add_argument("--overwrite", action="store_true", help="覆盖已有周记")
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.add_argument("--port", type=int, default=8765, help="本机监听端口,默认 8765")
web.add_argument("--config", default="config.yaml", help="要维护的 YAML 配置路径")

View File

@ -102,7 +102,7 @@ def load_previous_monthly_background(
workdays += 1
current += timedelta(days=1)
if workdays > 5:
return None, True
return None, False
# Load previous month's note
if target_day.month == 1:
@ -203,7 +203,6 @@ def generate_monthly(
properties = {
"version": get_version(),
"model": model.rsplit("/", 1)[-1],
"type": "monthly",
"is_read": False,
}
result = write_summary(output_path, add_obsidian_properties(content, properties))

View File

@ -1,6 +1,6 @@
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):
@ -33,3 +33,27 @@ def test_backfill_overwrite_still_skips_days_without_messages(tmp_path):
))
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)

15
tests/test_monthly.py Normal file
View 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

View File

@ -1430,7 +1430,7 @@ def test_cli_summarize_prefetches_before_reading(tmp_path, monkeypatch):
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")
"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):