# -*- 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()