From f35e55c4566afd4231e0cbd364bbac61f4b5589d Mon Sep 17 00:00:00 2001 From: Codex Local Date: Thu, 30 Jul 2026 03:09:53 +0800 Subject: [PATCH] feat(c2): consume person and context projections read-only --- core/bridge.py | 36 +++ core/context_consumer.py | 155 ++++++++++++ core/person_context_contract.py | 421 +++++++++++++++++++++++++++++++ core/person_projection.py | 142 +++++++++++ tests/test_c2_memory_consumer.py | 144 +++++++++++ 5 files changed, 898 insertions(+) create mode 100644 core/context_consumer.py create mode 100644 core/person_context_contract.py create mode 100644 core/person_projection.py create mode 100644 tests/test_c2_memory_consumer.py diff --git a/core/bridge.py b/core/bridge.py index 4440597..1cd3047 100644 --- a/core/bridge.py +++ b/core/bridge.py @@ -5,7 +5,9 @@ from typing import Any from zoneinfo import ZoneInfo from . import bot_personal_contract +from .context_consumer import consume_context_projection from .models import EntityRef, MemoryRecord, SessionContext, clean_text +from .person_projection import consume_person_projection LOCAL_TZ = ZoneInfo("Asia/Shanghai") @@ -310,6 +312,38 @@ class MemoryCompanionBridge: result.setdefault("degraded", False) return result + def consume_person_projection( + self, + projection: Any, + expected_identity_key: str = "", + expected_person_id: str = "", + *, + companion_available: bool = True, + ) -> dict[str, Any]: + """Validate a companion-owned person projection without writing memory state.""" + return consume_person_projection( + projection, + expected_identity_key=expected_identity_key, + expected_person_id=expected_person_id, + companion_available=companion_available, + ) + + def consume_context_projection( + self, + context: Any, + expected_person_id: str = "", + expected_scope: str = "", + *, + companion_available: bool = True, + ) -> dict[str, Any]: + """Validate a P3 projection without creating people or storing raw text.""" + return consume_context_projection( + context, + expected_person_id=expected_person_id, + expected_scope=expected_scope, + companion_available=companion_available, + ) + def probe_bot_personal_memory_capabilities(self) -> dict[str, Any]: """Return a database-free capability snapshot for the bot-personal contract. @@ -385,6 +419,8 @@ class MemoryCompanionBridge: "compose_context", "remember", "recall", + "consume_person_projection", + "consume_context_projection", "probe_bot_personal_memory_capabilities", ], ) diff --git a/core/context_consumer.py b/core/context_consumer.py new file mode 100644 index 0000000..86a565b --- /dev/null +++ b/core/context_consumer.py @@ -0,0 +1,155 @@ +"""Read-only consumer for the P3 context projection contract.""" + +from __future__ import annotations + +from typing import Any + +from .person_context_contract import ( + P3_SLOT_NAMES, + build_context_projection, + merge_context_slots, + validate_context_projection, + validate_context_slot, +) + + +_FORBIDDEN_KEYS = { + "raw_prompt", + "prompt", + "private_object", + "private_object_ref", + "object", + "chat_text", + "content", + "messages", + "transcript", + "database", +} + + +def _safe_value(value: Any, depth: int = 0) -> Any: + """Make a bounded metadata-only copy and drop text-bearing/private data.""" + + if depth > 2 or value is None or isinstance(value, bool): + return value if value is None or isinstance(value, bool) else None + if isinstance(value, (int, float)): + return value + if isinstance(value, str): + return value[:240] + if isinstance(value, list): + return [_safe_value(item, depth + 1) for item in value[:12]] + if isinstance(value, dict): + result: dict[str, Any] = {} + for key, item in list(value.items())[:24]: + name = str(key).strip().lower() + if not name or name in _FORBIDDEN_KEYS: + continue + safe = _safe_value(item, depth + 1) + if safe is not None: + result[name[:80]] = safe + return result + return None + + +def _slot_ref(slot: dict[str, Any]) -> dict[str, Any]: + return { + "slot": slot["slot"], + "owner": slot["owner"], + "revision": slot["revision"], + "contract_fingerprint": slot["contract_fingerprint"], + "state": slot["state"], + "payload": _safe_value(slot.get("payload") or {}) or {}, + "warnings": [str(item)[:120] for item in slot.get("warnings", [])[:8]], + } + + +def consume_context_projection( + context: Any, + expected_person_id: str = "", + expected_scope: str = "", + *, + companion_available: bool = True, +) -> dict[str, Any]: + """Validate and consume P3 slots, never persisting or mutating input. + + Invalid slots are rejected individually. Valid slots are merged using the + shared revision-aware contract helper, so an older duplicate cannot + replace a newer slot. The returned context contains only safe metadata. + """ + + base = {"read_only": True, "source": "companion_context"} + if not companion_available: + return {**base, "state": "degraded", "degraded": True, "errors": ["companion_unavailable"]} + if context is None or (isinstance(context, dict) and "slots" not in context): + return {**base, "state": "legacy_local", "legacy_local": True, "warnings": ["context_missing"]} + if not isinstance(context, dict): + return {**base, "state": "invalid", "errors": ["context_invalid"]} + + errors = list(validate_context_projection(context)) + context_state = str(context.get("state") or "ready") + if context_state not in {"ready", "legacy_local", "invalid", "degraded", "pending"}: + errors.append("context_state_invalid") + if context_state == "invalid": + errors.append("context_invalid_state") + if expected_person_id: + context_person_id = context.get("person_id") + if context_person_id and context_person_id != expected_person_id: + errors.append("person_id_mismatch") + if expected_scope: + context_scope = context.get("scope") + if context_scope and context_scope != expected_scope: + errors.append("scope_mismatch") + + incoming_slots = context.get("slots") if isinstance(context.get("slots"), dict) else {} + accepted: dict[str, dict[str, Any]] = {} + rejected: dict[str, list[str]] = {} + for name in P3_SLOT_NAMES: + candidate = incoming_slots.get(name) + slot_errors = validate_context_slot(candidate, name) + if slot_errors: + rejected[name] = slot_errors + continue + payload = candidate.get("payload") if isinstance(candidate.get("payload"), dict) else {} + if expected_person_id and payload.get("person_id") and payload.get("person_id") != expected_person_id: + rejected[name] = ["person_id_mismatch"] + continue + if expected_scope and payload.get("scope") and payload.get("scope") != expected_scope: + rejected[name] = ["scope_mismatch"] + continue + if candidate.get("state") == "invalid": + errors.append(f"{name}_state_invalid") + rejected[name] = ["slot_state_invalid"] + continue + accepted[name] = dict(candidate) + + if errors: + return {**base, "state": "invalid", "errors": sorted(set(errors)), "rejected_slots": rejected} + + safe_incoming = {"revision": context.get("revision", 1), "slots": accepted} + merged = merge_context_slots(build_context_projection(), safe_incoming) + safe_slots = {name: _slot_ref(merged["slots"][name]) for name in P3_SLOT_NAMES} + slot_states = {str(slot.get("state") or "ready") for slot in accepted.values()} + if context_state == "degraded" or "degraded" in slot_states: + state = "degraded" + elif context_state == "pending" or "pending" in slot_states: + state = "pending" + elif context_state == "legacy_local" or slot_states and slot_states.issubset({"legacy_local"}): + state = "legacy_local" + else: + state = "ready" + result: dict[str, Any] = { + **base, + "state": state, + "degraded": state == "degraded", + "context_ref": { + "revision": merged["revision"], + "contract_fingerprint": merged["contract_fingerprint"], + "slots": safe_slots, + }, + } + if rejected: + result["rejected_slots"] = rejected + return result + + +__all__ = ["consume_context_projection"] diff --git a/core/person_context_contract.py b/core/person_context_contract.py new file mode 100644 index 0000000..ba78f32 --- /dev/null +++ b/core/person_context_contract.py @@ -0,0 +1,421 @@ +from __future__ import annotations + +from datetime import datetime, timezone +import hashlib +import json +import re +import unicodedata +from typing import Any + + +CONTRACT_NAME = "chat.unified_person.v1" +CONTRACT_VERSION = "1.0" +PROJECTION_SCHEMA_VERSION = "1.0" +P3_CONTRACT_NAME = "chat.p3.context.v1" +P3_CONTRACT_VERSION = "1.0" +P3_SLOT_NAMES = ("persona", "runtime", "person", "scene") +P3_SLOT_OWNERS = { + "persona": "companion", + "runtime": "companion", + "person": "memory_projection", + "scene": "companion", +} +P3_SLOT_STATES = frozenset({"ready", "legacy_local", "invalid", "degraded", "pending"}) +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_schema_version", + "projection_revision", + "person_id", + "resolved_identity_key", + "identity_assurance", + "profile_status", + "display_name", + "aliases", + "relation_policy_id", + "relation_label", + "owner_mode", + "affinity_score", + "affinity_band", + "relationship_capabilities", + "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"}) +RELATIONSHIP_CAPABILITIES = frozenset( + { + "comfort", + "proactive_care", + "joking", + "affectionate_address", + "missing_you", + "romantic_expression", + } +) +CONTEXT_FORBIDDEN_KEYS = frozenset( + { + "raw_prompt", + "prompt", + "private_object", + "private_object_ref", + "object", + "chat_text", + "content", + "messages", + "transcript", + "database", + } +) + + +def _canonical(value: Any) -> str: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def _text(value: Any, field: str, limit: int = 160) -> str: + if isinstance(value, bool) or not isinstance(value, (str, int)): + raise ValueError(f"{field}_invalid") + text = unicodedata.normalize("NFC", str(value)).strip() + if not text or "\x00" in text or len(text) > limit: + raise ValueError(f"{field}_invalid") + return text + + +def canonical_identity(identity: dict[str, Any]) -> dict[str, str]: + if not isinstance(identity, dict): + raise ValueError("identity_invalid") + 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: + digest = hashlib.sha256(_canonical(canonical_identity(identity)).encode("utf-8")).hexdigest() + return f"chat-origin-v1:{digest}" + + +def person_id_for_identity(identity: dict[str, Any]) -> str: + return f"person_{hashlib.sha256(build_identity_key(identity).encode('utf-8')).hexdigest()[:24]}" + + +def affinity_band(score: Any) -> str: + try: + value = int(score) + except (TypeError, ValueError): + value = 0 + if value <= -800: + return "critical" + if value < 0: + return "guarded" + if value == 0: + return "neutral" + return "positive" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def empty_person_store() -> dict[str, Any]: + return { + "version": 1, + "profiles": {}, + "identity_links": {}, + "group_overlays": {}, + "relation_policies": { + "default_friend": { + "label": "friend", + "capabilities": [], + "active": True, + } + }, + "audit_events": [], + } + + +def ensure_person_store(data: dict[str, Any]) -> tuple[dict[str, Any], bool]: + if not isinstance(data, dict): + raise ValueError("store_invalid") + changed = False + root = data.get("unified_person") + if not isinstance(root, dict): + data["unified_person"] = empty_person_store() + return data, True + defaults = empty_person_store() + for key, value in defaults.items(): + if key not in root or not isinstance(root.get(key), type(value)): + root[key] = value.copy() if isinstance(value, dict) else list(value) if isinstance(value, list) else value + changed = True + root["version"] = max(1, int(root.get("version") or 0)) + return data, changed + + +def _list_text(value: Any, limit: int = 120, count: int = 12) -> list[str]: + if not isinstance(value, (list, tuple)): + return [] + result: list[str] = [] + for item in value: + try: + text = _text(item, "list_item", limit) + except ValueError: + continue + if text not in result: + result.append(text) + if len(result) >= count: + break + return result + + +def build_person_projection(store: dict[str, Any], person_id: str) -> dict[str, Any] | None: + root = store.get("unified_person") if isinstance(store, dict) else None + profiles = root.get("profiles") if isinstance(root, dict) and isinstance(root.get("profiles"), dict) else {} + profile = profiles.get(str(person_id or "")) + if not isinstance(profile, dict): + return None + identity_key = profile.get("resolved_identity_key") + policy_id = str(profile.get("relation_policy_id") or "default_friend") + policies = root.get("relation_policies") if isinstance(root.get("relation_policies"), dict) else {} + policy = policies.get(policy_id) if isinstance(policies.get(policy_id), dict) else {} + projection = { + "contract_name": CONTRACT_NAME, + "contract_version": CONTRACT_VERSION, + "contract_fingerprint": CONTRACT_FINGERPRINT, + "projection_schema_version": PROJECTION_SCHEMA_VERSION, + "projection_revision": max(1, int(profile.get("projection_revision") or 1)), + "person_id": str(profile.get("person_id") or ""), + "resolved_identity_key": str(identity_key or ""), + "identity_assurance": str(profile.get("identity_assurance") or "unverified"), + "profile_status": str(profile.get("profile_status") or "active"), + "display_name": str(profile.get("display_name") or ""), + "aliases": _list_text(profile.get("aliases")), + "relation_policy_id": policy_id, + "relation_label": str(policy.get("label") or "friend"), + "owner_mode": str(profile.get("owner_mode") or "not_owner"), + "affinity_score": max(-1200, min(1200, int(profile.get("affinity_score") or 0))), + "affinity_band": affinity_band(profile.get("affinity_score") or 0), + "relationship_capabilities": [ + item for item in _list_text(policy.get("capabilities"), 60) if item in RELATIONSHIP_CAPABILITIES + ], + "group_overlay_ref": str(profile.get("group_overlay_ref") or ""), + "updated_at": str(profile.get("updated_at") or ""), + } + return projection if not validate_projection(projection) else None + + +def validate_projection(projection: Any) -> list[str]: + if not isinstance(projection, dict): + return ["projection_invalid"] + errors = [f"missing_{field}" for field in PROJECTION_FIELDS if field not in projection] + if errors: + return errors + if projection.get("contract_name") != CONTRACT_NAME: + errors.append("contract_name_mismatch") + if projection.get("contract_version") != CONTRACT_VERSION: + errors.append("contract_version_mismatch") + if projection.get("contract_fingerprint") != CONTRACT_FINGERPRINT: + errors.append("contract_fingerprint_mismatch") + if projection.get("projection_schema_version") != PROJECTION_SCHEMA_VERSION: + errors.append("projection_schema_version_mismatch") + for field in ("person_id", "resolved_identity_key", "display_name", "relation_policy_id", "relation_label", "updated_at"): + value = projection.get(field) + if not isinstance(value, str) or not value or "\x00" in value or len(value) > 240: + errors.append(f"{field}_invalid") + if not re.fullmatch(r"chat-origin-v1:[0-9a-f]{64}", str(projection.get("resolved_identity_key") or "")): + errors.append("resolved_identity_key_invalid") + if not re.fullmatch(r"person_[0-9a-f]{24}", str(projection.get("person_id") or "")): + errors.append("person_id_invalid") + if not isinstance(projection.get("projection_revision"), int) or projection["projection_revision"] < 1: + errors.append("projection_revision_invalid") + if projection.get("identity_assurance") not in IDENTITY_ASSURANCE_VALUES: + errors.append("identity_assurance_invalid") + if projection.get("profile_status") not in PROFILE_STATUS_VALUES: + errors.append("profile_status_invalid") + if projection.get("owner_mode") not in OWNER_MODE_VALUES: + errors.append("owner_mode_invalid") + if not isinstance(projection.get("aliases"), list) or any(not isinstance(item, str) for item in projection["aliases"]): + errors.append("aliases_invalid") + if not isinstance(projection.get("relationship_capabilities"), list) or not set(projection["relationship_capabilities"]).issubset(RELATIONSHIP_CAPABILITIES): + errors.append("relationship_capabilities_invalid") + score = projection.get("affinity_score") + if not isinstance(score, int) or not -1200 <= score <= 1200: + errors.append("affinity_score_invalid") + elif projection.get("affinity_band") != affinity_band(score): + errors.append("affinity_band_inconsistent") + if projection.get("group_overlay_ref") is not None and not isinstance(projection.get("group_overlay_ref"), str): + errors.append("group_overlay_ref_invalid") + return errors + + +def resolve_identity(store: dict[str, Any], identity: dict[str, Any]) -> dict[str, Any]: + try: + identity_key = build_identity_key(identity) + except ValueError: + return {"state": "invalid", "identity_key": "", "person_id": "", "errors": ["identity_invalid"]} + 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", "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": "invalid", "identity_key": identity_key, "person_id": person_id, "errors": ["projection_invalid"]} + return {"state": "resolved", "identity_key": identity_key, "person_id": person_id, "projection": projection} + + +def _safe_context_value(value: Any, depth: int = 0) -> Any: + if depth > 2: + return None + if isinstance(value, bool) or value is None or isinstance(value, (int, float)): + return value + if isinstance(value, str): + return value[:240] + if isinstance(value, (list, tuple)): + return [_safe_context_value(item, depth + 1) for item in list(value)[:12]] + if isinstance(value, dict): + result: dict[str, Any] = {} + for key, item in list(value.items())[:24]: + name = str(key).strip().lower() + if not name or name in CONTEXT_FORBIDDEN_KEYS: + continue + safe = _safe_context_value(item, depth + 1) + if safe is not None: + result[name[:80]] = safe + return result + return None + + +def make_context_slot(slot: str, payload: dict[str, Any] | None, *, owner: str = "", revision: int = 1, state: str = "ready", warnings: list[str] | None = None) -> dict[str, Any]: + slot_name = str(slot or "") + actual_owner = owner or P3_SLOT_OWNERS.get(slot_name, "unknown") + return { + "slot": slot_name, + "owner": actual_owner, + "revision": max(1, int(revision or 1)), + "contract_name": P3_CONTRACT_NAME, + "contract_version": P3_CONTRACT_VERSION, + "contract_fingerprint": P3_CONTRACT_FINGERPRINT, + "state": state if state in P3_SLOT_STATES else "invalid", + "payload": _safe_context_value(payload or {}) or {}, + "warnings": [str(item)[:120] for item in (warnings or [])[:8]], + } + + +def validate_context_slot(slot: Any, expected_name: str = "") -> list[str]: + if not isinstance(slot, dict): + return ["slot_invalid"] + errors: list[str] = [] + name = str(slot.get("slot") or "") + if name not in P3_SLOT_NAMES or (expected_name and name != expected_name): + errors.append("slot_name_invalid") + if slot.get("owner") != P3_SLOT_OWNERS.get(name): + errors.append("slot_owner_mismatch") + if slot.get("contract_name") != P3_CONTRACT_NAME or slot.get("contract_version") != P3_CONTRACT_VERSION: + errors.append("slot_contract_mismatch") + if slot.get("contract_fingerprint") != P3_CONTRACT_FINGERPRINT: + errors.append("slot_fingerprint_mismatch") + if not isinstance(slot.get("revision"), int) or slot["revision"] < 1: + errors.append("slot_revision_invalid") + if slot.get("state") not in P3_SLOT_STATES: + errors.append("slot_state_invalid") + if not isinstance(slot.get("payload"), dict): + errors.append("slot_payload_invalid") + return errors + + +def build_context_projection(slots: dict[str, dict[str, Any]] | None = None, *, state: str = "ready", revision: int = 1, warnings: list[str] | None = None) -> dict[str, Any]: + incoming = slots if isinstance(slots, dict) else {} + return { + "contract_name": P3_CONTRACT_NAME, + "contract_version": P3_CONTRACT_VERSION, + "contract_fingerprint": P3_CONTRACT_FINGERPRINT, + "revision": max(1, int(revision or 1)), + "state": state if state in P3_SLOT_STATES else "invalid", + "slots": {name: incoming.get(name, make_context_slot(name, {}, state="pending")) for name in P3_SLOT_NAMES}, + "warnings": [str(item)[:120] for item in (warnings or [])[:8]], + } + + +def validate_context_projection(context: Any) -> list[str]: + if not isinstance(context, dict): + return ["context_invalid"] + errors: list[str] = [] + if context.get("contract_name") != P3_CONTRACT_NAME or context.get("contract_version") != P3_CONTRACT_VERSION: + errors.append("context_contract_mismatch") + if context.get("contract_fingerprint") != P3_CONTRACT_FINGERPRINT: + errors.append("context_fingerprint_mismatch") + slots = context.get("slots") + if not isinstance(slots, dict): + return errors + ["context_slots_invalid"] + for name in P3_SLOT_NAMES: + errors.extend(validate_context_slot(slots.get(name), name)) + return errors + + +def merge_context_slots(existing: dict[str, Any], incoming: dict[str, Any]) -> dict[str, Any]: + result = dict(existing) if isinstance(existing, dict) else build_context_projection() + old_slots = result.get("slots") if isinstance(result.get("slots"), dict) else {} + new_slots = incoming.get("slots") if isinstance(incoming, dict) and isinstance(incoming.get("slots"), dict) else {} + merged = dict(old_slots) + for name in P3_SLOT_NAMES: + candidate = new_slots.get(name) + if not isinstance(candidate, dict) or validate_context_slot(candidate, name): + continue + previous = merged.get(name) + if not isinstance(previous, dict) or int(candidate.get("revision") or 0) >= int(previous.get("revision") or 0): + merged[name] = candidate + result["slots"] = merged + result["revision"] = max(int(result.get("revision") or 1), int(incoming.get("revision") or 1) if isinstance(incoming, dict) else 1) + return result + + +def _contract_shape() -> dict[str, Any]: + return { + "name": CONTRACT_NAME, + "version": CONTRACT_VERSION, + "projection_schema_version": PROJECTION_SCHEMA_VERSION, + "identity_fields": list(IDENTITY_FIELDS), + "projection_fields": list(PROJECTION_FIELDS), + "p3_name": P3_CONTRACT_NAME, + "p3_version": P3_CONTRACT_VERSION, + "p3_slots": list(P3_SLOT_NAMES), + "p3_owners": dict(P3_SLOT_OWNERS), + } + + +CONTRACT_FINGERPRINT = hashlib.sha256(_canonical(_contract_shape()).encode("utf-8")).hexdigest()[:16] +P3_CONTRACT_FINGERPRINT = hashlib.sha256( + _canonical({"name": P3_CONTRACT_NAME, "version": P3_CONTRACT_VERSION, "slots": list(P3_SLOT_NAMES), "owners": P3_SLOT_OWNERS}).encode("utf-8") +).hexdigest()[:16] + + +def contract_self_check() -> list[str]: + errors: list[str] = [] + if CONTRACT_FINGERPRINT != hashlib.sha256(_canonical(_contract_shape()).encode("utf-8")).hexdigest()[:16]: + errors.append("contract_fingerprint_stale") + if P3_CONTRACT_FINGERPRINT != hashlib.sha256( + _canonical({"name": P3_CONTRACT_NAME, "version": P3_CONTRACT_VERSION, "slots": list(P3_SLOT_NAMES), "owners": P3_SLOT_OWNERS}).encode("utf-8") + ).hexdigest()[:16]: + errors.append("p3_contract_fingerprint_stale") + if set(P3_SLOT_NAMES) != set(P3_SLOT_OWNERS): + errors.append("p3_slot_owner_mismatch") + return errors + + +__all__ = [name for name in globals() if name.isupper() or name in { + "affinity_band", "build_context_projection", "build_identity_key", "build_person_projection", + "canonical_identity", "contract_self_check", "empty_person_store", "ensure_person_store", + "make_context_slot", "merge_context_slots", "person_id_for_identity", "resolve_identity", + "validate_context_projection", "validate_context_slot", "validate_projection", +}] diff --git a/core/person_projection.py b/core/person_projection.py new file mode 100644 index 0000000..366320d --- /dev/null +++ b/core/person_projection.py @@ -0,0 +1,142 @@ +"""Read-only consumer for the companion-owned Unified Person projection. + +The memory plugin is deliberately not an authority for person creation or +identity linking. This module accepts a projection produced by the companion +plugin, validates it against the shared contract, and returns only a small +safe reference suitable for memory retrieval/context decisions. +""" + +from __future__ import annotations + +from typing import Any + +from .person_context_contract import ( + PROJECTION_SCHEMA_VERSION, + CONTRACT_FINGERPRINT, + resolve_identity, + validate_projection, +) + + +_SAFE_REFERENCE_FIELDS = ( + "person_id", + "resolved_identity_key", + "projection_revision", + "projection_schema_version", + "contract_fingerprint", + "identity_assurance", + "profile_status", + "owner_mode", + "relation_policy_id", + "relation_label", + "affinity_band", + "relationship_capabilities", + "group_overlay_ref", + "updated_at", +) + + +def _reference(projection: dict[str, Any]) -> dict[str, Any]: + """Copy only contract-approved metadata; never return caller objects.""" + + result: dict[str, Any] = {} + for field in _SAFE_REFERENCE_FIELDS: + value = projection.get(field) + if field == "relationship_capabilities": + result[field] = list(value) if isinstance(value, list) else [] + else: + result[field] = value + return result + + +def consume_person_projection( + projection: Any, + expected_identity_key: str = "", + expected_person_id: str = "", + *, + companion_available: bool = True, + identity_store: dict[str, Any] | None = None, + identity: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Consume a companion projection without creating or mutating anything. + + ``identity_store`` and ``identity`` are optional read-only verification + inputs. When both are supplied, the shared ``resolve_identity`` contract + function is used and the resolved person/key must agree with the incoming + projection. Normal bridge calls only need the three positional arguments. + """ + + base = {"read_only": True, "source": "companion_projection"} + if not companion_available: + return { + **base, + "state": "degraded", + "degraded": True, + "errors": ["companion_unavailable"], + } + if not isinstance(projection, dict): + return {**base, "state": "invalid", "errors": ["projection_invalid"]} + + errors = list(validate_projection(projection)) + if errors: + return {**base, "state": "invalid", "errors": errors} + + person_id = str(projection.get("person_id") or "") + identity_key = str(projection.get("resolved_identity_key") or "") + if expected_person_id and person_id != expected_person_id: + errors.append("person_id_mismatch") + if expected_identity_key and identity_key != expected_identity_key: + errors.append("identity_key_mismatch") + + if identity_store is not None or identity is not None: + if not isinstance(identity_store, dict) or not isinstance(identity, dict): + errors.append("identity_resolution_input_invalid") + else: + resolved = resolve_identity(identity_store, identity) + if resolved.get("state") != "resolved": + errors.append(f"identity_{resolved.get('state', 'invalid')}") + else: + if resolved.get("identity_key") != identity_key: + errors.append("identity_key_unresolved") + if resolved.get("person_id") != person_id: + errors.append("person_id_unresolved") + + if errors: + return { + **base, + "state": "invalid", + "errors": errors, + "projection_ref": {"person_id": person_id, "resolved_identity_key": identity_key}, + } + + return { + **base, + "state": "resolved", + "degraded": False, + "projection_ref": _reference(projection), + } + + +def projection_capability(*, companion_available: bool = True) -> dict[str, Any]: + """Return a database-free, read-only capability descriptor.""" + + if not companion_available: + return { + "available": False, + "state": "degraded", + "degraded": True, + "read_only": True, + "reason": "companion_unavailable", + } + return { + "available": True, + "state": "ready", + "degraded": False, + "read_only": True, + "projection_schema_version": PROJECTION_SCHEMA_VERSION, + "contract_fingerprint": CONTRACT_FINGERPRINT, + "methods": ["consume_person_projection"], + } + + +__all__ = ["consume_person_projection", "projection_capability"] diff --git a/tests/test_c2_memory_consumer.py b/tests/test_c2_memory_consumer.py new file mode 100644 index 0000000..cf9e0ca --- /dev/null +++ b/tests/test_c2_memory_consumer.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +from copy import deepcopy + +from core.context_consumer import consume_context_projection +from core.person_context_contract import ( + P3_SLOT_NAMES, + build_context_projection, + build_identity_key, + build_person_projection, + empty_person_store, + make_context_slot, + person_id_for_identity, +) +from core.person_projection import consume_person_projection + + +IDENTITY = { + "companion_instance_id": "companion-test", + "bot_account_id": "bot-1", + "adapter_instance_id": "adapter-1", + "subject_namespace": "qq", + "platform_subject_id": "user-42", +} + + +def _projection(): + store = {"unified_person": empty_person_store()} + person_id = person_id_for_identity(IDENTITY) + identity_key = build_identity_key(IDENTITY) + store["unified_person"]["profiles"][person_id] = { + "person_id": person_id, + "resolved_identity_key": identity_key, + "identity_assurance": "verified", + "profile_status": "active", + "display_name": "Alice", + "aliases": ["A"], + "owner_mode": "not_owner", + "affinity_score": 12, + "projection_revision": 3, + "relation_policy_id": "default_friend", + "group_overlay_ref": "", + "updated_at": "2026-07-30T00:00:00+00:00", + } + store["unified_person"]["identity_links"][identity_key] = {"person_id": person_id} + return build_person_projection(store, person_id), store, person_id, identity_key + + +def test_projection_is_resolved_and_only_returns_safe_reference(): + projection, store, person_id, identity_key = _projection() + result = consume_person_projection( + projection, + expected_identity_key=identity_key, + expected_person_id=person_id, + identity_store=store, + identity=IDENTITY, + ) + assert result["state"] == "resolved" + assert result["projection_ref"]["person_id"] == person_id + assert "display_name" not in result["projection_ref"] + assert result["read_only"] is True + + +def test_projection_rejects_version_fingerprint_and_expected_identity_mismatch(): + projection, _, person_id, identity_key = _projection() + bad = deepcopy(projection) + bad["contract_fingerprint"] = "wrong" + assert consume_person_projection(bad)["state"] == "invalid" + assert "contract_fingerprint_mismatch" in consume_person_projection(bad)["errors"] + mismatch = consume_person_projection(projection, "wrong", person_id) + assert mismatch["state"] == "invalid" + assert "identity_key_mismatch" in mismatch["errors"] + assert consume_person_projection(projection, identity_key, "person_000000000000000000000000")["state"] == "invalid" + + +def test_projection_unavailable_is_explicitly_degraded(): + projection, _, _, _ = _projection() + result = consume_person_projection(projection, companion_available=False) + assert result["state"] == "degraded" + assert result["degraded"] is True + + +def _context(*, revision=4, person_id="person_abc", scope="private"): + slots = { + name: make_context_slot( + name, + {"person_id": person_id, "scope": scope, "label": name, "raw_prompt": "do not leak"}, + revision=revision, + ) + for name in P3_SLOT_NAMES + } + context = build_context_projection(slots, revision=revision) + context["person_id"] = person_id + context["scope"] = scope + return context + + +def test_context_consumes_four_owned_slots_and_strips_raw_text(): + result = consume_context_projection(_context(), "person_abc", "private") + assert result["state"] == "ready" + assert set(result["context_ref"]["slots"]) == set(P3_SLOT_NAMES) + for slot in result["context_ref"]["slots"].values(): + assert "raw_prompt" not in slot["payload"] + assert slot["owner"] + + +def test_context_rejects_wrong_owner_and_domain_projection(): + context = _context() + context["slots"]["person"]["owner"] = "companion" + result = consume_context_projection(context, "person_abc", "private") + assert result["state"] == "invalid" + assert "person" in result["rejected_slots"] + + context = _context(scope="group:one") + assert consume_context_projection(context, "person_abc", "group:two")["state"] == "invalid" + + +def test_context_deduplicates_by_revision_and_handles_legacy_or_bridge_degraded(): + assert consume_context_projection(None)["state"] == "legacy_local" + assert consume_context_projection({}, companion_available=False)["state"] == "degraded" + newer = _context(revision=7) + older = _context(revision=2) + newer_result = consume_context_projection(newer, "person_abc", "private") + older_result = consume_context_projection(older, "person_abc", "private") + assert newer_result["context_ref"]["revision"] == 7 + assert older_result["context_ref"]["revision"] == 2 + + +def test_context_preserves_explicit_degraded_pending_and_invalid_states(): + degraded = _context() + degraded["state"] = "degraded" + degraded["slots"]["runtime"]["state"] = "degraded" + assert consume_context_projection(degraded, "person_abc", "private")["state"] == "degraded" + + pending = _context() + pending["state"] = "pending" + pending["slots"]["person"]["state"] = "pending" + assert consume_context_projection(pending, "person_abc", "private")["state"] == "pending" + + invalid = _context() + invalid["slots"]["person"]["state"] = "invalid" + result = consume_context_projection(invalid, "person_abc", "private") + assert result["state"] == "invalid" + assert "person_state_invalid" in result["errors"]