# -*- coding: utf-8 -*- """Persistent P1 lifecycle service for companion-owned unified people. All mutating operations are copy-on-write under one process-local lock. This keeps JSON-store updates atomic from the plugin's perspective and makes an operation ID safe to retry after a caller timeout. """ from __future__ import annotations from copy import deepcopy from datetime import datetime, timezone import hashlib import json import threading from typing import Any try: from .unified_person_contract import ( build_identity_key, canonical_identity, ensure_unified_person_store, person_id_for_identity, ) except ImportError: from unified_person_contract import ( build_identity_key, canonical_identity, ensure_unified_person_store, person_id_for_identity, ) REGISTRY_VERSION = 1 _REGISTRY_LOCK = threading.RLock() _MAX_AUDIT_EVENTS = 1000 def _now() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds") def _canonical(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) def _result(ok: bool, code: str, **fields: Any) -> dict[str, Any]: result = { "ok": ok, "code": code, "operation_id": "", "changed": False, "person_id": "", "affected_person_ids": [], "projection_revision": 0, "audit_event_id": "", } result.update(fields) return result def _identifier(value: Any, field: str, limit: int = 160) -> str: if not isinstance(value, str): raise ValueError(f"{field} invalid") text = value.strip() if not text or "\x00" in text or len(text) > limit: raise ValueError(f"{field} invalid") return text def _observed_names(value: Any) -> list[str]: if value is None: return [] if not isinstance(value, list): raise ValueError("aliases invalid") names: list[str] = [] for item in value: if not isinstance(item, str): raise ValueError("aliases invalid") text = item.strip() if not text or "\x00" in text or len(text) > 120: raise ValueError("aliases invalid") if text not in names: names.append(text) return names def _revision(profile: dict[str, Any], now: str, operation_id: str) -> None: try: previous = int(profile.get("projection_revision") or 0) except (TypeError, ValueError): previous = 0 profile["projection_revision"] = max(1, previous + 1) profile["updated_at"] = now profile["last_operation_id"] = operation_id def _append_audit(root: dict[str, Any], *, operation_id: str, action: str, actor_id: str, code: str, now: str, details: dict[str, Any]) -> None: events = root.setdefault("audit_events", []) if not isinstance(events, list): events = [] root["audit_events"] = events events.append({ "event_id": operation_id, "action": action, "actor_id": actor_id, "code": code, "occurred_at": now, "details": deepcopy(details), }) if len(events) > _MAX_AUDIT_EVENTS: del events[:-_MAX_AUDIT_EVENTS] def _operation_result(root: dict[str, Any], operation_id: str, action: str, payload: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: operations = root.setdefault("operations", {}) if not isinstance(operations, dict): operations = {} root["operations"] = operations fingerprint = hashlib.sha256(_canonical({"action": action, "payload": payload}).encode("utf-8")).hexdigest() existing = operations.get(operation_id) if not isinstance(existing, dict): return None, {"fingerprint": fingerprint} if existing.get("fingerprint") != fingerprint: return _result(False, "operation_id_conflict", operation_id=operation_id), None result = deepcopy(existing.get("result") or {}) result["idempotent"] = True return result, None def _record_operation(root: dict[str, Any], *, operation_id: str, action: str, payload: dict[str, Any], metadata: dict[str, Any], result: dict[str, Any], now: str) -> None: result["operation_id"] = operation_id result.setdefault("affected_person_ids", [result["person_id"]] if result.get("person_id") else []) root["operations"][operation_id] = { "operation_id": operation_id, "action": action, "fingerprint": hashlib.sha256(_canonical({"action": action, "payload": payload}).encode("utf-8")).hexdigest(), "metadata": deepcopy(metadata), "result": deepcopy(result), "created_at": now, } def _ensure_registry(root: dict[str, Any]) -> None: root.setdefault("registry_version", REGISTRY_VERSION) root.setdefault("audit_events", []) root.setdefault("operations", {}) root.setdefault("merge_operations", {}) class UnifiedPersonRegistry: """Companion-only lifecycle authority. No consumer receives a write method.""" def __init__(self, store: dict[str, Any]) -> None: if not isinstance(store, dict): raise ValueError("store must be an object") self._store = store def _root_copy(self) -> dict[str, Any]: ensure_unified_person_store(self._store) root = self._store["unified_person"] work = deepcopy(root) _ensure_registry(work) return work def _commit(self, root: dict[str, Any]) -> None: self._store["unified_person"] = root def status(self) -> dict[str, Any]: with _REGISTRY_LOCK: root = self._root_copy() return { "registry_version": int(root.get("registry_version") or REGISTRY_VERSION), "profiles": len(root.get("profiles") or {}), "identity_links": len(root.get("identity_links") or {}), "audit_events": len(root.get("audit_events") or []), "operations": len(root.get("operations") or {}), } def audit_events(self, *, limit: int = 100) -> list[dict[str, Any]]: with _REGISTRY_LOCK: root = self._root_copy() events = root.get("audit_events") if isinstance(root.get("audit_events"), list) else [] return deepcopy(events[-max(1, min(int(limit), _MAX_AUDIT_EVENTS)):]) def upsert_observed_identity( self, identity: dict[str, Any], *, operation_id: str, display_name: str = "", aliases: list[str] | None = None, observed_at: str = "", ) -> dict[str, Any]: """Create one profile/link for one observed complete identity, never merge it.""" try: operation_id = _identifier(operation_id, "operation_id", 120) normalized = canonical_identity(identity) identity_key = build_identity_key(normalized) alias_values = _observed_names(aliases) name = _identifier(display_name, "display_name", 160) if display_name else normalized["platform_subject_id"] except ValueError: return _result(False, "invalid_identity") payload = {"identity_key": identity_key, "display_name": name, "aliases": alias_values} with _REGISTRY_LOCK: root = self._root_copy() repeated, fresh = _operation_result(root, operation_id, "upsert_observed_identity", payload) if repeated is not None: return repeated links = root["identity_links"] profiles = root["profiles"] existing = links.get(identity_key) now = observed_at or _now() if isinstance(existing, dict) and existing.get("status") == "active": person_id = str(existing.get("person_id") or "") profile = profiles.get(person_id) if not isinstance(profile, dict): return _result(False, "identity_link_conflict", operation_id=operation_id, identity_key=identity_key) result = _result(True, "identity_observed", person_id=person_id, identity_key=identity_key, created=False) _record_operation(root, operation_id=operation_id, action="upsert_observed_identity", payload=payload, metadata={}, result=result, now=now) self._commit(root) return result person_id = person_id_for_identity(normalized) if person_id in profiles: return _result(False, "person_id_conflict", operation_id=operation_id, person_id=person_id) profiles[person_id] = { "person_id": person_id, "resolved_identity_key": identity_key, "identity_keys": [identity_key], "identity_assurance": "observed", "profile_status": "active", "display_name": name, "aliases": alias_values, "relation_policy_id": "default_friend", "owner_mode": "not_owner", "affinity_score": 0, "warning_stage": "none", "confinement_state": "none", "confinement_until": "", "release_prompt_pending": False, "proactive_private_enabled": False, "group_overlay_ref": "", "projection_revision": 1, "created_at": now, "updated_at": now, "last_operation_id": operation_id, } history = deepcopy(existing.get("link_history") or []) if isinstance(existing, dict) else [] history.append({"action": "observed", "person_id": person_id, "at": now, "operation_id": operation_id}) links[identity_key] = { "identity_key": identity_key, "origin_identity_key": identity_key, "identity": normalized, "person_id": person_id, "identity_assurance": "observed", "status": "active", "created_at": now, "updated_at": now, "last_operation_id": operation_id, "link_history": history, } result = _result(True, "person_created", person_id=person_id, identity_key=identity_key, created=True, changed=True, affected_person_ids=[person_id], projection_revision=1, audit_event_id=operation_id) _append_audit(root, operation_id=operation_id, action="observed_upsert", actor_id="system", code=result["code"], now=now, details={"person_id": person_id, "identity_key": identity_key}) _record_operation(root, operation_id=operation_id, action="upsert_observed_identity", payload=payload, metadata={}, result=result, now=now) self._commit(root) return result def link_identity( self, identity: dict[str, Any], person_id: str, *, operation_id: str, actor_id: str, reason: str, authorized: bool, owner_authorized: bool = False, ) -> dict[str, Any]: """Explicitly bind an unlinked identity to an existing person; never auto-merge.""" try: operation_id = _identifier(operation_id, "operation_id", 120) actor_id = _identifier(actor_id, "actor_id", 160) reason = _identifier(reason, "reason", 400) person_id = _identifier(person_id, "person_id") normalized = canonical_identity(identity) identity_key = build_identity_key(normalized) except ValueError: return _result(False, "invalid_request") if not authorized: return _result(False, "unauthorized", operation_id=operation_id) payload = {"identity_key": identity_key, "person_id": person_id, "actor_id": actor_id, "reason": reason, "owner_authorized": bool(owner_authorized)} with _REGISTRY_LOCK: root = self._root_copy() repeated, fresh = _operation_result(root, operation_id, "link_identity", payload) if repeated is not None: return repeated profiles, links = root["profiles"], root["identity_links"] profile = profiles.get(person_id) if not isinstance(profile, dict) or profile.get("profile_status") != "active": return _result(False, "person_not_found", operation_id=operation_id, person_id=person_id) if profile.get("owner_mode") == "owner" and not owner_authorized: return _result(False, "owner_authorization_required", operation_id=operation_id, person_id=person_id) previous = links.get(identity_key) if isinstance(previous, dict) and previous.get("status") == "active": if previous.get("person_id") == person_id: result = _result(True, "identity_linked", person_id=person_id, identity_key=identity_key, linked=False) _record_operation(root, operation_id=operation_id, action="link_identity", payload=payload, metadata={}, result=result, now=_now()) self._commit(root) return result return _result(False, "identity_already_linked", operation_id=operation_id, identity_key=identity_key, person_id=str(previous.get("person_id") or "")) now = _now() before_profile = deepcopy(profile) history = deepcopy(previous.get("link_history") or []) if isinstance(previous, dict) else [] history.append({"action": "explicit_link", "person_id": person_id, "at": now, "operation_id": operation_id}) links[identity_key] = { "identity_key": identity_key, "origin_identity_key": identity_key, "identity": normalized, "person_id": person_id, "identity_assurance": "explicit_linked", "status": "active", "created_at": str(previous.get("created_at") or now) if isinstance(previous, dict) else now, "updated_at": now, "last_operation_id": operation_id, "link_history": history, } keys = profile.setdefault("identity_keys", []) if identity_key not in keys: keys.append(identity_key) _revision(profile, now, operation_id) result = _result(True, "identity_linked", person_id=person_id, identity_key=identity_key, linked=True, changed=True, affected_person_ids=[person_id], projection_revision=profile["projection_revision"], audit_event_id=operation_id) _append_audit(root, operation_id=operation_id, action="explicit_link", actor_id=actor_id, code=result["code"], now=now, details={"person_id": person_id, "identity_key": identity_key, "reason": reason, "owner_authorized": bool(owner_authorized)}) _record_operation(root, operation_id=operation_id, action="link_identity", payload=payload, metadata={"before_link": deepcopy(previous), "before_profile": before_profile}, result=result, now=now) self._commit(root) return result def unlink_identity(self, identity: dict[str, Any], *, operation_id: str, actor_id: str, reason: str, authorized: bool, owner_authorized: bool = False) -> dict[str, Any]: try: operation_id = _identifier(operation_id, "operation_id", 120) actor_id = _identifier(actor_id, "actor_id", 160) reason = _identifier(reason, "reason", 400) normalized = canonical_identity(identity) identity_key = build_identity_key(normalized) except ValueError: return _result(False, "invalid_request") if not authorized: return _result(False, "unauthorized", operation_id=operation_id) payload = {"identity_key": identity_key, "actor_id": actor_id, "reason": reason, "owner_authorized": bool(owner_authorized)} with _REGISTRY_LOCK: root = self._root_copy() repeated, fresh = _operation_result(root, operation_id, "unlink_identity", payload) if repeated is not None: return repeated link = root["identity_links"].get(identity_key) if not isinstance(link, dict): return _result(False, "identity_not_found", operation_id=operation_id, identity_key=identity_key) if link.get("status") != "active": result = _result(True, "identity_unlinked", identity_key=identity_key, person_id="", unlinked=False) _record_operation(root, operation_id=operation_id, action="unlink_identity", payload=payload, metadata={}, result=result, now=_now()) self._commit(root) return result person_id = str(link.get("person_id") or "") profile = root["profiles"].get(person_id) if not isinstance(profile, dict): return _result(False, "identity_link_conflict", operation_id=operation_id, identity_key=identity_key) if profile.get("owner_mode") == "owner" and not owner_authorized: return _result(False, "owner_authorization_required", operation_id=operation_id, person_id=person_id) active_keys = sorted( key for key, candidate in root["identity_links"].items() if isinstance(candidate, dict) and candidate.get("status") == "active" and candidate.get("person_id") == person_id ) if len(active_keys) <= 1: return _result(False, "last_identity_required", operation_id=operation_id, person_id=person_id) now = _now() before_link, before_profile = deepcopy(link), deepcopy(profile) history = link.setdefault("link_history", []) history.append({"action": "explicit_unlink", "person_id": person_id, "at": now, "operation_id": operation_id}) link.update({"status": "unlinked", "person_id": "", "previous_person_id": person_id, "updated_at": now, "last_operation_id": operation_id}) profile["identity_keys"] = [item for item in profile.get("identity_keys", []) if item != identity_key] if profile.get("resolved_identity_key") == identity_key: replacement_key = next(key for key in active_keys if key != identity_key) replacement_link = root["identity_links"][replacement_key] profile["resolved_identity_key"] = replacement_key profile["identity_assurance"] = replacement_link.get("identity_assurance") or "observed" _revision(profile, now, operation_id) result = _result(True, "identity_unlinked", identity_key=identity_key, person_id=person_id, unlinked=True, changed=True, affected_person_ids=[person_id], projection_revision=profile["projection_revision"], audit_event_id=operation_id) _append_audit(root, operation_id=operation_id, action="explicit_unlink", actor_id=actor_id, code=result["code"], now=now, details={"person_id": person_id, "identity_key": identity_key, "reason": reason, "owner_authorized": bool(owner_authorized)}) _record_operation(root, operation_id=operation_id, action="unlink_identity", payload=payload, metadata={"before_link": before_link, "before_profile": before_profile}, result=result, now=now) self._commit(root) return result def merge_people(self, source_person_id: str, target_person_id: str, *, operation_id: str, actor_id: str, reason: str, authorized: bool, owner_authorized: bool = False) -> dict[str, Any]: try: operation_id = _identifier(operation_id, "operation_id", 120) actor_id = _identifier(actor_id, "actor_id", 160) reason = _identifier(reason, "reason", 400) source_person_id = _identifier(source_person_id, "source_person_id") target_person_id = _identifier(target_person_id, "target_person_id") except ValueError: return _result(False, "invalid_request") if not authorized: return _result(False, "unauthorized", operation_id=operation_id) if source_person_id == target_person_id: return _result(False, "merge_same_person", operation_id=operation_id) payload = {"source_person_id": source_person_id, "target_person_id": target_person_id, "actor_id": actor_id, "reason": reason, "owner_authorized": bool(owner_authorized)} with _REGISTRY_LOCK: root = self._root_copy() repeated, fresh = _operation_result(root, operation_id, "merge_people", payload) if repeated is not None: return repeated profiles, links = root["profiles"], root["identity_links"] source, target = profiles.get(source_person_id), profiles.get(target_person_id) if not isinstance(source, dict) or not isinstance(target, dict): return _result(False, "person_not_found", operation_id=operation_id) if source.get("profile_status") != "active" or target.get("profile_status") != "active": return _result(False, "person_not_active", operation_id=operation_id) if (source.get("owner_mode") == "owner" or target.get("owner_mode") == "owner") and not owner_authorized: return _result(False, "owner_authorization_required", operation_id=operation_id) now = _now() source_revision = int(source.get("projection_revision") or 0) target_revision = int(target.get("projection_revision") or 0) merge_revision = max(source_revision, target_revision) + 1 moved_keys = sorted(key for key, link in links.items() if isinstance(link, dict) and link.get("status") == "active" and link.get("person_id") == source_person_id) before_links = {key: deepcopy(links[key]) for key in moved_keys} before_overlays = {key: deepcopy(value) for key, value in root.get("group_overlays", {}).items() if isinstance(value, dict) and value.get("person_id") == source_person_id} merged_aliases = [ alias for alias in source.get("aliases", []) if isinstance(alias, str) and alias not in target.get("aliases", []) ] snapshot = { "source_profile": deepcopy(source), "target_profile": deepcopy(target), "links": before_links, "overlays": before_overlays, "merged_aliases": merged_aliases, } for key in moved_keys: link = links[key] link.update({"person_id": target_person_id, "previous_person_id": source_person_id, "merge_operation_id": operation_id, "updated_at": now, "last_operation_id": operation_id}) link.setdefault("link_history", []).append({"action": "merge", "person_id": target_person_id, "at": now, "operation_id": operation_id}) target_keys = target.setdefault("identity_keys", []) for key in moved_keys: if key not in target_keys: target_keys.append(key) for alias in merged_aliases: if alias not in target.setdefault("aliases", []): target["aliases"].append(alias) source["identity_keys"] = [] source["profile_status"] = "suspended" source["merged_into_person_id"] = target_person_id source["merge_operation_id"] = operation_id for changed_profile in (source, target): changed_profile["projection_revision"] = merge_revision changed_profile["updated_at"] = now changed_profile["last_operation_id"] = operation_id for overlay in root.get("group_overlays", {}).values(): if isinstance(overlay, dict) and overlay.get("person_id") == source_person_id: overlay["person_id"] = target_person_id overlay["origin_person_id"] = source_person_id overlay["merge_operation_id"] = operation_id root["merge_operations"][operation_id] = { "operation_id": operation_id, "state": "active", "source_person_id": source_person_id, "target_person_id": target_person_id, "merge_revision": merge_revision, "snapshot": snapshot, "created_at": now, } result = _result(True, "people_merged", person_id=target_person_id, source_person_id=source_person_id, target_person_id=target_person_id, moved_identity_keys=moved_keys, changed=True, affected_person_ids=[source_person_id, target_person_id], projection_revision=target["projection_revision"], audit_event_id=operation_id) _append_audit(root, operation_id=operation_id, action="explicit_merge", actor_id=actor_id, code=result["code"], now=now, details={"source_person_id": source_person_id, "target_person_id": target_person_id, "reason": reason, "moved_identity_keys": moved_keys}) _record_operation(root, operation_id=operation_id, action="merge_people", payload=payload, metadata={}, result=result, now=now) self._commit(root) return result def split_merged_people(self, merge_operation_id: str, *, operation_id: str, actor_id: str, reason: str, authorized: bool, owner_authorized: bool = False) -> dict[str, Any]: try: merge_operation_id = _identifier(merge_operation_id, "merge_operation_id", 120) operation_id = _identifier(operation_id, "operation_id", 120) actor_id = _identifier(actor_id, "actor_id", 160) reason = _identifier(reason, "reason", 400) except ValueError: return _result(False, "invalid_request") if not authorized: return _result(False, "unauthorized", operation_id=operation_id) payload = {"merge_operation_id": merge_operation_id, "actor_id": actor_id, "reason": reason, "owner_authorized": bool(owner_authorized)} with _REGISTRY_LOCK: root = self._root_copy() repeated, fresh = _operation_result(root, operation_id, "split_merged_people", payload) if repeated is not None: return repeated merge = root["merge_operations"].get(merge_operation_id) if not isinstance(merge, dict): return _result(False, "merge_operation_not_found", operation_id=operation_id) if merge.get("state") != "active": return _result(False, "merge_operation_not_active", operation_id=operation_id) source_id, target_id = str(merge.get("source_person_id") or ""), str(merge.get("target_person_id") or "") snapshot = merge.get("snapshot") if isinstance(merge.get("snapshot"), dict) else {} moved_links = snapshot.get("links") if isinstance(snapshot.get("links"), dict) else {} links = root["identity_links"] if any( not isinstance(links.get(key), dict) or links[key].get("status") != "active" or links[key].get("person_id") != target_id or links[key].get("last_operation_id") != merge_operation_id for key in moved_links ): return _result(False, "split_conflict", operation_id=operation_id) source, target = root["profiles"].get(source_id), root["profiles"].get(target_id) if not isinstance(source, dict) or not isinstance(target, dict) or source.get("last_operation_id") != merge_operation_id: return _result(False, "split_conflict", operation_id=operation_id) if (source.get("owner_mode") == "owner" or target.get("owner_mode") == "owner") and not owner_authorized: return _result(False, "owner_authorization_required", operation_id=operation_id) overlays = root.setdefault("group_overlays", {}) before_overlays = snapshot.get("overlays") if isinstance(snapshot.get("overlays"), dict) else {} if any( not isinstance(overlays.get(key), dict) or overlays[key].get("person_id") != target_id or overlays[key].get("origin_person_id") != source_id or overlays[key].get("merge_operation_id") != merge_operation_id for key in before_overlays ): return _result(False, "split_conflict", operation_id=operation_id) replacement_key = "" if target.get("resolved_identity_key") in moved_links: remaining_keys = sorted( key for key, link in links.items() if isinstance(link, dict) and link.get("status") == "active" and link.get("person_id") == target_id and key not in moved_links ) if not remaining_keys: return _result(False, "split_conflict", operation_id=operation_id) replacement_key = remaining_keys[0] now = _now() source_revision = int(source.get("projection_revision") or 0) target_revision = int(target.get("projection_revision") or 0) snapshot_source = snapshot.get("source_profile") if isinstance(snapshot.get("source_profile"), dict) else {} snapshot_target = snapshot.get("target_profile") if isinstance(snapshot.get("target_profile"), dict) else {} recorded_merge_revision = int(merge.get("merge_revision") or 0) if recorded_merge_revision <= 0: recorded_merge_revision = max( int(snapshot_source.get("projection_revision") or 0), int(snapshot_target.get("projection_revision") or 0), ) + 1 split_revision = max(source_revision, target_revision, recorded_merge_revision) + 1 root["profiles"][source_id] = deepcopy(snapshot["source_profile"]) restored_source = root["profiles"][source_id] restored_source["projection_revision"] = split_revision restored_source["updated_at"] = now restored_source["last_operation_id"] = operation_id target_keys = target.get("identity_keys") if isinstance(target.get("identity_keys"), list) else [] target["identity_keys"] = [key for key in target_keys if key not in moved_links] merged_aliases = snapshot.get("merged_aliases") if not isinstance(merged_aliases, list): source_aliases = snapshot_source.get("aliases") if isinstance(snapshot_source.get("aliases"), list) else [] target_aliases_before_merge = snapshot_target.get("aliases") if isinstance(snapshot_target.get("aliases"), list) else [] merged_aliases = [alias for alias in source_aliases if isinstance(alias, str) and alias not in target_aliases_before_merge] target_aliases = target.get("aliases") if isinstance(target.get("aliases"), list) else [] target["aliases"] = [alias for alias in target_aliases if alias not in merged_aliases] if replacement_key: target["resolved_identity_key"] = replacement_key target["projection_revision"] = split_revision target["updated_at"] = now target["last_operation_id"] = operation_id for key, link in moved_links.items(): restored_link = deepcopy(link) restored_link["last_operation_id"] = operation_id restored_link["updated_at"] = now restored_link.setdefault("link_history", []).append({"action": "split", "person_id": source_id, "at": now, "operation_id": operation_id}) links[key] = restored_link for key, overlay_before_merge in before_overlays.items(): # Only this merge's ownership/provenance fields are reversible. # Group policy fields may have been independently updated after merge. overlay = overlays[key] overlay["person_id"] = overlay_before_merge["person_id"] for field in ("origin_person_id", "merge_operation_id"): if field in overlay_before_merge: overlay[field] = deepcopy(overlay_before_merge[field]) else: overlay.pop(field, None) merge["state"] = "reversed" merge["reversed_at"] = now merge["split_operation_id"] = operation_id result = _result(True, "people_split", person_id=source_id, source_person_id=source_id, target_person_id=target_id, merge_operation_id=merge_operation_id, changed=True, affected_person_ids=[source_id, target_id], projection_revision=root["profiles"][source_id]["projection_revision"], audit_event_id=operation_id) _append_audit(root, operation_id=operation_id, action="explicit_split", actor_id=actor_id, code=result["code"], now=now, details={"merge_operation_id": merge_operation_id, "reason": reason}) _record_operation(root, operation_id=operation_id, action="split_merged_people", payload=payload, metadata={}, result=result, now=now) self._commit(root) return result