feat: 历史同步优化与消息已读属性

- 历史同步: 本地缓存优先、断点续传、按月批量同步
- 新增 sync_monthly.py: 支持逐月往前推进同步
- 消息表新增 is_read 字段,默认 false
- Obsidian 文档 frontmatter 自动补充 is_read: false
- 新增 migrate_add_is_read.py / migrate_obsidian_is_read.py 迁移脚本
- 总结 prompt 补充: 不记录腾讯会议号
- 历史同步失败时记录日志到 ~/.larkx/logs/history-failures.jsonl
This commit is contained in:
Benature
2026-11-08 11:31:18 +08:00
parent 99ee792c07
commit c8658ad064
10 changed files with 420 additions and 9 deletions

View File

@ -2,10 +2,14 @@
from __future__ import annotations
from datetime import date, datetime, time, timedelta
import json
import os
from datetime import date, datetime, time, timedelta, timezone
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo
from larkx.config import DATA_DIR
from larkx.proto import decoders
@ -13,6 +17,40 @@ class HistoryError(RuntimeError):
"""History synchronization failed without exposing message content."""
def format_history_failures(failures: list[dict[str, str]]) -> str:
"""Format useful failure metadata without upstream response bodies."""
return ";".join(
f"{failure['chat_name'] or '<未命名会话>'} "
f"({failure['chat_id']}): {failure['error_type']}"
for failure in failures
)
def write_history_failures(
target_day: date, failures: list[dict[str, str]], path: Path | str | None = None
) -> Path:
"""Append private JSONL failure metadata for later diagnosis."""
destination = (
Path(path).expanduser()
if path is not None
else DATA_DIR / "logs" / "history-failures.jsonl"
)
if not failures:
return destination
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
fd = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
with os.fdopen(fd, "a", encoding="utf-8") as handle:
for failure in failures:
record = {
"logged_at": datetime.now(timezone.utc).isoformat(),
"date": target_day.isoformat(),
**failure,
}
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
destination.chmod(0o600)
return destination
def _feed_chats(client: Any, page_size: int = 50, max_pages: int = 100):
cursor = None
seen: set[str] = set()
@ -59,8 +97,9 @@ def sync_all_chats_for_day(
chat_ids: list[str] | None = None,
exclude_chat_ids: list[str] | None = None,
force: bool = False,
) -> dict[str, int]:
"""Save one natural day from every visible INBOX chat; never print content."""
chats: list[dict] | None = None,
) -> dict[str, Any]:
"""Save one natural day and retain safe failure metadata, never content."""
if not 1 <= batch_size <= 200:
raise HistoryError("历史消息批次大小必须在 1 到 200 之间。")
if start_ts is None:
@ -70,7 +109,8 @@ def sync_all_chats_for_day(
end = datetime.combine(target_day + timedelta(days=1), time.min, tzinfo=tz)
end_ts = int(end.timestamp())
own_id = str(getattr(client.auth, "user_id", "") or "")
chats = list(_feed_chats(client, page_size=50))
if chats is None:
chats = list(_feed_chats(client, page_size=50))
if chat_ids:
requested = {str(chat_id) for chat_id in chat_ids}
chats = [chat for chat in chats if str(chat.get("id") or "") in requested]
@ -86,6 +126,7 @@ def sync_all_chats_for_day(
"failed": 0,
"requests": 0,
"skipped": 0,
"failures": [],
}
for chat in chats:
@ -164,6 +205,13 @@ def sync_all_chats_for_day(
min_position_scanned,
min_time_scanned,
)
except Exception: # noqa: BLE001 - isolate chat failures without exposing upstream data
except Exception as error: # noqa: BLE001 - isolate chats without exposing content
stats["failed"] += 1
stats["failures"].append(
{
"chat_id": chat_id,
"chat_name": str(chat.get("name") or ""),
"error_type": type(error).__name__,
}
)
return stats