# -*- 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} # 渲染层用的窗口标识(CSS 类名/主题变量都用它,避免把中文名写进样式表) WINDOW_SLUGS = {"深夜": "late_night", "早晨": "morning", "下午": "afternoon", "晚上": "evening"} def window_for_plan_minutes( plan_date: Any, minutes: Any, *, timezone_name: str = "Asia/Shanghai" ) -> tuple[str, str]: """把「计划日 + 当日分钟数」还原成 (窗口名, 窗口日期)。 只给分钟数是不够的:深夜跨午夜,同一个「深夜」标签可能分属两个日程日—— 7/27 的 00:30 属于 **7/26 的深夜**,7/27 的 23:00 属于 7/27 的深夜。 时间轴上这两条会同时出现,不带日期就分不出谁是谁。 分钟数可能带 +1440 偏移(计划里时间回绕到次日),先拆出天偏移再还原成真实时刻, 然后交给 window_for_datetime——判定只保留那一处实现。 """ try: base = date.fromisoformat(str(plan_date)) if not isinstance(plan_date, date) else plan_date value = int(minutes) except (TypeError, ValueError): return "", "" day_offset, raw = divmod(value, 24 * 60) tz = timezone_or_default(timezone_name) moment = datetime.combine(base + timedelta(days=day_offset), datetime.min.time(), tzinfo=tz) + timedelta(minutes=raw) name, window_date, _start, _end = window_for_datetime(moment, timezone_name=getattr(tz, "key", timezone_name)) return name, window_date def window_for_minutes(minutes: Any) -> str: """把「当日分钟数」归入四段式窗口。 页面时间轴按分钟排段,没有 datetime 可用;跨零点的段会带 +1440 偏移,先取模。 深夜跨零点(22:00-06:00),所以它的判定要拆成两截。 """ try: value = int(minutes) % (24 * 60) except (TypeError, ValueError): return "" for name, start, end in WINDOW_DEFINITIONS: if start < end: if start <= value < end: return name elif value >= start or value < end: return name return "" 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