# -*- coding: utf-8 -*- """Runtime integration for the local unified agenda.""" from __future__ import annotations from datetime import datetime from typing import Any try: from .activity_capture import ActivityCapture from .agenda_contracts import migrate_store, normalize_observed_activity, normalize_window_snapshot from .unified_agenda import build_unified_agenda, format_agenda_context from .world_gateway import NullWorldGateway, WorldGatewayContract from .calendar_system import plan_item_to_event except ImportError: from activity_capture import ActivityCapture from agenda_contracts import migrate_store, normalize_observed_activity, normalize_window_snapshot from unified_agenda import build_unified_agenda, format_agenda_context from world_gateway import NullWorldGateway, WorldGatewayContract from calendar_system import plan_item_to_event class AgendaRuntimeMixin: def _agenda_prepare_store(self) -> None: data, changed = migrate_store(self.data) self.data = data if not hasattr(self, "_agenda_capture"): self._agenda_capture = ActivityCapture() if not hasattr(self, "_world_gateway"): self._world_gateway = WorldGatewayContract(NullWorldGateway()) if changed and hasattr(self, "_schedule_data_save"): self._schedule_data_save(delay=0.0) def _agenda_activities_store(self) -> list[dict[str, Any]]: self._agenda_prepare_store() activities = self.data.setdefault("observed_activities", []) if not isinstance(activities, list): activities = [] self.data["observed_activities"] = activities return activities def _agenda_snapshots_store(self) -> list[dict[str, Any]]: self._agenda_prepare_store() snapshots = self.data.setdefault("window_snapshots", []) if not isinstance(snapshots, list): snapshots = [] self.data["window_snapshots"] = snapshots return snapshots def _agenda_capture_inbound_message( self, *, text: str, event_time: datetime, source_ref: str, conversation_id: str, participant: str = "user", message_count: int = 1, ) -> dict[str, Any] | None: self._agenda_prepare_store() candidate = self._agenda_capture.capture_message( text=text, event_time=event_time, source_ref=source_ref, conversation_id=conversation_id, participant=participant, message_count=message_count, ) if candidate is None: return None activities = self._agenda_activities_store() existing = next((item for item in activities if isinstance(item, dict) and item.get("activity_id") == candidate.get("activity_id")), None) if existing is not None: existing.update(candidate) existing["version"] = int(existing.get("version") or 1) + 1 else: activities.append(candidate) activities[:] = activities[-500:] if hasattr(self, "_schedule_data_save"): self._schedule_data_save() return candidate def _agenda_capture_hard_fact(self, activity: dict[str, Any]) -> dict[str, Any]: self._agenda_prepare_store() normalized = normalize_observed_activity(activity) activities = self._agenda_activities_store() existing = next((item for item in activities if item.get("activity_id") == normalized.get("activity_id")), None) if existing is None: activities.append(normalized) else: existing.update(normalized) existing["version"] = int(existing.get("version") or 1) + 1 activities[:] = activities[-500:] if hasattr(self, "_schedule_data_save"): self._schedule_data_save() return normalized def _agenda_current_plan_items(self) -> list[dict[str, Any]]: events = self.data.get("calendar_events") if isinstance(self.data.get("calendar_events"), list) else [] projected = [] for event in events: if not isinstance(event, dict): continue source = str(event.get("source") or "") source_kind = str(event.get("source_kind") or "") if source == "daily_plan_projection" or source_kind == "planned": item = dict(event) item["plan_id"] = str(item.get("plan_id") or item.get("event_id") or "") item["title"] = str(item.get("title") or item.get("description") or "") projected.append(item) if projected: return projected plan = self.data.get("daily_plan") if isinstance(self.data.get("daily_plan"), dict) else {} items = plan.get("items") if isinstance(plan.get("items"), list) else [] result = [] plan_date = str(plan.get("date") or "") now = self._calendar_now() if hasattr(self, "_calendar_now") else datetime.now().astimezone() for index, item in enumerate(items): if not isinstance(item, dict): continue try: event = plan_item_to_event(plan_date, item, timezone_name=getattr(self, "_calendar_timezone_name", lambda: "Asia/Shanghai")(), index=index, now=now) except Exception: continue event["plan_id"] = event.get("event_id") event["title"] = event.get("title") or event.get("description") result.append(event) return result def _agenda_build(self, *, date_key: str = "") -> dict[str, Any]: self._agenda_prepare_store() now = self._calendar_now() if hasattr(self, "_calendar_now") else datetime.now().astimezone() return build_unified_agenda( plans=self._agenda_current_plan_items(), activities=self._agenda_activities_store(), now=now, date_key=date_key, ) def _agenda_context_for_prompt(self, *, max_entries: int = 8) -> str: return format_agenda_context(self._agenda_build(), max_entries=max_entries) def _agenda_snapshot_window(self, *, date_key: str, window: str, open_items: list[str] | None = None) -> dict[str, Any]: agenda = self._agenda_build(date_key=date_key) snapshot = normalize_window_snapshot( { "snapshot_id": self._agenda_snapshot_id(date_key, window), "date": date_key, "window": window, "planned": [item.get("title") or item.get("activity") for item in agenda.get("plans", []) if item.get("status") == "planned"], "observed": [item.get("title") for item in agenda.get("activities", []) if item.get("status") in {"active", "completed"}], "reconciled": [{"entry_id": item.get("entry_id"), "status": item.get("status")} for item in agenda.get("entries", [])], "open_items": open_items or [], "source_refs": [item.get("activity_id") for item in agenda.get("activities", [])], }, now=self._calendar_now() if hasattr(self, "_calendar_now") else datetime.now().astimezone(), ) snapshots = self._agenda_snapshots_store() existing = next((item for item in snapshots if item.get("snapshot_id") == snapshot.get("snapshot_id")), None) if existing is None: snapshots.append(snapshot) else: existing.update(snapshot) existing["version"] = int(existing.get("version") or 1) + 1 snapshots[:] = snapshots[-120:] if hasattr(self, "_schedule_data_save"): self._schedule_data_save() return snapshot def _agenda_window_for_now(self, now: datetime | None = None) -> tuple[str, int, int]: current = now or (self._calendar_now() if hasattr(self, "_calendar_now") else datetime.now().astimezone()) minute = current.hour * 60 + current.minute if minute < 360: return "深夜", 0, 360 if minute < 720: return "早晨", 360, 720 if minute < 1080: return "下午", 720, 1080 if minute < 1320: return "晚上", 1080, 1320 return "深夜", 1320, 1440 def _agenda_snapshot_id(self, date_key: str, window: str) -> str: return f"snapshot-{date_key}-{window}" async def _agenda_maintenance_tick(self) -> None: """Close completed local windows and run one guarded bedtime settlement.""" self._agenda_prepare_store() now = self._calendar_now() if hasattr(self, "_calendar_now") else datetime.now().astimezone() date_key = now.date().isoformat() windows = (("深夜", 0, 360), ("早晨", 360, 720), ("下午", 720, 1080), ("晚上", 1080, 1320)) snapshots = self._agenda_snapshots_store() existing_ids = {str(item.get("snapshot_id")) for item in snapshots if isinstance(item, dict)} for window, start_minute, end_minute in windows: if now.hour * 60 + now.minute < end_minute: continue snapshot_id = self._agenda_snapshot_id(date_key, window) if snapshot_id in existing_ids: continue snapshot = self._agenda_snapshot_window(date_key=date_key, window=window) if snapshot.get("snapshot_id") != snapshot_id: snapshot["snapshot_id"] = snapshot_id recorder = getattr(self, "_memory_companion_record_agenda_snapshot", None) if callable(recorder): try: await recorder(snapshot) except Exception: pass sleep_text = str(getattr(self, "daily_diary_time", "23:10") or "23:10") try: hour_text, minute_text = sleep_text.split(":", 1) bedtime_minute = int(hour_text) * 60 + int(minute_text) except (TypeError, ValueError): bedtime_minute = 1390 lead = max(0, int(getattr(self, "sleep_summary_lead_minutes", 30) or 30)) if now.hour * 60 + now.minute >= max(0, bedtime_minute - lead): diary = self.data.get("bot_diaries", []) today_has_diary = isinstance(diary, list) and any( isinstance(item, dict) and str(item.get("date") or "") == date_key for item in diary ) if not today_has_diary and bool(getattr(self, "enable_daily_diary", True)): ensure_diary = getattr(self, "_ensure_daily_diary", None) if callable(ensure_diary): try: await ensure_diary() except Exception: pass def _world_get_context(self, subject_id: str) -> dict[str, Any]: """Return only cached World context; production networking is disabled in Q5.""" self._agenda_prepare_store() now = self._calendar_now() if hasattr(self, "_calendar_now") else datetime.now().astimezone() cache = self.data.get("world_projection_cache") if isinstance(self.data.get("world_projection_cache"), list) else [] for item in reversed(cache): if not isinstance(item, dict) or str(item.get("subject_id") or "") != str(subject_id): continue fresh_until = str(item.get("fresh_until") or "") try: expiry = datetime.fromisoformat(fresh_until.replace("Z", "+00:00")) if expiry.tzinfo is None: expiry = expiry.replace(tzinfo=now.tzinfo) if now <= expiry: return {"status": "cached", "fresh": True, "projection": item} except (TypeError, ValueError): continue return {"status": "offline", "fresh": False, "projection": None} def _world_publish_activity(self, activity: dict[str, Any]) -> dict[str, Any]: """Keep the future publish boundary explicit without sending to a server.""" if not bool(getattr(self, "enable_world_gateway", False)): return {"ok": False, "reason": "world_gateway_disabled"} result = self._world_gateway.publish_activity(activity) return {"ok": bool(result.ok), "reason": result.reason, "data": result.data}