diff --git a/p4_b1b_guards.py b/p4_b1b_guards.py new file mode 100644 index 0000000..397b693 --- /dev/null +++ b/p4_b1b_guards.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +"""Reject-only placeholders for unavailable P4-B1b live-effect authorities.""" + + +HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE = "p4_b1b_host_owner_capability_unavailable" +REVIEW_PRODUCER_UNAVAILABLE_CODE = "p4_b1b_review_producer_unavailable" + + +def reject_unverified_owner_capability(claim: object = None) -> dict[str, object]: + """Deny every proposed host-owner capability without reading the claim.""" + + del claim + return { + "accepted": False, + "live_effect_permitted": False, + "code": HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE, + } + + +def reject_unverified_review_producer(candidate: object = None) -> dict[str, object]: + """Deny every proposed review producer without reading the candidate.""" + + del candidate + return { + "accepted": False, + "live_effect_permitted": False, + "code": REVIEW_PRODUCER_UNAVAILABLE_CODE, + } diff --git a/p6_four_package_manifest.py b/p6_four_package_manifest.py new file mode 100644 index 0000000..5e6ff96 --- /dev/null +++ b/p6_four_package_manifest.py @@ -0,0 +1,124 @@ +"""Pure validation for the P6 four-package manifest contract.""" + +import hashlib +import json +import re + + +FOUR_PACKAGE_MANIFEST_SCHEMA = "ops.p6.four_package_manifest.v1" +FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA = "ops.p6.four_package_manifest_report.v1" +FOUR_PACKAGE_IDS = ("companion", "memory", "ops_archive", "peiban") + +_REQUIRED_MANIFEST_FIELDS = ( + "schema", + "package_id", + "manifest_version", + "package_fingerprint", + "compatibility_fingerprint", +) +_MANIFEST_VERSION_PATTERN = re.compile(r"^[1-9]\d*\.[0-9]+$") +_SHA256_PATTERN = re.compile(r"^[0-9a-f]{64}$") + + +def _contract_payload() -> dict[str, object]: + return { + "schema": FOUR_PACKAGE_MANIFEST_SCHEMA, + "report_schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA, + "package_ids": list(FOUR_PACKAGE_IDS), + "required_manifest_fields": list(_REQUIRED_MANIFEST_FIELDS), + } + + +def manifest_contract() -> dict[str, object]: + """Return a fresh descriptor for the value-only manifest contract.""" + descriptor = _contract_payload() + canonical_payload = json.dumps( + descriptor, + ensure_ascii=True, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + descriptor["contract_fingerprint"] = hashlib.sha256(canonical_payload).hexdigest() + return descriptor + + +def _unverifiable_report(reason_code: str) -> dict[str, object]: + return { + "schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA, + "status": "unverifiable", + "reason_code": reason_code, + "expected_package_ids": list(FOUR_PACKAGE_IDS), + } + + +def _verified_report() -> dict[str, object]: + return { + "schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA, + "status": "verified", + "reason_code": "four_package_manifest_verified", + "expected_package_ids": list(FOUR_PACKAGE_IDS), + } + + +def verify_four_package_manifests(manifests: object) -> dict[str, object]: + """Verify only the supplied in-memory four-package manifest values.""" + if type(manifests) is not dict: + return _unverifiable_report("manifest_collection_not_exact_dict") + + for package_id in manifests: + if type(package_id) is not str or package_id not in FOUR_PACKAGE_IDS: + return _unverifiable_report("unexpected_package_manifest") + + for package_id in FOUR_PACKAGE_IDS: + if package_id not in manifests: + return _unverifiable_report("missing_package_manifest") + + common_compatibility_fingerprint = None + for package_id in FOUR_PACKAGE_IDS: + package_manifest = manifests[package_id] + if type(package_manifest) is not dict: + return _unverifiable_report("package_manifest_not_exact_dict") + + for field_name in package_manifest: + if type(field_name) is not str or field_name not in _REQUIRED_MANIFEST_FIELDS: + return _unverifiable_report("unexpected_manifest_field") + + for field_name in _REQUIRED_MANIFEST_FIELDS: + if field_name not in package_manifest: + return _unverifiable_report("missing_manifest_field") + + schema = package_manifest["schema"] + if type(schema) is not str or schema != FOUR_PACKAGE_MANIFEST_SCHEMA: + return _unverifiable_report("manifest_schema_mismatch") + + declared_package_id = package_manifest["package_id"] + if type(declared_package_id) is not str or declared_package_id != package_id: + return _unverifiable_report("manifest_package_id_mismatch") + + manifest_version = package_manifest["manifest_version"] + if ( + type(manifest_version) is not str + or _MANIFEST_VERSION_PATTERN.fullmatch(manifest_version) is None + ): + return _unverifiable_report("manifest_version_invalid") + + package_fingerprint = package_manifest["package_fingerprint"] + if ( + type(package_fingerprint) is not str + or _SHA256_PATTERN.fullmatch(package_fingerprint) is None + ): + return _unverifiable_report("package_fingerprint_invalid") + + compatibility_fingerprint = package_manifest["compatibility_fingerprint"] + if ( + type(compatibility_fingerprint) is not str + or _SHA256_PATTERN.fullmatch(compatibility_fingerprint) is None + ): + return _unverifiable_report("compatibility_fingerprint_invalid") + + if common_compatibility_fingerprint is None: + common_compatibility_fingerprint = compatibility_fingerprint + elif compatibility_fingerprint != common_compatibility_fingerprint: + return _unverifiable_report("compatibility_fingerprint_mismatch") + + return _verified_report() diff --git a/tests/test_p4_b1b_guards.py b/tests/test_p4_b1b_guards.py new file mode 100644 index 0000000..00d9473 --- /dev/null +++ b/tests/test_p4_b1b_guards.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +"""Contract tests for the P4-B1b reject-only guard boundary.""" + +import ast +from pathlib import Path +import sys +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +import p4_b1b_guards as guards +from p4_b1b_guards import ( + HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE, + REVIEW_PRODUCER_UNAVAILABLE_CODE, + reject_unverified_owner_capability, + reject_unverified_review_producer, +) +from unified_person_contract import empty_unified_person_store +from unified_person_registry import UnifiedPersonRegistry + + +class _PoisonClaim: + """Raises if a guard tries to observe it through common Python protocols.""" + + def __getattribute__(self, name: str) -> object: + raise AssertionError(f"unexpected attribute access: {name}") + + def __getitem__(self, key: object) -> object: + raise AssertionError(f"unexpected mapping access: {key}") + + def __iter__(self) -> object: + raise AssertionError("unexpected iteration") + + def __len__(self) -> int: + raise AssertionError("unexpected length access") + + def __bool__(self) -> bool: + raise AssertionError("unexpected truthiness access") + + def __repr__(self) -> str: + raise AssertionError("unexpected repr access") + + +class P4B1bGuardTests(unittest.TestCase): + def test_owner_capability_is_always_denied_with_the_stable_code(self) -> None: + result = reject_unverified_owner_capability() + + self.assertEqual( + result, + { + "accepted": False, + "live_effect_permitted": False, + "code": "p4_b1b_host_owner_capability_unavailable", + }, + ) + self.assertEqual(HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE, result["code"]) + + def test_review_producer_is_always_denied_with_the_stable_code(self) -> None: + result = reject_unverified_review_producer() + + self.assertEqual( + result, + { + "accepted": False, + "live_effect_permitted": False, + "code": "p4_b1b_review_producer_unavailable", + }, + ) + self.assertEqual(REVIEW_PRODUCER_UNAVAILABLE_CODE, result["code"]) + + def test_poison_claims_are_discarded_without_observation(self) -> None: + self.assertFalse(reject_unverified_owner_capability(_PoisonClaim())["accepted"]) + self.assertFalse(reject_unverified_review_producer(_PoisonClaim())["accepted"]) + + def test_forged_dicts_never_enable_a_live_effect(self) -> None: + forged_claim = { + "accepted": True, + "live_effect_permitted": True, + "owner": True, + "review_producer": "trusted", + "code": "allow_everything", + } + + for guard, code in ( + (reject_unverified_owner_capability, HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE), + (reject_unverified_review_producer, REVIEW_PRODUCER_UNAVAILABLE_CODE), + ): + with self.subTest(guard=guard.__name__): + result = guard(forged_claim) + self.assertEqual( + result, + { + "accepted": False, + "live_effect_permitted": False, + "code": code, + }, + ) + + def test_every_call_returns_an_independent_plain_dict(self) -> None: + first = reject_unverified_owner_capability() + second = reject_unverified_owner_capability() + review = reject_unverified_review_producer() + + self.assertIsInstance(first, dict) + self.assertIsInstance(review, dict) + self.assertIsNot(first, second) + self.assertIsNot(first, review) + first["accepted"] = True + first["code"] = "forged" + self.assertEqual(False, second["accepted"]) + self.assertEqual(HOST_OWNER_CAPABILITY_UNAVAILABLE_CODE, second["code"]) + self.assertEqual( + REVIEW_PRODUCER_UNAVAILABLE_CODE, + reject_unverified_review_producer()["code"], + ) + + def test_module_has_no_import_or_call_integration_surface(self) -> None: + source = Path(guards.__file__).read_text(encoding="utf-8") + tree = ast.parse(source) + + imports = [ + node + for node in ast.walk(tree) + if isinstance(node, (ast.Import, ast.ImportFrom)) + ] + calls = [node for node in ast.walk(tree) if isinstance(node, ast.Call)] + self.assertEqual([], imports) + self.assertEqual([], calls) + + def test_guard_usage_does_not_create_p4_effect_in_an_isolated_registry_store(self) -> None: + store = {"unified_person": empty_unified_person_store()} + registry = UnifiedPersonRegistry(store) + before = registry.status() + + reject_unverified_owner_capability({"owner": "forged"}) + reject_unverified_review_producer({"producer": "forged"}) + + self.assertEqual(before, registry.status()) + self.assertNotIn("p4_effect", store["unified_person"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_p6_four_package_manifest.py b/tests/test_p6_four_package_manifest.py new file mode 100644 index 0000000..ccfc2c7 --- /dev/null +++ b/tests/test_p6_four_package_manifest.py @@ -0,0 +1,178 @@ +import hashlib +import json +import unittest + +from p6_four_package_manifest import ( + FOUR_PACKAGE_IDS, + FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA, + FOUR_PACKAGE_MANIFEST_SCHEMA, + manifest_contract, + verify_four_package_manifests, +) + + +def _synthetic_manifests() -> dict[str, dict[str, str]]: + compatibility_fingerprint = "a" * 64 + return { + package_id: { + "schema": FOUR_PACKAGE_MANIFEST_SCHEMA, + "package_id": package_id, + "manifest_version": "1.0", + "package_fingerprint": f"{index:064x}", + "compatibility_fingerprint": compatibility_fingerprint, + } + for index, package_id in enumerate(FOUR_PACKAGE_IDS, start=1) + } + + +class _Poison: + def __bool__(self) -> bool: + raise AssertionError("truthiness must not be evaluated") + + def __iter__(self): + raise AssertionError("iteration must not be evaluated") + + def __repr__(self) -> str: + raise AssertionError("repr must not be evaluated") + + +class _DictSubclass(dict): + pass + + +class FourPackageManifestTests(unittest.TestCase): + def assert_unverifiable(self, manifests: object, reason_code: str) -> None: + report = verify_four_package_manifests(manifests) + self.assertEqual(type(report), dict) + self.assertEqual(report["schema"], FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA) + self.assertEqual(report["status"], "unverifiable") + self.assertEqual(report["reason_code"], reason_code) + self.assertEqual(report["expected_package_ids"], list(FOUR_PACKAGE_IDS)) + self.assertNotIn("manifests", report) + self.assertNotIn("fingerprint", report) + + def test_contract_descriptor_is_exact_and_canonical(self) -> None: + descriptor = manifest_contract() + payload = { + "schema": FOUR_PACKAGE_MANIFEST_SCHEMA, + "report_schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA, + "package_ids": list(FOUR_PACKAGE_IDS), + "required_manifest_fields": [ + "schema", + "package_id", + "manifest_version", + "package_fingerprint", + "compatibility_fingerprint", + ], + } + expected_fingerprint = hashlib.sha256( + json.dumps( + payload, + ensure_ascii=True, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + ).hexdigest() + self.assertEqual( + descriptor, + {**payload, "contract_fingerprint": expected_fingerprint}, + ) + self.assertEqual(type(descriptor), dict) + + def test_contract_descriptors_are_fresh(self) -> None: + first = manifest_contract() + second = manifest_contract() + self.assertIsNot(first, second) + self.assertIsNot(first["package_ids"], second["package_ids"]) + first["package_ids"].append("changed") + self.assertEqual(second["package_ids"], list(FOUR_PACKAGE_IDS)) + + def test_synthetic_consistent_manifests_verify(self) -> None: + report = verify_four_package_manifests(_synthetic_manifests()) + self.assertEqual( + report, + { + "schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA, + "status": "verified", + "reason_code": "four_package_manifest_verified", + "expected_package_ids": list(FOUR_PACKAGE_IDS), + }, + ) + + def test_reports_are_fresh(self) -> None: + first = verify_four_package_manifests(_synthetic_manifests()) + second = verify_four_package_manifests(_synthetic_manifests()) + self.assertIsNot(first, second) + self.assertIsNot(first["expected_package_ids"], second["expected_package_ids"]) + first["expected_package_ids"].append("changed") + self.assertEqual(second["expected_package_ids"], list(FOUR_PACKAGE_IDS)) + + def test_rejects_non_exact_outer_dict(self) -> None: + self.assert_unverifiable([], "manifest_collection_not_exact_dict") + self.assert_unverifiable(_Poison(), "manifest_collection_not_exact_dict") + self.assert_unverifiable(_DictSubclass(_synthetic_manifests()), "manifest_collection_not_exact_dict") + + def test_rejects_missing_and_unexpected_package_manifests(self) -> None: + missing = _synthetic_manifests() + del missing["peiban"] + self.assert_unverifiable(missing, "missing_package_manifest") + + unexpected = _synthetic_manifests() + unexpected["unexpected"] = unexpected["companion"].copy() + self.assert_unverifiable(unexpected, "unexpected_package_manifest") + + def test_rejects_non_exact_package_manifests_without_inspecting_them(self) -> None: + manifests = _synthetic_manifests() + manifests["companion"] = _Poison() + self.assert_unverifiable(manifests, "package_manifest_not_exact_dict") + + manifests = _synthetic_manifests() + manifests["companion"] = _DictSubclass(manifests["companion"]) + self.assert_unverifiable(manifests, "package_manifest_not_exact_dict") + + def test_rejects_missing_and_unexpected_fields(self) -> None: + missing = _synthetic_manifests() + del missing["companion"]["schema"] + self.assert_unverifiable(missing, "missing_manifest_field") + + unexpected = _synthetic_manifests() + unexpected["companion"]["extra"] = "ignored" + self.assert_unverifiable(unexpected, "unexpected_manifest_field") + + def test_rejects_schema_and_package_id_mismatch(self) -> None: + wrong_schema = _synthetic_manifests() + wrong_schema["companion"]["schema"] = "ops.p6.other.v1" + self.assert_unverifiable(wrong_schema, "manifest_schema_mismatch") + + wrong_id = _synthetic_manifests() + wrong_id["companion"]["package_id"] = "memory" + self.assert_unverifiable(wrong_id, "manifest_package_id_mismatch") + + def test_rejects_invalid_versions(self) -> None: + for invalid_version in ("0.0", "1", "1.", "1.a", 1.0, _Poison()): + with self.subTest(invalid_version=type(invalid_version).__name__): + manifests = _synthetic_manifests() + manifests["companion"]["manifest_version"] = invalid_version + self.assert_unverifiable(manifests, "manifest_version_invalid") + + def test_rejects_invalid_fingerprints_without_inspecting_poison_values(self) -> None: + invalid_package_fingerprint = _synthetic_manifests() + invalid_package_fingerprint["companion"]["package_fingerprint"] = "A" * 64 + self.assert_unverifiable(invalid_package_fingerprint, "package_fingerprint_invalid") + + poison_package_fingerprint = _synthetic_manifests() + poison_package_fingerprint["companion"]["package_fingerprint"] = _Poison() + self.assert_unverifiable(poison_package_fingerprint, "package_fingerprint_invalid") + + invalid_compatibility_fingerprint = _synthetic_manifests() + invalid_compatibility_fingerprint["companion"]["compatibility_fingerprint"] = "g" * 64 + self.assert_unverifiable(invalid_compatibility_fingerprint, "compatibility_fingerprint_invalid") + + def test_rejects_inconsistent_compatibility_fingerprints(self) -> None: + manifests = _synthetic_manifests() + manifests["memory"]["compatibility_fingerprint"] = "b" * 64 + self.assert_unverifiable(manifests, "compatibility_fingerprint_mismatch") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_p6_manifest_joint_workspace.py b/tests/test_p6_manifest_joint_workspace.py new file mode 100644 index 0000000..5b184d7 --- /dev/null +++ b/tests/test_p6_manifest_joint_workspace.py @@ -0,0 +1,51 @@ +import importlib.util +import unittest + +import p6_four_package_manifest as companion_manifest + + +_MEMORY_MANIFEST_MODULE_PATH = ( + r"D:\CODEX\projects\我会永远陪着你\astrbot_plugin_memory_companion-main" + r"\core\p6_four_package_manifest.py" +) + + +def _load_memory_manifest_module(): + spec = importlib.util.spec_from_file_location( + "p6_memory_manifest_joint_workspace", + _MEMORY_MANIFEST_MODULE_PATH, + ) + if spec is None or spec.loader is None: + raise AssertionError("memory P6 manifest module could not be loaded") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _synthetic_manifests() -> dict[str, dict[str, str]]: + return { + package_id: { + "schema": companion_manifest.FOUR_PACKAGE_MANIFEST_SCHEMA, + "package_id": package_id, + "manifest_version": "1.0", + "package_fingerprint": f"{index:064x}", + "compatibility_fingerprint": "c" * 64, + } + for index, package_id in enumerate(companion_manifest.FOUR_PACKAGE_IDS, start=1) + } + + +class P6ManifestJointWorkspaceTests(unittest.TestCase): + def test_value_contracts_match_across_companion_and_memory(self) -> None: + memory_manifest = _load_memory_manifest_module() + self.assertEqual(companion_manifest.manifest_contract(), memory_manifest.manifest_contract()) + + manifests = _synthetic_manifests() + self.assertEqual( + companion_manifest.verify_four_package_manifests(manifests), + memory_manifest.verify_four_package_manifests(manifests), + ) + + +if __name__ == "__main__": + unittest.main()