from __future__ import annotations import argparse import copy import json import os import subprocess import time from pathlib import Path import pytest from scripts import leo_behavior_manifest as behavior from scripts import leo_identity_manifest as identity from scripts import leo_identity_profile as profile_runtime from scripts import run_leo_identity_reconstruction_canary as canary ROOT = Path(__file__).resolve().parents[1] def _write(path: Path, value: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(value, encoding="utf-8") def _write_json(path: Path, value: dict) -> None: _write(path, json.dumps(value, indent=2, sort_keys=True) + "\n") def _fixture(tmp_path: Path) -> dict[str, Path | dict]: repo = tmp_path / "repo" profile = repo / "profile-template" hermes = repo / "hermes-runtime" compiled = tmp_path / "compiled-profile" _write( profile / "config.yaml", """model: provider: fixture-local default: identity-v1 max_tokens: 512 memory: enabled: false gateway: execution_mode: local_no_send telegram: bot_token: never-emit-this-fixture-value transport: endpoint: https://fixture-user:fixture-password@example.invalid/v1 headers: ['Authorization: Bearer fixture-secret'] tools: allowed: [identity_readback] write_enabled: false identity_runtime: network_send_enabled: false database_write_enabled: false allowed_tools: [identity_readback] """, ) _write(profile / "skills" / "identity" / "SKILL.md", "# identity readback\n") _write(profile / "plugins" / "identity" / "__init__.py", "BOUNDARY = True\n") _write(profile / "bin" / "identity_readback.py", "READ_ONLY = True\n") _write(hermes / "run_agent.py", "RUNTIME = 'identity-v1'\n") _write(hermes / "agent" / "prompt_builder.py", "SOUL_IS_GENERATED = True\n") _write(hermes / "gateway" / "run.py", "SESSION_IS_IDENTITY = False\n") _write(hermes / "hermes_cli" / "tools_config.py", "TOOLS = ('identity_readback',)\n") _write(hermes / "tools" / "registry.py", "READ_ONLY = True\n") for name in ( "leo_behavior_manifest.py", "leo_identity_manifest.py", "leo_identity_profile.py", "run_leo_identity_reconstruction_canary.py", ): _write(repo / "scripts" / name, (ROOT / "scripts" / name).read_text(encoding="utf-8")) fingerprint_path = repo / "fixtures" / "database-fingerprint.json" constitution_path = repo / "fixtures" / "constitution.json" database_identity_path = repo / "fixtures" / "database-identity.json" fingerprint = { "schema": identity.DATABASE_FINGERPRINT_SCHEMA, "status": "ok", "environment": "disposable_fixture", "fingerprint_sha256": "1" * 64, "table_rows_sha256": "2" * 64, "structure_sha256": "3" * 64, "table_count": 2, "total_rows": 2, "read_consistency": { "status": "stable_wal_marker", "before": { "database": "fixture", "database_user": "reader", "system_identifier": "12345", "wal_lsn": "0/1", }, "after": { "database": "fixture", "database_user": "reader", "system_identifier": "12345", "wal_lsn": "0/1", }, }, } constitution = { "schema": identity.CONSTITUTION_SCHEMA, "identity_name": "Leo", "rules": [ {"id": "evidence", "text": "Never use temporary session memory as canonical evidence."}, {"id": "truth", "text": "Fail closed when a pinned identity input drifts."}, ], } database_identity = { "schema": identity.DATABASE_IDENTITY_SCHEMA, "identity_name": "Leo", "database_fingerprint_sha256": "1" * 64, "source_provenance": { "mode": identity.SYNTHETIC_DATABASE_MODE, "canonical_authority_granted": False, "same_transaction_as_fingerprint": False, "export_receipt_sha256": None, }, "records": [ { "table": "public.personas", "row_id": "persona-1", "kind": "persona", "rank": 0, "text": "Leo is an evidence-bound reasoning interface.", "status": "active", "evidence_sha256": "a" * 64, }, { "table": "public.beliefs", "row_id": "belief-1", "kind": "belief", "rank": 0, "text": "Exact provenance is stronger than plausible recollection.", "status": "active", "evidence_sha256": "b" * 64, }, ], } _write_json(fingerprint_path, fingerprint) _write_json(constitution_path, constitution) _write_json(database_identity_path, database_identity) subprocess.run(["git", "init", "-q", str(repo)], check=True) subprocess.run(["git", "-C", str(repo), "config", "user.email", "test@example.com"], check=True) subprocess.run(["git", "-C", str(repo), "config", "user.name", "Test"], check=True) subprocess.run(["git", "-C", str(repo), "add", "."], check=True) subprocess.run( ["git", "-C", str(repo), "commit", "-qm", "fixture"], check=True, env={ **dict(__import__("os").environ), "GIT_AUTHOR_DATE": "2026-01-01T00:00:00Z", "GIT_COMMITTER_DATE": "2026-01-01T00:00:00Z", }, ) behavior_manifest = behavior.build_manifest(profile, hermes, repo) manifest = identity.build_identity_manifest( behavior_manifest=behavior_manifest, database_fingerprint_path=fingerprint_path, constitution_path=constitution_path, database_identity_path=database_identity_path, source_root=repo, ) return { "repo": repo, "profile": profile, "hermes": hermes, "compiled": compiled, "fingerprint": fingerprint_path, "constitution": constitution_path, "database_identity": database_identity_path, "behavior": behavior_manifest, "manifest": manifest, } def _fully_rehash_manifest(fixture: dict[str, Path | dict], manifest: dict) -> None: identity_hash = behavior.canonical_sha256(manifest["identity_inputs"]) manifest["identity_inputs_sha256"] = identity_hash fingerprint = identity.load_json(fixture["fingerprint"], "database fingerprint") rules = identity.canonical_rules(identity.load_json(fixture["constitution"], "constitution")) records = identity.canonical_database_records( identity.load_json(fixture["database_identity"], "database identity"), fingerprint_sha256=fingerprint["fingerprint_sha256"], ) database_provenance = identity.database_identity_provenance( identity.load_json(fixture["database_identity"], "database identity"), fingerprint=fingerprint, ) rendered = identity.render_identity_views( identity_inputs_sha256=identity_hash, database_fingerprint_sha256=fingerprint["fingerprint_sha256"], database_provenance=database_provenance, rules=rules, records=records, ) for name, content in rendered.items(): manifest["compiled_views"][name]["sha256"] = behavior.sha256_bytes(content.encode("utf-8")) manifest["compiled_views"][name]["generated_from_identity_inputs_sha256"] = identity_hash stable = {key: value for key, value in manifest.items() if key != "manifest_sha256"} manifest["manifest_sha256"] = behavior.canonical_sha256(stable) def _rehash_behavior_manifest(manifest: dict) -> None: manifest["identity_runtime_sha256"] = behavior.canonical_sha256(behavior.identity_runtime_payload(manifest)) manifest["static_runtime_sha256"] = behavior.canonical_sha256(behavior.static_runtime_payload(manifest)) manifest["behavior_sha256"] = behavior.canonical_sha256(behavior.stable_manifest_payload(manifest)) def _canary_args(fixture: dict[str, Path | dict], output: Path, *, inject_drift: bool = False) -> argparse.Namespace: return argparse.Namespace( profile_template=fixture["profile"], hermes_root=fixture["hermes"], deployment_root=fixture["repo"], source_root=fixture["repo"], database_fingerprint=fixture["fingerprint"], constitution=fixture["constitution"], database_identity=fixture["database_identity"], output=output, inject_drift_before_restart=inject_drift, ) def test_manifest_compiles_generated_views_and_reproduces_identity_across_queries(tmp_path: Path) -> None: fixture = _fixture(tmp_path) manifest = fixture["manifest"] assert isinstance(manifest, dict) rebuilt = identity.build_identity_manifest( behavior_manifest=fixture["behavior"], database_fingerprint_path=fixture["fingerprint"], constitution_path=fixture["constitution"], database_identity_path=fixture["database_identity"], source_root=fixture["repo"], ) assert rebuilt == manifest compile_receipt = profile_runtime.compile_profile( manifest, source_root=fixture["repo"], profile_template=fixture["profile"], profile=fixture["compiled"], hermes_root=fixture["hermes"], deployment_root=fixture["repo"], ) first = profile_runtime.query_profile( fixture["compiled"], query=profile_runtime.FIXED_QUERY, source_root=fixture["repo"], hermes_root=fixture["hermes"], deployment_root=fixture["repo"], ) second = profile_runtime.query_profile( fixture["compiled"], query=profile_runtime.FIXED_QUERY, source_root=fixture["repo"], hermes_root=fixture["hermes"], deployment_root=fixture["repo"], ) assert compile_receipt["status"] == "pass" assert "never-emit-this-fixture-value" not in (fixture["compiled"] / "config.yaml").read_text(encoding="utf-8") assert "fixture-password" not in (fixture["compiled"] / "config.yaml").read_text(encoding="utf-8") assert "fixture-secret" not in (fixture["compiled"] / "config.yaml").read_text(encoding="utf-8") assert (fixture["compiled"] / "SOUL.md").read_text(encoding="utf-8").startswith("