# -*- 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), }