From 2d4d6a7cb81793428eb793dbe476f414fb777002 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Tue, 28 Jul 2026 01:40:17 +0800 Subject: [PATCH] feat: complete unified person P0-P2 bridge --- _conf_schema.json | 18 + core_store.py | 82 +++ docs/unified_person_projection_v1.sample.json | 29 + docs/统一人物系统P1开发回执-20260727.md | 42 ++ docs/统一人物系统P2桥接回执-20260728.md | 32 + docs/统一人物系统开发回执-20260727.md | 57 ++ docs/错题本.md | 42 +- main.py | 33 + memory_companion_adapter.py | 113 +++ platform_compat.py | 8 +- tests/test_p2_unified_person_bridge.py | 226 ++++++ tests/test_unified_person_contract.py | 309 ++++++++ tests/test_unified_person_registry.py | 308 ++++++++ unified_person_contract.py | 663 ++++++++++++++++++ unified_person_registry.py | 586 ++++++++++++++++ 15 files changed, 2546 insertions(+), 2 deletions(-) create mode 100644 docs/unified_person_projection_v1.sample.json create mode 100644 docs/统一人物系统P1开发回执-20260727.md create mode 100644 docs/统一人物系统P2桥接回执-20260728.md create mode 100644 docs/统一人物系统开发回执-20260727.md create mode 100644 tests/test_p2_unified_person_bridge.py create mode 100644 tests/test_unified_person_contract.py create mode 100644 tests/test_unified_person_registry.py create mode 100644 unified_person_contract.py create mode 100644 unified_person_registry.py diff --git a/_conf_schema.json b/_conf_schema.json index fed199f..0b5b584 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -5641,6 +5641,24 @@ "default": true, "condition": {} }, + "unified_person_companion_instance_id": { + "description": "统一人物陪伴实例 ID", + "type": "string", + "hint": "统一人物五维身份中的稳定陪伴实例 ID。必须与建档/迁移时使用的值完全一致;留空时记忆桥不会获得人物权威。", + "default": "", + "condition": { + "enable_memory_companion_bridge": true + } + }, + "unified_person_subject_namespace_map": { + "description": "统一人物身份命名空间映射", + "type": "text", + "hint": "按 adapter_instance_id 精确配置 subject_namespace,每行 adapter=namespace。必须与建档/迁移一致,不做平台名或裸 ID 猜测;缺少当前 adapter 映射时记忆桥不会获得人物权威。", + "default": "", + "condition": { + "enable_memory_companion_bridge": true + } + }, "memory_companion_context_timeout_seconds": { "description": "记忆上下文超时(秒)", "type": "float", diff --git a/core_store.py b/core_store.py index 184934e..bbd3a9e 100644 --- a/core_store.py +++ b/core_store.py @@ -74,6 +74,15 @@ except Exception: from .calendar_system import CALENDAR_VERSION from .agenda_contracts import AGENDA_VERSION, migrate_store +from .unified_person_contract import ( + apply_unified_person_migration, + build_person_projection, + empty_unified_person_store, + ensure_unified_person_store, + preview_unified_person_migration, + rollback_unified_person_migration, +) +from .unified_person_registry import UnifiedPersonRegistry from .bot_self_store import ( build_bot_self_migration_preview, ensure_bot_self_store, @@ -350,6 +359,7 @@ class CoreStoreMixin: "version": DATA_VERSION, "users": {}, "groups": {}, + "unified_person": empty_unified_person_store(), "daily_plan": {}, "daily_plan_history": [], "calendar_version": CALENDAR_VERSION, @@ -431,6 +441,7 @@ class CoreStoreMixin: data.setdefault("version", DATA_VERSION) data.setdefault("users", {}) data.setdefault("groups", {}) + data, _ = ensure_unified_person_store(data) data.setdefault("daily_plan", {}) data.setdefault("daily_plan_history", []) data.setdefault("calendar_version", CALENDAR_VERSION) @@ -558,6 +569,77 @@ class CoreStoreMixin: saver() return result + def _unified_person_migration_preview( + self, + *, + identity_context: dict[str, Any] | None = None, + owner_user_ids: set[str] | list[str] | tuple[str, ...] = (), + ) -> dict[str, Any]: + return preview_unified_person_migration( + self.data, + identity_context=identity_context, + private_user_aliases=getattr(self, "private_user_aliases", {}), + owner_user_ids=owner_user_ids, + ) + + def _apply_unified_person_migration( + self, + *, + identity_context: dict[str, Any] | None = None, + owner_user_ids: set[str] | list[str] | tuple[str, ...] = (), + migration_id: str = "legacy_v1", + ) -> dict[str, Any]: + result = apply_unified_person_migration( + self.data, + identity_context=identity_context, + private_user_aliases=getattr(self, "private_user_aliases", {}), + owner_user_ids=owner_user_ids, + migration_id=migration_id, + ) + if result.get("applied"): + saver = getattr(self, "_schedule_data_save", None) + if callable(saver): + saver() + return result + + def _rollback_unified_person_migration(self, migration_id: str) -> dict[str, Any]: + result = rollback_unified_person_migration(self.data, migration_id) + if result.get("rolled_back"): + saver = getattr(self, "_schedule_data_save", None) + if callable(saver): + saver() + return result + + def _get_unified_person_projection(self, person_id: str) -> dict[str, Any] | None: + return build_person_projection(self.data, person_id) + + def _unified_person_registry(self) -> UnifiedPersonRegistry: + return UnifiedPersonRegistry(self.data) + + def _unified_person_registry_status(self) -> dict[str, Any]: + return self._unified_person_registry().status() + + def _unified_person_audit_events(self, *, limit: int = 100) -> list[dict[str, Any]]: + return self._unified_person_registry().audit_events(limit=limit) + + def _apply_unified_person_lifecycle(self, method: str, *args: Any, **kwargs: Any) -> dict[str, Any]: + registry = self._unified_person_registry() + operation = getattr(registry, method, None) + if not callable(operation) or method not in { + "upsert_observed_identity", + "link_identity", + "unlink_identity", + "merge_people", + "split_merged_people", + }: + return {"ok": False, "code": "unsupported_lifecycle_operation"} + result = operation(*args, **kwargs) + if result.get("ok") and not result.get("idempotent"): + saver = getattr(self, "_schedule_data_save", None) + if callable(saver): + saver() + return result + @staticmethod def _split_shared_activity(activity: dict[str, Any]) -> dict[str, Any]: return split_shared_activity(activity) diff --git a/docs/unified_person_projection_v1.sample.json b/docs/unified_person_projection_v1.sample.json new file mode 100644 index 0000000..742bbf4 --- /dev/null +++ b/docs/unified_person_projection_v1.sample.json @@ -0,0 +1,29 @@ +{ + "contract_name": "ops.unified_person.v1", + "contract_version": "1.0", + "contract_fingerprint": "633e2d235345d5c1bb72f8e6247e61932c5215ad2817242eefb709b502aefe03", + "projection_revision": 1, + "person_id": "person_d301001be7a1ce40df26a3eb", + "resolved_identity_key": "ops-origin-v1:9d1e0a54d988272076d6c76bfd01a4eb8b7ba2b9d06f7d014149ff37659344d6", + "identity_assurance": "verified", + "profile_status": "active", + "display_name": "Alice", + "aliases": [ + "Alice" + ], + "relation_policy_id": "default_friend", + "relation_label": "friend", + "relationship_capabilities": [ + "hugging" + ], + "owner_mode": "not_owner", + "affinity_score": 12, + "affinity_band": "positive", + "warning_stage": "none", + "confinement_state": "none", + "confinement_until": "", + "release_prompt_pending": false, + "proactive_private_enabled": false, + "group_overlay_ref": "", + "updated_at": "2026-07-27T00:00:00+00:00" +} diff --git a/docs/统一人物系统P1开发回执-20260727.md b/docs/统一人物系统P1开发回执-20260727.md new file mode 100644 index 0000000..33f56dd --- /dev/null +++ b/docs/统一人物系统P1开发回执-20260727.md @@ -0,0 +1,42 @@ +# OPS Unified Person P1 Development Receipt + +## Scope + +- Repository: `astrbot_plugin_private_companion-main` +- Start: `ops-main` at `54b4aa297a0f27791d9e677c598094457c67c64a`, with the approved P0 worktree changes present. +- P0 descriptor and fingerprint remain unchanged: `633e2d235345d5c1bb72f8e6247e61932c5215ad2817242eefb709b502aefe03`. +- This P1 patch implements companion-owned person registry and identity lifecycle only. It does not implement affinity, confinement, firewall, commands, pages, deployment, or memory-plugin writes. + +## Schema and Service + +- `unified_person` now persists `registry_version`, `audit_events`, idempotent `operations`, and reversible `merge_operations` alongside P0 profiles and identity links. +- `unified_person_registry.py` uses copy-on-write under a process-local lock. One complete five-part identity has one active link; concurrent observations cannot create duplicate profiles or links. +- `upsert_observed_identity` creates a separate deterministic person only for the exact observed five-part identity. It never follows aliases or names. +- `link_identity`, `unlink_identity`, `merge_people`, and `split_merged_people` require explicit authorization, actor, reason, and operation ID. Owner profiles additionally require `owner_authorized`. +- Merge suspends rather than deletes the source profile, snapshots exact source/target profile, active-link, and group-overlay state, and split restores that recorded mapping rather than guessing from current identities. +- Merge sets both affected profiles to `max(source_revision, target_revision) + 1`; split sets both to a value strictly higher than the merge-time maximum. Consumers therefore never observe a cross-person identity mapping change at a stale or repeated projection revision. +- DEV-003 correction: split restores only the merge-owned source profile, moved identity links, merge-added aliases, and the group-overlay `person_id`/merge-provenance fields. It deliberately preserves any later unrelated target-profile and overlay state. A moved link or merge-owned overlay whose person, origin, or merge provenance no longer matches rejects split with `split_conflict` before any write. Split revisions are higher than the recorded merge revision and both current profile revisions. +- Unlink rejects the final active identity. If it unlinks the resolved primary while another active link exists, it picks the lexicographically first remaining key and updates the profile revision. + +## API + +- Internal companion wrappers: `_unified_person_registry_status`, `_unified_person_audit_events`, and `_apply_unified_person_lifecycle` with a fixed lifecycle-method allowlist. +- Read-only Extension API additions: `get_unified_person_registry_status()` and `get_unified_person_audit_events(limit=...)`. +- Lifecycle writes are deliberately not exposed over the cross-plugin Extension API. +- Every result includes `ok`, `code`, `operation_id`, `changed`, `person_id`, `affected_person_ids`, `projection_revision`, and `audit_event_id`. Retrying the same operation ID with the identical payload returns the stored result with `idempotent=true`; a changed payload yields `operation_id_conflict`. + +## Verification + +- Directed: `C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe -m unittest tests.test_unified_person_contract tests.test_unified_person_registry -v` - 16 tests passed. +- Full: `C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe -m unittest discover -s tests -q` - 266 tests passed. +- `compileall` and `git diff --check` passed. `compileall` emitted only the pre-existing unreadable `.pytest_cache` notice and exited 0. +- Counterfactual coverage includes a cross-thread same-identity upsert, weak/unauthorized binding refusal, owner authorization refusal, last-identity refusal, exact split restoration, operation-ID conflict, and no-change assertions after failed mutations. +- DEV-003 directed regression adds post-merge unrelated target-profile and group-overlay updates that survive split while the overlay's prior provenance is restored, plus changed/deleted moved-link cases that fail with zero state changes. P0 fingerprint and projection fixture remain unchanged. + +## Risks and Next Steps + +- The lock is process-local because this plugin's JSON StoreManager is process-local. Multi-process shared-store deployment is outside current architecture and must not be added without a transactional backend. +- P1 has no owner profile administration UI; `owner_authorized` is an internal trusted-caller gate that P2 must bind to the configured owner profile and audit policy. +- Memory must continue to consume only P0 read APIs and P1 projection revisions; it must never call lifecycle write methods or invent a `person_id`. + +No commit, push, or deployment was performed. diff --git a/docs/统一人物系统P2桥接回执-20260728.md b/docs/统一人物系统P2桥接回执-20260728.md new file mode 100644 index 0000000..81c5ed7 --- /dev/null +++ b/docs/统一人物系统P2桥接回执-20260728.md @@ -0,0 +1,32 @@ +# OPS Unified Person P2 Bridge Receipt + +## Scope + +- Repository: `astrbot_plugin_private_companion-main` only. +- This correction wires the existing direct `MemoryCompanion.compose_context` path to the frozen P0 read-only person projection. +- It does not attach attributes to AstrBot events because the relative hook order is not proven here. + +## Runtime Identity + +- `companion_instance_id`: required explicit `unified_person_companion_instance_id` configuration. +- `bot_account_id`: current event Bot self ID; ambiguous or missing values fail closed. +- `adapter_instance_id`: the unique exact platform instance returned by `_preferred_platform_instance_id(kind=event.get_platform_name())`. A platform kind/name is only a lookup hint; a missing resolver or ambiguous instance set fails closed. +- `subject_namespace`: exact lookup from `unified_person_subject_namespace_map`, configured as one `adapter=namespace` pair per line. +- `platform_subject_id`: current `event.get_sender_id()` value. A conflicting caller-supplied `user_id` fails closed. +- Both new configuration values default to empty. The bridge therefore does not activate person authority until deployment identity values are explicitly reviewed and configured. + +## Person Gate + +- The adapter calls local read-only `resolve_identity` with all five dimensions. +- Only `state=resolved`, active profile, `verified` or `explicit_linked` assurance, and an active exact stored link may add `unified_person_projection` plus `unified_person_source_identity` to `session_context`. +- Missing dimensions, pending identities, identity conflicts, low assurance, changed links, cross-user calls, and cross-platform calls keep person authority absent. +- Resolution never creates, links, merges, or otherwise mutates a person. + +## Verification + +- Directed: P2 bridge, P0 contract, P1 registry, compose-argument, and platform-alias suites - 28 tests passed. +- Full: `python -m unittest discover -s tests -q` - 272 tests passed. +- `compileall` and `git diff --check` passed; `compileall` emitted only the pre-existing unreadable `.pytest_cache` notice. +- Counterfactual coverage includes unique platform-name-to-instance resolution, exact selection among same-kind instances, ambiguous platform-kind rejection, empty instance configuration, missing namespace mapping, pending, observed/low assurance, cross-user, conflicting caller user, cross-platform, and unlinked-link cases. +- P0 descriptor, fixture, and fingerprint remain unchanged. +- No commit, push, deployment, or production migration was performed. diff --git a/docs/统一人物系统开发回执-20260727.md b/docs/统一人物系统开发回执-20260727.md new file mode 100644 index 0000000..88de872 --- /dev/null +++ b/docs/统一人物系统开发回执-20260727.md @@ -0,0 +1,57 @@ +# OPS Unified Person System Development Receipt + +## Scope and starting point + +- Repository: `astrbot_plugin_private_companion-main` +- Actual branch and commit: `ops-main`, `54b4aa297a0f27791d9e677c598094457c67c64a` +- Scope completed here: P0 shared contract, identity key normalization, read-only producer endpoints, fixed projection sample, and a non-automatic reversible legacy migration foundation. +- No code from the memory repository, root documentation, `peiban`, deployment scripts, VM, or remote was modified. + +## Contract + +- Name/version: `ops.unified_person.v1` / `1.0` +- Sample version: `1.0` +- Descriptor keys: `name`, `version`, `sample_version`, `required_fields`, `enums`, `identity_key_fields` +- Deterministic fingerprint: `633e2d235345d5c1bb72f8e6247e61932c5215ad2817242eefb709b502aefe03` +- Fingerprint algorithm: SHA-256 of canonical JSON with `sort_keys=True` and `separators=(',', ':')`. +- Identity key: `ops-origin-v1:`. It requires `companion_instance_id`, `bot_account_id`, `adapter_instance_id`, `subject_namespace`, and `platform_subject_id`; it never emits a bare platform identifier or raw canonical identity JSON. +- Identity normalization accepts strings and non-boolean integers only, rejects booleans, floats (including NaN/Infinity), and containers, applies NFC and edge trimming only, preserves internal whitespace, rejects NUL and values longer than 160 characters, and lowercases only `subject_namespace`. +- The fingerprinted enum includes all frozen relationship capabilities, including `comfort`, `proactive_care`, `hugging`, `public_favoritism`, and `nsfw`; legal configured capabilities are preserved in the projection. +- Fixed consumer sample: `docs/unified_person_projection_v1.sample.json`. + +## Data and migration + +- New persisted root: `unified_person`, with `profiles`, `identity_links`, `relation_policies`, `group_overlays`, and scoped migration metadata. +- Store initialization only installs empty containers. It never performs a migration at startup. +- `preview_unified_person_migration` is non-mutating. Incomplete companion/Bot/adapter/namespace context returns `legacy_unresolved` and applies no change. `apply_unified_person_migration` retains a scoped, non-recursive pre-migration backup and is idempotent by `migration_id`. `rollback_unified_person_migration` restores that scoped backup while retaining the current backup registry, without deleting legacy `users`, `groups`, scores, or configuration. +- Legacy `relationship_score` is preserved only as `affinity_baseline`; no event history is fabricated. +- Legacy `private_user_aliases` become `legacy_alias_candidates`, not identity links. They require explicit owner confirmation before any binding. +- Legacy `relationship_role=owner` is only a warning unless an explicit backend owner ID is supplied to the migration call. + +## Read-only producer bridge + +`PrivateCompanionExtensionAPI` now exposes: + +- `get_unified_person_contract()` +- `get_unified_person_projection(person_id)` +- `resolve_unified_person_identity(identity)` + +Resolution requires the exact complete identity. An unregistered identity returns `state=pending_companion`; it creates nothing. Invalid or incomplete input returns `state=quarantined` with `error_code=invalid_identity`. + +## Hook order + +No request Hook order was changed in this P0-only patch. Firewall classification, prompt sanitation, affinity ledger settlement, confinement, owner commands, and memory write/recall gates remain deliberately unimplemented and must not be considered enabled. + +## Verification + +- Directed: `C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe -m unittest tests.test_unified_person_contract -v` - 9 tests passed. +- Full: `C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe -m unittest discover -s tests -q` - 259 tests passed. +- The directed tests are counterfactual for the old unsafe behavior: a raw/missing namespace key, auto-linking legacy aliases, a mutable unresolved resolve, an invalid sample, or a non-idempotent migration makes them fail. + +## Remaining work and cross-plugin dependency + +- The companion side must still implement explicit administrator merge/split, person creation from real message identity, relation policies, owner-profile configuration, affinity event ledger, confinement/recovery state machine, command authorization, firewall, and page/API controls. +- Memory must compare the descriptor fingerprint before consuming a projection, call only the read-only bridge methods above, and map unavailable/unresolved input to the frozen coordination states. It must not construct `person_id` from an identity key. +- The scoped migration backup is a compatibility rollback mechanism, not a substitute for an operator's normal persisted-store backup before a production migration. + +No commit, push, or deployment was performed. diff --git a/docs/错题本.md b/docs/错题本.md index b4dafea..086b83e 100644 --- a/docs/错题本.md +++ b/docs/错题本.md @@ -177,4 +177,44 @@ - Root cause: new-install defaults, the flat persisted value, and the nested `schedule_detail_config` persisted value are separate paths; startup migration can copy the nested value back over the flat one; the script also assumed a Unix developer environment. - Fix or workaround: set all three defaults to `true`; after stopping AstrBot, deploy writes the VM JSON config before startup; Bash accepts `VM`, `SSH_KEY`, `SSH_PORT`, `PYTHON_BIN`, `SKIP_LOCAL_TESTS`, and `DETAIL_ENHANCEMENT_ENABLED`; add `ops/deploy-plugin.ps1`. - Prevention rule: configuration switches must be checked at schema, runtime fallback, and production persistence layers; cross-machine deploy commands must make SSH and test-runtime dependencies explicit. -- Validation evidence: `python -m unittest discover -s tests -q` passed 250 tests; commits `d8a5c18`, `c3d7151`, and `6f1a80c` were pushed; final VM verification found `FLAT=True`, `NESTED=True`, matching `main.py` and schema hashes, `active`, and `NRestarts=0`. \ No newline at end of file +- Validation evidence: `python -m unittest discover -s tests -q` passed 250 tests; commits `d8a5c18`, `c3d7151`, and `6f1a80c` were pushed; final VM verification found `FLAT=True`, `NESTED=True`, matching `main.py` and schema hashes, `active`, and `NRestarts=0`. + +## 2026-07-27 - Unified person contract cannot infer a cross-platform identity from legacy aliases + +- Phase: OPS unified person P0 contract and migration foundation. +- Type: API contract / privacy / data migration. +- Symptom: the previous private-user alias compatibility setting can look like an identity-link source, but its old format has no immutable Bot, adapter, or subject namespace evidence. +- Root cause: legacy `private_user_aliases` was designed to merge local private delivery records, before the five-part identity key and explicit owner-controlled merge policy existed. +- Fix or workaround: contract identity keys now use `ops-origin-v1:`, require all five identity dimensions, and migration stores legacy aliases only as `legacy_alias_candidates`. It does not create an `identity_link` from them. +- Prevention rule: only an explicit administrator merge with audit evidence may link identities. Nicknames, weak aliases, bare platform IDs, device IDs, and old delivery aliases are never cross-platform binding proof. +- Validation evidence: `tests/test_unified_person_contract.py` covers namespaced key derivation, read-only unresolved behavior, legacy-alias quarantine, migration idempotence, rollback, and the fixed projection sample. + +## 2026-07-27 - Person lifecycle needs explicit owner and primary-identity safeguards + +- Phase: P1 companion person registry and identity lifecycle. +- Type: authorization / data integrity / rollback. +- Symptom: a generic authorized lifecycle request could otherwise attach or detach identities from an owner profile; detaching a profile's primary or final active identity could leave an invalid projection. +- Root cause: P0 established the read-only contract but did not yet have a lifecycle service enforcing owner-specific authorization or active-link cardinality. +- Fix or workaround: registry mutations require operation IDs and emit fixed result fields/audit evidence. Owner link, unlink, merge, and split require `owner_authorized`; unlinking the final active link is rejected; primary-link unlink deterministically promotes another active key. +- Prevention rule: never infer person binding from names or aliases; never expose a profile whose resolved identity is inactive; lifecycle changes must be copy-on-write, retry-safe, and reversible only from their recorded operation evidence. +- Validation evidence: P1 registry tests cover cross-thread upsert, owner gates, last-identity rejection, primary failover, explicit merge/split restoration, duplicate operation IDs, and failed-operation zero writes. + +## 2026-07-28 - Split must not restore a whole target profile snapshot + +- Phase: DEV-003 unified-person lifecycle hardening. +- Type: data integrity / reversible lifecycle / concurrency safety. +- Symptom: `split_merged_people` required the target profile to remain untouched after merge and restored the entire target snapshot. A harmless later target update therefore either blocked a valid split or would be lost if the guard were relaxed. +- Root cause: the merge snapshot mixed source provenance with target rollback state, while target updates have no reason to belong to the identity mapping being reversed. +- Fix or workaround: record merge revision and merge-added aliases as provenance; split validates merge-owned moved links and overlay person/origin/merge provenance before mutation, restores only the source and moved resources, and removes only merge-owned target additions. For overlays it rolls back only `person_id`, `origin_person_id`, and `merge_operation_id`, preserving independent post-merge policy state. The current target profile otherwise remains authoritative. Changed, re-bound, or deleted moved links return `split_conflict` without partial writes. +- Prevention rule: reversible operations may restore only resources they can prove they own. Never replace an aggregate target record from an old snapshot when independent updates can occur after the original operation. +- Validation evidence: `tests.test_unified_person_registry` covers preserved target follow-up state, re-bound/deleted moved-link zero-write conflicts, revision monotonicity, and existing owner/idempotency paths. + +## 2026-07-28 - Person authority needs explicit runtime identity dimensions + +- Phase: DEV-003 person-memory bridge wiring. +- Type: identity boundary / fail-closed integration. +- Symptom: direct `MemoryCompanion.compose_context` calls carried ordinary session IDs but no frozen unified-person projection, while the runtime had no canonical companion-instance or subject-namespace source. +- Root cause: P0 exposed read-only resolve APIs but deliberately did not invent deployment identity dimensions; the feature-context adapter never supplied an explicit five-part identity. +- Fix or workaround: add empty-by-default `unified_person_companion_instance_id` and exact `adapter_instance_id=subject_namespace` configuration. Resolve the event platform kind/name through `_preferred_platform_instance_id` and reject ambiguous instances; then resolve only the current event Bot, exact adapter, and sender. Inject projection/source only for an active exact link with `verified` or `explicit_linked` assurance. +- Prevention rule: plugin names, UMO prefixes, platform labels, nicknames, and bare IDs are not substitutes for configured identity dimensions. Missing, pending, mismatched, or low-assurance inputs must omit person authority. +- Validation evidence: `tests.test_p2_unified_person_bridge` covers the real compose call, configuration defaults, resolved and fail-closed counterexamples without changing the P0 fingerprint. diff --git a/main.py b/main.py index 601cc5a..c0abecd 100644 --- a/main.py +++ b/main.py @@ -156,6 +156,7 @@ except ModuleNotFoundError as exc: logger.warning("[PrivateCompanion] self_timeline.py 缺失,已跳过 Bot 自身时间线注入能力。请重新安装完整版本。") from .core_store import CoreStoreMixin +from .unified_person_contract import contract_manifest, resolve_identity from .agenda_runtime import AgendaRuntimeMixin from .platform_compat import PlatformCompatibilityMixin from .runtime_compat import probe_runtime_capabilities @@ -249,6 +250,32 @@ class PrivateCompanionExtensionAPI: result = getter() if callable(getter) else capabilities return result if isinstance(result, dict) else {"compatibility_level": "unknown", "capabilities": {}} + def get_unified_person_contract(self) -> dict[str, Any]: + """Expose the frozen P0 descriptor for consumer fingerprint checks.""" + return contract_manifest() + + def get_unified_person_projection(self, person_id: str) -> dict[str, Any] | None: + """Read-only bridge endpoint. It never creates a person as a side effect.""" + return self._plugin._get_unified_person_projection(str(person_id or "").strip()) + + def get_unified_person_registry_status(self) -> dict[str, Any]: + return self._plugin._unified_person_registry_status() + + def get_unified_person_audit_events(self, *, limit: int = 100) -> list[dict[str, Any]]: + return self._plugin._unified_person_audit_events(limit=limit) + + def resolve_unified_person_identity(self, identity: dict[str, Any]) -> dict[str, Any]: + """Resolve only an exact five-part identity key; no nickname or bare ID fallback.""" + try: + return resolve_identity(self._plugin.data, identity) + except ValueError as exc: + return { + "state": "quarantined", + "person_id": "", + "error_code": "invalid_identity", + "reason": _single_line(exc, 120), + } + def register_proactive_ability(self, spec: dict[str, Any]) -> bool: return self._plugin.register_external_proactive_ability(spec) @@ -1876,6 +1903,12 @@ class PrivateCompanionPlugin( # 而运维版把那个开关硬编码成 False(原意只是「不用 LivingMemory」), # 结果把唯一长期记忆源也一起关掉,Bot 个人归档链路在 VM 上整条静默停摆。 self.enable_memory_companion_bridge = self._cfg_bool(c, "enable_memory_companion_bridge", True) + self.unified_person_companion_instance_id = self._cfg_str( + c, "unified_person_companion_instance_id", "" + ) + self.unified_person_subject_namespace_map = self._cfg_raw( + c, "unified_person_subject_namespace_map", "" + ) self.memory_companion_context_timeout_seconds = self._cfg_float(c, "memory_companion_context_timeout_seconds", 1.2, 0.2) self.enable_memory_companion_emotional_drift = self._cfg_bool(c, "enable_memory_companion_emotional_drift", True) self.enable_memory_companion_cross_window_emotion = self._cfg_bool(c, "enable_memory_companion_cross_window_emotion", True) diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index 16fb17b..d440434 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -14,6 +14,7 @@ from astrbot.api import logger from .helpers import _missing_optional_model_dependency, _safe_float, _safe_int, _single_line from .bot_personal_dto import PrivacyRejected, build_bot_personal_dto from .bot_personal_outbox import due_outbox, enqueue_outbox, update_outbox +from .unified_person_contract import build_identity_key, resolve_identity def _media_file_name(value: Any, limit: int = 120) -> str: @@ -387,6 +388,112 @@ class MemoryCompanionAdapterMixin: known_ids.add(value) return next(iter(known_ids)) if len(known_ids) == 1 else "" + @staticmethod + def _memory_companion_subject_namespace_map(value: Any) -> dict[str, str]: + if isinstance(value, dict): + items = value.items() + elif isinstance(value, str): + pairs: list[tuple[str, str]] = [] + for raw_line in value.splitlines(): + line = raw_line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + adapter_id, namespace = line.split("=", 1) + pairs.append((adapter_id, namespace)) + items = pairs + else: + return {} + result: dict[str, str] = {} + for raw_adapter_id, raw_namespace in items: + adapter_id = _single_line(raw_adapter_id, 160) + namespace = _single_line(raw_namespace, 160).lower() + if adapter_id and namespace: + result[adapter_id] = namespace + return result + + def _memory_companion_unified_person_authority( + self, + event: Any | None, + *, + expected_user_id: str = "", + ) -> dict[str, Any]: + """Resolve exact configured identity; never synthesize missing dimensions.""" + if event is None: + return {} + companion_instance_id = _single_line( + getattr(self, "unified_person_companion_instance_id", ""), + 160, + ) + namespace_map = self._memory_companion_subject_namespace_map( + getattr(self, "unified_person_subject_namespace_map", {}) + ) + try: + sender_id = _single_line(event.get_sender_id(), 160) + except Exception: + sender_id = "" + expected_user_id = _single_line(expected_user_id, 160) + if not sender_id or (expected_user_id and expected_user_id != sender_id): + return {} + try: + platform_hint = _single_line(event.get_platform_name(), 160) + except Exception: + platform_hint = "" + instance_resolver = getattr(self, "_preferred_platform_instance_id", None) + if not platform_hint or not callable(instance_resolver): + return {} + try: + adapter_instance_id = _single_line(instance_resolver(kind=platform_hint), 160) + except Exception: + adapter_instance_id = "" + bot_account_id = _single_line(self._memory_companion_bridge_bot_id(event), 160) + subject_namespace = namespace_map.get(adapter_instance_id, "") + if not all((companion_instance_id, bot_account_id, adapter_instance_id, subject_namespace)): + return {} + source_identity = { + "companion_instance_id": companion_instance_id, + "bot_account_id": bot_account_id, + "adapter_instance_id": adapter_instance_id, + "subject_namespace": subject_namespace, + "platform_subject_id": sender_id, + } + try: + identity_key = build_identity_key(source_identity) + except ValueError: + return {} + data = getattr(self, "data", None) + resolved = resolve_identity(data, source_identity) if isinstance(data, dict) else {} + if resolved.get("state") != "resolved" or resolved.get("identity_key") != identity_key: + return {} + projection = resolved.get("projection") + if not isinstance(projection, dict): + return {} + if projection.get("profile_status") != "active": + return {} + if projection.get("identity_assurance") not in {"verified", "explicit_linked"}: + return {} + person_id = _single_line(resolved.get("person_id"), 160) + if not person_id or projection.get("person_id") != person_id or projection.get("resolved_identity_key") != identity_key: + return {} + root = data.get("unified_person") if isinstance(data.get("unified_person"), dict) else {} + links = root.get("identity_links") if isinstance(root.get("identity_links"), dict) else {} + link = links.get(identity_key) + if ( + not isinstance(link, dict) + or link.get("status") != "active" + or link.get("person_id") != person_id + or link.get("identity_key") not in (None, identity_key) + ): + return {} + try: + if build_identity_key(link.get("identity")) != identity_key: + return {} + except ValueError: + return {} + return { + "unified_person_projection": projection, + "unified_person_source_identity": source_identity, + } + def _memory_companion_schedule_session_context(self, *, message_text: str = "") -> dict[str, Any]: user_id, user = self._memory_companion_schedule_owner_context() umo = _single_line(user.get("umo"), 200) if isinstance(user, dict) else "" @@ -652,6 +759,12 @@ class MemoryCompanionAdapterMixin: "strict_session_only": bool(strict_session_only), "topic_fit_policy": "旧话题和未完成话头只作可选参考;和当前问题不贴时先放着,不必为了兑现它改变本轮话题。", } + session_context.update( + self._memory_companion_unified_person_authority( + event, + expected_user_id=session_context.get("user_id", ""), + ) + ) try: bot_mood, bot_energy = self._memory_companion_bot_emotional_state() configured_timeout = max(0.2, min(6.0, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2))) diff --git a/platform_compat.py b/platform_compat.py index 795802f..19e445b 100644 --- a/platform_compat.py +++ b/platform_compat.py @@ -214,6 +214,7 @@ class PlatformCompatibilityMixin: platforms = list(manager.get_insts()) except Exception: platforms = list(getattr(manager, "platform_insts", []) or []) + requested_matches: list[str] = [] matches: list[str] = [] active_instances: list[str] = [] for platform in platforms: @@ -237,12 +238,17 @@ class PlatformCompatibilityMixin: _single_line(getattr(meta, "id", ""), 80), _single_line(getattr(meta, "name", ""), 80), }: - return instance_id + if instance_id and instance_id not in requested_matches: + requested_matches.append(instance_id) platform_kind = self._platform_kind_from_meta(meta) if platform_kind != desired: continue if instance_id and instance_id not in matches: matches.append(instance_id) + if len(requested_matches) == 1: + return requested_matches[0] + if len(requested_matches) > 1: + return "" if len(matches) == 1: return matches[0] if not matches and len(active_instances) == 1: diff --git a/tests/test_p2_unified_person_bridge.py b/tests/test_p2_unified_person_bridge.py new file mode 100644 index 0000000..a625447 --- /dev/null +++ b/tests/test_p2_unified_person_bridge.py @@ -0,0 +1,226 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +import asyncio +import importlib +import json +import pathlib +import sys +import types +import unittest +from types import SimpleNamespace + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +import _host_stub # noqa: E402 + +_host_stub.install() + +_PACKAGE_NAME = "_p2_person_bridge_companion" +if _PACKAGE_NAME not in sys.modules: + package = types.ModuleType(_PACKAGE_NAME) + package.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])] + sys.modules[_PACKAGE_NAME] = package + +adapter_module = importlib.import_module(f"{_PACKAGE_NAME}.memory_companion_adapter") +contract = importlib.import_module(f"{_PACKAGE_NAME}.unified_person_contract") +platform_module = importlib.import_module(f"{_PACKAGE_NAME}.platform_compat") +registry_module = importlib.import_module(f"{_PACKAGE_NAME}.unified_person_registry") + + +class _Bridge: + def __init__(self) -> None: + self.calls: list[dict] = [] + + async def compose_context(self, **kwargs): + self.calls.append(kwargs) + return "context" + + +class _Platform: + def __init__(self, instance_id: str, name: str) -> None: + self._meta = SimpleNamespace(id=instance_id, name=name, description=name) + self.status = None + + def meta(self): + return self._meta + + +class _PlatformManager: + def __init__(self, platforms: list[_Platform]) -> None: + self._platforms = platforms + + def get_insts(self): + return list(self._platforms) + + +class _Host(adapter_module.MemoryCompanionAdapterMixin, platform_module.PlatformCompatibilityMixin): + def __init__(self) -> None: + self.enable_memory_companion_feature_context = True + self.memory_companion_context_top_k = 5 + self.memory_companion_context_max_chars = 900 + self.memory_companion_context_timeout_seconds = 2.0 + self.unified_person_companion_instance_id = "companion-a" + self.unified_person_subject_namespace_map = ( + "onebot-main=onebot.sender_id\n" + "webchat-main=webchat.sender_id" + ) + self.context = SimpleNamespace( + platform_manager=_PlatformManager([ + _Platform("onebot-main", "aiocqhttp"), + _Platform("webchat-main", "webchat"), + ]) + ) + self.bridge = _Bridge() + self.data = {"unified_person": contract.empty_unified_person_store()} + + def _memory_companion_bridge(self): + return self.bridge + + def _memory_companion_bridge_bot_id(self, event=None): + return "bot-1" + + def _memory_companion_bot_emotional_state(self): + return "steady", 0.5 + + def _sender_display_name(self, event): + return "Alice" + + +def _event(subject_id: str, *, adapter: str = "aiocqhttp"): + return SimpleNamespace( + unified_msg_origin=f"{adapter}:FriendMessage:{subject_id}", + get_sender_id=lambda: subject_id, + get_platform_name=lambda: adapter, + is_private_chat=lambda: True, + ) + + +def _identity(subject_id: str, *, adapter: str = "onebot-main") -> dict[str, str]: + namespace = "webchat.sender_id" if adapter == "webchat-main" else "onebot.sender_id" + return { + "companion_instance_id": "companion-a", + "bot_account_id": "bot-1", + "adapter_instance_id": adapter, + "subject_namespace": namespace, + "platform_subject_id": subject_id, + } + + +class UnifiedPersonComposeBridgeTests(unittest.TestCase): + def test_explicit_identity_configuration_is_visible_and_fail_closed_by_default(self): + schema_path = pathlib.Path(__file__).resolve().parents[1] / "_conf_schema.json" + schema = json.loads(schema_path.read_text(encoding="utf-8")) + items = schema["external_memory_config"]["items"] + companion = items["unified_person_companion_instance_id"] + namespace_map = items["unified_person_subject_namespace_map"] + self.assertEqual((companion["type"], companion["default"]), ("string", "")) + self.assertEqual((namespace_map["type"], namespace_map["default"]), ("text", "")) + + def _register( + self, + host: _Host, + subject_id: str, + *, + adapter: str = "onebot-main", + assurance: str = "verified", + ) -> str: + identity = _identity(subject_id, adapter=adapter) + registry = registry_module.UnifiedPersonRegistry(host.data) + result = registry.upsert_observed_identity( + identity, + operation_id=f"observe-{adapter}-{subject_id}", + display_name=f"user-{subject_id}", + ) + person_id = result["person_id"] + identity_key = contract.build_identity_key(identity) + host.data["unified_person"]["profiles"][person_id]["identity_assurance"] = assurance + host.data["unified_person"]["identity_links"][identity_key]["identity_assurance"] = assurance + return person_id + + def _compose(self, host: _Host, event, *, user_id: str = "") -> dict: + asyncio.run( + host._memory_companion_compose_feature_context( + kind="p2_person_gate", + query="current message", + event=event, + user_id=user_id, + ) + ) + return host.bridge.calls[-1]["session_context"] + + def test_resolved_high_assurance_projection_reaches_real_compose_context(self): + host = _Host() + person_id = self._register(host, "42") + + session = self._compose(host, _event("42")) + + self.assertEqual(session["unified_person_projection"]["person_id"], person_id) + self.assertEqual(session["unified_person_projection"]["identity_assurance"], "verified") + self.assertEqual(session["unified_person_source_identity"], _identity("42")) + + def test_platform_hint_resolves_exact_instance_and_ambiguity_fails_closed(self): + exact_host = _Host() + exact_host.context.platform_manager = _PlatformManager([ + _Platform("onebot-a", "napcat-a"), + _Platform("onebot-b", "napcat-b"), + ]) + exact_host.unified_person_subject_namespace_map = ( + "onebot-a=onebot.sender_id\n" + "onebot-b=onebot.sender_id" + ) + exact_person_id = self._register(exact_host, "42", adapter="onebot-a") + + exact = self._compose(exact_host, _event("42", adapter="onebot-a")) + self.assertEqual(exact["unified_person_projection"]["person_id"], exact_person_id) + self.assertEqual(exact["unified_person_source_identity"]["adapter_instance_id"], "onebot-a") + + ambiguous = self._compose(exact_host, _event("42", adapter="onebot")) + self.assertNotIn("unified_person_projection", ambiguous) + + exact_host.context.platform_manager = _PlatformManager([ + _Platform("onebot-a", "aiocqhttp"), + _Platform("onebot-b", "aiocqhttp"), + ]) + ambiguous_name = self._compose(exact_host, _event("42", adapter="aiocqhttp")) + self.assertNotIn("unified_person_projection", ambiguous_name) + + def test_missing_dimension_pending_and_low_assurance_fail_closed(self): + missing_host = _Host() + missing_host.unified_person_companion_instance_id = "" + missing = self._compose(missing_host, _event("42")) + self.assertNotIn("unified_person_projection", missing) + + missing_namespace_host = _Host() + missing_namespace_host.unified_person_subject_namespace_map = "" + missing_namespace = self._compose(missing_namespace_host, _event("42")) + self.assertNotIn("unified_person_projection", missing_namespace) + + pending_host = _Host() + pending = self._compose(pending_host, _event("42")) + self.assertNotIn("unified_person_projection", pending) + + observed_host = _Host() + self._register(observed_host, "42", assurance="observed") + observed = self._compose(observed_host, _event("42")) + self.assertNotIn("unified_person_projection", observed) + + def test_cross_user_cross_platform_and_changed_link_never_gain_authority(self): + host = _Host() + person_id = self._register(host, "42") + + cross_user = self._compose(host, _event("99")) + self.assertNotIn("unified_person_projection", cross_user) + mismatched_argument = self._compose(host, _event("42"), user_id="99") + self.assertNotIn("unified_person_projection", mismatched_argument) + cross_platform = self._compose(host, _event("42", adapter="webchat")) + self.assertNotIn("unified_person_projection", cross_platform) + + identity_key = contract.build_identity_key(_identity("42")) + host.data["unified_person"]["identity_links"][identity_key]["status"] = "unlinked" + changed_link = self._compose(host, _event("42")) + self.assertNotIn("unified_person_projection", changed_link) + self.assertEqual(host.data["unified_person"]["profiles"][person_id]["profile_status"], "active") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_unified_person_contract.py b/tests/test_unified_person_contract.py new file mode 100644 index 0000000..8e9ec54 --- /dev/null +++ b/tests/test_unified_person_contract.py @@ -0,0 +1,309 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +from copy import deepcopy +import hashlib +import json +from pathlib import Path +import unittest + +from unified_person_contract import ( + CONTRACT_FINGERPRINT, + CONTRACT_NAME, + CONTRACT_VERSION, + apply_unified_person_migration, + build_identity_key, + build_person_projection, + contract_manifest, + empty_unified_person_store, + ensure_unified_person_store, + preview_unified_person_migration, + resolve_identity, + rollback_unified_person_migration, + validate_projection, +) + + +ROOT = Path(__file__).resolve().parents[1] + + +class UnifiedPersonContractTests(unittest.TestCase): + def test_descriptor_uses_the_cross_plugin_canonical_shape_and_hash(self): + descriptor = contract_manifest() + self.assertEqual(set(descriptor), {"name", "version", "sample_version", "required_fields", "enums", "identity_key_fields", "contract_fingerprint"}) + self.assertEqual(descriptor["name"], CONTRACT_NAME) + self.assertEqual(descriptor["version"], CONTRACT_VERSION) + self.assertEqual(descriptor["sample_version"], "1.0") + canonical = json.dumps( + {key: value for key, value in descriptor.items() if key != "contract_fingerprint"}, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ) + self.assertEqual(hashlib.sha256(canonical.encode("utf-8")).hexdigest(), CONTRACT_FINGERPRINT) + self.assertEqual(CONTRACT_FINGERPRINT, "633e2d235345d5c1bb72f8e6247e61932c5215ad2817242eefb709b502aefe03") + self.assertEqual( + descriptor["enums"]["relationship_capabilities"], + [ + "acting_cute", "affectionate_address", "comfort", "confession", "exclusivity", "flirting", + "hand_holding", "head_pat", "hugging", "jealousy", "joking", "leaning_close", "missing_you", + "nsfw", "proactive_care", "public_favoritism", "romantic_expression", "sweet_talk", + ], + ) + + def test_identity_key_requires_all_namespaces_and_never_exposes_raw_json(self): + identity = { + "companion_instance_id": "companion-a", + "bot_account_id": "bot-1", + "adapter_instance_id": "telegram-main", + "subject_namespace": "Telegram.User", + "platform_subject_id": "42", + } + key = build_identity_key(identity) + self.assertEqual(key, "ops-origin-v1:9d1e0a54d988272076d6c76bfd01a4eb8b7ba2b9d06f7d014149ff37659344d6") + self.assertNotIn("telegram-main", key) + changed_bot = dict(identity, bot_account_id="bot-2") + self.assertNotEqual(key, build_identity_key(changed_bot)) + with self.assertRaises(ValueError): + build_identity_key({"platform_subject_id": "42"}) + + def test_identity_text_normalization_matches_the_frozen_cross_plugin_rules(self): + base = { + "companion_instance_id": " cafe\u0301 ", + "bot_account_id": 0, + "adapter_instance_id": "adapter one", + "subject_namespace": " Telegram.User ", + "platform_subject_id": " subject id ", + } + normalized_key = build_identity_key(base) + equivalent = { + "companion_instance_id": "caf\u00e9", + "bot_account_id": "0", + "adapter_instance_id": "adapter one", + "subject_namespace": "telegram.user", + "platform_subject_id": "subject id", + } + self.assertEqual(normalized_key, build_identity_key(equivalent)) + self.assertNotEqual( + normalized_key, + build_identity_key({**equivalent, "adapter_instance_id": "adapter one"}), + ) + for field, value in ( + ("bot_account_id", True), + ("bot_account_id", {"value": "bot"}), + ("bot_account_id", ["bot"]), + ("bot_account_id", ("bot",)), + ("bot_account_id", {"bot"}), + ("bot_account_id", 1.0), + ("bot_account_id", float("nan")), + ("bot_account_id", float("inf")), + ("bot_account_id", "bot\x00id"), + ("bot_account_id", "x" * 161), + ): + with self.subTest(field=field, value_type=type(value).__name__): + with self.assertRaises(ValueError): + build_identity_key({**equivalent, field: value}) + + def test_fixed_projection_sample_is_valid_and_uses_integer_revision(self): + sample = json.loads((ROOT / "docs" / "unified_person_projection_v1.sample.json").read_text(encoding="utf-8")) + self.assertEqual(validate_projection(sample), []) + self.assertIsInstance(sample["projection_revision"], int) + self.assertEqual(sample["relationship_capabilities"], ["hugging"]) + self.assertEqual(sample["person_id"], "person_d301001be7a1ce40df26a3eb") + + def test_resolve_is_read_only_when_person_is_not_registered(self): + store = {"unified_person": empty_unified_person_store()} + before = deepcopy(store) + result = resolve_identity(store, { + "companion_instance_id": "companion-a", + "bot_account_id": "bot-1", + "adapter_instance_id": "telegram-main", + "subject_namespace": "telegram.user", + "platform_subject_id": "42", + }) + self.assertEqual(result["state"], "pending_companion") + self.assertEqual(store, before) + invalid = resolve_identity(store, {"platform_subject_id": "42"}) + self.assertEqual(invalid["state"], "quarantined") + self.assertEqual(invalid["error_code"], "invalid_identity") + self.assertEqual(store, before) + + def test_missing_migration_context_is_legacy_unresolved_and_writes_nothing(self): + store = {"users": {"42": {"nickname": "Alice", "relationship_score": 12}}} + before = deepcopy(store) + preview = preview_unified_person_migration(store) + self.assertFalse(preview["ok"]) + self.assertEqual(preview["coordination_status"], "legacy_unresolved") + self.assertEqual(preview["would_create_profiles"], 0) + applied = apply_unified_person_migration(store, migration_id="no-context") + self.assertFalse(applied["applied"]) + self.assertEqual(applied["error_code"], "identity_context_incomplete") + self.assertEqual(store, before) + + def test_preview_apply_idempotence_and_rollback_preserve_legacy_sources(self): + store = { + "users": { + "42": {"nickname": "Alice", "relationship_score": 12, "relationship_role": "owner"}, + }, + "groups": { + "g1": {"members": {"42": {"nickname": "群名片"}, "99": {"nickname": "Bob"}}}, + }, + } + legacy_before = deepcopy({"users": store["users"], "groups": store["groups"]}) + context = { + "companion_instance_id": "companion-a", + "bot_account_id": "bot-1", + "adapter_instance_id": "telegram-main", + "subject_namespace": "telegram.user", + } + preview = preview_unified_person_migration( + store, + identity_context=context, + private_user_aliases={"AliceNick": "42"}, + ) + self.assertEqual(preview["mode"], "preview") + self.assertEqual(preview["would_create_profiles"], 2) + self.assertEqual(preview["would_create_identity_links"], 2) + self.assertEqual(preview["legacy_alias_candidates"], 1) + self.assertNotIn("unified_person", store) + + applied = apply_unified_person_migration( + store, + identity_context=context, + private_user_aliases={"AliceNick": "42"}, + migration_id="test-legacy-v1", + now="2026-07-27T00:00:00+00:00", + ) + self.assertTrue(applied["applied"]) + self.assertEqual({"users": store["users"], "groups": store["groups"]}, legacy_before) + self.assertEqual(len(store["unified_person"]["profiles"]), 2) + self.assertEqual(len(store["unified_person"]["identity_links"]), 2) + self.assertEqual(store["unified_person"]["migration"]["legacy_alias_candidates"], [{"alias": "AliceNick", "canonical": "42"}]) + self.assertEqual(resolve_identity(store, {**context, "platform_subject_id": "AliceNick"})["state"], "pending_companion") + + second = apply_unified_person_migration(store, identity_context=context, migration_id="test-legacy-v1") + self.assertTrue(second["idempotent"]) + second_migration = apply_unified_person_migration(store, identity_context=context, migration_id="test-legacy-v2") + self.assertTrue(second_migration["applied"]) + backups = store["unified_person"]["migration"]["backups"] + self.assertEqual(backups["test-legacy-v1"]["migration"]["backups"], {}) + self.assertEqual(backups["test-legacy-v2"]["migration"]["backups"], {}) + self.assertTrue(rollback_unified_person_migration(store, "test-legacy-v2")["rolled_back"]) + self.assertEqual(set(store["unified_person"]["migration"]["backups"]), {"test-legacy-v1", "test-legacy-v2"}) + self.assertTrue(apply_unified_person_migration(store, identity_context=context, migration_id="test-legacy-v2")["applied"]) + self.assertTrue(rollback_unified_person_migration(store, "test-legacy-v1")["rolled_back"]) + self.assertEqual(store["unified_person"]["profiles"], {}) + self.assertTrue(rollback_unified_person_migration(store, "test-legacy-v1")["rolled_back"]) + + def test_projection_uses_policy_capabilities_and_contract_validator(self): + store = {"unified_person": empty_unified_person_store()} + _, changed = ensure_unified_person_store(store) + self.assertFalse(changed) + identity = { + "companion_instance_id": "companion-a", + "bot_account_id": "bot-1", + "adapter_instance_id": "telegram-main", + "subject_namespace": "telegram.user", + "platform_subject_id": "42", + } + result = apply_unified_person_migration( + store, + identity_context={key: value for key, value in identity.items() if key != "platform_subject_id"}, + migration_id="projection-v1", + now="2026-07-27T00:00:00+00:00", + ) + self.assertTrue(result["applied"]) + # Add an explicit profile/link in the empty legacy store to exercise bridge rendering. + key = build_identity_key(identity) + person_id = "person_test" + store["unified_person"]["identity_links"][key] = {"person_id": person_id, "identity_assurance": "verified"} + store["unified_person"]["profiles"][person_id] = { + "person_id": person_id, + "resolved_identity_key": key, + "identity_assurance": "verified", + "profile_status": "active", + "display_name": "Alice", + "aliases": ["Alice"], + "relation_policy_id": "default_friend", + "owner_mode": "not_owner", + "affinity_score": 12, + "warning_stage": "none", + "confinement_state": "none", + "confinement_until": "", + "release_prompt_pending": False, + "proactive_private_enabled": False, + "group_overlay_ref": "", + "projection_revision": 1, + "updated_at": "2026-07-27T00:00:00+00:00", + } + store["unified_person"]["relation_policies"]["default_friend"]["capabilities"] = ["comfort", "hugging", "public_favoritism", "nsfw"] + projection = build_person_projection(store, person_id) + self.assertIsNotNone(projection) + self.assertEqual(validate_projection(projection), []) + self.assertEqual(projection["relationship_capabilities"], ["comfort", "hugging", "public_favoritism", "nsfw"]) + + def test_corrupted_storage_is_normalized_or_rejected_before_bridge_output(self): + broken_store = {"unified_person": {"version": "not-an-integer"}} + _, changed = ensure_unified_person_store(broken_store) + self.assertTrue(changed) + self.assertEqual(broken_store["unified_person"]["version"], 1) + + store = {"unified_person": empty_unified_person_store()} + identity = { + "companion_instance_id": "companion-a", + "bot_account_id": "bot-1", + "adapter_instance_id": "telegram-main", + "subject_namespace": "telegram.user", + "platform_subject_id": "42", + } + key = build_identity_key(identity) + store["unified_person"]["identity_links"][key] = {"person_id": "person_bad", "identity_assurance": "bad"} + store["unified_person"]["profiles"]["person_bad"] = { + "person_id": "person_bad", + "resolved_identity_key": key, + "identity_assurance": "bad", + "profile_status": "bad", + "display_name": "Alice", + "aliases": [], + "relation_policy_id": "default_friend", + "owner_mode": "bad", + "affinity_score": 999999, + "warning_stage": "bad", + "confinement_state": "bad", + "confinement_until": "", + "release_prompt_pending": False, + "proactive_private_enabled": False, + "group_overlay_ref": "", + "projection_revision": 0, + "updated_at": "2026-07-27T00:00:00+00:00", + } + projection = build_person_projection(store, "person_bad") + self.assertIsNotNone(projection) + self.assertEqual(validate_projection(projection), []) + self.assertEqual(projection["profile_status"], "active") + self.assertEqual(projection["warning_stage"], "none") + self.assertEqual(projection["confinement_state"], "none") + self.assertEqual(projection["projection_revision"], 1) + self.assertEqual(projection["affinity_score"], 1200) + self.assertEqual(projection["affinity_band"], "positive") + + valid_profile = deepcopy(store["unified_person"]["profiles"]["person_bad"]) + valid_policy = deepcopy(store["unified_person"]["relation_policies"]["default_friend"]) + for field, invalid in ( + ("person_id", ""), + ("resolved_identity_key", "not-an-origin-key"), + ("display_name", "x" * 161), + ("relation_policy_id", "\x00"), + ("aliases", ["bad\x00alias"]), + ("updated_at", ""), + ): + with self.subTest(field=field): + store["unified_person"]["profiles"]["person_bad"] = {**valid_profile, field: invalid} + self.assertIsNone(build_person_projection(store, "person_bad")) + store["unified_person"]["profiles"]["person_bad"] = valid_profile + store["unified_person"]["relation_policies"]["default_friend"] = {**valid_policy, "label": "\x00"} + self.assertIsNone(build_person_projection(store, "person_bad")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_unified_person_registry.py b/tests/test_unified_person_registry.py new file mode 100644 index 0000000..c8e0eb1 --- /dev/null +++ b/tests/test_unified_person_registry.py @@ -0,0 +1,308 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +from copy import deepcopy +import threading +import unittest + +from unified_person_contract import build_identity_key, build_person_projection, empty_unified_person_store, resolve_identity, validate_projection +from unified_person_registry import UnifiedPersonRegistry + + +RESULT_FIELDS = { + "ok", "code", "operation_id", "changed", "person_id", "affected_person_ids", "projection_revision", "audit_event_id", +} + + +def identity(subject_id: str, *, bot: str = "bot-1", adapter: str = "telegram-main", namespace: str = "telegram.user") -> dict[str, str]: + return { + "companion_instance_id": "companion-a", + "bot_account_id": bot, + "adapter_instance_id": adapter, + "subject_namespace": namespace, + "platform_subject_id": subject_id, + } + + +class UnifiedPersonRegistryTests(unittest.TestCase): + def setUp(self) -> None: + self.store = {"unified_person": empty_unified_person_store()} + self.registry = UnifiedPersonRegistry(self.store) + + def _observe(self, subject_id: str, operation_id: str) -> dict: + return self.registry.upsert_observed_identity(identity(subject_id), operation_id=operation_id, display_name=f"user-{subject_id}") + + def test_concurrent_same_identity_upsert_creates_one_profile_and_link(self): + barrier = threading.Barrier(8) + results: list[dict] = [] + result_lock = threading.Lock() + + def worker(index: int) -> None: + barrier.wait() + result = self._observe("42", f"observe-{index}") + with result_lock: + results.append(result) + + threads = [threading.Thread(target=worker, args=(index,)) for index in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + self.assertEqual(len(results), 8) + self.assertEqual(sum(result["code"] == "person_created" for result in results), 1) + self.assertEqual(len(self.store["unified_person"]["profiles"]), 1) + self.assertEqual(len(self.store["unified_person"]["identity_links"]), 1) + for result in results: + self.assertTrue(RESULT_FIELDS.issubset(result)) + self.assertTrue(result["operation_id"].startswith("observe-")) + other_bot = self.registry.upsert_observed_identity(identity("42", bot="bot-2"), operation_id="observe-other-bot") + other_namespace = self.registry.upsert_observed_identity(identity("42", namespace="telegram.channel_author"), operation_id="observe-other-namespace") + self.assertNotEqual(other_bot["person_id"], other_namespace["person_id"]) + self.assertEqual(len(self.store["unified_person"]["profiles"]), 3) + + def test_explicit_link_unlink_is_idempotent_and_never_uses_weak_aliases(self): + first = self._observe("42", "observe-42") + person_id = first["person_id"] + before = deepcopy(self.store) + denied = self.registry.link_identity( + identity("alice-name"), person_id, operation_id="link-denied", actor_id="operator", reason="nickname match", authorized=False, + ) + self.assertEqual(denied["code"], "unauthorized") + self.assertEqual(denied["operation_id"], "link-denied") + self.assertEqual(self.store, before) + + linked = self.registry.link_identity( + identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id"), + person_id, + operation_id="link-explicit", + actor_id="owner-person", + reason="owner verified account binding", + authorized=True, + ) + self.assertTrue(linked["changed"]) + self.assertEqual(linked["person_id"], person_id) + repeated = self.registry.link_identity( + identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id"), + person_id, + operation_id="link-explicit", + actor_id="owner-person", + reason="owner verified account binding", + authorized=True, + ) + self.assertTrue(repeated["idempotent"]) + resolved = resolve_identity(self.store, identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id")) + self.assertEqual(resolved["person_id"], person_id) + self.assertEqual(resolved["projection"]["resolved_identity_key"], build_identity_key(identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id"))) + + unlinked = self.registry.unlink_identity( + identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id"), + operation_id="unlink-explicit", actor_id="owner-person", reason="binding revoked", authorized=True, + ) + self.assertTrue(unlinked["changed"]) + link = self.store["unified_person"]["identity_links"][unlinked["identity_key"]] + self.assertEqual(link["status"], "unlinked") + self.assertEqual(link["origin_identity_key"], unlinked["identity_key"]) + + def test_merge_split_restore_exact_links_and_require_owner_authorization(self): + source_id = self._observe("42", "observe-source")["person_id"] + target_id = self._observe("99", "observe-target")["person_id"] + self.store["unified_person"]["profiles"][source_id]["owner_mode"] = "owner" + self.store["unified_person"]["profiles"][source_id]["projection_revision"] = 10 + self.store["unified_person"]["profiles"][target_id]["projection_revision"] = 2 + before = deepcopy(self.store) + denied = self.registry.merge_people( + source_id, target_id, operation_id="merge-denied", actor_id="operator", reason="owner request", authorized=True, + ) + self.assertEqual(denied["code"], "owner_authorization_required") + self.assertEqual(self.store, before) + merged = self.registry.merge_people( + source_id, target_id, operation_id="merge-1", actor_id="owner-person", reason="explicit account merge", authorized=True, owner_authorized=True, + ) + self.assertTrue(merged["changed"]) + self.assertEqual(self.store["unified_person"]["profiles"][source_id]["profile_status"], "suspended") + source_key = build_identity_key(identity("42")) + self.assertEqual(self.store["unified_person"]["identity_links"][source_key]["person_id"], target_id) + consumed_merge_projection = resolve_identity(self.store, identity("42"))["projection"] + merge_revision = consumed_merge_projection["projection_revision"] + self.assertEqual(merge_revision, 11) + split_denied = self.registry.split_merged_people( + "merge-1", operation_id="split-denied", actor_id="operator", reason="try", authorized=True, + ) + self.assertEqual(split_denied["code"], "owner_authorization_required") + split = self.registry.split_merged_people( + "merge-1", operation_id="split-1", actor_id="owner-person", reason="explicit undo", authorized=True, owner_authorized=True, + ) + self.assertTrue(split["changed"]) + self.assertEqual(self.store["unified_person"]["identity_links"][source_key]["person_id"], source_id) + self.assertEqual(self.store["unified_person"]["profiles"][source_id]["profile_status"], "active") + self.assertEqual(self.store["unified_person"]["merge_operations"]["merge-1"]["state"], "reversed") + split_projection = resolve_identity(self.store, identity("42"))["projection"] + self.assertGreater(split_projection["projection_revision"], merge_revision) + + def test_split_preserves_unrelated_target_follow_up_state(self): + source_id = self._observe("42", "observe-source-follow-up")["person_id"] + target_id = self._observe("99", "observe-target-follow-up")["person_id"] + source = self.store["unified_person"]["profiles"][source_id] + source["aliases"] = ["source-only-alias"] + overlay_key = "group-follow-up" + self.store["unified_person"]["group_overlays"][overlay_key] = { + "person_id": source_id, + "origin_person_id": "preexisting-origin", + "merge_operation_id": "preexisting-merge", + "group_id": "group-1", + "policy": {"quiet_hours": False}, + } + merged = self.registry.merge_people( + source_id, target_id, operation_id="merge-follow-up", actor_id="operator", + reason="explicit account merge", authorized=True, + ) + self.assertTrue(merged["ok"]) + merged_overlay = self.store["unified_person"]["group_overlays"][overlay_key] + self.assertEqual(merged_overlay["person_id"], target_id) + self.assertEqual(merged_overlay["origin_person_id"], source_id) + self.assertEqual(merged_overlay["merge_operation_id"], "merge-follow-up") + merged_overlay["policy"]["quiet_hours"] = True + merged_overlay["post_merge_note"] = "must survive split" + target = self.store["unified_person"]["profiles"][target_id] + target.update({ + "display_name": "target after merge", + "relation_policy_id": "default_friend", + "aliases": list(target.get("aliases") or []) + ["target-follow-up-alias"], + "unrelated_follow_up": {"note": "must survive split"}, + "projection_revision": merged["projection_revision"] + 7, + "last_operation_id": "target-unrelated-follow-up", + }) + current_target_revision = target["projection_revision"] + + split = self.registry.split_merged_people( + "merge-follow-up", operation_id="split-follow-up", actor_id="operator", + reason="explicit undo", authorized=True, + ) + + self.assertTrue(split["ok"]) + restored_source = self.store["unified_person"]["profiles"][source_id] + preserved_target = self.store["unified_person"]["profiles"][target_id] + self.assertEqual(restored_source["aliases"], ["source-only-alias"]) + self.assertEqual(preserved_target["display_name"], "target after merge") + self.assertIn("target-follow-up-alias", preserved_target["aliases"]) + self.assertNotIn("source-only-alias", preserved_target["aliases"]) + self.assertEqual(preserved_target["unrelated_follow_up"], {"note": "must survive split"}) + restored_overlay = self.store["unified_person"]["group_overlays"][overlay_key] + self.assertEqual(restored_overlay["person_id"], source_id) + self.assertEqual(restored_overlay["origin_person_id"], "preexisting-origin") + self.assertEqual(restored_overlay["merge_operation_id"], "preexisting-merge") + self.assertTrue(restored_overlay["policy"]["quiet_hours"]) + self.assertEqual(restored_overlay["post_merge_note"], "must survive split") + self.assertGreater(restored_source["projection_revision"], merged["projection_revision"]) + self.assertGreater(preserved_target["projection_revision"], merged["projection_revision"]) + self.assertGreater(restored_source["projection_revision"], current_target_revision) + self.assertEqual(restored_source["projection_revision"], preserved_target["projection_revision"]) + after_split = deepcopy(self.store) + repeated = self.registry.split_merged_people( + "merge-follow-up", operation_id="split-follow-up", actor_id="operator", + reason="explicit undo", authorized=True, + ) + self.assertTrue(repeated["idempotent"]) + self.assertEqual(self.store, after_split) + + def test_split_conflicts_without_writes_when_a_moved_link_changes(self): + for mutation in ("rebind", "delete"): + with self.subTest(mutation=mutation): + self.store = {"unified_person": empty_unified_person_store()} + self.registry = UnifiedPersonRegistry(self.store) + source_id = self._observe("42", f"observe-source-{mutation}")["person_id"] + target_id = self._observe("99", f"observe-target-{mutation}")["person_id"] + merged = self.registry.merge_people( + source_id, target_id, operation_id=f"merge-{mutation}", actor_id="operator", + reason="explicit account merge", authorized=True, + ) + self.assertTrue(merged["ok"]) + source_key = build_identity_key(identity("42")) + if mutation == "rebind": + self.store["unified_person"]["identity_links"][source_key]["last_operation_id"] = "later-explicit-rebind" + else: + del self.store["unified_person"]["identity_links"][source_key] + before = deepcopy(self.store) + + split = self.registry.split_merged_people( + f"merge-{mutation}", operation_id=f"split-{mutation}", actor_id="operator", + reason="must not overwrite changed link", authorized=True, + ) + + self.assertEqual(split["code"], "split_conflict") + self.assertEqual(self.store, before) + + def test_split_conflicts_without_writes_when_overlay_provenance_changes(self): + source_id = self._observe("42", "observe-source-overlay-conflict")["person_id"] + target_id = self._observe("99", "observe-target-overlay-conflict")["person_id"] + self.store["unified_person"]["group_overlays"]["group-overlay-conflict"] = { + "person_id": source_id, + "group_id": "group-1", + "policy": {"quiet_hours": False}, + } + merged = self.registry.merge_people( + source_id, target_id, operation_id="merge-overlay-conflict", actor_id="operator", + reason="explicit account merge", authorized=True, + ) + self.assertTrue(merged["ok"]) + self.store["unified_person"]["group_overlays"]["group-overlay-conflict"]["origin_person_id"] = "later-origin" + before = deepcopy(self.store) + + split = self.registry.split_merged_people( + "merge-overlay-conflict", operation_id="split-overlay-conflict", actor_id="operator", + reason="must not overwrite changed overlay provenance", authorized=True, + ) + + self.assertEqual(split["code"], "split_conflict") + self.assertEqual(self.store, before) + + def test_operation_id_conflict_and_bad_requests_do_not_partially_write(self): + first = self._observe("42", "same-operation") + before = deepcopy(self.store) + conflict = self.registry.upsert_observed_identity(identity("99"), operation_id="same-operation", display_name="user-99") + self.assertEqual(conflict["code"], "operation_id_conflict") + self.assertEqual(self.store, before) + malformed = self.registry.upsert_observed_identity({"platform_subject_id": "42"}, operation_id="malformed") + self.assertEqual(malformed["code"], "invalid_identity") + self.assertEqual(self.store, before) + self.assertTrue(RESULT_FIELDS.issubset(first)) + + def test_owner_link_unlink_and_primary_failover_preserve_a_valid_projection(self): + owner_id = self._observe("42", "observe-owner")["person_id"] + self.store["unified_person"]["profiles"][owner_id]["owner_mode"] = "owner" + before = deepcopy(self.store) + denied_link = self.registry.link_identity( + identity("43"), owner_id, operation_id="owner-link-denied", actor_id="operator", reason="test", authorized=True, + ) + self.assertEqual(denied_link["code"], "owner_authorization_required") + self.assertEqual(self.store, before) + linked = self.registry.link_identity( + identity("43"), owner_id, operation_id="owner-link", actor_id="owner", reason="verified", authorized=True, owner_authorized=True, + ) + self.assertTrue(linked["changed"]) + denied_unlink = self.registry.unlink_identity( + identity("42"), operation_id="owner-unlink-denied", actor_id="operator", reason="test", authorized=True, + ) + self.assertEqual(denied_unlink["code"], "owner_authorization_required") + primary_key = build_identity_key(identity("42")) + unlinked = self.registry.unlink_identity( + identity("42"), operation_id="owner-unlink", actor_id="owner", reason="verified revoke", authorized=True, owner_authorized=True, + ) + self.assertTrue(unlinked["changed"]) + profile = self.store["unified_person"]["profiles"][owner_id] + self.assertNotEqual(profile["resolved_identity_key"], primary_key) + projection = build_person_projection(self.store, owner_id) + self.assertIsNotNone(projection) + self.assertEqual(validate_projection(projection), []) + + lone = self._observe("99", "observe-lone")["person_id"] + before_last_unlink = deepcopy(self.store) + last = self.registry.unlink_identity( + identity("99"), operation_id="unlink-last", actor_id="owner", reason="not allowed", authorized=True, + ) + self.assertEqual(last["code"], "last_identity_required") + self.assertEqual(self.store, before_last_unlink) + + +if __name__ == "__main__": + unittest.main() diff --git a/unified_person_contract.py b/unified_person_contract.py new file mode 100644 index 0000000..e65c6ab --- /dev/null +++ b/unified_person_contract.py @@ -0,0 +1,663 @@ +# -*- 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} diff --git a/unified_person_registry.py b/unified_person_registry.py new file mode 100644 index 0000000..b085937 --- /dev/null +++ b/unified_person_registry.py @@ -0,0 +1,586 @@ +# -*- 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