# -*- coding: utf-8 -*- """Stable, read-only payloads for the operations companion page API.""" from __future__ import annotations from copy import deepcopy from datetime import datetime from typing import Any try: from .bot_self_store import BOT_SELF_LIST_NAMESPACES, build_bot_self_migration_preview, ensure_bot_self_store except ImportError: from bot_self_store import BOT_SELF_LIST_NAMESPACES, build_bot_self_migration_preview, ensure_bot_self_store AGENDA_STATUS_KEYS = ( "planned", "active", "completed", "partially_completed", "deferred", "cancelled", "overridden", "unknown", ) def _list_tail(value: Any, limit: int) -> list[Any]: if not isinstance(value, list): return [] return [deepcopy(item) for item in value[-max(0, int(limit)) :] if isinstance(item, dict)] def _iso_now() -> str: return datetime.now().astimezone().isoformat(timespec="seconds") def _latest_timestamp(items: list[dict[str, Any]], *keys: str) -> str: values = [] for item in items: for key in keys: value = str(item.get(key) or "").strip() if value: values.append(value) break return max(values) if values else "" def build_bot_self_summary(data: dict[str, Any]) -> dict[str, Any]: ensure_bot_self_store(data) store = data.get("bot_self_store") if isinstance(data.get("bot_self_store"), dict) else {} namespaces: dict[str, dict[str, Any]] = {} all_records: list[dict[str, Any]] = [] for namespace in (*BOT_SELF_LIST_NAMESPACES, "bot_persona_state"): raw = store.get(namespace) records = raw if isinstance(raw, list) else ([raw] if isinstance(raw, dict) and raw else []) safe_records = [deepcopy(item) for item in records if isinstance(item, dict)] all_records.extend(safe_records) namespaces[namespace] = { "count": len(safe_records), "latest_at": _latest_timestamp(safe_records, "updated_at", "created_at", "occurred_at", "generated_at"), } return { "version": int(store.get("version") or 1), "storage_domain": "bot_self", "owner": "bot", "status": "ready", "namespaces": namespaces, "total_records": len(all_records), "latest_at": _latest_timestamp(all_records, "updated_at", "created_at", "occurred_at", "generated_at"), "migration": build_bot_self_migration_preview(data), } def build_bot_self_detail(data: dict[str, Any], namespace: str, *, limit: int = 50) -> dict[str, Any]: ensure_bot_self_store(data) store = data.get("bot_self_store") if isinstance(data.get("bot_self_store"), dict) else {} allowed = set(BOT_SELF_LIST_NAMESPACES) | {"bot_persona_state"} if namespace not in allowed: raise ValueError("unsupported Bot self namespace") raw = store.get(namespace) records = raw if isinstance(raw, list) else ([raw] if isinstance(raw, dict) and raw else []) return { "namespace": namespace, "owner": "bot", "storage_domain": "bot_self", "items": [deepcopy(item) for item in records[-max(1, min(int(limit), 200)) :] if isinstance(item, dict)], } def build_agenda_summary(data: dict[str, Any]) -> dict[str, Any]: plan = data.get("daily_plan") if isinstance(data.get("daily_plan"), dict) else {} plan_items = [item for item in plan.get("items", []) if isinstance(item, dict)] observed = data.get("observed_activities") if isinstance(data.get("observed_activities"), list) else [] history = data.get("agenda_reconciliation_history") if isinstance(data.get("agenda_reconciliation_history"), list) else [] status_counts = {key: 0 for key in AGENDA_STATUS_KEYS} for item in plan_items: status = str(item.get("status") or item.get("lifecycle_status") or "planned").strip() status_counts[status if status in status_counts else "unknown"] += 1 return { "plan_date": str(plan.get("date") or ""), "plan_version": int(plan.get("version") or 1), "plan_item_count": len(plan_items), "observed_activity_count": len([item for item in observed if isinstance(item, dict)]), "reconciliation_count": len([item for item in history if isinstance(item, dict)]), "status_counts": status_counts, "current_time": _iso_now(), "timezone": datetime.now().astimezone().tzname() or "local", "latest_reconciliation_at": _latest_timestamp( [item for item in history if isinstance(item, dict)], "reconciled_at", "updated_at", "generated_at", ), } def build_agenda_detail(data: dict[str, Any], *, limit: int = 100) -> dict[str, Any]: plan = data.get("daily_plan") if isinstance(data.get("daily_plan"), dict) else {} plan_items = [deepcopy(item) for item in plan.get("items", []) if isinstance(item, dict)] observed = _list_tail(data.get("observed_activities"), limit) snapshots = _list_tail(data.get("window_snapshots"), limit) history = _list_tail(data.get("agenda_reconciliation_history"), limit) return { "plan_date": str(plan.get("date") or ""), "plan": plan_items[-max(1, min(int(limit), 200)) :], "observed": observed, "window_snapshots": snapshots, "reconciliation_history": history, "source_policy": { "plan": "planned", "observed": "real_or_projected_activity", "world": "world_context_only_until_enabled", }, } def build_memory_boundary_summary(plugin: Any, data: dict[str, Any]) -> dict[str, Any]: bridge = None bridge_status: dict[str, Any] = {} getter = getattr(plugin, "_memory_companion_bridge", None) if callable(getter): try: bridge = getter() except Exception: bridge = None status_getter = getattr(plugin, "_memory_companion_coordination_status", None) if callable(status_getter): try: value = status_getter() if isinstance(value, dict): bridge_status = deepcopy(value) except Exception: bridge_status = {} runtime = data.get("runtime_settings") if isinstance(data.get("runtime_settings"), dict) else {} return { "policy": "user_only", "status": "ready" if bridge is not None else "unavailable", "bridge_available": bridge is not None, "bridge_name": str(getattr(bridge, "display_name", "") or "") if bridge is not None else "", "coordination": bridge_status, "bot_self_external_write": False, "bot_self_store_migrated": bool(runtime.get("bot_self_store_migrated", False)), "checked_at": _iso_now(), "boundary_note": "Bot 日程、人格、创作、梦境和自我时间线只保存在陪伴插件自有空间。", }