astrbot_plugin_private_comp.../agenda_contracts.py
agent-bot 85d5069bbd feat: complete M6.1.3-R2 through M6.1.7 bot personal archive contract
M6.1.3-R2 非五类兼容(阻断修复):DTO date 缺失时从 occurred_at 派生,
刻意不做时区换算以与 _infer_window 同一时钟;calendar_event 取 start_at、
creative_progress 取 project.updated_at;未知 kind 不再默认 bot_observed_activity;
capture_hard_fact L4→L3;TYPE_CONTRACTS 覆盖全部 12 类,修复非五类 source_kind
兜底成 observed 污染本地记录;proactive_message 的 image_path 改为 has_image+
image_name(原样透传会被自身隐私校验整条静默丢弃);snapshot/daily_plan 透传 version。

M6.1.4 创作/媒体/主观分域:creative_progress 补 chunk 形参(生产调用点一直 TypeError
导致创作推进整步被阻断)并只留里程碑摘要;photo_generation 改为媒体索引
(原 payload 带 prompt 键与绝对路径,100% 静默丢弃);幂等键纳入隐私校验;
禁用键清单收窄,放行媒体标识键;两条 Bridge 路径统一送 body payload。

M6.1.5 Bot 专用检索 Profiles:按 Profile 分槽注入,固定槽位与条数、跨槽去重、
声明当前以本地运行态为准;旧版记忆插件回退通用检索。

M6.1.6 分层只读 API:新增 build_agenda_runtime_view 与 GET /agenda/runtime,
记忆插件停用时仍完整返回并标降级。

M6.1.7 隐私与残余收口:DTO 新增 contexts 禁用键;已删除娱乐功能(qzone/news/
web_exploration)的残余配置入口从展示面隐藏,旧值保留不删。

测试:174 项通过(pytest 与 unittest 双口径)。联合 E2E 135 项全部通过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 01:37:40 +08:00

303 行
12 KiB
Python

