# -*- coding: utf-8 -*- """Versioned, read-only unified-person contract owned by PrivateCompanion. This module deliberately has no AstrBot dependency. The memory plugin may only consume the projections produced here; person creation, linking, and migration remain in the companion plugin's data domain. """ from __future__ import annotations from copy import deepcopy from datetime import datetime, timezone import hashlib import json from typing import Any import unicodedata import re CONTRACT_NAME = "ops.unified_person.v1" CONTRACT_VERSION = "1.0" CONTRACT_SAMPLE_VERSION = "1.0" UNIFIED_PERSON_STORE_VERSION = 1 UNIFIED_PERSON_MIGRATION_VERSION = 1 IDENTITY_FIELDS = ( "companion_instance_id", "bot_account_id", "adapter_instance_id", "subject_namespace", "platform_subject_id", ) PROJECTION_FIELDS = ( "contract_name", "contract_version", "contract_fingerprint", "projection_revision", "person_id", "resolved_identity_key", "identity_assurance", "profile_status", "display_name", "aliases", "relation_policy_id", "relation_label", "relationship_capabilities", "owner_mode", "affinity_score", "affinity_band", "warning_stage", "confinement_state", "confinement_until", "release_prompt_pending", "proactive_private_enabled", "group_overlay_ref", "updated_at", ) IDENTITY_ASSURANCE_VALUES = frozenset({"unverified", "observed", "verified", "explicit_linked"}) PROFILE_STATUS_VALUES = frozenset({"active", "suspended", "quarantined", "deleted"}) OWNER_MODE_VALUES = frozenset({"none", "owner", "not_owner"}) AFFINITY_BAND_VALUES = frozenset({"critical", "guarded", "neutral", "positive"}) WARNING_STAGE_VALUES = frozenset({"none", "warning_1", "warning_2", "confinement"}) CONFINEMENT_STATE_VALUES = frozenset({"none", "active", "released"}) COORDINATION_STATUS_VALUES = frozenset({ "resolved", "pending_companion", "contract_mismatch", "identity_conflict", "quarantined", "legacy_unresolved", }) RELATIONSHIP_CAPABILITIES = frozenset({ "comfort", "proactive_care", "joking", "hugging", "hand_holding", "head_pat", "leaning_close", "sweet_talk", "affectionate_address", "missing_you", "acting_cute", "jealousy", "flirting", "romantic_expression", "confession", "exclusivity", "public_favoritism", "nsfw", }) def _canonical_json(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) def _contract_shape() -> dict[str, Any]: return { "name": CONTRACT_NAME, "version": CONTRACT_VERSION, "sample_version": CONTRACT_SAMPLE_VERSION, "required_fields": sorted(PROJECTION_FIELDS), "identity_key_fields": sorted(IDENTITY_FIELDS), "enums": { "identity_assurance": sorted(IDENTITY_ASSURANCE_VALUES), "profile_status": sorted(PROFILE_STATUS_VALUES), "owner_mode": sorted(OWNER_MODE_VALUES), "affinity_band": sorted(AFFINITY_BAND_VALUES), "warning_stage": sorted(WARNING_STAGE_VALUES), "confinement_state": sorted(CONFINEMENT_STATE_VALUES), "coordination_status": sorted(COORDINATION_STATUS_VALUES), "relationship_capabilities": sorted(RELATIONSHIP_CAPABILITIES), }, } CONTRACT_FINGERPRINT = hashlib.sha256(_canonical_json(_contract_shape()).encode("utf-8")).hexdigest() def contract_manifest() -> dict[str, Any]: """Return a deterministic manifest suitable for bridge capability checks.""" manifest = _contract_shape() manifest["contract_fingerprint"] = CONTRACT_FINGERPRINT return manifest def _text(value: Any, field: str, *, limit: int = 160) -> str: if isinstance(value, bool) or not isinstance(value, (str, int)): raise ValueError(f"{field} must be a scalar string") text = unicodedata.normalize("NFC", str(value)).strip() if not text: raise ValueError(f"{field} is required") if "\x00" in text or len(text) > limit: raise ValueError(f"{field} is invalid") return text def canonical_identity(identity: dict[str, Any]) -> dict[str, str]: """Normalize all five identity dimensions without inferring equivalence.""" if not isinstance(identity, dict): raise ValueError("identity must be an object") result = {field: _text(identity.get(field), field) for field in IDENTITY_FIELDS} result["subject_namespace"] = result["subject_namespace"].lower() return result def build_identity_key(identity: dict[str, Any]) -> str: """A stable complete identity key. It never falls back to a bare platform ID.""" normalized = _canonical_json(canonical_identity(identity)) digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest() return f"ops-origin-v1:{digest}" def person_id_for_identity(identity: dict[str, Any]) -> str: digest = hashlib.sha256(build_identity_key(identity).encode("utf-8")).hexdigest() return f"person_{digest[:24]}" def affinity_band(score: Any) -> str: numeric = int(score) if numeric <= -800: return "critical" if numeric < 0: return "guarded" if numeric == 0: return "neutral" return "positive" def _utc_now() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds") def empty_unified_person_store() -> dict[str, Any]: return { "version": UNIFIED_PERSON_STORE_VERSION, "profiles": {}, "identity_links": {}, "relation_policies": { "default_friend": { "relation_policy_id": "default_friend", "label": "friend", "sort_order": 100, "capabilities": [], "proactive_private_enabled": False, "active": True, }, }, "group_overlays": {}, "registry_version": 1, "audit_events": [], "operations": {}, "merge_operations": {}, "migration": {"version": 0, "applied_ids": [], "backups": {}}, } def ensure_unified_person_store(data: dict[str, Any]) -> tuple[dict[str, Any], bool]: """Install only empty, forward-compatible containers; never migrate automatically.""" if not isinstance(data, dict): raise ValueError("store must be an object") changed = False root = data.get("unified_person") if not isinstance(root, dict): data["unified_person"] = empty_unified_person_store() return data, True defaults = empty_unified_person_store() for key, default in defaults.items(): if key not in root or not isinstance(root.get(key), type(default)): root[key] = deepcopy(default) changed = True try: current_version = int(root.get("version") or 0) except (TypeError, ValueError): current_version = 0 root["version"] = max(current_version, UNIFIED_PERSON_STORE_VERSION) migration = root["migration"] for key, default in defaults["migration"].items(): if key not in migration or not isinstance(migration.get(key), type(default)): migration[key] = deepcopy(default) changed = True return data, changed def _safe_score(value: Any) -> int: try: score = int(value) except (TypeError, ValueError): score = 0 return max(-1200, min(1200, score)) def _enum(value: Any, allowed: frozenset[str], default: str) -> str: text = str(value or "").strip() return text if text in allowed else default def _positive_int(value: Any, default: int = 1) -> int: try: result = int(value) except (TypeError, ValueError): return default return max(1, result) def _safe_aliases(value: Any) -> list[str]: if not isinstance(value, list): return [] result: list[str] = [] for item in value: try: text = _text(item, "alias", limit=120) except ValueError: continue if text not in result: result.append(text) return result def _projection_aliases(value: Any) -> list[str] | None: if not isinstance(value, list): return None if any(not isinstance(item, str) or not item.strip() or "\x00" in item or len(item) > 120 for item in value): return None return list(value) def _relation_policy(root: dict[str, Any], relation_policy_id: str) -> dict[str, Any]: policies = root.get("relation_policies") if isinstance(root.get("relation_policies"), dict) else {} policy = policies.get(relation_policy_id) if isinstance(policy, dict): return policy return policies.get("default_friend") if isinstance(policies.get("default_friend"), dict) else {} def build_person_projection(store: dict[str, Any], person_id: str) -> dict[str, Any] | None: """Build the sole bridge payload. This function is intentionally read-only.""" root = store.get("unified_person") if isinstance(store, dict) else None if not isinstance(root, dict): return None profiles = root.get("profiles") if isinstance(root.get("profiles"), dict) else {} profile = profiles.get(str(person_id or "")) if not isinstance(profile, dict): return None policy_id = profile.get("relation_policy_id") if not isinstance(policy_id, str) or not policy_id: return None policy = _relation_policy(root, policy_id) score = _safe_score(profile.get("affinity_score")) capabilities = [item for item in _safe_aliases(policy.get("capabilities")) if item in RELATIONSHIP_CAPABILITIES] identity_key = profile.get("resolved_identity_key") if not isinstance(identity_key, str): return None aliases = _projection_aliases(profile.get("aliases")) if aliases is None: return None person_value = profile.get("person_id") display_name = profile.get("display_name") relation_label = policy.get("label") updated_at = profile.get("updated_at") if not all(isinstance(item, str) for item in (person_value, display_name, relation_label, updated_at)): return None links = root.get("identity_links") if isinstance(root.get("identity_links"), dict) else {} link = links.get(identity_key) if isinstance(links.get(identity_key), dict) else {} assurance = _enum( profile.get("identity_assurance") or link.get("identity_assurance"), IDENTITY_ASSURANCE_VALUES, "unverified", ) projection = { "contract_name": CONTRACT_NAME, "contract_version": CONTRACT_VERSION, "contract_fingerprint": CONTRACT_FINGERPRINT, "projection_revision": _positive_int(profile.get("projection_revision")), "person_id": person_value, "resolved_identity_key": identity_key, "identity_assurance": assurance, "profile_status": _enum(profile.get("profile_status"), PROFILE_STATUS_VALUES, "active"), "display_name": display_name, "aliases": aliases, "relation_policy_id": policy_id, "relation_label": relation_label, "relationship_capabilities": capabilities, "owner_mode": "owner" if profile.get("owner_mode") == "owner" else "not_owner", "affinity_score": score, "affinity_band": affinity_band(score), "warning_stage": _enum(profile.get("warning_stage"), WARNING_STAGE_VALUES, "none"), "confinement_state": _enum(profile.get("confinement_state"), CONFINEMENT_STATE_VALUES, "none"), "confinement_until": str(profile.get("confinement_until") or ""), "release_prompt_pending": bool(profile.get("release_prompt_pending")), "proactive_private_enabled": bool(profile.get("proactive_private_enabled", policy.get("proactive_private_enabled", False))), "group_overlay_ref": str(profile.get("group_overlay_ref") or ""), "updated_at": updated_at, } # A corrupted persisted record must not escape as an invalid bridge payload. return projection if not validate_projection(projection) else None def validate_projection(projection: dict[str, Any]) -> list[str]: """Validate an incoming projection without silently coercing contract fields.""" if not isinstance(projection, dict): return ["projection must be an object"] errors = [f"missing {field}" for field in PROJECTION_FIELDS if field not in projection] if errors: return errors if projection["contract_name"] != CONTRACT_NAME: errors.append("contract_name mismatch") if projection["contract_version"] != CONTRACT_VERSION: errors.append("contract_version mismatch") if projection["contract_fingerprint"] != CONTRACT_FINGERPRINT: errors.append("contract_fingerprint mismatch") if not isinstance(projection["projection_revision"], int) or projection["projection_revision"] < 1: errors.append("projection_revision invalid") for field in ("person_id", "display_name", "relation_policy_id", "relation_label"): if not isinstance(projection[field], str) or not projection[field] or "\x00" in projection[field] or len(projection[field]) > 160: errors.append(f"{field} invalid") identity_key = projection["resolved_identity_key"] if not isinstance(identity_key, str) or not re.fullmatch(r"ops-origin-v1:[0-9a-f]{64}", identity_key): errors.append("resolved_identity_key invalid") if not isinstance(projection["updated_at"], str) or not projection["updated_at"] or "\x00" in projection["updated_at"] or len(projection["updated_at"]) > 80: errors.append("updated_at invalid") if not isinstance(projection["aliases"], list) or any( not isinstance(item, str) or not item.strip() or "\x00" in item or len(item) > 120 for item in projection["aliases"] ): errors.append("aliases invalid") if not isinstance(projection["relationship_capabilities"], list) or not set(projection["relationship_capabilities"]).issubset(RELATIONSHIP_CAPABILITIES): errors.append("relationship_capabilities invalid") enum_checks = { "identity_assurance": IDENTITY_ASSURANCE_VALUES, "profile_status": PROFILE_STATUS_VALUES, "owner_mode": OWNER_MODE_VALUES, "affinity_band": AFFINITY_BAND_VALUES, "warning_stage": WARNING_STAGE_VALUES, "confinement_state": CONFINEMENT_STATE_VALUES, } for field, allowed in enum_checks.items(): if projection[field] not in allowed: errors.append(f"{field} invalid") if not isinstance(projection["affinity_score"], int) or not -1200 <= projection["affinity_score"] <= 1200: errors.append("affinity_score invalid") elif projection["affinity_band"] != affinity_band(projection["affinity_score"]): errors.append("affinity_band inconsistent") for field in ("release_prompt_pending", "proactive_private_enabled"): if not isinstance(projection[field], bool): errors.append(f"{field} invalid") for field in ("confinement_until", "group_overlay_ref"): if not isinstance(projection[field], str): errors.append(f"{field} invalid") return errors def resolve_identity(store: dict[str, Any], identity: dict[str, Any]) -> dict[str, Any]: """Resolve an identity only. No bridge consumer can create a person through it.""" try: identity_key = build_identity_key(identity) except ValueError: return {"state": "quarantined", "identity_key": "", "person_id": "", "error_code": "invalid_identity"} root = store.get("unified_person") if isinstance(store, dict) else None links = root.get("identity_links") if isinstance(root, dict) and isinstance(root.get("identity_links"), dict) else {} link = links.get(identity_key) if not isinstance(link, dict): return {"state": "pending_companion", "identity_key": identity_key, "person_id": ""} person_id = str(link.get("person_id") or "") projection = build_person_projection(store, person_id) if projection is None: return {"state": "identity_conflict", "identity_key": identity_key, "person_id": person_id} projection["resolved_identity_key"] = identity_key return {"state": "resolved", "identity_key": identity_key, "person_id": person_id, "projection": projection} def _migration_context(identity_context: dict[str, Any] | None) -> dict[str, str] | None: """Accept only an explicit source context; legacy IDs alone are not identities.""" if not isinstance(identity_context, dict): return None try: return { "companion_instance_id": _text(identity_context.get("companion_instance_id"), "companion_instance_id"), "bot_account_id": _text(identity_context.get("bot_account_id"), "bot_account_id"), "adapter_instance_id": _text(identity_context.get("adapter_instance_id"), "adapter_instance_id"), "subject_namespace": _text(identity_context.get("subject_namespace"), "subject_namespace").lower(), } except ValueError: return None def _identity_for_subject(context: dict[str, str], subject_id: Any) -> dict[str, str]: identity = dict(context) identity["platform_subject_id"] = _text(subject_id, "platform_subject_id") return identity def _legacy_display_name(record: dict[str, Any], subject_id: str) -> str: for field in ("nickname", "name", "display_name"): value = str(record.get(field) or "").strip() if value: return value[:120] return subject_id[:120] def preview_unified_person_migration( store: dict[str, Any], *, identity_context: dict[str, Any] | None = None, private_user_aliases: dict[str, Any] | None = None, owner_user_ids: set[str] | list[str] | tuple[str, ...] = (), ) -> dict[str, Any]: """Produce a non-mutating migration plan and explicitly flag ambiguous legacy data.""" context = _migration_context(identity_context) if context is None: return { "ok": False, "mode": "preview", "migration_version": UNIFIED_PERSON_MIGRATION_VERSION, "contract_name": CONTRACT_NAME, "contract_version": CONTRACT_VERSION, "contract_fingerprint": CONTRACT_FINGERPRINT, "coordination_status": "legacy_unresolved", "error_code": "identity_context_incomplete", "would_create_profiles": 0, "would_create_identity_links": 0, "would_create_group_overlays": 0, "legacy_affinity_baselines": 0, "legacy_alias_candidates": 0, "warnings": ["Migration requires explicit companion, bot, adapter, and subject namespace context."], "rollback": "No migration was applied.", } users = store.get("users") if isinstance(store, dict) and isinstance(store.get("users"), dict) else {} groups = store.get("groups") if isinstance(store, dict) and isinstance(store.get("groups"), dict) else {} aliases = private_user_aliases if isinstance(private_user_aliases, dict) else {} owner_ids = {str(item).strip() for item in owner_user_ids if str(item).strip()} planned_profiles: dict[str, str] = {} overlay_count = 0 warnings: list[str] = [] legacy_score_count = 0 for user_id, record in users.items(): subject_id = str(user_id or "").strip() if not subject_id: warnings.append("legacy user with empty user_id skipped") continue identity = _identity_for_subject(context, subject_id) planned_profiles[subject_id] = person_id_for_identity(identity) if isinstance(record, dict) and "relationship_score" in record: legacy_score_count += 1 if isinstance(record, dict) and str(record.get("relationship_role") or "").strip().lower() in {"owner", "master", "主人"} and subject_id not in owner_ids: warnings.append(f"legacy owner role for {subject_id} requires backend owner confirmation") for group_id, group in groups.items(): members = group.get("members") if isinstance(group, dict) and isinstance(group.get("members"), dict) else {} for member_id in members: subject_id = str(member_id or "").strip() if not subject_id: continue planned_profiles.setdefault(subject_id, person_id_for_identity(_identity_for_subject(context, subject_id))) overlay_count += 1 alias_count = 0 for alias, canonical in aliases.items(): alias_text = str(alias or "").strip() canonical_text = str(canonical or "").strip() if not alias_text or not canonical_text: warnings.append("empty private_user_aliases entry skipped") continue if canonical_text not in planned_profiles: warnings.append(f"alias {alias_text} targets unknown legacy user {canonical_text}") continue alias_count += 1 warnings.append(f"legacy private_user_alias {alias_text} -> {canonical_text} retained for owner confirmation; no identity link will be created") return { "ok": True, "mode": "preview", "migration_version": UNIFIED_PERSON_MIGRATION_VERSION, "contract_name": CONTRACT_NAME, "contract_version": CONTRACT_VERSION, "contract_fingerprint": CONTRACT_FINGERPRINT, "identity_context": deepcopy(context), "would_create_profiles": len(planned_profiles), "would_create_identity_links": len(planned_profiles), "legacy_alias_candidates": alias_count, "would_create_group_overlays": overlay_count, "legacy_affinity_baselines": legacy_score_count, "warnings": warnings, "rollback": "Restores the pre-migration unified_person section; legacy users, aliases, groups, and scores are never deleted.", } def apply_unified_person_migration( store: dict[str, Any], *, identity_context: dict[str, Any] | None = None, private_user_aliases: dict[str, Any] | None = None, owner_user_ids: set[str] | list[str] | tuple[str, ...] = (), migration_id: str = "legacy_v1", now: str | None = None, ) -> dict[str, Any]: """Apply the reviewed migration idempotently and retain a scoped rollback snapshot.""" report = preview_unified_person_migration( store, identity_context=identity_context, private_user_aliases=private_user_aliases, owner_user_ids=owner_user_ids, ) migration_id = _text(migration_id, "migration_id", limit=80) if not report.get("ok"): return { **report, "mode": "apply", "applied": False, "idempotent": False, "migration_id": migration_id, } ensure_unified_person_store(store) root = store["unified_person"] migration = root["migration"] applied = migration["applied_ids"] if migration_id in applied: return {**report, "mode": "apply", "applied": False, "idempotent": True, "migration_id": migration_id} backup = deepcopy(root) backup_migration = backup.get("migration") if isinstance(backup.get("migration"), dict) else {} backup_migration["backups"] = {} backup["migration"] = backup_migration migration["backups"][migration_id] = backup context = _migration_context(identity_context) if context is None: # Guard for future changes to preview semantics. return {**report, "mode": "apply", "applied": False, "idempotent": False, "migration_id": migration_id} owner_ids = {str(item).strip() for item in owner_user_ids if str(item).strip()} users = store.get("users") if isinstance(store.get("users"), dict) else {} groups = store.get("groups") if isinstance(store.get("groups"), dict) else {} timestamp = now or _utc_now() def add_subject(subject_id: str, record: dict[str, Any] | None = None) -> str: identity = _identity_for_subject(context, subject_id) identity_key = build_identity_key(identity) person_id = person_id_for_identity(identity) profiles = root["profiles"] if person_id not in profiles: source = record if isinstance(record, dict) else {} score = _safe_score(source.get("relationship_score")) profiles[person_id] = { "person_id": person_id, "resolved_identity_key": identity_key, "identity_assurance": "unverified", "profile_status": "active", "display_name": _legacy_display_name(source, subject_id), "aliases": _safe_aliases(source.get("alias_user_ids")), "relation_policy_id": "default_friend", "owner_mode": "owner" if subject_id in owner_ids else "not_owner", "affinity_score": score, "affinity_baseline": {"source": "legacy_relationship_score", "value": score}, "warning_stage": "none", "confinement_state": "none", "confinement_until": "", "release_prompt_pending": False, "proactive_private_enabled": False, "group_overlay_ref": "", "projection_revision": 1, "updated_at": timestamp, } root["identity_links"].setdefault(identity_key, { "identity_key": identity_key, "identity": identity, "person_id": person_id, "identity_assurance": "unverified", "status": "active", "origin": "legacy_migration", "created_at": timestamp, }) return person_id for user_id, record in users.items(): subject_id = str(user_id or "").strip() if subject_id: add_subject(subject_id, record if isinstance(record, dict) else None) for group_id, group in groups.items(): members = group.get("members") if isinstance(group, dict) and isinstance(group.get("members"), dict) else {} for member_id, member in members.items(): subject_id = str(member_id or "").strip() if not subject_id: continue person_id = add_subject(subject_id, member if isinstance(member, dict) else None) overlay_key = f"{str(group_id)}:{person_id}" root["group_overlays"].setdefault(overlay_key, { "group_id": str(group_id), "person_id": person_id, "origin_identity_key": build_identity_key(_identity_for_subject(context, subject_id)), "legacy_member": deepcopy(member) if isinstance(member, dict) else {}, "created_at": timestamp, }) aliases = private_user_aliases if isinstance(private_user_aliases, dict) else {} legacy_alias_candidates: list[dict[str, str]] = [] for alias, canonical in aliases.items(): alias_text, canonical_text = str(alias or "").strip(), str(canonical or "").strip() if not alias_text or not canonical_text: continue canonical_key = build_identity_key(_identity_for_subject(context, canonical_text)) if not isinstance(root["identity_links"].get(canonical_key), dict): continue legacy_alias_candidates.append({"alias": alias_text, "canonical": canonical_text}) if legacy_alias_candidates: root["migration"].setdefault("legacy_alias_candidates", []) existing_candidates = root["migration"]["legacy_alias_candidates"] for candidate in legacy_alias_candidates: if candidate not in existing_candidates: existing_candidates.append(candidate) applied.append(migration_id) migration["version"] = UNIFIED_PERSON_MIGRATION_VERSION return {**report, "mode": "apply", "applied": True, "idempotent": False, "migration_id": migration_id} def rollback_unified_person_migration(store: dict[str, Any], migration_id: str) -> dict[str, Any]: """Restore the scoped pre-migration section without touching legacy source data.""" ensure_unified_person_store(store) migration_id = _text(migration_id, "migration_id", limit=80) root = store["unified_person"] backup = root["migration"]["backups"].get(migration_id) if not isinstance(backup, dict): return {"ok": False, "rolled_back": False, "reason": "migration backup not found", "migration_id": migration_id} restored = deepcopy(backup) restored_migration = restored.get("migration") if isinstance(restored.get("migration"), dict) else {} restored_migration["backups"] = deepcopy(root["migration"].get("backups") or {}) restored["migration"] = restored_migration store["unified_person"] = restored return {"ok": True, "rolled_back": True, "migration_id": migration_id}