diff --git a/activity_capture.py b/activity_capture.py new file mode 100644 index 0000000..4645bff --- /dev/null +++ b/activity_capture.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +"""Low-noise local activity capture for the operations companion.""" +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any + +try: + from .agenda_contracts import normalize_observed_activity, stable_id +except ImportError: + from agenda_contracts import normalize_observed_activity, stable_id + +COLLABORATION_HINTS = { + "代码", "插件", "开发", "排障", "测试", "部署", "运维", "NAS", "VM", "项目", "创作", "一起", "继续" +} + + +def classify_interaction(text: str, *, message_count: int = 1) -> str: + content = str(text or "").strip() + if not content: + return "ordinary" + if any(token in content for token in COLLABORATION_HINTS) and len(content) >= 8: + return "sustained" if message_count >= 2 else "candidate" + if message_count >= 4 and len(content) >= 12: + return "sustained" + if len(content) <= 12: + return "ordinary" + return "short" + + +class ActivityCapture: + def __init__(self, *, window_minutes: int = 30, min_sustained_messages: int = 3): + self.window_minutes = max(5, int(window_minutes)) + self.min_sustained_messages = max(2, int(min_sustained_messages)) + + def capture_message( + self, + *, + text: str, + event_time: datetime, + source_ref: str, + conversation_id: str, + participant: str = "user", + message_count: int = 1, + topic: str = "", + ) -> dict[str, Any] | None: + interaction = classify_interaction(text, message_count=message_count) + if interaction not in {"sustained", "candidate"}: + return None + if interaction == "candidate" and message_count < self.min_sustained_messages and not any( + token in str(text or "") for token in COLLABORATION_HINTS + ): + return None + start = event_time - timedelta(minutes=min(self.window_minutes, max(1, message_count - 1) * 3)) + title = str(topic or text or "持续互动").strip().replace("\n", " ")[:120] + return normalize_observed_activity( + { + "activity_id": stable_id("activity", conversation_id, topic or "conversation", start.isoformat()), + "title": title, + "kind": "user_collaboration" if interaction == "sustained" else "conversation_candidate", + "start_at": start.isoformat(), + "end_at": event_time.isoformat(), + "source_kind": "real", + "source": "conversation", + "source_refs": [source_ref], + "participants": [participant, "bot"], + "evidence_level": "L2" if interaction == "sustained" else "L1", + "certainty": "high" if interaction == "sustained" else "low", + "status": "active" if interaction == "sustained" else "unknown", + }, + now=event_time, + ) + + @staticmethod + def split_for_storage(activity: dict[str, Any]) -> dict[str, Any]: + try: + from .bot_self_store import split_shared_activity + except ImportError: + from bot_self_store import split_shared_activity + return split_shared_activity(activity) + + def capture_hard_fact( + self, + *, + title: str, + start_at: datetime, + end_at: datetime | None, + source: str, + source_refs: list[str], + participants: list[str] | None = None, + kind: str = "tool_activity", + ) -> dict[str, Any]: + return normalize_observed_activity( + { + "activity_id": stable_id("activity", source, title, start_at.isoformat(), *source_refs), + "title": title, + "kind": kind, + "start_at": start_at.isoformat(), + "end_at": end_at.isoformat() if end_at else "", + "source_kind": "real", + "source": source, + "source_refs": source_refs, + "participants": participants or ["bot"], + "evidence_level": "L4", + "certainty": "high", + "status": "completed" if end_at else "active", + }, + now=start_at, + ) diff --git a/agenda_contracts.py b/agenda_contracts.py new file mode 100644 index 0000000..b4203bd --- /dev/null +++ b/agenda_contracts.py @@ -0,0 +1,232 @@ +# -*- 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 +import hashlib +from typing import Any, Iterable + +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"} + + +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), + "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": [], + } + 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 diff --git a/agenda_runtime.py b/agenda_runtime.py new file mode 100644 index 0000000..d2c90fc --- /dev/null +++ b/agenda_runtime.py @@ -0,0 +1,250 @@ +# -*- 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} \ No newline at end of file diff --git a/bot_self_store.py b/bot_self_store.py new file mode 100644 index 0000000..76bf7fd --- /dev/null +++ b/bot_self_store.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- +"""Bot-owned storage helpers for the operations companion.""" +from __future__ import annotations + +from copy import deepcopy +from datetime import datetime +import hashlib +from typing import Any + +BOT_SELF_STORE_VERSION = 1 +BOT_SELF_NAMESPACES = ( + "bot_self_memory", + "bot_self_timeline", + "bot_agenda_history", + "bot_persona_state", + "ops_activity_history", + "legacy_quarantine", +) +BOT_SELF_LIST_NAMESPACES = { + "bot_self_memory", + "bot_self_timeline", + "bot_agenda_history", + "ops_activity_history", + "legacy_quarantine", +} +LEGACY_BOT_FIELDS = ( + "daily_plan", + "daily_plan_history", + "calendar_events", + "calendar_event_history", + "observed_activities", + "window_snapshots", + "agenda_reconciliation_history", + "bot_diaries", + "dream_fragments", + "daily_dream", + "daily_outfit_photo", + "daily_outfit_history", + "creative_projects", + "creative_memory_pool", + "proactive_candidate_pool", +) + + +def _text(value: Any, limit: int = 240) -> str: + return str(value or "").strip()[:limit] + + +def _now_iso(now: datetime | None = None) -> str: + return (now or datetime.now().astimezone()).isoformat(timespec="seconds") + + +def _stable_id(namespace: str, idempotency_key: str) -> str: + digest = hashlib.sha256(f"{namespace}|{idempotency_key}".encode("utf-8")).hexdigest()[:20] + return f"bot-{namespace}-{digest}" + + +def default_bot_self_store() -> dict[str, Any]: + return { + "version": BOT_SELF_STORE_VERSION, + "bot_self_memory": [], + "bot_self_timeline": [], + "bot_agenda_history": [], + "bot_persona_state": {}, + "ops_activity_history": [], + "legacy_quarantine": [], + } + + +def ensure_bot_self_store(data: dict[str, Any]) -> tuple[dict[str, Any], bool]: + changed = False + store = data.get("bot_self_store") if isinstance(data, dict) else None + if not isinstance(store, dict): + store = default_bot_self_store() + data["bot_self_store"] = store + return data, True + if store.get("version") != BOT_SELF_STORE_VERSION: + store["version"] = BOT_SELF_STORE_VERSION + changed = True + for namespace in BOT_SELF_NAMESPACES: + expected: Any = [] if namespace in BOT_SELF_LIST_NAMESPACES else {} + if not isinstance(store.get(namespace), type(expected)): + store[namespace] = expected + changed = True + return data, changed + + +def record_bot_self_entry( + data: dict[str, Any], + namespace: str, + payload: dict[str, Any], + *, + idempotency_key: str, + now: datetime | None = None, + max_items: int = 500, +) -> dict[str, Any]: + if namespace not in BOT_SELF_LIST_NAMESPACES: + raise ValueError(f"unsupported Bot self namespace: {namespace}") + if not isinstance(payload, dict): + raise TypeError("Bot self payload must be an object") + if not _text(idempotency_key, 240): + raise ValueError("idempotency_key is required") + ensure_bot_self_store(data) + records = data["bot_self_store"][namespace] + current = _now_iso(now) + record = deepcopy(payload) + record_id = _text(record.get("record_id") or record.get("id"), 160) or _stable_id(namespace, idempotency_key) + record.update( + { + "record_id": record_id, + "idempotency_key": _text(idempotency_key, 240), + "occurred_at": _text(record.get("occurred_at"), 80) or current, + "created_at": _text(record.get("created_at"), 80) or current, + "updated_at": current, + "source_refs": list(record.get("source_refs") or []) if isinstance(record.get("source_refs"), list) else [], + "visibility": _text(record.get("visibility"), 40) or "bot_self", + "version": max(1, int(record.get("version") or 1)), + "owner": "bot", + "storage_domain": "bot_self", + } + ) + existing = next((item for item in records if isinstance(item, dict) and item.get("idempotency_key") == record["idempotency_key"]), None) + if existing is None: + records.append(record) + else: + record["created_at"] = existing.get("created_at") or record["created_at"] + record["version"] = int(existing.get("version") or 1) + 1 + existing.clear() + existing.update(record) + if max_items > 0: + del records[:-max_items] + return deepcopy(record) + + +def set_bot_persona_state(data: dict[str, Any], state: dict[str, Any], *, now: datetime | None = None) -> dict[str, Any]: + ensure_bot_self_store(data) + current = _now_iso(now) + current_state = deepcopy(state) if isinstance(state, dict) else {} + current_state.setdefault("updated_at", current) + current_state["owner"] = "bot" + current_state["storage_domain"] = "bot_self" + data["bot_self_store"]["bot_persona_state"] = current_state + return deepcopy(current_state) + + +def build_bot_self_migration_preview(data: dict[str, Any]) -> dict[str, Any]: + ensure_bot_self_store(data) + fields: dict[str, int] = {} + total = 0 + for field in LEGACY_BOT_FIELDS: + value = data.get(field) + count = len(value) if isinstance(value, (list, dict)) else (1 if value else 0) + fields[field] = count + total += count + quarantined = len(data["bot_self_store"].get("legacy_quarantine") or []) + return { + "version": BOT_SELF_STORE_VERSION, + "legacy_fields": fields, + "legacy_total": total, + "quarantine_entries": quarantined, + "destructive": False, + "status": "preview_only", + } + + +def quarantine_legacy_bot_records(data: dict[str, Any], *, now: datetime | None = None) -> dict[str, Any]: + ensure_bot_self_store(data) + preview = build_bot_self_migration_preview(data) + key = "legacy-v1" + record = record_bot_self_entry( + data, + "legacy_quarantine", + { + "kind": "legacy_bot_data", + "legacy_fields": preview["legacy_fields"], + "legacy_total": preview["legacy_total"], + "migration_mode": "non_destructive", + "occurred_at": _now_iso(now), + }, + idempotency_key=key, + now=now, + max_items=20, + ) + return {"preview": preview, "quarantine_record": record, "status": "quarantined_without_deletion"} + + +def split_shared_activity(activity: dict[str, Any]) -> dict[str, Any]: + """Separate explicit user and Bot sides without inventing user facts.""" + source = deepcopy(activity) if isinstance(activity, dict) else {} + user_side = source.get("user_side") if isinstance(source.get("user_side"), dict) else {} + bot_side = source.get("bot_side") if isinstance(source.get("bot_side"), dict) else {} + participants = source.get("participants") if isinstance(source.get("participants"), list) else [] + return { + "bot": { + "activity": bot_side, + "participants": [item for item in participants if str(item).lower() in {"bot", "assistant", "self"}], + "evidence_level": source.get("evidence_level") or "L2", + "source_refs": list(source.get("source_refs") or []) if isinstance(source.get("source_refs"), list) else [], + }, + "user": { + "activity": user_side, + "participants": [item for item in participants if str(item).lower() not in {"bot", "assistant", "self"}], + "evidence_level": source.get("user_evidence_level") or source.get("evidence_level") or "L2", + "source_refs": list(source.get("source_refs") or []) if isinstance(source.get("source_refs"), list) else [], + "eligible": bool(user_side), + }, + "source_activity_id": _text(source.get("activity_id") or source.get("id"), 160), + } diff --git a/calendar_system.py b/calendar_system.py index c7205e5..7f19365 100644 --- a/calendar_system.py +++ b/calendar_system.py @@ -8,9 +8,9 @@ from typing import Any, Iterable from zoneinfo import ZoneInfo -CALENDAR_VERSION = 1 +CALENDAR_VERSION = 2 CALENDAR_TYPES = {"personal_agenda", "work_agenda", "maintenance_agenda", "external_schedule"} -EVENT_STATUSES = {"planned", "active", "completed", "cancelled"} +EVENT_STATUSES = {"planned", "active", "completed", "partially_completed", "overridden", "deferred", "cancelled", "unknown"} class CalendarEventError(ValueError): @@ -138,6 +138,12 @@ def normalize_event( "all_day": bool(raw.get("all_day", False)), "recurrence": deepcopy(raw.get("recurrence")) if isinstance(raw.get("recurrence"), dict) else None, "source": _text(raw.get("source"), 80) or "bot_generated", + "source_kind": _text(raw.get("source_kind"), 32) or ("planned" if _text(raw.get("source"), 80) == "daily_plan_projection" else "real"), + "evidence_level": _text(raw.get("evidence_level"), 8).upper() or ("L0" if _text(raw.get("source"), 80) == "daily_plan_projection" else "L3"), + "source_refs": deepcopy(raw.get("source_refs")) if isinstance(raw.get("source_refs"), list) else [], + "participants": deepcopy(raw.get("participants")) if isinstance(raw.get("participants"), list) else [], + "visibility": _text(raw.get("visibility"), 32) or "private", + "version": max(1, int(raw.get("version") or 1)), "status": status, "editable": bool(raw.get("editable", True)), "priority": _text(raw.get("priority"), 20) or "normal", @@ -293,4 +299,4 @@ def plan_item_to_event(plan_date: str, item: dict[str, Any], *, timezone_name: s "created_at": now, "updated_at": now, } - return normalize_event(raw, timezone_name=timezone_name, now=now, index=index) \ No newline at end of file + return normalize_event(raw, timezone_name=timezone_name, now=now, index=index) diff --git a/core_store.py b/core_store.py index c2d0fa4..3985fcb 100644 --- a/core_store.py +++ b/core_store.py @@ -1,4 +1,4 @@ -# -*- coding: utf-8 -*- +# -*- coding: utf-8 -*- """ CoreStoreMixin — 配置、数据存储、用户/群组基础访问 """ @@ -73,6 +73,15 @@ except Exception: Solar = None from .calendar_system import CALENDAR_VERSION +from .agenda_contracts import AGENDA_VERSION, migrate_store +from .bot_self_store import ( + build_bot_self_migration_preview, + ensure_bot_self_store, + quarantine_legacy_bot_records, + record_bot_self_entry, + set_bot_persona_state, + split_shared_activity, +) from .constants import ( DEFAULT_DAILY_PLAN_ITEMS, DEFAULT_HUMANIZED_STATE, @@ -346,6 +355,21 @@ class CoreStoreMixin: "calendar_version": CALENDAR_VERSION, "calendar_events": [], "calendar_event_history": [], + "agenda_version": AGENDA_VERSION, + "observed_activities": [], + "window_snapshots": [], + "agenda_reconciliation_history": [], + "world_projection_cache": [], + "world_outbox": [], + "bot_self_store": { + "version": 1, + "bot_self_memory": [], + "bot_self_timeline": [], + "bot_agenda_history": [], + "bot_persona_state": {}, + "ops_activity_history": [], + "legacy_quarantine": [], + }, "daily_state": {}, "state_conditions": [], "state_generated_day": "", @@ -410,6 +434,17 @@ class CoreStoreMixin: data.setdefault("calendar_version", CALENDAR_VERSION) data.setdefault("calendar_events", []) data.setdefault("calendar_event_history", []) + data.setdefault("agenda_version", AGENDA_VERSION) + data.setdefault("observed_activities", []) + data.setdefault("window_snapshots", []) + data.setdefault("agenda_reconciliation_history", []) + data.setdefault("world_projection_cache", []) + data.setdefault("world_outbox", []) + data, bot_self_changed = ensure_bot_self_store(data) + if bot_self_changed: + data.setdefault("runtime_settings", {}) + if isinstance(data["runtime_settings"], dict): + data["runtime_settings"]["bot_self_store_migrated"] = True data.setdefault("daily_state", {}) data.setdefault("state_conditions", []) data.setdefault("state_generated_day", "") @@ -482,6 +517,46 @@ class CoreStoreMixin: value = data.get(field) if isinstance(data, dict) else None return str(value) if value is not None else default + def _bot_self_record( + self, + namespace: str, + payload: dict[str, Any], + *, + idempotency_key: str, + max_items: int = 500, + ) -> dict[str, Any]: + record = record_bot_self_entry( + self.data, + namespace, + payload, + idempotency_key=idempotency_key, + max_items=max_items, + ) + saver = getattr(self, "_schedule_data_save", None) + if callable(saver): + saver() + return record + + def _bot_self_set_persona_state(self, state: dict[str, Any]) -> dict[str, Any]: + result = set_bot_persona_state(self.data, state) + saver = getattr(self, "_schedule_data_save", None) + if callable(saver): + saver() + return result + + def _bot_self_migration_preview(self) -> dict[str, Any]: + return build_bot_self_migration_preview(self.data) + + def _bot_self_quarantine_legacy(self) -> dict[str, Any]: + result = quarantine_legacy_bot_records(self.data) + saver = getattr(self, "_schedule_data_save", None) + if callable(saver): + saver() + return result + + @staticmethod + def _split_shared_activity(activity: dict[str, Any]) -> dict[str, Any]: + return split_shared_activity(activity) def _record_cache_metric(self, namespace: str, *, hit: bool, detail: str = "") -> None: name = _single_line(namespace, 80) if not name: @@ -765,7 +840,9 @@ class CoreStoreMixin: if manager is not None: try: data = manager.load_initial_store() + data, agenda_changed = migrate_store(data) changed = self._sanitize_store_control_tags_inplace(data) + changed = changed or agenda_changed repeat_changed = self._sanitize_proactive_candidate_repeat_counts_inplace(data) compacted = self._compact_store_history_inplace(data) if changed: @@ -785,7 +862,9 @@ class CoreStoreMixin: if not isinstance(data, dict): return self._new_store() data = self._ensure_store_defaults(data) + data, agenda_changed = migrate_store(data) changed = self._sanitize_store_control_tags_inplace(data) + changed = changed or agenda_changed repeat_changed = self._sanitize_proactive_candidate_repeat_counts_inplace(data) compacted = self._compact_store_history_inplace(data) if changed: diff --git a/daily_state.py b/daily_state.py index e152b99..b1e2006 100644 --- a/daily_state.py +++ b/daily_state.py @@ -408,7 +408,7 @@ class DailyStateMixin: def _calendar_set_status(self, event_id: str, status: str, *, save: bool = True) -> dict[str, Any]: status = _single_line(status, 20).lower() - if status not in {"planned", "completed", "cancelled"}: + if status not in {"planned", "active", "completed", "partially_completed", "overridden", "deferred", "cancelled", "unknown"}: raise CalendarEventError("unsupported status: " + status) result = self._calendar_update_event(event_id, {"status": status}, save=save, allow_conflict=True) history = self._calendar_event_history_store() @@ -13587,6 +13587,7 @@ class DailyStateMixin: if self._proactive_generation_disabled(): return for label, task_factory in ( + ("统一日程窗口结算", self._agenda_maintenance_tick), ("技能成长结算", self._maybe_settle_skill_growth), ("B站无聊观看", self._maybe_trigger_bilibili_boredom_watch), ("网页探索", self._maybe_trigger_web_exploration), diff --git a/docs/运维陪伴错题本.md b/docs/运维陪伴错题本.md index f3254d2..92a79f1 100644 --- a/docs/运维陪伴错题本.md +++ b/docs/运维陪伴错题本.md @@ -1,4 +1,4 @@ -# 运维陪伴插件错题本 +# 运维陪伴插件错题本 > 适用仓库:`astrbot_plugin_private_companion-main` > 分支:`ops-main` @@ -103,3 +103,42 @@ - 修复或规避:本次不修改 VM Provider 配置;记录为独立部署后配置项,避免把环境问题混入插件替换。 - 预防规则:验收主动日记、主动消息等 LLM 任务时,同时检查 Provider 可用性;区分旧日志、当前进程日志和代码回归。 - 验证证据:部署后新进程加载日志无该错误;服务保持 `active` 且 `NRestarts=0`。 + +## 2026-07-25 — 旧 daily_plan 不能直接交给统一对账器 + +- 阶段:Q5.0–Q5.3 本地统一真实日程 +- 类型:API契约 / 功能行为 +- 现象:旧计划项使用 `time/end/activity`,统一对账器需要 `start_at/end_at/title`;直接读取会导致计划无法和实际活动匹配。 +- 根因:Q4 日历已能把计划投影为 `calendar_events`,但新统一视图初始仍读取原始 `daily_plan.items`。 +- 修复或规避:统一视图优先读取 `calendar_events` 中的计划投影;没有投影时再通过 `plan_item_to_event` 转换旧计划。 +- 预防规则:任何新日程模块不得直接假设旧 `daily_plan` 已经是完整事件合同;入口必须经过规范化层。 +- 验证证据:`tests.test_agenda_system` 的 legacy daily plan 转换测试通过。 + +## 2026-07-25 — World 接入阶段必须默认离线 + +- 阶段:Q5.7 World 离线接口预留 +- 类型:安全 / API契约 / 环境 +- 现象:World Server 尚未实现时,如果陪伴插件直接请求外部服务,会把本地日程稳定性绑定到未完成的跨 Bot 服务。 +- 根因:World 文档是未来合同,不是当前运行时能力;生产接入还需要授权、撤销、过期和双端幂等验证。 +- 修复或规避:新增 `WorldGatewayContract` 和 `NullWorldGateway`,默认不联网;只允许读取带 `fresh_until` 的缓存,外部失败静默降级。 +- 预防规则:本地统一日程稳定运行和观察期结束前,不启用 World 生产投影;共同活动必须等待双端确认。 +- 验证证据:`tests.test_agenda_system` 的离线网关和过期缓存测试通过;`world_gateway.py` 编译通过。 +## 2026-07-25 — Bot 自有记忆不能继续走外部记忆桥 + +- 阶段:C6.0–C6.5 Bot 自有存储与用户记忆边界 +- 类型:安全 / API契约 / 功能行为 +- 现象:Bot 日程、窗口快照、主动行为、创作和梦境原先可以通过 `record_schedule_fragment`、`record_calendar_event` 或其他 Bridge 写入记忆插件,容易和用户记忆混合。 +- 根因:陪伴插件的 Bot 自我连续性和记忆插件的用户事实没有硬隔离,调用方只依赖方法名和降级路径判断归属。 +- 修复或规避:新增 `bot_self_store.py` 和 `bot_self_store` 命名空间;Bot 自有记录使用本地幂等存储;主 MemoryCompanion 与旧 RememberYou 适配器停止写入 Bot 日程和自我记录;用户图片摘要和用户习惯仍保留用户记忆入口。 +- 预防规则:任何跨插件写入前必须确认主体是用户;没有明确用户证据的共同活动不得进入用户记忆;禁止用 `record_schedule_fragment` 作为 Bot 数据降级通道。 +- 验证证据:`tests.test_bot_self_store`、全量 `unittest discover -s tests` 共 29 项通过;核心 Python 编译通过;`git diff --check` 通过。 + +## 2026-07-25 — 混合活动必须显式拆出用户侧 + +- 阶段:C6.2 共同对话拆分 +- 类型:功能行为 / API契约 +- 现象:一条“Bot 与用户共同完成某事”的活动,不能直接整段当作用户记忆。 +- 根因:参与者列表只能说明谁在场,不能证明用户具体做了什么。 +- 修复或规避:新增 `split_shared_activity()` 和 `ActivityCapture.split_for_storage()`;只有输入明确提供 `user_side` 时才允许生成用户侧记录,Bot 侧统一进入本地 Bot 存储。 +- 预防规则:参与者不等于用户事实;必须保留来源引用、证据等级和拆分结果。 +- 验证证据:共享活动缺少 `user_side` 时 `eligible=false`;显式用户侧测试通过。 diff --git a/docs/错题本.md b/docs/错题本.md index dea5c50..3efc1be 100644 --- a/docs/错题本.md +++ b/docs/错题本.md @@ -148,3 +148,13 @@ - 修复或规避:新增独立 `dialogue_agenda` / `shared_interaction` 层;只保存事件级派生记录和 `source_message_ids`,按 `scope/session_id/participants/visibility` 隔离;无明确时间只允许待续话题,不触发硬提醒。 - 预防规则:每个新日程事件先回答“主体是谁、证据在哪、谁可见、是否确认、提醒强度是什么”;普通聊天不自动转日程。 - 验证证据:核对 `calendar_system.py`、`memory_companion_adapter.py`、MemoryCompanion `core/bridge.py` 与 `core/service.py` 的日历、时间线、open-loop、session 和共享经历接口;评估文档已写入 `docs/对话日程可行性评估.md`。 + +## 2026-07-25 — 统一日程不等于删除来源流 + +- 阶段:统一真实日程与 World Server 接入评估 +- 类型:功能行为 / API契约 +- 现象:如果为了避免“计划下午看电影、实际下午写代码”的割裂而把计划和实际直接压成一条数据流,将无法解释计划为何被覆盖,也无法处理延期、部分完成和共同活动双端同步。 +- 根因:用户看到的是统一日程视图,但计划、实际活动、World 共同事件和对方活动投影的事实性、主体、权限和生命周期不同。 +- 修复或规避:采用 `PlanItem`、`ObservedActivity`、`WorldEvent` 和 `UnifiedAgendaEntry` 四层模型;通过 `ScheduleReconciler` 生成最终视图;对方活动只进入 `world_context`,共同活动由唯一 `WorldEvent` 投影到双方本地 `shared_activity`。 +- 预防规则:任何“合并日程”设计必须同时保留来源、证据、主体、状态、可见性和对账原因;禁止直接把计划覆盖写成事实。 +- 验证证据:已核对 OPS 的 `calendar_system.py`、`planning.py`、`self_timeline.py`、`temporal_context.py`,World Server 文档和 `C:\Users\Administrator\Downloads\世界.md`;方案已写入 `docs/统一真实日程与World接入改造评估.md`。 diff --git a/main.py b/main.py index fde6b2c..78fcc7c 100644 --- a/main.py +++ b/main.py @@ -158,6 +158,7 @@ except ModuleNotFoundError as exc: logger.warning("[PrivateCompanion] self_timeline.py 缺失,已跳过 Bot 自身时间线注入能力。请重新安装完整版本。") from .core_store import CoreStoreMixin +from .agenda_runtime import AgendaRuntimeMixin from .platform_compat import PlatformCompatibilityMixin from .runtime_compat import probe_runtime_capabilities from .integration_status import IntegrationStatusMixin @@ -904,6 +905,7 @@ _PROACTIVE_ONLY_TEMP_UNLOCK_RELATED = { ) class PrivateCompanionPlugin( CoreStoreMixin, + AgendaRuntimeMixin, PlatformCompatibilityMixin, AstrBotKnowledgeMixin, IntegrationStatusMixin, @@ -2083,6 +2085,7 @@ class PrivateCompanionPlugin( self._qzone_last_bot = None startup_load_started = time.perf_counter() self.data = self._load_data_sync() + self._agenda_prepare_store() self._apply_tts_runtime_overrides() load_elapsed_ms = int((time.perf_counter() - startup_load_started) * 1000) if load_elapsed_ms > 1200: @@ -8174,6 +8177,17 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge self._schedule_next_proactive(user, now=received_ts) user["inbound_count"] = _safe_int(user.get("inbound_count"), 0) + 1 user["episode_message_count"] = _safe_int(user.get("episode_message_count"), 0, 0) + 1 + try: + self._agenda_capture_inbound_message( + text=safe_text or text, + event_time=datetime.fromtimestamp(received_ts, tz=zoneinfo.ZoneInfo(self._calendar_timezone_name())), + source_ref=f"{_single_line(getattr(event, 'unified_msg_origin', ''), 160)}:{int(received_ts)}", + conversation_id=_single_line(getattr(event, "unified_msg_origin", ""), 160) or f"private:{user_id}", + participant=user_id, + message_count=user["episode_message_count"], + ) + except Exception as exc: + logger.debug("[PrivateCompanion] agenda activity capture skipped: %s", _single_line(exc, 160)) self._apply_user_rest_silence_from_message(user, safe_text or text, now=received_ts) if _safe_float(user.get("awaiting_reply_since"), 0) > 0: user["reply_count"] = _safe_int(user.get("reply_count"), 0) + 1 @@ -8903,6 +8917,12 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge ) except Exception as exc: logger.debug("[PrivateCompanion] temporal context failed: %s", _single_line(exc, 160)) + try: + agenda_context = self._agenda_context_for_prompt(max_entries=8) + if agenda_context: + prompt_surface.add("conversation.unified_agenda", agenda_context, priority=21, source="unified_agenda") + except Exception as exc: + logger.debug("[PrivateCompanion] unified agenda context failed: %s", _single_line(exc, 160)) reply_style_prompt = self._format_reply_style_prompt() if reply_style_prompt: prompt_surface.add("reply.style", reply_style_prompt, priority=12, source="reply_style") @@ -10500,8 +10520,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge elif action in {"当前细化", "查看当前细化"}: response = self._format_current_detail_view() elif action in {"查看今日日程", "查看日程", "今日日程", "日程"}: - plan = self.data.get("daily_plan", {}) - response = self._format_daily_plan(plan) + response = self._agenda_format_for_user() elif action in daily_schedule_regenerate_actions: response = ( "正在重新细化指定的日程段。" @@ -11451,6 +11470,17 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge _safe_int(expression_feedback.get("demoted_rules"), 0, 0), ) user["episode_message_count"] = _safe_int(user.get("episode_message_count"), 0, 0) + 1 + try: + self._agenda_capture_inbound_message( + text=safe_text or text, + event_time=datetime.fromtimestamp(received_ts, tz=zoneinfo.ZoneInfo(self._calendar_timezone_name())), + source_ref=f"{_single_line(getattr(event, 'unified_msg_origin', ''), 160)}:{int(received_ts)}", + conversation_id=_single_line(getattr(event, "unified_msg_origin", ""), 160) or f"private:{user_id}", + participant=user_id, + message_count=user["episode_message_count"], + ) + except Exception as exc: + logger.debug("[PrivateCompanion] agenda activity capture skipped: %s", _single_line(exc, 160)) if self._expression_private_learning_source_enabled(user, user_id): self._update_expression_profile_from_message(user, safe_text or text) self._refresh_expression_voice_profile() diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index af2b77c..517cb6d 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -673,75 +673,98 @@ class MemoryCompanionAdapterMixin: "只在与本轮直接相关时自然接住;不要主动列举记忆、不要提及检索过程,也不要把它当作其他用户的信息。" ) - async def _memory_companion_record_calendar_event(self, event: dict[str, Any], *, action: str = "updated", reason: str = "") -> None: - if not isinstance(event, dict): return - bridge = self._memory_companion_bridge() - recorder = getattr(bridge, "record_calendar_event", None) if bridge is not None else None - if not callable(recorder): recorder = getattr(bridge, "record_schedule_fragment", None) if bridge is not None else None - if not callable(recorder): return - event_id = _single_line(event.get("event_id"), 120); title = _single_line(event.get("title") or event.get("description"), 160) - if not event_id or not title: return + async def _memory_companion_record_bot_self_local( + self, + *, + namespace: str, + kind: str, + payload: dict[str, Any], + idempotency_key: str, + ) -> None: + recorder = getattr(self, "_bot_self_record", None) + if not callable(recorder): + return + safe_payload: dict[str, Any] = {"kind": _single_line(kind, 80)} + for key, value in (payload or {}).items(): + if key in {"self", "event", "user", "group"}: + continue + if isinstance(value, (str, int, float, bool)) or value is None: + safe_payload[key] = value + elif isinstance(value, dict): + safe_payload[key] = { + str(item_key): _single_line(item_value, 240) + for item_key, item_value in list(value.items())[:20] + if isinstance(item_value, (str, int, float, bool)) or item_value is None + } + elif isinstance(value, (list, tuple)): + safe_payload[key] = [_single_line(item, 160) for item in list(value)[:20]] + else: + safe_payload[key] = _single_line(value, 240) try: - await recorder(content=_single_line(f"????{action}?{title}?{event.get('start_at')} ? {event.get('end_at')}???={event.get('status') or 'planned'}?{reason}", 520), scope="unknown", session_id="private_companion:calendar", message_id=f"private_companion_calendar_{event_id}_{action}", memory_id=f"private_companion_calendar_{event_id}", metadata={"event_id": event_id, "action": action, "calendar": event.get("calendar"), "start_at": event.get("start_at"), "end_at": event.get("end_at"), "status": event.get("status"), "source": event.get("source"), "reason": reason}, source_plugin="private_companion", confidence=0.92, importance=0.62) + recorder(namespace, safe_payload, idempotency_key=_single_line(idempotency_key, 240)) except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_calendar_event"): return - logger.debug("[PrivateCompanion] MemoryCompanion calendar write failed: %s", _single_line(exc, 120)) - + logger.debug("[PrivateCompanion] Bot 自有记录写入失败: %s", _single_line(exc, 120)) + async def _memory_companion_record_calendar_event(self, event: dict[str, Any], *, action: str = "updated", reason: str = "") -> None: + if not isinstance(event, dict): + return + event_id = _single_line(event.get("event_id"), 120) + if not event_id: + return + await self._memory_companion_record_bot_self_local( + namespace="bot_agenda_history", + kind="calendar_event", + payload={ + "event_id": event_id, + "action": _single_line(action, 40), + "reason": _single_line(reason, 240), + "title": _single_line(event.get("title") or event.get("description"), 200), + "start_at": _single_line(event.get("start_at"), 80), + "end_at": _single_line(event.get("end_at"), 80), + "status": _single_line(event.get("status"), 40), + "source_refs": [event_id], + }, + idempotency_key=f"calendar:{event_id}:{_single_line(action, 40)}", + ) + async def _memory_companion_record_agenda_snapshot(self, snapshot: dict[str, Any]) -> None: + if not isinstance(snapshot, dict): + return + snapshot_id = _single_line(snapshot.get("snapshot_id"), 120) + if not snapshot_id: + return + await self._memory_companion_record_bot_self_local( + namespace="bot_agenda_history", + kind="agenda_snapshot", + payload={ + "snapshot_id": snapshot_id, + "date": _single_line(snapshot.get("date"), 40), + "window": _single_line(snapshot.get("window"), 40), + "planned": snapshot.get("planned") if isinstance(snapshot.get("planned"), list) else [], + "observed": snapshot.get("observed") if isinstance(snapshot.get("observed"), list) else [], + "reconciled": snapshot.get("reconciled") if isinstance(snapshot.get("reconciled"), list) else [], + "open_items": snapshot.get("open_items") if isinstance(snapshot.get("open_items"), list) else [], + "source_refs": snapshot.get("source_refs") if isinstance(snapshot.get("source_refs"), list) else [], + "generated_at": _single_line(snapshot.get("generated_at"), 80), + }, + idempotency_key=f"agenda_snapshot:{snapshot_id}", + ) async def _memory_companion_record_daily_plan(self, plan: dict[str, Any]) -> None: if not isinstance(plan, dict): return - bridge = self._memory_companion_bridge() - recorder = getattr(bridge, "record_schedule_fragment", None) if bridge is not None else None - if not callable(recorder): - return date_text = _single_line(plan.get("date"), 40) - items = plan.get("items") - if not date_text or not isinstance(items, list) or not items: + if not date_text: return - lines: list[str] = [] - for item in items[:16]: - if not isinstance(item, dict): - continue - line = _single_line( - " ".join( - part - for part in [ - _single_line(item.get("time"), 12), - _single_line(item.get("activity"), 180), - f"情绪:{_single_line(item.get('mood'), 40)}" if _single_line(item.get("mood"), 40) else "", - f"可分享:{_single_line(item.get('message_seed'), 80)}" if _single_line(item.get("message_seed"), 80) else "", - ] - if part - ), - 260, - ) - if line: - lines.append(line) - if not lines: - return - content = f"{date_text} 的 Bot 当日生活日程已生成:\n" + "\n".join(f"- {line}" for line in lines) - try: - await recorder( - content=content, - scope="unknown", - session_id="private_companion:schedule", - message_id=f"private_companion_daily_plan_{date_text}", - memory_id=f"private_companion_daily_plan_{date_text}", - metadata={ - "date": date_text, - "source": _single_line(plan.get("source"), 40), - "item_count": len(lines), - "provider_id": _single_line(plan.get("provider_id"), 120), - }, - source_plugin="private_companion", - confidence=0.86, - importance=0.5, - ) - except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_daily_plan"): - return - logger.debug("[PrivateCompanion] MemoryCompanion 日程写入失败: %s", _single_line(exc, 120)) - + await self._memory_companion_record_bot_self_local( + namespace="bot_agenda_history", + kind="daily_plan", + payload={ + "date": date_text, + "source": _single_line(plan.get("source"), 40), + "provider_id": _single_line(plan.get("provider_id"), 120), + "items": plan.get("items") if isinstance(plan.get("items"), list) else [], + "source_refs": [f"daily_plan:{date_text}"], + }, + idempotency_key=f"daily_plan:{date_text}", + ) async def _memory_companion_record_detail_enhancement( self, *, @@ -751,75 +774,23 @@ class MemoryCompanionAdapterMixin: ) -> None: if not isinstance(segment, dict) or not isinstance(detail, dict): return - bridge = self._memory_companion_bridge() - recorder = getattr(bridge, "record_schedule_fragment", None) if bridge is not None else None - if not callable(recorder): - return date_text = _single_line(plan.get("date") if isinstance(plan, dict) else "", 40) - start = 0 - end = 0 - try: - start = int(segment.get("start") or 0) - end = int(segment.get("end") or 0) - except Exception: - start, end = 0, 0 - if not date_text or start < 0: + start = _safe_int(segment.get("start"), 0, 0, 1440) + end = _safe_int(segment.get("end"), 0, 0, 1440) + if not date_text: return - try: - start_text = self._minutes_to_hhmm(start) - end_text = self._minutes_to_hhmm(end) - except Exception: - start_text = str(start) - end_text = str(end or "") - summary = _single_line(detail.get("summary"), 180) - events = [] - for item in detail.get("today_events") if isinstance(detail.get("today_events"), list) else []: - if isinstance(item, dict): - text = _single_line(item.get("event"), 160) - if text: - events.append(text) - proactive = [] - for item in detail.get("proactive_events") if isinstance(detail.get("proactive_events"), list) else []: - if isinstance(item, dict): - text = _single_line( - item.get("topic") or item.get("motive") or item.get("why") or item.get("reason"), - 100, - ) - if text: - proactive.append(text) - if not summary and not events and not proactive: - return - parts = [f"{date_text} {start_text}-{end_text} 的 Bot 日程细化:"] - if summary: - parts.append(summary) - if events: - parts.append("生活片段:" + ";".join(events[:4])) - if proactive: - parts.append("可能主动念头:" + ";".join(proactive[:3])) - try: - await recorder( - content="\n".join(parts), - scope="unknown", - session_id="private_companion:schedule", - message_id=f"private_companion_detail_{date_text}_{start}_{end}", - memory_id=f"private_companion_detail_{date_text}_{start}_{end}", - metadata={ - "date": date_text, - "start": start_text, - "end": end_text, - "summary": summary, - "event_count": len(events), - "proactive_count": len(proactive), - }, - source_plugin="private_companion", - confidence=0.84, - importance=0.42, - ) - except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_detail_enhancement"): - return - logger.debug("[PrivateCompanion] MemoryCompanion 细化写入失败: %s", _single_line(exc, 120)) - + await self._memory_companion_record_bot_self_local( + namespace="bot_agenda_history", + kind="detail_enhancement", + payload={ + "date": date_text, + "start": start, + "end": end, + "detail": detail, + "source_refs": [f"detail:{date_text}:{start}:{end}"], + }, + idempotency_key=f"detail:{date_text}:{start}:{end}", + ) def _memory_companion_build_group_context( self, *, @@ -984,67 +955,22 @@ class MemoryCompanionAdapterMixin: content = _single_line(text, 1000) if not content: return - bridge = self._memory_companion_bridge() - visible_turn_recorder = getattr(bridge, "record_visible_turn", None) if bridge is not None else None - proactive_recorder = getattr(bridge, "record_proactive_message", None) if bridge is not None else None - if not callable(visible_turn_recorder) and not callable(proactive_recorder): - return - umo = _single_line(user.get("umo"), 200) - if not umo: - return - platform = umo.split(":", 1)[0] if ":" in umo else "" - name = _single_line(user.get("nickname") or user.get("display_name") or user_id, 80) - metadata = { - "reason": _single_line(reason, 80), - "action": _single_line(action, 80), - "motive": _single_line(motive, 180), - "action_summary": _single_line(action_summary, 240), - "image_path": _single_line(image_path, 300), - "extra_count": int(extra_count or 0), - "clean_visible_text": content, - } - try: - message_id = f"private_companion_proactive_{uuid.uuid4().hex}" - if callable(visible_turn_recorder): - await visible_turn_recorder( - role="assistant", - content=content, - scope="private", - session_id=umo, - platform=platform, - user_id=str(user_id or ""), - user_name=name, - message_id=message_id, - source="private_companion_proactive", - metadata=metadata, - ) - if callable(proactive_recorder): - await proactive_recorder( - content=f"Bot 主动向 {name or user_id} 发送:{content}", - scope="private", - session_id=umo, - platform=platform, - message_id=message_id, - subject={"kind": "bot", "id": "self", "name": "Bot", "role": "bot_self"}, - object={"kind": "user", "id": str(user_id or ""), "name": name, "role": "private_companion_target"}, - metadata={ - **metadata, - "date": self._memory_companion_now_iso()[:10], - "event_type": "proactive_message", - "action_label": "主动私聊", - "query_anchors": ["主动消息", "主动私聊", "刚才主动说了什么", "最近主动联系", "发送给用户"], - }, - source_plugin="private_companion", - confidence=0.92, - importance=0.58, - tags=["proactive", "proactive_message", "bot_action", "private_companion"], - occurred_at=self._memory_companion_now_iso(), - ) - except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_proactive_message"): - return - logger.debug("[PrivateCompanion] MemoryCompanion 主动消息桥接写入失败: %s", _single_line(exc, 120)) - + await self._memory_companion_record_bot_self_local( + namespace="bot_self_timeline", + kind="proactive_message", + payload={ + "user_id": _single_line(user_id, 120), + "text": content, + "reason": _single_line(reason, 100), + "action": _single_line(action, 80), + "motive": _single_line(motive, 180), + "action_summary": _single_line(action_summary, 240), + "image_path": _single_line(image_path, 300), + "extra_count": int(extra_count or 0), + "source_refs": ["proactive_message"], + }, + idempotency_key=f"proactive:{_single_line(user_id, 120)}:{_single_line(action, 80)}:{content[:80]}", + ) async def _memory_companion_record_image_observation( self, event: Any | None, @@ -1127,107 +1053,26 @@ class MemoryCompanionAdapterMixin: scene_preset: str = "", reference_image_path: str = "", ) -> None: - prompt_text = _single_line(prompt, 900) - if not prompt_text and not image_path: + if not _single_line(prompt, 900) and not _single_line(image_path, 260): return - bridge = self._memory_companion_bridge() - recorder = getattr(bridge, "record_event", None) if bridge is not None else None - if not callable(recorder): - recorder = getattr(bridge, "record_persona_life", None) if bridge is not None else None - if not callable(recorder): - return - is_private = False - try: - is_private = bool(getattr(event, "is_private_chat", lambda: False)()) - except Exception: - is_private = False - scope = "private" if is_private else "group" - session_id = _single_line(getattr(event, "unified_msg_origin", "") if event is not None else "", 180) - platform = session_id.split(":", 1)[0] if ":" in session_id else "" - user_id = "" - user_name = "" - if event is not None: - try: - user_id = _single_line(event.get_sender_id(), 80) - except Exception: - user_id = "" - try: - user_name = _single_line(self._sender_display_name(event), 80) - except Exception: - user_name = "" - kind_text = _single_line(intent_kind or kind, 40) or "图片" - backend_text = _single_line(backend, 80) - scene_text = _single_line(scene_preset, 80) - ref_text = _single_line(reference_image_path, 260) - status = "生成并发送" if sent else "生成" - content = ( - f"Bot 通过生图能力{status}了一张{kind_text}。" - f"画面要求:{prompt_text or '未记录'}。" - f"{' 场景预设:' + scene_text + '。' if scene_text else ''}" - f"{' 后端:' + backend_text + '。' if backend_text else ''}" - f"{' 使用了参考图。' if ref_text and '已使用' in str(note or '') else ''}" - f"{' 图片路径:' + _single_line(image_path, 260) + '。' if image_path else ''}" + await self._memory_companion_record_bot_self_local( + namespace="bot_self_timeline", + kind="photo_generation", + payload={ + "prompt": _single_line(prompt, 900), + "kind": _single_line(kind, 40), + "intent_kind": _single_line(intent_kind, 40), + "backend": _single_line(backend, 80), + "image_path": _single_line(image_path, 260), + "note": _single_line(note, 220), + "sent": bool(sent), + "trigger": _single_line(trigger, 40), + "scene_preset": _single_line(scene_preset, 80), + "reference_image_path": _single_line(reference_image_path, 260), + "source_refs": ["photo_generation"], + }, + idempotency_key=f"photo:{_single_line(image_path, 260)}:{_single_line(prompt, 120)}", ) - memory_key = uuid.uuid4().hex[:12] - try: - await recorder( - content=content, - memory_type="photo_generation", - scope=scope, - session_id=session_id, - platform=platform, - message_id=f"private_companion_photo_{memory_key}", - memory_id=f"private_companion_photo_{memory_key}", - subject={"kind": "bot", "id": "self", "name": "Bot", "role": "bot_self"}, - object={"kind": "user", "id": user_id, "name": user_name, "role": "conversation_partner"}, - visibility="private_pair" if scope == "private" else "group_public", - sayability="direct", - reality_level="bot_action", - lifecycle="recent", - confidence=0.86, - importance=0.52, - review_status="auto", - tags=[ - "photo_generation", - "image", - "bot_action", - "private_companion", - _single_line(kind_text, 40), - _single_line(trigger, 40), - ], - metadata={ - "date": self._memory_companion_now_iso()[:10], - "event_type": "photo_generation", - "action_label": "生图/拍照", - "trigger": _single_line(trigger, 40), - "kind": _single_line(kind, 40), - "intent_kind": _single_line(intent_kind, 40), - "backend": backend_text, - "prompt": prompt_text, - "image_path": _single_line(image_path, 260), - "note": _single_line(note, 220), - "sent": bool(sent), - "scene_preset": scene_text, - "reference_image_path": ref_text, - "used_reference": bool(ref_text and "已使用" in str(note or "")), - "query_anchors": [ - "刚才生成了什么图", - "刚才发了什么图", - "刚才画了什么", - "表情包", - "自拍", - "生图", - "图片生成", - ], - }, - source_plugin="private_companion", - occurred_at=self._memory_companion_now_iso(), - ) - except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_photo_generation"): - return - logger.debug("[PrivateCompanion] MemoryCompanion 生图记录写入失败: %s", _single_line(exc, 120)) - async def _memory_companion_record_user_habit( self, *, @@ -1327,134 +1172,48 @@ class MemoryCompanionAdapterMixin: logger.debug("[PrivateCompanion] MemoryCompanion 用户习惯写入失败: %s", _single_line(exc, 120)) async def _memory_companion_record_daily_outfit(self, item: dict[str, Any]) -> None: - if not isinstance(item, dict) or not _single_line(item.get("path"), 300): + if not isinstance(item, dict): return - bridge = self._memory_companion_bridge() - recorder = getattr(bridge, "record_persona_life", None) if bridge is not None else None - if not callable(recorder): - return - date_text = _single_line(item.get("date"), 20) - prompt = _single_line(item.get("prompt"), 600) - note = _single_line(item.get("note"), 160) - path = _single_line(item.get("path"), 300) - schedule_hint = "" - try: - schedule_hint = _single_line(self._daily_outfit_schedule_text(), 280) - except Exception: - schedule_hint = "" - content = ( - f"{date_text or '今天'}的 Bot 每日穿搭图已生成。" - f"这条记忆用于回答当前穿搭、衣服颜色、今天穿什么等问题。" + date_text = _single_line(item.get("date"), 40) or _single_line(self._memory_companion_now_iso(), 10) + await self._memory_companion_record_bot_self_local( + namespace="bot_self_timeline", + kind="daily_outfit", + payload={ + "date": date_text, + "item": item, + "source_refs": [f"daily_outfit:{date_text}"], + }, + idempotency_key=f"daily_outfit:{date_text}", ) - if schedule_hint: - content += f" 穿搭依据:{schedule_hint}。" - if prompt: - content += f" 穿搭提示摘要:{prompt[:360]}" - try: - await recorder( - content=content, - scope="unknown", - session_id="private_companion:daily_outfit", - message_id=f"private_companion_daily_outfit_{date_text or 'today'}", - memory_id=f"private_companion_daily_outfit_{date_text or 'today'}", - metadata={ - "date": date_text, - "image_path": path, - "backend": _single_line(item.get("backend"), 80), - "note": note, - "prompt_preview": prompt, - "query_anchors": ["今日穿搭", "每日穿搭", "衣服颜色", "穿什么", "穿了什么", "当前穿着"], - }, - source_plugin="private_companion", - confidence=0.76, - importance=0.62, - tags=["daily_outfit", "outfit", "clothing", "current_state", "persona_life", "衣服颜色", "今日穿搭"], - occurred_at=self._memory_companion_now_iso(), - ) - except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_daily_outfit"): - return - logger.debug("[PrivateCompanion] MemoryCompanion 每日穿搭写入失败: %s", _single_line(exc, 120)) - async def _memory_companion_record_creative_progress( self, *, project: dict[str, Any], - chunk: str = "", + title: str = "", + work_type: str = "", + next_direction: str = "", + important: list[str] | None = None, + threads: list[str] | None = None, extract: dict[str, Any] | None = None, event: Any | None = None, ) -> None: if not isinstance(project, dict): return - bridge = self._memory_companion_bridge() - recorder = getattr(bridge, "record_creative_work", None) if bridge is not None else None - if not callable(recorder): - return - project_id = _single_line(project.get("id"), 60) - title = _single_line(project.get("title"), 60) or "未命名作品" - work_type = _single_line(project.get("work_type"), 40) or "创作" - premise = _single_line(project.get("premise"), 180) - chunk_text = _single_line(chunk, 360) - extract = extract if isinstance(extract, dict) else {} - next_direction = _single_line(extract.get("next_direction") or project.get("next_hint"), 160) - important = extract.get("important_facts") if isinstance(extract.get("important_facts"), list) else [] - threads = extract.get("new_threads") if isinstance(extract.get("new_threads"), list) else [] - important_text = ";".join(_single_line(item, 80) for item in important[:3] if _single_line(item, 80)) - thread_text = ";".join(_single_line(item, 80) for item in threads[:3] if _single_line(item, 80)) - content_parts = [ - f"Bot 私下创作项目《{title}》({work_type})有新进展。", - f"核心设定:{premise}" if premise else "", - f"最新片段:{chunk_text}" if chunk_text else "", - f"新增线索:{thread_text}" if thread_text else "", - f"必须记住:{important_text}" if important_text else "", - f"下一步:{next_direction}" if next_direction else "", - ] - content = " ".join(part for part in content_parts if part) - if not content.strip(): - return - session_id = "private_companion:creative" - group_id = "" - platform = "" - if event is not None: - session_id = _single_line(getattr(event, "unified_msg_origin", ""), 180) or session_id - platform = session_id.split(":", 1)[0] if ":" in session_id else "" - try: - if not bool(getattr(event, "is_private_chat", lambda: False)()): - group_id = _single_line(getattr(event, "get_group_id", lambda: "")(), 80) - except Exception: - group_id = "" - try: - await recorder( - content=content, - scope="unknown", - session_id=session_id, - platform=platform, - group_id=group_id, - message_id=f"private_companion_creative_{project_id}_{_single_line(project.get('current_chars'), 20)}", - memory_id=f"private_companion_creative_{project_id}_{_single_line(project.get('current_chars'), 20)}", - metadata={ - "project_id": project_id, - "title": title, - "work_type": work_type, - "status": _single_line(project.get("status"), 30), - "current_chars": project.get("current_chars"), - "target_chars": project.get("target_chars"), - "next_direction": next_direction, - "important_facts": important[:5], - "new_threads": threads[:5], - "query_anchors": [title, work_type, "私下创作", "创作项目", "上次写到哪", "小说片段", "人工修订"], - }, - source_plugin="private_companion", - confidence=0.8, - importance=0.72, - tags=["creative_work", "private_companion", "creative_project", work_type, title], - occurred_at=self._memory_companion_now_iso(), - ) - except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_creative_progress"): - return - logger.debug("[PrivateCompanion] MemoryCompanion 创作进展写入失败: %s", _single_line(exc, 120)) - + await self._memory_companion_record_bot_self_local( + namespace="bot_self_timeline", + kind="creative_progress", + payload={ + "title": _single_line(title, 160), + "work_type": _single_line(work_type, 80), + "project": project, + "next_direction": _single_line(next_direction, 240), + "important": list(important or [])[:5], + "threads": list(threads or [])[:5], + "extract": extract or {}, + "source_refs": ["creative_progress"], + }, + idempotency_key=f"creative:{_single_line(title, 160)}:{_single_line(project.get('updated_at') or project.get('id'), 120)}", + ) def _memory_companion_now_iso(self) -> str: try: return self._environment_now().isoformat(timespec="seconds") @@ -1479,72 +1238,19 @@ class MemoryCompanionAdapterMixin: content = _single_line(text, 800) if not content: return - bridge = self._memory_companion_bridge() - recorder = getattr(bridge, "record_qzone_action", None) if bridge is not None else None - if not callable(recorder): - recorder = getattr(bridge, "record_persona_life", None) if bridge is not None else None - if not callable(recorder): - return - reason_text = _single_line(reason, 40) or "qzone_publish" - session_id = "private_companion:qzone" - platform = "" - if event is not None: - session_id = _single_line(getattr(event, "unified_msg_origin", ""), 180) or session_id - platform = session_id.split(":", 1)[0] if ":" in session_id else "" - safe_image_count = _safe_int(image_count, 0, 0, 99) - image_part = f";配图 {safe_image_count} 张" if safe_image_count > 0 else "" - verify_part = ";已反查确认" if verified else "" - memory_content = f"Bot 刚刚发布了一条 QQ 空间说说:{content}{image_part}{verify_part}。" - memory_key = _single_line(tid, 40) or uuid.uuid4().hex[:12] - date_text = "" - try: - date_text = self._environment_now().date().isoformat() - except Exception: - date_text = self._memory_companion_now_iso()[:10] - try: - await recorder( - content=memory_content, - scope="unknown", - session_id=session_id, - platform=platform, - message_id=f"private_companion_qzone_{memory_key}", - memory_id=f"private_companion_qzone_{memory_key}", - memory_type="qzone_action", - reality_level="bot_action", - sayability="direct", - metadata={ - "date": date_text, - "event_type": "qzone_publish", - "action_label": "QQ 空间说说", - "reason": reason_text, - "tid": _single_line(tid, 80), - "text": content, - "clean_visible_text": content, - "image_count": safe_image_count, - "verified": bool(verified) if verified is not None else None, - "query_anchors": [ - "QQ空间", - "说说", - "QQ 空间说说", - "刚才发了什么", - "刚刚发了什么", - "发了什么说说", - "最近已发说说", - "空间动态", - "公开动态余味", - ], - }, - source_plugin="private_companion", - confidence=0.84, - importance=0.58, - tags=["qzone", "qzone_publish", "bot_action", "persona_life", "说说", "QQ空间", reason_text], - occurred_at=self._memory_companion_now_iso(), - ) - except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_qzone_publish"): - return - logger.debug("[PrivateCompanion] MemoryCompanion QQ 空间发布写入失败: %s", _single_line(exc, 120)) - + await self._memory_companion_record_bot_self_local( + namespace="bot_self_timeline", + kind="qzone_publish", + payload={ + "text": content, + "reason": _single_line(reason, 80), + "tid": _single_line(tid, 160), + "image_count": _safe_int(image_count, 0, 0, 99), + "verified": verified, + "source_refs": ["qzone_publish"], + }, + idempotency_key=f"qzone:{_single_line(tid, 160) or content[:100]}", + ) def _memory_companion_apply_emotional_drift(self, *, session_id: str = "") -> None: """Pull pending emotional drift events from the memory plugin and apply to daily_state. @@ -1666,45 +1372,22 @@ class MemoryCompanionAdapterMixin: dream_type: str = "", user_id: str = "", ) -> None: - """Record a dream fragment into the memory plugin for cross-session continuity.""" if not getattr(self, "enable_memory_companion_dream_fragment", True): return dream_text = _single_line(content, 800) if not dream_text: return - bridge = self._memory_companion_bridge() - if bridge is None: - return - recorder = getattr(bridge, "record_persona_life", None) - if not callable(recorder): - return - parts = [f"Bot 梦境碎片:{dream_text}"] - if mood: - parts.append(f"梦醒情绪:{_single_line(mood, 60)}") - if dream_type: - parts.append(f"梦境类型:{_single_line(dream_type, 40)}") - full_content = " ".join(parts) - try: - await recorder( - content=full_content, - scope="unknown", - session_id="private_companion:dream", - memory_id=f"private_companion_dream_{uuid.uuid4().hex[:12]}", - metadata={ - "dream_type": _single_line(dream_type, 40), - "dream_mood": _single_line(mood, 60), - "query_anchors": ["梦境", "梦到", "做梦", "梦里的", "梦见"], - }, - source_plugin="private_companion", - importance=0.48, - tags=["dream", "dream_fragment", "persona_life", "梦境碎片"], - occurred_at=self._memory_companion_now_iso(), - ) - except Exception as exc: - if self._memory_companion_optional_dependency_failed(exc, where="record_dream_fragment"): - return - logger.debug("[PrivateCompanion] 梦境碎片写入失败: %s", _single_line(exc, 120)) - + await self._memory_companion_record_bot_self_local( + namespace="bot_self_timeline", + kind="dream_fragment", + payload={ + "content": dream_text, + "mood": _single_line(mood, 60), + "dream_type": _single_line(dream_type, 40), + "source_refs": ["dream_fragment"], + }, + idempotency_key=f"dream:{dream_text[:120]}:{_single_line(mood, 60)}", + ) def _memory_companion_get_relationship_phase(self, *, session_id: str = "") -> dict[str, Any]: """Get current relationship phase from the memory plugin.""" bridge = self._memory_companion_bridge() diff --git a/remember_you_adapter.py b/remember_you_adapter.py index 7a8e1b4..c88143e 100644 --- a/remember_you_adapter.py +++ b/remember_you_adapter.py @@ -9,7 +9,7 @@ from typing import Any from astrbot.api import logger -from .helpers import _single_line +from .helpers import _safe_int, _single_line class RememberYouAdapterMixin: @@ -270,59 +270,35 @@ class RememberYouAdapterMixin: return "" return text[: max(300, int(max_chars or 1200))] + async def _remember_you_record_bot_self_local( + self, + *, + kind: str, + payload: dict[str, Any], + idempotency_key: str, + ) -> None: + recorder = getattr(self, "_bot_self_record", None) + if not callable(recorder): + return + try: + recorder( + "bot_self_timeline", + {"kind": _single_line(kind, 80), **payload}, + idempotency_key=_single_line(idempotency_key, 240), + ) + except Exception as exc: + logger.debug("[PrivateCompanion] RememberYou Bot 自有记录失败: %s", _single_line(exc, 120)) async def _remember_you_record_daily_plan(self, plan: dict[str, Any]) -> None: if not isinstance(plan, dict): return - bridge = self._remember_you_bridge() - recorder = getattr(bridge, "record_schedule_fragment", None) if bridge is not None else None - if not callable(recorder): - return date_text = _single_line(plan.get("date"), 40) - items = plan.get("items") - if not date_text or not isinstance(items, list) or not items: + if not date_text: return - lines: list[str] = [] - for item in items[:16]: - if not isinstance(item, dict): - continue - line = _single_line( - " ".join( - part - for part in [ - _single_line(item.get("time"), 12), - _single_line(item.get("activity"), 180), - f"情绪:{_single_line(item.get('mood'), 40)}" if _single_line(item.get("mood"), 40) else "", - f"可分享:{_single_line(item.get('message_seed'), 80)}" if _single_line(item.get("message_seed"), 80) else "", - ] - if part - ), - 260, - ) - if line: - lines.append(line) - if not lines: - return - content = f"{date_text} 的 Bot 当日生活日程已生成:\n" + "\n".join(f"- {line}" for line in lines) - try: - await recorder( - content=content, - scope="unknown", - session_id="private_companion:schedule", - message_id=f"private_companion_daily_plan_{date_text}", - memory_id=f"private_companion_daily_plan_{date_text}", - metadata={ - "date": date_text, - "source": _single_line(plan.get("source"), 40), - "item_count": len(lines), - "provider_id": _single_line(plan.get("provider_id"), 120), - }, - source_plugin="private_companion", - confidence=0.86, - importance=0.5, - ) - except Exception as exc: - logger.debug("[PrivateCompanion] RememberYou 日程写入失败: %s", _single_line(exc, 120)) - + await self._remember_you_record_bot_self_local( + kind="daily_plan", + payload={"date": date_text, "plan": plan, "source_refs": [f"daily_plan:{date_text}"]}, + idempotency_key=f"daily_plan:{date_text}", + ) async def _remember_you_record_detail_enhancement( self, *, @@ -332,73 +308,16 @@ class RememberYouAdapterMixin: ) -> None: if not isinstance(segment, dict) or not isinstance(detail, dict): return - bridge = self._remember_you_bridge() - recorder = getattr(bridge, "record_schedule_fragment", None) if bridge is not None else None - if not callable(recorder): - return date_text = _single_line(plan.get("date") if isinstance(plan, dict) else "", 40) - start = 0 - end = 0 - try: - start = int(segment.get("start") or 0) - end = int(segment.get("end") or 0) - except Exception: - start, end = 0, 0 - if not date_text or start < 0: + start = _safe_int(segment.get("start"), 0, 0, 1440) + end = _safe_int(segment.get("end"), 0, 0, 1440) + if not date_text: return - try: - start_text = self._minutes_to_hhmm(start) - end_text = self._minutes_to_hhmm(end) - except Exception: - start_text = str(start) - end_text = str(end or "") - summary = _single_line(detail.get("summary"), 180) - events = [] - for item in detail.get("today_events") if isinstance(detail.get("today_events"), list) else []: - if isinstance(item, dict): - text = _single_line(item.get("event"), 160) - if text: - events.append(text) - proactive = [] - for item in detail.get("proactive_events") if isinstance(detail.get("proactive_events"), list) else []: - if isinstance(item, dict): - text = _single_line( - item.get("topic") or item.get("motive") or item.get("why") or item.get("reason"), - 100, - ) - if text: - proactive.append(text) - if not summary and not events and not proactive: - return - parts = [f"{date_text} {start_text}-{end_text} 的 Bot 日程细化:"] - if summary: - parts.append(summary) - if events: - parts.append("生活片段:" + ";".join(events[:4])) - if proactive: - parts.append("可能主动念头:" + ";".join(proactive[:3])) - try: - await recorder( - content="\n".join(parts), - scope="unknown", - session_id="private_companion:schedule", - message_id=f"private_companion_detail_{date_text}_{start}_{end}", - memory_id=f"private_companion_detail_{date_text}_{start}_{end}", - metadata={ - "date": date_text, - "start": start_text, - "end": end_text, - "summary": summary, - "event_count": len(events), - "proactive_count": len(proactive), - }, - source_plugin="private_companion", - confidence=0.84, - importance=0.42, - ) - except Exception as exc: - logger.debug("[PrivateCompanion] RememberYou 细化写入失败: %s", _single_line(exc, 120)) - + await self._remember_you_record_bot_self_local( + kind="detail_enhancement", + payload={"date": date_text, "start": start, "end": end, "detail": detail, "source_refs": [f"detail:{date_text}:{start}:{end}"]}, + idempotency_key=f"detail:{date_text}:{start}:{end}", + ) def _remember_you_build_group_context( self, *, @@ -528,41 +447,11 @@ class RememberYouAdapterMixin: content = _single_line(text, 1000) if not content: return - bridge = self._remember_you_bridge() - recorder = getattr(bridge, "record_proactive_message", None) if bridge is not None else None - if not callable(recorder): - return - umo = _single_line(user.get("umo"), 200) - if not umo: - return - platform = umo.split(":", 1)[0] if ":" in umo else "" - name = _single_line(user.get("nickname") or user.get("display_name") or user_id, 80) - metadata = { - "reason": _single_line(reason, 80), - "action": _single_line(action, 80), - "motive": _single_line(motive, 180), - "action_summary": _single_line(action_summary, 240), - "image_path": _single_line(image_path, 300), - "extra_count": int(extra_count or 0), - "clean_visible_text": content, - } - try: - await recorder( - content=f"Bot 主动向 {name or user_id} 发送:{content}", - scope="private", - session_id=umo, - platform=platform, - message_id=f"private_companion_proactive_{uuid.uuid4().hex}", - subject={"kind": "bot", "id": "self", "name": "Bot", "role": "bot_self"}, - object={"kind": "user", "id": str(user_id or ""), "name": name, "role": "private_companion_target"}, - metadata=metadata, - source_plugin="private_companion", - confidence=0.92, - importance=0.58, - ) - except Exception as exc: - logger.debug("[PrivateCompanion] RememberYou 主动消息桥接写入失败: %s", _single_line(exc, 120)) - + await self._remember_you_record_bot_self_local( + kind="proactive_message", + payload={"user_id": _single_line(user_id, 120), "text": content, "reason": _single_line(reason, 100), "action": _single_line(action, 80), "motive": _single_line(motive, 180), "action_summary": _single_line(action_summary, 240), "image_path": _single_line(image_path, 300), "extra_count": int(extra_count or 0), "source_refs": ["proactive_message"]}, + idempotency_key=f"proactive:{_single_line(user_id, 120)}:{_single_line(action, 80)}:{content[:80]}", + ) async def _remember_you_record_image_observation( self, event: Any | None, diff --git a/schedule_reconciler.py b/schedule_reconciler.py new file mode 100644 index 0000000..52be4cf --- /dev/null +++ b/schedule_reconciler.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +"""Deterministic plan/actual reconciliation for the local agenda.""" +from __future__ import annotations + +from datetime import datetime +from typing import Any + +try: + from .agenda_contracts import agenda_entry_from_activity, agenda_entry_from_plan, normalize_observed_activity + from .calendar_system import parse_datetime +except ImportError: + from agenda_contracts import agenda_entry_from_activity, agenda_entry_from_plan, normalize_observed_activity + from calendar_system import parse_datetime + +PRIORITY = {"L0": 0, "L1": 1, "L2": 2, "L3": 3, "L4": 4, "L5": 5} + + +def _tokens(value: Any) -> set[str]: + text = str(value or "").lower() + return {token for token in text.replace(",", " ").replace("。", " ").split() if len(token) >= 2} + + +def _interval(item: dict[str, Any], now: datetime) -> tuple[datetime | None, datetime | None]: + try: + start = parse_datetime(item.get("start_at"), default=now) + except Exception: + return None, None + try: + end = parse_datetime(item.get("end_at"), default=start) + except Exception: + end = start + return start, end + + +def _overlaps(plan: dict[str, Any], activity: dict[str, Any], now: datetime) -> bool: + ps, pe = _interval(plan, now) + a_s, a_e = _interval(activity, now) + if not ps or not a_s: + return False + if pe <= ps: + pe = ps + if a_e <= a_s: + a_e = a_s + return ps < a_e and a_s < pe + + +def _title_matches(plan: dict[str, Any], activity: dict[str, Any]) -> bool: + plan_tokens = _tokens(plan.get("title") or plan.get("activity")) + activity_tokens = _tokens(activity.get("title")) + return bool(plan_tokens and activity_tokens and plan_tokens.intersection(activity_tokens)) + + +def reconcile( + plans: list[dict[str, Any]], + activities: list[dict[str, Any]], + *, + now: datetime, +) -> dict[str, Any]: + normalized_activities = [] + for activity in activities: + try: + normalized_activities.append(normalize_observed_activity(activity, now=now)) + except Exception: + continue + matched: dict[str, list[dict[str, Any]]] = {} + used_activity_ids: set[str] = set() + results = [] + entries = [] + for raw_plan in plans: + plan = dict(raw_plan) + plan_id = str(plan.get("plan_id") or plan.get("event_id") or "") + overlaps = [activity for activity in normalized_activities if _overlaps(plan, activity, now)] + matching = [activity for activity in overlaps if _title_matches(plan, activity)] + selected = matching or overlaps + if selected: + matched[plan_id] = selected + used_activity_ids.update(str(item.get("activity_id")) for item in selected) + strongest = max((PRIORITY.get(str(item.get("evidence_level")), 0) for item in selected), default=0) + if matching: + status = "completed" if all(item.get("status") == "completed" for item in selected) else "active" + reason = "实际活动与计划主题和时间匹配" + elif strongest >= PRIORITY["L2"]: + status = "overridden" + reason = "实际活动覆盖原计划" + else: + status = "unknown" + reason = "活动证据不足" + plan["status"] = status + plan["reconciliation_reason"] = reason + plan["reconciled_activity_ids"] = [item.get("activity_id") for item in selected] + entries.append(agenda_entry_from_plan(plan, reason=reason)) + entries.extend(agenda_entry_from_activity(item, source_refs=[plan_id, item.get("activity_id")]) for item in selected) + else: + if plan.get("status") not in {"cancelled", "deferred"} and _plan_is_past(plan, now): + plan["status"] = "unknown" + plan["reconciliation_reason"] = "窗口结束但没有足够实际证据" + entries.append(agenda_entry_from_plan(plan, reason=plan.get("reconciliation_reason", ""))) + results.append(plan) + for activity in normalized_activities: + if str(activity.get("activity_id")) not in used_activity_ids: + entries.append(agenda_entry_from_activity(activity)) + entries.sort(key=lambda item: (0 if item.get("kind") == "observed_activity" else 1, str(item.get("start_at") or ""))) + return {"plans": results, "activities": normalized_activities, "entries": entries, "matched": matched} + + +def _plan_is_past(plan: dict[str, Any], now: datetime) -> bool: + _, end = _interval(plan, now) + return bool(end and end <= now) diff --git a/self_timeline.py b/self_timeline.py index 6e57beb..cfeae02 100644 --- a/self_timeline.py +++ b/self_timeline.py @@ -5,7 +5,10 @@ import re from datetime import datetime, timedelta from typing import Any -from .helpers import _now_ts, _safe_float, _safe_int, _single_line, _today_key +try: + from .helpers import _now_ts, _safe_float, _safe_int, _single_line, _today_key +except ImportError: + from helpers import _now_ts, _safe_float, _safe_int, _single_line, _today_key class SelfTimelineMixin: @@ -124,6 +127,7 @@ class SelfTimelineMixin: entries.extend(self._self_timeline_from_private_reading(data)) entries.extend(self._self_timeline_from_photo_generation(data)) entries.extend(self._self_timeline_from_qzone_publish(data)) + entries.extend(self._self_timeline_from_bot_self_store(data)) now = _now_ts() scored: list[tuple[float, float, dict[str, Any]]] = [] @@ -138,6 +142,42 @@ class SelfTimelineMixin: scored.sort(key=lambda item: (item[0], item[1]), reverse=True) return [item[2] for item in scored] + def _self_timeline_from_bot_self_store(self, data: dict[str, Any]) -> list[dict[str, Any]]: + store = data.get("bot_self_store") if isinstance(data.get("bot_self_store"), dict) else {} + records: list[dict[str, Any]] = [] + for namespace in ("bot_self_timeline", "bot_agenda_history", "ops_activity_history"): + values = store.get(namespace) if isinstance(store.get(namespace), list) else [] + for item in values[-80:]: + if not isinstance(item, dict): + continue + occurred_at = _single_line(item.get("occurred_at") or item.get("created_at"), 80) + try: + ts = datetime.fromisoformat(occurred_at.replace("Z", "+00:00")).timestamp() if occurred_at else 0.0 + except (TypeError, ValueError): + ts = 0.0 + kind = _single_line(item.get("kind"), 60) or namespace + summary = _single_line( + item.get("title") or item.get("summary") or item.get("text") or item.get("content") or kind, + 220, + ) + detail = _single_line( + item.get("reason") or item.get("action_summary") or item.get("note") or item.get("status"), + 180, + ) + records.append( + { + "source": "Bot自有记录", + "ts": ts, + "date": self._self_timeline_date_from_ts(ts), + "when": self._self_timeline_when_from_ts(ts), + "summary": summary, + "detail": detail, + "keywords": "Bot 自有记录 日程 活动 时间线 " + " ".join( + _single_line(item.get(key), 120) for key in ("kind", "title", "summary", "text", "content", "reason") + ), + } + ) + return records def _self_timeline_from_daily_plan(self, data: dict[str, Any]) -> list[dict[str, Any]]: plan = data.get("daily_plan") if isinstance(data.get("daily_plan"), dict) else {} items = plan.get("items") if isinstance(plan.get("items"), list) else plan.get("schedule") diff --git a/tests/test_agenda_system.py b/tests/test_agenda_system.py new file mode 100644 index 0000000..9c6bde2 --- /dev/null +++ b/tests/test_agenda_system.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import unittest +from datetime import datetime +from zoneinfo import ZoneInfo + +from activity_capture import ActivityCapture, classify_interaction +from agenda_contracts import ( + AGENDA_VERSION, + migrate_store, + normalize_observed_activity, + normalize_plan_item, +) +from schedule_reconciler import reconcile +from unified_agenda import build_unified_agenda, format_agenda_context +from world_gateway import NullWorldGateway, WorldGatewayContract +from agenda_runtime import AgendaRuntimeMixin + +TZ = ZoneInfo("Asia/Shanghai") + + +def dt(value: str) -> datetime: + return datetime.fromisoformat(value).replace(tzinfo=TZ) + + + +class DummyAgenda(AgendaRuntimeMixin): + def __init__(self, data=None): + self.data = data or {} + self.now = dt("2026-07-25T18:00:00") + self.saved = 0 + + def _calendar_now(self): + return self.now + + def _calendar_timezone_name(self): + return "Asia/Shanghai" + + def _schedule_data_save(self, delay=1.5): + self.saved += 1 +class AgendaSystemTests(unittest.TestCase): + def test_store_migration_adds_agenda_fields_without_dropping_data(self): + data, changed = migrate_store({"daily_plan": {"date": "2026-07-25", "items": [{"time": "10:00", "activity": "测试"}]}, "users": {"u": {}}}) + self.assertTrue(changed) + self.assertEqual(data["agenda_version"], AGENDA_VERSION) + self.assertEqual(data["users"]["u"], {}) + self.assertEqual(data["daily_plan"]["items"][0]["source_kind"], "planned") + self.assertEqual(data["daily_plan"]["items"][0]["evidence_level"], "L0") + + def test_evidence_level_does_not_allow_weak_real_activity_as_fact(self): + activity = normalize_observed_activity({"title": "猜测中的活动", "source_kind": "real", "evidence_level": "L1"}) + self.assertEqual(activity["status"], "unknown") + + def test_capture_ignores_small_talk_and_captures_collaboration(self): + self.assertEqual(classify_interaction("你好"), "ordinary") + capture = ActivityCapture() + activity = capture.capture_message( + text="我们继续测试这个插件的消息流", + event_time=dt("2026-07-25T14:00:00"), + source_ref="message-2", + conversation_id="private:u1", + participant="u1", + message_count=3, + ) + self.assertIsNotNone(activity) + self.assertEqual(activity["evidence_level"], "L2") + self.assertEqual(activity["kind"], "user_collaboration") + + def test_reconcile_overrides_plan_when_real_activity_has_different_topic(self): + plans = [{"plan_id": "p1", "title": "看电影", "start_at": "2026-07-25T14:00:00+08:00", "end_at": "2026-07-25T16:00:00+08:00", "status": "planned"}] + activities = [{"activity_id": "a1", "title": "共同编写插件", "start_at": "2026-07-25T14:10:00+08:00", "end_at": "2026-07-25T15:30:00+08:00", "evidence_level": "L2", "status": "completed"}] + result = reconcile(plans, activities, now=dt("2026-07-25T16:00:00")) + self.assertEqual(result["plans"][0]["status"], "overridden") + self.assertEqual(result["entries"][0]["kind"], "observed_activity") + + def test_reconcile_marks_past_plan_unknown_without_evidence(self): + result = reconcile( + [{"plan_id": "p1", "title": "阅读", "start_at": "2026-07-25T09:00:00+08:00", "end_at": "2026-07-25T10:00:00+08:00", "status": "planned"}], + [], + now=dt("2026-07-25T11:00:00"), + ) + self.assertEqual(result["plans"][0]["status"], "unknown") + + def test_unified_context_keeps_plan_and_actual_source_distinct(self): + agenda = build_unified_agenda( + plans=[{"plan_id": "p1", "title": "看电影", "start_at": "2026-07-25T14:00:00+08:00", "end_at": "2026-07-25T16:00:00+08:00"}], + activities=[{"activity_id": "a1", "title": "共同编写插件", "start_at": "2026-07-25T14:10:00+08:00", "end_at": "2026-07-25T15:30:00+08:00", "evidence_level": "L2"}], + now=dt("2026-07-25T15:00:00"), + ) + text = format_agenda_context(agenda) + self.assertIn("实际", text) + self.assertIn("计划", text) + self.assertEqual(agenda["current"]["kind"], "observed_activity") + + def test_runtime_converts_legacy_daily_plan_to_timed_plan(self): + runtime = DummyAgenda({"daily_plan": {"date": "2026-07-25", "items": [{"time": "17:00", "end": "18:00", "activity": "测试"}]}}) + agenda = runtime._agenda_build() + self.assertEqual(agenda["plans"][0]["title"], "测试") + self.assertEqual(agenda["plans"][0]["start_at"], "2026-07-25T17:00:00+08:00") + + def test_window_snapshot_is_idempotent(self): + runtime = DummyAgenda({}) + first = runtime._agenda_snapshot_window(date_key="2026-07-25", window="下午") + second = runtime._agenda_snapshot_window(date_key="2026-07-25", window="下午") + self.assertEqual(first["snapshot_id"], "snapshot-2026-07-25-下午") + self.assertEqual(second["snapshot_id"], first["snapshot_id"]) + self.assertEqual(len(runtime.data["window_snapshots"]), 1) + + def test_world_cache_without_fresh_projection_is_offline(self): + runtime = DummyAgenda({"world_projection_cache": [{"subject_id": "b", "fresh_until": "2026-07-24T23:00:00+08:00"}]}) + self.assertEqual(runtime._world_get_context("b")["status"], "offline") + def test_world_gateway_is_offline_by_default(self): + gateway = WorldGatewayContract(NullWorldGateway()) + result = gateway.get_world_context("bot-b", dt("2026-07-25T15:00:00")) + self.assertFalse(result.ok) + self.assertEqual(result.reason, "world_gateway_disabled") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_bot_self_store.py b/tests/test_bot_self_store.py new file mode 100644 index 0000000..29a6387 --- /dev/null +++ b/tests/test_bot_self_store.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import unittest +from datetime import datetime + +from activity_capture import ActivityCapture +from bot_self_store import ( + build_bot_self_migration_preview, + default_bot_self_store, + ensure_bot_self_store, + quarantine_legacy_bot_records, + record_bot_self_entry, + split_shared_activity, +) +from self_timeline import SelfTimelineMixin + + +class BotSelfStoreTests(unittest.TestCase): + def test_store_initialization_and_idempotent_record(self): + data = {} + data, changed = ensure_bot_self_store(data) + self.assertTrue(changed) + first = record_bot_self_entry( + data, + "bot_agenda_history", + {"kind": "agenda_snapshot", "date": "2026-07-25", "occurred_at": "2026-07-25T18:00:00+08:00"}, + idempotency_key="snapshot-2026-07-25-晚上", + now=datetime(2026, 7, 25, 18, 0), + ) + second = record_bot_self_entry( + data, + "bot_agenda_history", + {"kind": "agenda_snapshot", "date": "2026-07-25", "summary": "更新后的快照"}, + idempotency_key="snapshot-2026-07-25-晚上", + now=datetime(2026, 7, 25, 18, 1), + ) + self.assertEqual(first["record_id"], second["record_id"]) + self.assertEqual(len(data["bot_self_store"]["bot_agenda_history"]), 1) + self.assertEqual(second["version"], 2) + self.assertEqual(second["owner"], "bot") + self.assertEqual(second["storage_domain"], "bot_self") + + def test_migration_preview_is_non_destructive_and_quarantine_is_idempotent(self): + data = { + "daily_plan": {"date": "2026-07-25"}, + "calendar_events": [{"event_id": "e1"}], + "bot_diaries": [{"date": "2026-07-25"}], + } + preview = build_bot_self_migration_preview(data) + self.assertEqual(preview["status"], "preview_only") + self.assertFalse(preview["destructive"]) + result = quarantine_legacy_bot_records(data) + again = quarantine_legacy_bot_records(data) + self.assertEqual(result["quarantine_record"]["record_id"], again["quarantine_record"]["record_id"]) + self.assertEqual(len(data["bot_self_store"]["legacy_quarantine"]), 1) + self.assertIn("daily_plan", data) + self.assertIn("calendar_events", data) + + def test_shared_activity_requires_explicit_user_side(self): + split = split_shared_activity( + { + "activity_id": "a1", + "participants": ["user", "bot"], + "evidence_level": "L2", + "source_refs": ["msg-1"], + "bot_side": {"summary": "Bot 参与插件开发"}, + } + ) + self.assertFalse(split["user"]["eligible"]) + self.assertEqual(split["bot"]["activity"]["summary"], "Bot 参与插件开发") + + def test_activity_capture_exposes_split_contract(self): + split = ActivityCapture.split_for_storage( + { + "activity_id": "a2", + "participants": ["user", "bot"], + "user_side": {"summary": "用户确认切换 ops 分支"}, + "bot_side": {"summary": "Bot 执行了插件调整"}, + "source_refs": ["msg-2"], + } + ) + self.assertTrue(split["user"]["eligible"]) + self.assertEqual(split["user"]["activity"]["summary"], "用户确认切换 ops 分支") + + +class SelfTimelineBotStoreTests(unittest.TestCase): + def test_self_timeline_reads_bot_store_with_real_time(self): + class Dummy(SelfTimelineMixin): + data = { + "bot_self_store": { + "bot_self_timeline": [ + { + "kind": "proactive_message", + "text": "提醒用户检查备份", + "occurred_at": "2026-07-24T21:00:00+08:00", + } + ], + "bot_agenda_history": [], + "ops_activity_history": [], + } + } + + entries = Dummy()._self_timeline_from_bot_self_store(Dummy.data) + self.assertEqual(len(entries), 1) + self.assertEqual(entries[0]["source"], "Bot自有记录") + self.assertEqual(entries[0]["date"], "2026-07-24") + + +if __name__ == "__main__": + unittest.main() diff --git a/unified_agenda.py b/unified_agenda.py new file mode 100644 index 0000000..87228fa --- /dev/null +++ b/unified_agenda.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +"""Read model for the local unified agenda.""" +from __future__ import annotations + +from datetime import datetime +from typing import Any + +try: + from .schedule_reconciler import reconcile +except ImportError: + from schedule_reconciler import reconcile + + +def build_unified_agenda( + *, + plans: list[dict[str, Any]], + activities: list[dict[str, Any]], + now: datetime, + date_key: str = "", +) -> dict[str, Any]: + result = reconcile(plans, activities, now=now) + entries = result["entries"] + if date_key: + entries = [item for item in entries if str(item.get("date") or item.get("start_at", ""))[:10] == date_key] + current = None + ordered_entries = sorted(entries, key=lambda item: (0 if item.get("kind") == "observed_activity" else 1, str(item.get("start_at") or ""))) + for entry in ordered_entries: + if entry.get("status") not in {"cancelled", "unknown"}: + start = str(entry.get("start_at") or "") + end = str(entry.get("end_at") or "") + if start <= now.isoformat() <= end: + current = entry + break + return { + "generated_at": now.isoformat(timespec="seconds"), + "date": date_key or now.date().isoformat(), + "current": current, + "entries": entries, + "plans": result["plans"], + "activities": result["activities"], + "matched": result["matched"], + } + + +def format_agenda_context(agenda: dict[str, Any], *, max_entries: int = 8) -> str: + if not isinstance(agenda, dict): + return "" + lines = [f"当前统一日程日期:{agenda.get('date') or '未知'}"] + current = agenda.get("current") + if isinstance(current, dict): + lines.append(f"当前实际活动:{current.get('title') or '未命名'}(证据等级 {current.get('evidence_level') or '未知'})") + entries = agenda.get("entries") if isinstance(agenda.get("entries"), list) else [] + for item in entries[:max_entries]: + title = str(item.get("title") or "未命名")[:80] + status = str(item.get("status") or "unknown") + kind = str(item.get("kind") or "") + prefix = "实际" if kind == "observed_activity" else "计划" + reason = str((item.get("reconciliation") or {}).get("reason") or "") + lines.append(f"- {prefix}:{title}({status})" + (f";{reason}" if reason else "")) + return "\n".join(lines) diff --git a/world_gateway.py b/world_gateway.py new file mode 100644 index 0000000..9229548 --- /dev/null +++ b/world_gateway.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +"""Offline-first World gateway contract. + +The production gateway is intentionally not implemented in this phase. The +null gateway preserves local behavior and makes the future boundary testable. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any + + +@dataclass +class WorldResult: + ok: bool + data: Any = None + reason: str = "" + fresh_until: str = "" + request_id: str = "" + + +class NullWorldGateway: + enabled = False + + def publish_activity(self, activity: dict[str, Any]) -> WorldResult: + return WorldResult(False, reason="world_gateway_disabled") + + def get_world_context(self, subject_id: str, now: datetime) -> WorldResult: + return WorldResult(False, data=[], reason="world_gateway_disabled") + + def get_schedule_projection(self, subject_id: str, date: str) -> WorldResult: + return WorldResult(False, data=[], reason="world_gateway_disabled") + + def confirm_shared_activity(self, candidate: dict[str, Any]) -> WorldResult: + return WorldResult(False, reason="world_gateway_disabled") + + def revoke_projection(self, ref: str) -> WorldResult: + return WorldResult(False, reason="world_gateway_disabled") + + +@dataclass +class WorldGatewayContract: + gateway: Any = field(default_factory=NullWorldGateway) + timeout_seconds: float = 2.0 + failure_cooldown_seconds: float = 60.0 + + def _call(self, method: str, *args: Any, **kwargs: Any) -> WorldResult: + if self.gateway is None: + return WorldResult(False, reason="world_gateway_missing") + try: + result = getattr(self.gateway, method)(*args, **kwargs) + return result if isinstance(result, WorldResult) else WorldResult(True, data=result) + except Exception as exc: + return WorldResult(False, reason=f"world_gateway_error:{type(exc).__name__}") + + def publish_activity(self, activity: dict[str, Any]) -> WorldResult: + return self._call("publish_activity", activity) + + def get_world_context(self, subject_id: str, now: datetime) -> WorldResult: + return self._call("get_world_context", subject_id, now) + + def get_schedule_projection(self, subject_id: str, date: str) -> WorldResult: + return self._call("get_schedule_projection", subject_id, date) + + def confirm_shared_activity(self, candidate: dict[str, Any]) -> WorldResult: + return self._call("confirm_shared_activity", candidate) + + def revoke_projection(self, ref: str) -> WorldResult: + return self._call("revoke_projection", ref) +def projection_is_fresh(projection: dict[str, Any], now: datetime) -> bool: + if not isinstance(projection, dict): + return False + fresh_until = str(projection.get("fresh_until") or "").strip() + if not fresh_until: + return False + try: + current = now if now.tzinfo is not None else now.astimezone() + expiry = datetime.fromisoformat(fresh_until.replace("Z", "+00:00")) + if expiry.tzinfo is None: + expiry = expiry.replace(tzinfo=current.tzinfo) + return current <= expiry + except (TypeError, ValueError): + return False \ No newline at end of file