# -*- coding: utf-8 -*-
"""Contracts for the local unified agenda.
The module deliberately uses plain dictionaries at the storage boundary so old
JSON stores remain readable and AstrBot plugin state stays serializable.
"""
from __future__ import annotations
from copy import deepcopy
from datetime import datetime, date, timedelta
import hashlib
from typing import Any, Iterable
from zoneinfo import ZoneInfo
try:
from .calendar_system import isoformat, parse_datetime
except ImportError:
from calendar_system import isoformat, parse_datetime
AGENDA_VERSION = 1
AGENDA_STATUSES = {
"planned",
"active",
"completed",
"partially_completed",
"overridden",
"deferred",
"cancelled",
"unknown",
}
EVIDENCE_LEVELS = {"L0", "L1", "L2", "L3", "L4", "L5"}
SOURCE_KINDS = {"real", "planned", "simulated", "projection"}
WINDOW_DEFINITIONS = (
("深夜", 22 * 60, 6 * 60),
("早晨", 6 * 60, 12 * 60),
("下午", 12 * 60, 18 * 60),
("晚上", 18 * 60, 22 * 60),
)
WINDOW_NAMES = {item[0] for item in WINDOW_DEFINITIONS}
def timezone_or_default(timezone_name: Any = "Asia/Shanghai") -> ZoneInfo:
try:
return ZoneInfo(_text(timezone_name, 64) or "Asia/Shanghai")
except Exception:
return ZoneInfo("Asia/Shanghai")
def window_bounds(window_date: str | date, window: str, *, timezone_name: str = "Asia/Shanghai") -> tuple[datetime, datetime]:
name = _text(window, 24)
if name not in WINDOW_NAMES:
raise AgendaContractError(f"unknown window: {name}")
target = date.fromisoformat(str(window_date)) if not isinstance(window_date, date) else window_date
start_minute = next(item[1] for item in WINDOW_DEFINITIONS if item[0] == name)
end_minute = next(item[2] for item in WINDOW_DEFINITIONS if item[0] == name)
tz = timezone_or_default(timezone_name)
start = datetime.combine(target, datetime.min.time(), tzinfo=tz) + timedelta(minutes=start_minute)
end_day = target + timedelta(days=1) if end_minute <= start_minute else target
end = datetime.combine(end_day, datetime.min.time(), tzinfo=tz) + timedelta(minutes=end_minute)
return start, end
def window_for_datetime(value: datetime, *, timezone_name: str = "Asia/Shanghai") -> tuple[str, str, datetime, datetime]:
tz = timezone_or_default(timezone_name)
current = value.astimezone(tz) if value.tzinfo else value.replace(tzinfo=tz)
minute = current.hour * 60 + current.minute
if minute >= 22 * 60:
name, window_date = "深夜", current.date()
elif minute < 6 * 60:
name, window_date = "深夜", current.date() - timedelta(days=1)
elif minute < 12 * 60:
name, window_date = "早晨", current.date()
elif minute < 18 * 60:
name, window_date = "下午", current.date()
else:
name, window_date = "晚上", current.date()
start, end = window_bounds(window_date, name, timezone_name=getattr(tz, "key", timezone_name))
return name, window_date.isoformat(), start, end
def interval_overlaps_window(item: dict[str, Any], start: datetime, end: datetime, *, timezone_name: str = "Asia/Shanghai") -> bool:
if not isinstance(item, dict):
return False
try:
item_start = parse_datetime(item.get("start_at") or item.get("start"), timezone_name=timezone_name)
item_end = parse_datetime(item.get("end_at") or item.get("end"), timezone_name=timezone_name, default=item_start)
except Exception:
return False
return item_start < end and item_end > start
def source_ref_list(value: Any, limit: int = 30) -> list[str]:
return _list(value, limit)
class AgendaContractError(ValueError):
pass
def _text(value: Any, limit: int = 240) -> str:
return str(value or "").strip()[:limit]
def _list(value: Any, limit: int = 20) -> list[str]:
if not isinstance(value, (list, tuple, set)):
return []
result = []
for item in value:
text = _text(item, 160)
if text and text not in result:
result.append(text)
if len(result) >= limit:
break
return result
def _now_iso(now: datetime | None = None) -> str:
current = now or datetime.now().astimezone()
return isoformat(current)
def stable_id(prefix: str, *parts: Any) -> str:
raw = "|".join(_text(part, 240) for part in parts)
digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
return f"{_text(prefix, 32) or 'agenda'}-{digest}"
def normalize_source_kind(value: Any, default: str = "real") -> str:
candidate = _text(value, 32).lower()
return candidate if candidate in SOURCE_KINDS else default
def normalize_evidence_level(value: Any, default: str = "L1") -> str:
candidate = _text(value, 8).upper()
return candidate if candidate in EVIDENCE_LEVELS else default
def normalize_plan_item(raw: dict[str, Any], *, plan_id: str = "", now: datetime | None = None) -> dict[str, Any]:
if not isinstance(raw, dict):
raise AgendaContractError("plan item must be an object")
title = _text(raw.get("title") or raw.get("activity") or raw.get("description"), 240)
if not title:
raise AgendaContractError("plan item requires a title")
current = _now_iso(now)
result = deepcopy(raw)
result.update(
{
"plan_id": _text(plan_id or raw.get("plan_id") or raw.get("event_id"), 120)
or stable_id("plan", title, raw.get("date"), raw.get("time")),
"title": title,
"source_kind": "planned",
"evidence_level": "L0",
"status": _text(raw.get("status") or raw.get("lifecycle_status"), 32) or "planned",
"source_refs": _list(raw.get("source_refs") or raw.get("basis")),
"participants": _list(raw.get("participants")),
"certainty": _text(raw.get("certainty"), 24) or "medium",
"visibility": _text(raw.get("visibility"), 32) or "private",
"version": max(1, int(raw.get("version") or 1)),
"updated_at": _text(raw.get("updated_at"), 64) or current,
}
)
if result["status"] not in AGENDA_STATUSES:
result["status"] = "planned"
return result
def normalize_observed_activity(raw: dict[str, Any], *, now: datetime | None = None) -> dict[str, Any]:
if not isinstance(raw, dict):
raise AgendaContractError("observed activity must be an object")
title = _text(raw.get("title") or raw.get("summary") or raw.get("activity"), 240)
if not title:
raise AgendaContractError("observed activity requires a title")
source_refs = _list(raw.get("source_refs") or raw.get("evidence_refs"))
current = _now_iso(now)
activity_id = _text(raw.get("activity_id") or raw.get("id"), 120) or stable_id(
"activity", title, raw.get("start_at"), raw.get("end_at"), *source_refs
)
result = deepcopy(raw)
result.update(
{
"activity_id": activity_id,
"title": title,
"kind": _text(raw.get("kind"), 48) or "conversation",
"source_kind": normalize_source_kind(raw.get("source_kind"), "real"),
"source": _text(raw.get("source"), 64) or "conversation",
"source_refs": source_refs,
"participants": _list(raw.get("participants")),
"evidence_level": normalize_evidence_level(raw.get("evidence_level"), "L2"),
"certainty": _text(raw.get("certainty"), 24) or "medium",
"visibility": _text(raw.get("visibility"), 32) or "private",
"status": _text(raw.get("status"), 32) or "active",
"version": max(1, int(raw.get("version") or 1)),
"updated_at": _text(raw.get("updated_at"), 64) or current,
}
)
if result["status"] not in AGENDA_STATUSES:
result["status"] = "active"
if result["source_kind"] == "real" and result["evidence_level"] in {"L0", "L1"}:
result["status"] = "unknown"
return result
def normalize_window_snapshot(raw: dict[str, Any], *, now: datetime | None = None) -> dict[str, Any]:
if not isinstance(raw, dict):
raise AgendaContractError("window snapshot must be an object")
date_key = _text(raw.get("date"), 20)
window = _text(raw.get("window"), 24)
if not date_key or not window:
raise AgendaContractError("window snapshot requires date and window")
result = deepcopy(raw)
result.update(
{
"snapshot_id": _text(raw.get("snapshot_id"), 120) or stable_id("snapshot", date_key, window),
"date": date_key,
"window": window,
"planned": _list(raw.get("planned"), 30),
"observed": _list(raw.get("observed"), 30),
"reconciled": deepcopy(raw.get("reconciled")) if isinstance(raw.get("reconciled"), list) else [],
"open_items": _list(raw.get("open_items"), 30),
"source_refs": _list(raw.get("source_refs"), 30),
"generated_at": _text(raw.get("generated_at"), 64) or _now_iso(now),
"window_date": date_key,
"start_at": _text(raw.get("start_at"), 80),
"end_at": _text(raw.get("end_at"), 80),
"timezone": _text(raw.get("timezone"), 64) or "Asia/Shanghai",
"source_kind": _text(raw.get("source_kind"), 24) or "projection",
"evidence_level": normalize_evidence_level(raw.get("evidence_level"), "L2"),
"certainty": _text(raw.get("certainty"), 24) or "medium",
"version": max(1, int(raw.get("version") or 1)),
}
)
return result
def migrate_store(data: dict[str, Any]) -> tuple[dict[str, Any], bool]:
if not isinstance(data, dict):
raise AgendaContractError("store must be an object")
changed = False
defaults = {
"agenda_version": AGENDA_VERSION,
"observed_activities": [],
"window_snapshots": [],
"agenda_reconciliation_history": [],
"world_projection_cache": [],
"world_outbox": [],
"bot_personal_outbox": [],
"bot_personal_outbox_version": 1,
}
for key, default in defaults.items():
if key not in data or not isinstance(data.get(key), type(default)):
data[key] = deepcopy(default)
changed = True
plan = data.get("daily_plan")
if isinstance(plan, dict) and plan.get("items"):
normalized_items = []
for item in plan.get("items", []):
if isinstance(item, dict):
try:
normalized_items.append(normalize_plan_item(item, now=datetime.now().astimezone()))
except AgendaContractError:
normalized_items.append(item)
if normalized_items != plan.get("items"):
plan["items"] = normalized_items
changed = True
data["agenda_version"] = max(AGENDA_VERSION, int(data.get("agenda_version") or 0))
return data, changed
def agenda_entry_from_plan(plan: dict[str, Any], *, reason: str = "") -> dict[str, Any]:
result = {
"entry_id": stable_id("agenda", "plan", plan.get("plan_id")),
"title": _text(plan.get("title") or plan.get("activity"), 240),
"kind": "plan",
"status": _text(plan.get("status"), 32) or "planned",
"source_refs": [_text(plan.get("plan_id"), 120)],
"source_kind": "planned",
"evidence_level": "L0",
"visibility": _text(plan.get("visibility"), 32) or "private",
"reconciliation": {"reason": reason} if reason else {},
}
for key in ("start_at", "end_at", "date", "time", "end", "calendar", "participants", "version"):
if key in plan:
result[key] = deepcopy(plan[key])
return result
def agenda_entry_from_activity(activity: dict[str, Any], *, source_refs: Iterable[str] = ()) -> dict[str, Any]:
refs = [_text(item, 120) for item in source_refs if _text(item, 120)] or [_text(activity.get("activity_id"), 120)]
result = {
"entry_id": stable_id("agenda", "activity", activity.get("activity_id")),
"title": _text(activity.get("title"), 240),
"kind": "observed_activity",
"status": _text(activity.get("status"), 32) or "active",
"source_refs": refs,
"source_kind": normalize_source_kind(activity.get("source_kind"), "real"),
"evidence_level": normalize_evidence_level(activity.get("evidence_level"), "L2"),
"visibility": _text(activity.get("visibility"), 32) or "private",
"certainty": _text(activity.get("certainty"), 24) or "medium",
}
for key in ("start_at", "end_at", "participants", "calendar", "fresh_until", "version"):
if key in activity:
result[key] = deepcopy(activity[key])
return result