# -*- 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, ) from .p4_affinity_confinement import ( new_shadow_state, replay_shadow_events, settle_shadow_event, ) from .p4_manual_review import ( P4_REVIEW_ALLOWED_ASSURANCES, ensure_review_container, normalize_decision_request, normalize_review_candidate, queue_candidate, queue_decision, validate_review_operation_replay, runtime_owner_identity, runtime_scope_identity, consume_p4_review_producer_attestation, ) except ImportError: from unified_person_contract import ( build_identity_key, canonical_identity, ensure_unified_person_store, person_id_for_identity, ) from p4_affinity_confinement import ( new_shadow_state, replay_shadow_events, settle_shadow_event, ) from p4_manual_review import ( P4_REVIEW_ALLOWED_ASSURANCES, ensure_review_container, normalize_decision_request, normalize_review_candidate, queue_candidate, queue_decision, validate_review_operation_replay, runtime_owner_identity, runtime_scope_identity, consume_p4_review_producer_attestation, ) REGISTRY_VERSION = 1 _REGISTRY_LOCK = threading.RLock() _MAX_AUDIT_EVENTS = 1000 _P4_SHADOW_VERSION = 1 _P4_EFFECT_VERSION = 1 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", {}) def _p4_shadow_container(root: dict[str, Any]) -> dict[str, Any]: """Return the additive, companion-only P4-A persistence container.""" container = root.get("p4_shadow") if not isinstance(container, dict): container = {} root["p4_shadow"] = container if not isinstance(container.get("version"), int): container["version"] = _P4_SHADOW_VERSION people = container.get("people") if not isinstance(people, dict): container["people"] = {} return container def _p4_shadow_event_fingerprint(person_id: str, event: dict[str, Any]) -> str: return hashlib.sha256(_canonical({"person_id": person_id, "event": event}).encode("utf-8")).hexdigest() def _normalize_p4_shadow_event(event: Any) -> tuple[dict[str, Any] | None, list[str]]: """Let the pure engine sanitize one event before it reaches persistence.""" result = settle_shadow_event(new_shadow_state(), deepcopy(event)) state = result.get("state") if isinstance(result, dict) else None event_id = str(result.get("event_id") or "") if isinstance(result, dict) else "" log = state.get("event_log") if isinstance(state, dict) else None if not event_id or not isinstance(log, list): details = result.get("details") if isinstance(result, dict) and isinstance(result.get("details"), dict) else {} codes = details.get("codes") if isinstance(details.get("codes"), list) else ["invalid_p4_shadow_event"] return None, [str(item) for item in codes] for item in log: if isinstance(item, dict) and item.get("event_id") == event_id: return deepcopy(item), [] return None, ["invalid_p4_shadow_event"] def _new_p4_shadow_person_entry(person_id: str, now: str) -> dict[str, Any]: state = new_shadow_state() return { "person_id": person_id, "origin_person_id": person_id, "state": state, # This is an append-only, engine-sanitized ledger. It must remain # replayable for a future owner misjudgment event, so the registry never # truncates it independently of the deterministic engine. "events": [], "created_at": now, "updated_at": now, "last_operation_id": "", } def _replay_p4_shadow_entry(entry: Any, person_id: str) -> tuple[dict[str, Any] | None, dict[str, dict[str, Any]] | None, str]: """Fail closed if a persisted P4 entry loses its identity or replay proof.""" if not isinstance(entry, dict): return None, None, "p4_shadow_corrupt" if entry.get("person_id") != person_id or entry.get("origin_person_id") != person_id: return None, None, "p4_shadow_person_conflict" envelopes = entry.get("events") if not isinstance(envelopes, list): return None, None, "p4_shadow_corrupt" events: list[dict[str, Any]] = [] event_index: dict[str, dict[str, Any]] = {} for envelope in envelopes: if not isinstance(envelope, dict): return None, None, "p4_shadow_corrupt" if envelope.get("person_id") != person_id or envelope.get("origin_person_id") != person_id: return None, None, "p4_shadow_person_conflict" event = envelope.get("event") event_id = envelope.get("event_id") if not isinstance(event, dict) or not isinstance(event_id, str) or event.get("event_id") != event_id or event_id in event_index: return None, None, "p4_shadow_corrupt" fingerprint = envelope.get("event_fingerprint") if not isinstance(fingerprint, str) or fingerprint != _p4_shadow_event_fingerprint(person_id, event): return None, None, "p4_shadow_corrupt" event_index[event_id] = envelope events.append(event) replay = replay_shadow_events(events) state = replay.get("state") if isinstance(replay, dict) else None if not isinstance(state, dict): return None, None, "p4_shadow_corrupt" # The persisted state is only a cached replay result. A mismatch must not # silently change a later safety decision. if entry.get("state") != state: return None, None, "p4_shadow_state_mismatch" return deepcopy(state), event_index, "" def _p4_shadow_summary(state: dict[str, Any]) -> dict[str, Any]: return { "mode": str(state.get("mode") or "shadow"), "policy_version": str(state.get("policy_version") or ""), "score": int(state.get("score") or 0), "warning_stage": str(state.get("warning_stage") or "none"), "confinement_state": str(state.get("confinement_state") or "none"), "confinement_round": int(state.get("confinement_round") or 0), "release_prompt_pending": bool(state.get("release_prompt_pending")), } def _p4_effect_container(root: dict[str, Any]) -> dict[str, Any]: """Return the P4-B preparation ledger, never the P4-A shadow ledger.""" container = root.get("p4_effect") if not isinstance(container, dict): container = {} root["p4_effect"] = container if not isinstance(container.get("version"), int): container["version"] = _P4_EFFECT_VERSION if not isinstance(container.get("people"), dict): container["people"] = {} return container def _p4_effect_fingerprint(origin_person_id: str, event: dict[str, Any]) -> str: return hashlib.sha256(_canonical({"origin_person_id": origin_person_id, "event": event}).encode("utf-8")).hexdigest() def _p4_effect_state(events: list[dict[str, Any]]) -> dict[str, Any] | None: replay = replay_shadow_events(events) state = replay.get("state") if isinstance(replay, dict) else None if not isinstance(state, dict): return None state = deepcopy(state) state["mode"] = "effect_preparation" return state def _new_p4_effect_person_entry(person_id: str, now: str) -> dict[str, Any]: state = new_shadow_state() state["mode"] = "effect_preparation" return { "person_id": person_id, "state": state, "events": [], "created_at": now, "updated_at": now, "last_operation_id": "", } def _replay_p4_effect_entry(entry: Any, person_id: str) -> tuple[dict[str, Any] | None, dict[str, dict[str, Any]] | None, str]: """Validate an effect-preparation entry; origin survives a person merge.""" if not isinstance(entry, dict) or entry.get("person_id") != person_id: return None, None, "p4_effect_person_conflict" envelopes = entry.get("events") if not isinstance(envelopes, list): return None, None, "p4_effect_corrupt" event_index: dict[str, dict[str, Any]] = {} events: list[dict[str, Any]] = [] for envelope in envelopes: if not isinstance(envelope, dict) or envelope.get("person_id") != person_id: return None, None, "p4_effect_corrupt" origin = envelope.get("origin_person_id") event = envelope.get("event") event_id = envelope.get("event_id") if not isinstance(origin, str) or not origin or not isinstance(event, dict) or not isinstance(event_id, str): return None, None, "p4_effect_corrupt" if event.get("event_id") != event_id or event_id in event_index: return None, None, "p4_effect_corrupt" if envelope.get("event_fingerprint") != _p4_effect_fingerprint(origin, event): return None, None, "p4_effect_corrupt" event_index[event_id] = envelope events.append(event) state = _p4_effect_state(events) if not isinstance(state, dict) or entry.get("state") != state: return None, None, "p4_effect_state_mismatch" return state, event_index, "" def _p4_effect_summary(state: dict[str, Any]) -> dict[str, Any]: return _p4_shadow_summary(state) def _merge_p4_effect_people(root: dict[str, Any], source_person_id: str, target_person_id: str, operation_id: str, now: str) -> dict[str, Any] | None: """Merge preparation records without changing P4-A or profile fields.""" container = root.get("p4_effect") if not isinstance(container, dict) or not isinstance(container.get("people"), dict): return None people = container["people"] source_before = deepcopy(people.get(source_person_id)) target_before = deepcopy(people.get(target_person_id)) for entry, person_id in ((source_before, source_person_id), (target_before, target_person_id)): if entry is not None: _state, _index, error = _replay_p4_effect_entry(entry, person_id) if error: raise ValueError(error) envelopes: list[dict[str, Any]] = [] seen: dict[str, str] = {} for entry in (target_before, source_before): if not isinstance(entry, dict): continue for envelope in entry.get("events", []): event_id = str(envelope.get("event_id") or "") if isinstance(envelope, dict) else "" fingerprint = str(envelope.get("event_fingerprint") or "") if isinstance(envelope, dict) else "" if not event_id or not fingerprint: raise ValueError("p4_effect_corrupt") previous = seen.get(event_id) if previous is not None: if previous != fingerprint: raise ValueError("p4_effect_event_id_conflict") continue seen[event_id] = fingerprint moved = deepcopy(envelope) moved["person_id"] = target_person_id envelopes.append(moved) snapshot = {"source": source_before, "target": target_before} if not envelopes: return snapshot state = _p4_effect_state([item["event"] for item in envelopes]) if not isinstance(state, dict): raise ValueError("p4_effect_replay_failed") people[target_person_id] = { "person_id": target_person_id, "state": state, "events": envelopes, "created_at": str((target_before or source_before or {}).get("created_at") or now), "updated_at": now, "last_operation_id": operation_id, } people.pop(source_person_id, None) return snapshot def _restore_p4_effect_after_split(root: dict[str, Any], merge: dict[str, Any], source_person_id: str, target_person_id: str, merge_operation_id: str) -> str: """Restore the exact pre-merge ledger or reject post-merge mutations.""" if "p4_effect_snapshot" not in merge: return "" snapshot = merge.get("p4_effect_snapshot") if not isinstance(snapshot, dict): return "p4_effect_split_conflict" container = root.get("p4_effect") if not isinstance(container, dict) or not isinstance(container.get("people"), dict): return "p4_effect_split_conflict" people = container["people"] current_source = people.get(source_person_id) current_target = people.get(target_person_id) if current_source is not None: return "p4_effect_split_conflict" if current_target is not None: if not isinstance(current_target, dict) or current_target.get("last_operation_id") != merge_operation_id: return "p4_effect_split_conflict" _state, _index, error = _replay_p4_effect_entry(current_target, target_person_id) if error: return error for person_id, key in ((source_person_id, "source"), (target_person_id, "target")): previous = snapshot.get(key) if previous is None: people.pop(person_id, None) elif isinstance(previous, dict): people[person_id] = deepcopy(previous) else: return "p4_effect_split_conflict" return "" 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 read_p4_shadow_state(self, person_id: str) -> dict[str, Any]: """Read one active person's non-projecting P4-A shadow state.""" try: person_id = _identifier(person_id, "person_id") except ValueError: return _result(False, "invalid_request") with _REGISTRY_LOCK: root = self._root_copy() profile = root["profiles"].get(person_id) if not isinstance(profile, dict): return _result(False, "person_not_found", person_id=person_id) if profile.get("person_id") != person_id: return _result(False, "person_profile_conflict", person_id=person_id) if profile.get("profile_status") != "active": return _result(False, "person_not_active", person_id=person_id) container = root.get("p4_shadow") people = container.get("people") if isinstance(container, dict) and isinstance(container.get("people"), dict) else {} entry = people.get(person_id) if entry is None: state = new_shadow_state() return _result( True, "p4_shadow_state", person_id=person_id, origin_person_id=person_id, p4_shadow_exists=False, p4_shadow_state=state, p4_shadow_summary=_p4_shadow_summary(state), event_count=0, ) state, event_index, error = _replay_p4_shadow_entry(entry, person_id) if error: return _result(False, error, person_id=person_id) assert state is not None and event_index is not None return _result( True, "p4_shadow_state", person_id=person_id, origin_person_id=person_id, p4_shadow_exists=True, p4_shadow_state=state, p4_shadow_summary=_p4_shadow_summary(state), event_count=len(event_index), ) def record_p4_shadow_event( self, person_id: str, event: dict[str, Any], *, operation_id: str, actor_id: str = "system", ) -> dict[str, Any]: """Persist one engine-sanitized P4-A event without changing a profile. The profile and P0/P2 projection deliberately remain untouched. The resulting state is a replayable shadow ledger under ``p4_shadow`` only. """ try: operation_id = _identifier(operation_id, "operation_id", 120) person_id = _identifier(person_id, "person_id") actor_id = _identifier(actor_id, "actor_id", 160) except ValueError: return _result(False, "invalid_request") if not isinstance(event, dict): return _result(False, "invalid_p4_shadow_event", operation_id=operation_id, person_id=person_id) for field in ("person_id", "origin_person_id"): claimed = event.get(field) if claimed not in (None, "", person_id): return _result(False, "p4_shadow_person_mismatch", operation_id=operation_id, person_id=person_id) normalized_event, event_errors = _normalize_p4_shadow_event(event) if normalized_event is None: return _result( False, "invalid_p4_shadow_event", operation_id=operation_id, person_id=person_id, event_errors=event_errors, ) event_id = str(normalized_event["event_id"]) payload = { "person_id": person_id, "actor_id": actor_id, "event": normalized_event, } with _REGISTRY_LOCK: root = self._root_copy() repeated, fresh = _operation_result(root, operation_id, "record_p4_shadow_event", payload) if repeated is not None: return repeated profile = root["profiles"].get(person_id) if not isinstance(profile, dict): return _result(False, "person_not_found", operation_id=operation_id, person_id=person_id) if profile.get("person_id") != person_id: return _result(False, "person_profile_conflict", operation_id=operation_id, person_id=person_id) if profile.get("profile_status") != "active": return _result(False, "person_not_active", operation_id=operation_id, person_id=person_id) container = _p4_shadow_container(root) people = container["people"] entry = people.get(person_id) if entry is None: entry = _new_p4_shadow_person_entry(person_id, _now()) current_state = deepcopy(entry["state"]) event_index: dict[str, dict[str, Any]] = {} else: current_state, event_index, error = _replay_p4_shadow_entry(entry, person_id) if error: return _result(False, error, operation_id=operation_id, person_id=person_id) assert current_state is not None and event_index is not None known = event_index.get(event_id) fingerprint = _p4_shadow_event_fingerprint(person_id, normalized_event) if known is not None: if known.get("event_fingerprint") != fingerprint: return _result(False, "p4_shadow_event_id_conflict", operation_id=operation_id, person_id=person_id, event_id=event_id) result = _result( True, "p4_shadow_event_duplicate", operation_id=operation_id, person_id=person_id, origin_person_id=person_id, event_id=event_id, event_duplicate=True, p4_shadow_summary=_p4_shadow_summary(current_state), ) _record_operation( root, operation_id=operation_id, action="record_p4_shadow_event", payload=payload, metadata={"event_id": event_id, "origin_person_id": person_id, "duplicate_event": True}, result=result, now=_now(), ) self._commit(root) return result now = _now() envelope = { "event_id": event_id, "person_id": person_id, "origin_person_id": person_id, "event": deepcopy(normalized_event), "event_fingerprint": fingerprint, "recorded_at": now, "operation_id": operation_id, } entry["events"].append(envelope) replay = replay_shadow_events([item["event"] for item in entry["events"]]) replay_state = replay.get("state") if isinstance(replay, dict) else None settlements = replay.get("settlements") if isinstance(replay, dict) else None if not isinstance(replay_state, dict) or not isinstance(settlements, list): return _result(False, "p4_shadow_replay_failed", operation_id=operation_id, person_id=person_id) settlement = next( (item for item in settlements if isinstance(item, dict) and item.get("event_id") == event_id), None, ) if not isinstance(settlement, dict): return _result(False, "p4_shadow_replay_failed", operation_id=operation_id, person_id=person_id) entry["state"] = deepcopy(replay_state) entry["updated_at"] = now entry["last_operation_id"] = operation_id people[person_id] = entry result = _result( True, "p4_shadow_event_recorded", operation_id=operation_id, person_id=person_id, origin_person_id=person_id, event_id=event_id, changed=True, affected_person_ids=[person_id], audit_event_id=operation_id, event_outcome=str(settlement.get("outcome") or ""), event_applied=bool(settlement.get("applied")), p4_shadow_summary=_p4_shadow_summary(replay_state), ) _append_audit( root, operation_id=operation_id, action="p4_shadow_event_recorded", actor_id=actor_id, code=result["code"], now=now, details={ "person_id": person_id, "origin_person_id": person_id, "event_id": event_id, "event_kind": str(normalized_event.get("kind") or "invalid"), "event_outcome": result["event_outcome"], "event_applied": result["event_applied"], }, ) _record_operation( root, operation_id=operation_id, action="record_p4_shadow_event", payload=payload, metadata={"event_id": event_id, "origin_person_id": person_id}, result=result, now=now, ) self._commit(root) return result def read_p4_effect_state(self, person_id: str) -> dict[str, Any]: """Read P4-B preparation state without projecting it into a profile.""" try: person_id = _identifier(person_id, "person_id") except ValueError: return _result(False, "invalid_request") with _REGISTRY_LOCK: root = self._root_copy() profile = root["profiles"].get(person_id) if not isinstance(profile, dict): return _result(False, "person_not_found", person_id=person_id) if profile.get("profile_status") != "active": return _result(False, "person_not_active", person_id=person_id) entry = _p4_effect_container(root)["people"].get(person_id) if entry is None: state = _new_p4_effect_person_entry(person_id, "")["state"] return _result(True, "p4_effect_empty", person_id=person_id, p4_effect_exists=False, p4_effect_state=state, p4_effect_summary=_p4_effect_summary(state), event_count=0) state, event_index, error = _replay_p4_effect_entry(entry, person_id) if error: return _result(False, error, person_id=person_id) assert state is not None and event_index is not None return _result(True, "p4_effect_read", person_id=person_id, p4_effect_exists=True, p4_effect_state=state, p4_effect_summary=_p4_effect_summary(state), event_count=len(event_index)) def record_p4_effect_event( self, person_id: str, event: dict[str, Any], *, operation_id: str, actor_id: str = "system", ) -> dict[str, Any]: """Append one P4-B preparation event without a runtime effect. This is deliberately separate from ``record_p4_shadow_event``. It writes no profile/projection field and is not connected to a Hook, reply, confinement gate, or owner command. """ try: operation_id = _identifier(operation_id, "operation_id", 120) person_id = _identifier(person_id, "person_id") actor_id = _identifier(actor_id, "actor_id", 160) except ValueError: return _result(False, "invalid_request") if not isinstance(event, dict): return _result(False, "invalid_p4_effect_event", operation_id=operation_id, person_id=person_id) for field in ("person_id", "origin_person_id"): if event.get(field) not in (None, "", person_id): return _result(False, "p4_effect_person_mismatch", operation_id=operation_id, person_id=person_id) normalized_event, event_errors = _normalize_p4_shadow_event(event) if normalized_event is None: return _result(False, "invalid_p4_effect_event", operation_id=operation_id, person_id=person_id, event_errors=event_errors) event_id = str(normalized_event["event_id"]) payload = {"person_id": person_id, "actor_id": actor_id, "event": normalized_event} with _REGISTRY_LOCK: root = self._root_copy() repeated, fresh = _operation_result(root, operation_id, "record_p4_effect_event", payload) if repeated is not None: return repeated profile = root["profiles"].get(person_id) if not isinstance(profile, dict): return _result(False, "person_not_found", operation_id=operation_id, person_id=person_id) if profile.get("profile_status") != "active": return _result(False, "person_not_active", operation_id=operation_id, person_id=person_id) people = _p4_effect_container(root)["people"] entry = people.get(person_id) if entry is None: entry = _new_p4_effect_person_entry(person_id, _now()) event_index: dict[str, dict[str, Any]] = {} else: current_state, event_index, error = _replay_p4_effect_entry(entry, person_id) if error: return _result(False, error, operation_id=operation_id, person_id=person_id) assert current_state is not None and event_index is not None fingerprint = _p4_effect_fingerprint(person_id, normalized_event) known = event_index.get(event_id) if known is not None: if known.get("event_fingerprint") != fingerprint: return _result(False, "p4_effect_event_id_conflict", operation_id=operation_id, person_id=person_id, event_id=event_id) result = _result(True, "p4_effect_event_duplicate", operation_id=operation_id, person_id=person_id, event_id=event_id, event_duplicate=True, p4_effect_summary=_p4_effect_summary(entry["state"])) _record_operation(root, operation_id=operation_id, action="record_p4_effect_event", payload=payload, metadata={"event_id": event_id, "duplicate_event": True}, result=result, now=_now()) self._commit(root) return result now = _now() entry["events"].append({"event_id": event_id, "person_id": person_id, "origin_person_id": person_id, "event": deepcopy(normalized_event), "event_fingerprint": fingerprint, "recorded_at": now, "operation_id": operation_id}) replay_state = _p4_effect_state([item["event"] for item in entry["events"]]) if not isinstance(replay_state, dict): return _result(False, "p4_effect_replay_failed", operation_id=operation_id, person_id=person_id) entry["state"] = replay_state entry["updated_at"] = now entry["last_operation_id"] = operation_id people[person_id] = entry result = _result(True, "p4_effect_event_recorded", operation_id=operation_id, person_id=person_id, origin_person_id=person_id, event_id=event_id, changed=True, affected_person_ids=[person_id], audit_event_id=operation_id, p4_effect_summary=_p4_effect_summary(replay_state)) _append_audit(root, operation_id=operation_id, action="p4_effect_event_recorded", actor_id=actor_id, code=result["code"], now=now, details={"person_id": person_id, "event_id": event_id, "event_kind": str(normalized_event.get("kind") or "invalid")}) _record_operation(root, operation_id=operation_id, action="record_p4_effect_event", payload=payload, metadata={"event_id": event_id}, result=result, now=now) self._commit(root) return result def record_p4_manual_review_candidate( self, person_id: str, candidate: dict[str, Any], *, operation_id: str, producer_attestation: Any = None, producer_request: Any = None, producer_event: Any = None, producer_state: Any = None, ) -> dict[str, Any]: """Queue one P3-proven P4 review candidate in its own ledger only. This is an observer write. It neither consults a claimed owner field nor writes ``p4_shadow``/``p4_effect`` or a profile projection. """ try: operation_id = _identifier(operation_id, "operation_id", 120) person_id = _identifier(person_id, "person_id") except ValueError: return _result(False, "invalid_request") # Validate all immutable fields before reading any prior operation, but # postpone expiry to preserve an exact operation-ID replay result. normalized, code = normalize_review_candidate( candidate, now=datetime.min.replace(tzinfo=timezone.utc), ) if normalized is None: return _result(False, code, operation_id=operation_id, person_id=person_id) if normalized["person_id"] != person_id: return _result(False, "p4_review_candidate_person_mismatch", operation_id=operation_id, person_id=person_id) if producer_attestation is None: return _result(False, "p4_review_producer_unavailable", operation_id=operation_id, person_id=person_id) if ( consume_p4_review_producer_attestation( producer_attestation, producer_request, producer_event, producer_state, candidate, operation_id=operation_id, ) is None ): return _result(False, "p4_review_producer_attestation_invalid", operation_id=operation_id, person_id=person_id) payload = {"person_id": person_id, "candidate": normalized} with _REGISTRY_LOCK: root = self._root_copy() repeated, _fresh = _operation_result(root, operation_id, "record_p4_manual_review_candidate", payload) if repeated is not None: integrity_code = validate_review_operation_replay( root.get("p4_review"), action="record_p4_manual_review_candidate", result=repeated, payload=payload, ) if integrity_code: return _result(False, integrity_code, operation_id=operation_id, person_id=person_id) return repeated # Expiry is a live safety property only for new work. It does not # weaken the replay guarantee for an already committed operation. normalized, code = normalize_review_candidate(candidate, now=datetime.now(timezone.utc)) if normalized is None: return _result(False, code, operation_id=operation_id, person_id=person_id) profile = root["profiles"].get(person_id) if not isinstance(profile, dict): return _result(False, "person_not_found", operation_id=operation_id, person_id=person_id) if profile.get("person_id") != person_id: return _result(False, "person_profile_conflict", operation_id=operation_id, person_id=person_id) if profile.get("profile_status") != "active": return _result(False, "person_not_active", operation_id=operation_id, person_id=person_id) assurance = profile.get("identity_assurance") if assurance not in P4_REVIEW_ALLOWED_ASSURANCES: return _result(False, "p4_review_person_assurance_insufficient", operation_id=operation_id, person_id=person_id) if normalized["p3_proof"]["identity_assurance"] != assurance: return _result(False, "p4_review_person_assurance_mismatch", operation_id=operation_id, person_id=person_id) container, container_code = ensure_review_container(root) if container is None: return _result(False, container_code, operation_id=operation_id, person_id=person_id) now = _now() record, queue_code = queue_candidate( container, normalized, operation_id=operation_id, recorded_at=now, ) if record is None: return _result(False, queue_code, operation_id=operation_id, person_id=person_id) candidate_id = normalized["candidate_id"] if queue_code == "p4_review_candidate_duplicate": result = _result( True, queue_code, operation_id=operation_id, person_id=person_id, candidate_id=candidate_id, event_id=normalized["event_id"], candidate_duplicate=True, live_effect_permitted=False, effect_applied=False, ) _record_operation( root, operation_id=operation_id, action="record_p4_manual_review_candidate", payload=payload, metadata={"candidate_id": candidate_id, "duplicate_candidate": True}, result=result, now=now, ) self._commit(root) return result result = _result( True, queue_code, operation_id=operation_id, person_id=person_id, candidate_id=candidate_id, event_id=normalized["event_id"], changed=True, affected_person_ids=[person_id], audit_event_id=operation_id, live_effect_permitted=False, effect_applied=False, ) _append_audit( root, operation_id=operation_id, action="p4_manual_review_candidate_recorded", actor_id="p4_manual_review_observer", code=result["code"], now=now, details={ "person_id": person_id, "candidate_id": candidate_id, "event_id": normalized["event_id"], "reason_code": normalized["reason_code"], "p3_security_status": normalized["p3_proof"]["security_status"], }, ) _record_operation( root, operation_id=operation_id, action="record_p4_manual_review_candidate", payload=payload, metadata={"candidate_id": candidate_id, "event_id": normalized["event_id"]}, result=result, now=now, ) self._commit(root) return result def record_p4_manual_review_decision( self, event: Any, configured_owner_ids: Any, person_id: str, candidate_id: str, *, operation_id: str, decision: str, reason_code: str, ) -> dict[str, Any]: """Record a human conclusion only after direct runtime-owner proof. ``actor_id`` and ``occurred_at`` are deliberately not caller inputs: the actor comes only from ``event.get_sender_id()`` and the timestamp is produced by this persistence boundary. Approval remains audit-only. """ request, code = normalize_decision_request( person_id=person_id, candidate_id=candidate_id, decision=decision, reason_code=reason_code, operation_id=operation_id, ) if request is None: return _result(False, code, operation_id=str(operation_id or ""), person_id=str(person_id or "")) owner = runtime_owner_identity(event, configured_owner_ids) if owner.get("accepted") is not True: return _result(False, str(owner.get("code") or "p4_review_owner_runtime_unavailable"), operation_id=request["operation_id"], person_id=request["person_id"]) actor_id = str(owner["actor_id"]) scope = runtime_scope_identity(event) scope_kind = str(scope.get("scope_kind") or "") scope_id = str(scope.get("scope_id") or "") if not scope_kind or not scope_id: return _result(False, "p4_review_scope_runtime_unavailable", operation_id=request["operation_id"], person_id=request["person_id"]) payload = { "person_id": request["person_id"], "candidate_id": request["candidate_id"], "actor_id": actor_id, "scope_kind": scope_kind, "scope_id": scope_id, "decision": request["decision"], "reason_code": request["reason_code"], } with _REGISTRY_LOCK: root = self._root_copy() repeated, _fresh = _operation_result(root, request["operation_id"], "record_p4_manual_review_decision", payload) if repeated is not None: integrity_code = validate_review_operation_replay( root.get("p4_review"), action="record_p4_manual_review_decision", result=repeated, payload=payload, ) if integrity_code: return _result(False, integrity_code, operation_id=request["operation_id"], person_id=request["person_id"]) return repeated profile = root["profiles"].get(request["person_id"]) if not isinstance(profile, dict): return _result(False, "person_not_found", operation_id=request["operation_id"], person_id=request["person_id"]) if profile.get("person_id") != request["person_id"]: return _result(False, "person_profile_conflict", operation_id=request["operation_id"], person_id=request["person_id"]) if profile.get("profile_status") != "active": return _result(False, "person_not_active", operation_id=request["operation_id"], person_id=request["person_id"]) if profile.get("identity_assurance") not in P4_REVIEW_ALLOWED_ASSURANCES: return _result(False, "p4_review_person_assurance_insufficient", operation_id=request["operation_id"], person_id=request["person_id"]) container = root.get("p4_review") if not isinstance(container, dict): return _result(False, "p4_review_candidate_not_found", operation_id=request["operation_id"], person_id=request["person_id"]) if container.get("version") != 1 or any(not isinstance(container.get(key), dict) for key in ("candidates", "event_index", "decisions")): return _result(False, "p4_review_corrupt", operation_id=request["operation_id"], person_id=request["person_id"]) now = _now() record, queue_code = queue_decision( container, person_id=request["person_id"], candidate_id=request["candidate_id"], actor_id=actor_id, scope_kind=scope_kind, scope_id=scope_id, decision=request["decision"], reason_code=request["reason_code"], operation_id=request["operation_id"], occurred_at=now, now=datetime.now(timezone.utc), ) if record is None: return _result(False, queue_code, operation_id=request["operation_id"], person_id=request["person_id"]) if queue_code == "p4_review_decision_duplicate": result = _result( True, queue_code, operation_id=request["operation_id"], person_id=request["person_id"], candidate_id=request["candidate_id"], decision=request["decision"], scope_kind=scope_kind, scope_id=scope_id, decision_duplicate=True, live_effect_permitted=False, effect_applied=False, ) _record_operation( root, operation_id=request["operation_id"], action="record_p4_manual_review_decision", payload=payload, metadata={"candidate_id": request["candidate_id"], "duplicate_decision": True}, result=result, now=now, ) self._commit(root) return result result = _result( True, queue_code, operation_id=request["operation_id"], person_id=request["person_id"], candidate_id=request["candidate_id"], event_id=record["event_id"], decision=request["decision"], actor_id=actor_id, occurred_at=now, scope_kind=scope_kind, scope_id=scope_id, changed=True, affected_person_ids=[request["person_id"]], audit_event_id=request["operation_id"], live_effect_permitted=False, effect_applied=False, ) _append_audit( root, operation_id=request["operation_id"], action="p4_manual_review_decision_recorded", actor_id=actor_id, code=result["code"], now=now, details={ "person_id": request["person_id"], "candidate_id": request["candidate_id"], "event_id": record["event_id"], "decision": request["decision"], "reason_code": request["reason_code"], "scope_kind": scope_kind, "scope_id": scope_id, }, ) _record_operation( root, operation_id=request["operation_id"], action="record_p4_manual_review_decision", payload=payload, metadata={"candidate_id": request["candidate_id"], "decision": request["decision"]}, result=result, now=now, ) self._commit(root) return result 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, } try: p4_effect_snapshot = _merge_p4_effect_people( root, source_person_id, target_person_id, operation_id, now, ) except ValueError as exc: return _result(False, str(exc) or "p4_effect_merge_conflict", operation_id=operation_id) 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 merge_record = { "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, } if p4_effect_snapshot is not None: merge_record["p4_effect_snapshot"] = p4_effect_snapshot root["merge_operations"][operation_id] = merge_record 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] p4_effect_error = _restore_p4_effect_after_split( root, merge, source_id, target_id, merge_operation_id, ) if p4_effect_error: return _result(False, p4_effect_error, operation_id=operation_id) 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