From f61d5f2021c9939ce8630e5d11fbcead4a272650 Mon Sep 17 00:00:00 2001 From: Fresh Software Date: Tue, 28 Jul 2026 10:28:01 -0700 Subject: [PATCH 1/2] Import Pass 30 native Locus64 source --- .github/workflows/native-core.yml | 116 + Cargo.lock | 818 +- Cargo.toml | 39 +- EXPORT_STRESS_REMEDIATION_LEDGER.md | 2 +- HANDOFF_STATUS.md | 115 +- L64_APPROVAL_GATES.md | 130 +- L64_HISTORICAL_APPROVAL_LEDGER.md | 140 + LINEAR_EXECUTION_RAIL.md | 89 +- LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md | 436 +- LOCUS64_CONSTRAINT_CORE_CHANGE_CHAIN.athens | 39 + ...OCUMENTATION_COHERENCE_CHANGE_CHAIN.athens | 23 + LOCUS64_EXECUTION_COHERENCE_RAIL.athens | 61 + ...S64_GOLDEN_PORTABILITY_CHANGE_CHAIN.athens | 26 + LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md | 62 + LOCUS64_HISTORICAL_LAW_LEDGER.md | 608 ++ ...64_INCREMENTAL_CLOSURE_CHANGE_CHAIN.athens | 46 + LOCUS64_LANGUAGE_SPEC.md | 741 +- ...HORITY_ISLAND_DELETION_CHANGE_CHAIN.athens | 22 + ...Y_AUTHORITY_QUARANTINE_CHANGE_CHAIN.athens | 58 + ..._LEGACY_CACHE_DELETION_CHANGE_CHAIN.athens | 41 + ...AGE_READINESS_DELETION_CHANGE_CHAIN.athens | 41 + ..._PLAN_STORAGE_DELETION_CHANGE_CHAIN.athens | 41 + ...VERLAY_POLICY_DELETION_CHANGE_CHAIN.athens | 48 + ...4_NATIVE_CLI_HARDENING_CHANGE_CHAIN.athens | 35 + LOCUS64_NATIVE_CONSTITUTION.md | 121 + LOCUS64_NATIVE_EXECUTION_CHANGE_CHAIN.athens | 21 + ...ATIVE_PROCESS_CONTRACT_CHANGE_CHAIN.athens | 30 + LOCUS64_NATIVE_RAIL.athens | 25 + LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens | 41 + ...ATIVE_UPPER_PROJECTION_CHANGE_CHAIN.athens | 60 + LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md | 39 + LOCUS64_PROOF_CONGRUENCE_CHANGE_CHAIN.athens | 46 + LOCUS64_RESEARCH_ADMIN_CLASSIFICATION.md | 11 + ...4_RESIDUE_REMOTE_PROOF_CHANGE_CHAIN.athens | 19 + LOCUS64_STACK.md | 83 +- ...64_SYMBOLIC_COMMITMENT_CHANGE_CHAIN.athens | 62 + README.md | 142 +- SEMANTIC_USAGE_GUIDE.md | 379 +- SOURCE_REFERENCE_MANIFEST.md | 131 +- USAGE_GUIDE.md | 183 +- bin/l64-admin.cmd | 7 - fixtures/README.md | 19 - fixtures/cki_registry.genome.rna | 277 - l64-admin/Cargo.toml | 22 - l64-admin/src/main.rs | 1521 ---- l64-admin/tests/admin.rs | 1908 ---- l64-atlas/.gitignore | 1 - l64-atlas/Cargo.toml | 13 - l64-atlas/src/lib.rs | 539 -- l64-bundle/Cargo.toml | 13 - l64-bundle/src/lib.rs | 2001 ----- l64-canon/.gitignore | 1 - l64-canon/Cargo.toml | 11 - l64-canon/src/lib.rs | 143 - l64-cert/.gitignore | 1 - l64-cert/Cargo.toml | 22 - l64-cert/src/lib.rs | 6657 -------------- l64-certification/Cargo.toml | 9 + l64-certification/README.md | 12 + l64-certification/src/lib.rs | 243 + l64-certification/tests/architecture.rs | 55 + l64-certification/tests/certification.rs | 100 + l64-change/Cargo.toml | 11 + l64-change/README.md | 7 + l64-change/src/lib.rs | 348 + l64-change/tests/architecture.rs | 106 + l64-change/tests/change.rs | 112 + l64-cli/Cargo.toml | 39 +- l64-cli/src/golden_tests.rs | 280 + l64-cli/src/main.rs | 1908 ---- l64-cli/src/native_main.rs | 16 + l64-cli/src/native_membrane.rs | 1322 +++ l64-cli/tests/cli.rs | 1370 --- l64-command/src/lib.rs | 42 - l64-core/.gitignore | 1 - l64-core/Cargo.toml | 10 - l64-core/src/codons.rs | 609 -- l64-core/src/lexons.rs | 96 - l64-core/src/lib.rs | 7967 ----------------- l64-core/src/macro_codons.rs | 95 - l64-core/src/molecular.rs | 344 - l64-core/src/witness.rs | 35 - l64-execution/Cargo.toml | 10 + l64-execution/README.md | 5 + l64-execution/src/lib.rs | 197 + l64-execution/tests/architecture.rs | 38 + l64-execution/tests/execution.rs | 63 + l64-kernel/.gitignore | 1 - l64-kernel/Cargo.toml | 12 - l64-kernel/src/lib.rs | 792 -- l64-locus/Cargo.toml | 12 - l64-locus/src/lib.rs | 612 -- {l64-testkit => l64-native}/Cargo.toml | 4 +- l64-native/README.md | 50 + l64-native/src/closure.rs | 63 + l64-native/src/codec.rs | 73 + l64-native/src/codec/io.rs | 130 + l64-native/src/codec/reader.rs | 69 + l64-native/src/codec/validation.rs | 264 + l64-native/src/context.rs | 22 + l64-native/src/dimension.rs | 66 + l64-native/src/dna.rs | 117 + l64-native/src/graph.rs | 100 + l64-native/src/graph/closure.rs | 202 + l64-native/src/graph/construction.rs | 379 + l64-native/src/graph/context.rs | 8 + l64-native/src/graph/derived.rs | 105 + l64-native/src/graph/storage.rs | 126 + l64-native/src/graph/typing.rs | 126 + l64-native/src/journal.rs | 32 + l64-native/src/kernel.rs | 7 + l64-native/src/kernel/equality.rs | 3 + l64-native/src/kernel/equality/canonical.rs | 125 + l64-native/src/kernel/equality/proof.rs | 158 + l64-native/src/kernel/equality/validation.rs | 288 + l64-native/src/kernel/proposal.rs | 271 + l64-native/src/kernel/transaction.rs | 183 + l64-native/src/kernel/types.rs | 229 + l64-native/src/kernel/validation.rs | 85 + l64-native/src/lib.rs | 29 + l64-native/src/rna.rs | 182 + l64-native/src/rna/compile.rs | 212 + l64-native/src/rna/parse.rs | 229 + l64-native/src/rna/render.rs | 70 + l64-native/src/rna/sequence.rs | 203 + l64-native/src/route.rs | 59 + l64-native/src/symbol.rs | 134 + l64-native/tests/architecture.rs | 73 + l64-native/tests/closure.rs | 346 + l64-native/tests/codec.rs | 97 + l64-native/tests/constraints.rs | 328 + l64-native/tests/dna.rs | 96 + l64-native/tests/equality.rs | 273 + l64-native/tests/rna.rs | 150 + l64-native/tests/symbol.rs | 65 + l64-native/tests/workloads.rs | 111 + l64-observation/Cargo.toml | 11 + l64-observation/README.md | 11 + l64-observation/src/lib.rs | 266 + l64-observation/tests/architecture.rs | 57 + l64-observation/tests/observation.rs | 122 + l64-observe/Cargo.toml | 17 - l64-observe/src/lib.rs | 2729 ------ l64-policy/Cargo.toml | 11 - l64-policy/src/lib.rs | 677 -- {l64-command => l64-projection}/Cargo.toml | 5 +- l64-projection/README.md | 15 + l64-projection/examples/native_projection.rs | 29 + l64-projection/src/analysis.rs | 37 + l64-projection/src/atlas.rs | 112 + l64-projection/src/certification.rs | 97 + l64-projection/src/lib.rs | 25 + l64-projection/src/order.rs | 9 + l64-projection/src/replay.rs | 60 + l64-projection/src/report.rs | 82 + l64-projection/src/research.rs | 100 + l64-projection/src/set.rs | 102 + l64-projection/src/source.rs | 194 + l64-projection/tests/architecture.rs | 54 + l64-projection/tests/projection.rs | 259 + l64-registry/.gitignore | 1 - l64-registry/Cargo.toml | 9 - l64-registry/data/seed.v1.json | 1136 --- l64-registry/src/lib.rs | 388 - l64-release/Cargo.toml | 9 + l64-release/src/lib.rs | 168 + l64-release/tests/release.rs | 44 + l64-research/Cargo.toml | 13 - l64-research/src/lib.rs | 2928 ------ l64-runtime/.gitignore | 1 - l64-runtime/Cargo.toml | 12 - l64-runtime/src/lib.rs | 753 -- l64-selector/.gitignore | 1 - l64-selector/Cargo.toml | 11 - l64-selector/src/lib.rs | 730 -- l64-symbolic/Cargo.toml | 5 + l64-symbolic/DESIGN.md | 75 + l64-symbolic/README.md | 33 + l64-symbolic/examples/symbolic_audit.rs | 48 + l64-symbolic/examples/symbolic_commitment.rs | 28 + l64-symbolic/src/lib.rs | 447 + l64-symbolic/tests/algebra.rs | 116 + l64-symbolic/tests/architecture.rs | 26 + l64-testkit/src/lib.rs | 242 - l64-transport/Cargo.toml | 10 + l64-transport/README.md | 17 + l64-transport/src/lib.rs | 304 + l64-transport/src/stream.rs | 222 + l64-transport/tests/architecture.rs | 68 + l64-transport/tests/transport.rs | 148 + l64/Cargo.toml | 3 - l64/src/main.rs | 162 +- samples/chain_rule_bundle.dna | Bin 1870 -> 0 bytes samples/chain_rule_integrated_bundle.dna | Bin 2643 -> 0 bytes samples/golden/certified_triangle.rna | 10 + samples/golden/equality_chain.rna | 6 + .../expected/certified_triangle.certify.txt | 17 + .../expected/certified_triangle.dna.hex | 1 + .../certified_triangle.normalized.rna | 10 + .../expected/certified_triangle.run.txt | 19 + .../expected/equality_chain.certify.txt | 17 + .../golden/expected/equality_chain.dna.hex | 1 + .../expected/equality_chain.normalized.rna | 6 + .../golden/expected/equality_chain.run.txt | 19 + .../invalid_child_context.certify.txt | 24 + .../expected/invalid_child_context.dna.hex | 1 + .../invalid_child_context.normalized.rna | 7 + .../expected/invalid_child_context.run.txt | 20 + .../expected/matrix_multiply.certify.txt | 17 + .../golden/expected/matrix_multiply.dna.hex | 1 + .../expected/matrix_multiply.normalized.rna | 8 + .../golden/expected/matrix_multiply.run.txt | 19 + .../golden/expected/mixed_bundle.certify.txt | 38 + .../golden/expected/mixed_bundle.observe.txt | 57 + samples/golden/expected/mixed_bundle.run.txt | 41 + .../expected/open_obligation.certify.txt | 17 + .../golden/expected/open_obligation.dna.hex | 1 + .../expected/open_obligation.normalized.rna | 5 + .../golden/expected/open_obligation.run.txt | 19 + .../triangle.release.authority.dna.hex | 1 + .../expected/triangle.release.projection.txt | 14 + .../golden/expected/triangle.release.record | 9 + .../expected/triangle_to_equality.compare.txt | 38 + samples/golden/invalid_child_context.rna | 7 + samples/golden/matrix_multiply.rna | 8 + samples/golden/open_obligation.rna | 5 + samples/imported_claim_bundle.dna | Bin 3188 -> 0 bytes samples/imported_claim_stress_gap_bundle.dna | Bin 2165 -> 0 bytes samples/native_equality.rna | 6 + samples/native_triangle.rna | 10 + samples/research/claim_chain_rule.json | 14 - samples/research/coverage_chain_rule.json | 8 - samples/research/export_capability_truth.json | 19 - .../research/export_explain_execution.json | 20 - .../research/export_namespace_contract.json | 19 - .../export_predict_impact_contract.json | 18 - .../export_validate_inspection_report.json | 20 - .../research/producer_host_chain_rule.json | 8 - samples/research/promotion_chain_rule.json | 9 - .../remediation_explain_execution.json | 21 - samples/research/repro_chain_rule.json | 8 - .../signature_full_compound_completion.json | 11 - .../research/signature_operational_truth.json | 18 - .../task_full_compound_completion.json | 12 - samples/research/task_operational_truth.json | 21 - scripts/run-native-demo.sh | 57 + scripts/torture-test.ps1 | 283 - scripts/verify-cli-hardening.sh | 69 + scripts/verify-documentation-coherence.sh | 217 + scripts/verify-golden-portability.sh | 51 + ...verify-legacy-authority-island-deletion.sh | 26 + scripts/verify-low-memory.ps1 | 81 +- scripts/verify-native-carrier.sh | 62 + scripts/verify-native-scale.sh | 63 + scripts/verify-portability-receipts.sh | 46 + scripts/verify-process-contract.sh | 80 + scripts/write-portability-receipt.sh | 69 + 257 files changed, 15942 insertions(+), 40253 deletions(-) create mode 100644 .github/workflows/native-core.yml create mode 100644 L64_HISTORICAL_APPROVAL_LEDGER.md create mode 100644 LOCUS64_CONSTRAINT_CORE_CHANGE_CHAIN.athens create mode 100644 LOCUS64_DOCUMENTATION_COHERENCE_CHANGE_CHAIN.athens create mode 100644 LOCUS64_EXECUTION_COHERENCE_RAIL.athens create mode 100644 LOCUS64_GOLDEN_PORTABILITY_CHANGE_CHAIN.athens create mode 100644 LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md create mode 100644 LOCUS64_HISTORICAL_LAW_LEDGER.md create mode 100644 LOCUS64_INCREMENTAL_CLOSURE_CHANGE_CHAIN.athens create mode 100644 LOCUS64_LEGACY_AUTHORITY_ISLAND_DELETION_CHANGE_CHAIN.athens create mode 100644 LOCUS64_LEGACY_AUTHORITY_QUARANTINE_CHANGE_CHAIN.athens create mode 100644 LOCUS64_LEGACY_CACHE_DELETION_CHANGE_CHAIN.athens create mode 100644 LOCUS64_LEGACY_LINEAGE_READINESS_DELETION_CHANGE_CHAIN.athens create mode 100644 LOCUS64_LEGACY_PLAN_STORAGE_DELETION_CHANGE_CHAIN.athens create mode 100644 LOCUS64_LEGACY_REGISTRY_OVERLAY_POLICY_DELETION_CHANGE_CHAIN.athens create mode 100644 LOCUS64_NATIVE_CLI_HARDENING_CHANGE_CHAIN.athens create mode 100644 LOCUS64_NATIVE_CONSTITUTION.md create mode 100644 LOCUS64_NATIVE_EXECUTION_CHANGE_CHAIN.athens create mode 100644 LOCUS64_NATIVE_PROCESS_CONTRACT_CHANGE_CHAIN.athens create mode 100644 LOCUS64_NATIVE_RAIL.athens create mode 100644 LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens create mode 100644 LOCUS64_NATIVE_UPPER_PROJECTION_CHANGE_CHAIN.athens create mode 100644 LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md create mode 100644 LOCUS64_PROOF_CONGRUENCE_CHANGE_CHAIN.athens create mode 100644 LOCUS64_RESEARCH_ADMIN_CLASSIFICATION.md create mode 100644 LOCUS64_RESIDUE_REMOTE_PROOF_CHANGE_CHAIN.athens create mode 100644 LOCUS64_SYMBOLIC_COMMITMENT_CHANGE_CHAIN.athens delete mode 100644 bin/l64-admin.cmd delete mode 100644 fixtures/README.md delete mode 100644 fixtures/cki_registry.genome.rna delete mode 100644 l64-admin/Cargo.toml delete mode 100644 l64-admin/src/main.rs delete mode 100644 l64-admin/tests/admin.rs delete mode 100644 l64-atlas/.gitignore delete mode 100644 l64-atlas/Cargo.toml delete mode 100644 l64-atlas/src/lib.rs delete mode 100644 l64-bundle/Cargo.toml delete mode 100644 l64-bundle/src/lib.rs delete mode 100644 l64-canon/.gitignore delete mode 100644 l64-canon/Cargo.toml delete mode 100644 l64-canon/src/lib.rs delete mode 100644 l64-cert/.gitignore delete mode 100644 l64-cert/Cargo.toml delete mode 100644 l64-cert/src/lib.rs create mode 100644 l64-certification/Cargo.toml create mode 100644 l64-certification/README.md create mode 100644 l64-certification/src/lib.rs create mode 100644 l64-certification/tests/architecture.rs create mode 100644 l64-certification/tests/certification.rs create mode 100644 l64-change/Cargo.toml create mode 100644 l64-change/README.md create mode 100644 l64-change/src/lib.rs create mode 100644 l64-change/tests/architecture.rs create mode 100644 l64-change/tests/change.rs create mode 100644 l64-cli/src/golden_tests.rs delete mode 100644 l64-cli/src/main.rs create mode 100644 l64-cli/src/native_main.rs create mode 100644 l64-cli/src/native_membrane.rs delete mode 100644 l64-cli/tests/cli.rs delete mode 100644 l64-command/src/lib.rs delete mode 100644 l64-core/.gitignore delete mode 100644 l64-core/Cargo.toml delete mode 100644 l64-core/src/codons.rs delete mode 100644 l64-core/src/lexons.rs delete mode 100644 l64-core/src/lib.rs delete mode 100644 l64-core/src/macro_codons.rs delete mode 100644 l64-core/src/molecular.rs delete mode 100644 l64-core/src/witness.rs create mode 100644 l64-execution/Cargo.toml create mode 100644 l64-execution/README.md create mode 100644 l64-execution/src/lib.rs create mode 100644 l64-execution/tests/architecture.rs create mode 100644 l64-execution/tests/execution.rs delete mode 100644 l64-kernel/.gitignore delete mode 100644 l64-kernel/Cargo.toml delete mode 100644 l64-kernel/src/lib.rs delete mode 100644 l64-locus/Cargo.toml delete mode 100644 l64-locus/src/lib.rs rename {l64-testkit => l64-native}/Cargo.toml (61%) create mode 100644 l64-native/README.md create mode 100644 l64-native/src/closure.rs create mode 100644 l64-native/src/codec.rs create mode 100644 l64-native/src/codec/io.rs create mode 100644 l64-native/src/codec/reader.rs create mode 100644 l64-native/src/codec/validation.rs create mode 100644 l64-native/src/context.rs create mode 100644 l64-native/src/dimension.rs create mode 100644 l64-native/src/dna.rs create mode 100644 l64-native/src/graph.rs create mode 100644 l64-native/src/graph/closure.rs create mode 100644 l64-native/src/graph/construction.rs create mode 100644 l64-native/src/graph/context.rs create mode 100644 l64-native/src/graph/derived.rs create mode 100644 l64-native/src/graph/storage.rs create mode 100644 l64-native/src/graph/typing.rs create mode 100644 l64-native/src/journal.rs create mode 100644 l64-native/src/kernel.rs create mode 100644 l64-native/src/kernel/equality.rs create mode 100644 l64-native/src/kernel/equality/canonical.rs create mode 100644 l64-native/src/kernel/equality/proof.rs create mode 100644 l64-native/src/kernel/equality/validation.rs create mode 100644 l64-native/src/kernel/proposal.rs create mode 100644 l64-native/src/kernel/transaction.rs create mode 100644 l64-native/src/kernel/types.rs create mode 100644 l64-native/src/kernel/validation.rs create mode 100644 l64-native/src/lib.rs create mode 100644 l64-native/src/rna.rs create mode 100644 l64-native/src/rna/compile.rs create mode 100644 l64-native/src/rna/parse.rs create mode 100644 l64-native/src/rna/render.rs create mode 100644 l64-native/src/rna/sequence.rs create mode 100644 l64-native/src/route.rs create mode 100644 l64-native/src/symbol.rs create mode 100644 l64-native/tests/architecture.rs create mode 100644 l64-native/tests/closure.rs create mode 100644 l64-native/tests/codec.rs create mode 100644 l64-native/tests/constraints.rs create mode 100644 l64-native/tests/dna.rs create mode 100644 l64-native/tests/equality.rs create mode 100644 l64-native/tests/rna.rs create mode 100644 l64-native/tests/symbol.rs create mode 100644 l64-native/tests/workloads.rs create mode 100644 l64-observation/Cargo.toml create mode 100644 l64-observation/README.md create mode 100644 l64-observation/src/lib.rs create mode 100644 l64-observation/tests/architecture.rs create mode 100644 l64-observation/tests/observation.rs delete mode 100644 l64-observe/Cargo.toml delete mode 100644 l64-observe/src/lib.rs delete mode 100644 l64-policy/Cargo.toml delete mode 100644 l64-policy/src/lib.rs rename {l64-command => l64-projection}/Cargo.toml (54%) create mode 100644 l64-projection/README.md create mode 100644 l64-projection/examples/native_projection.rs create mode 100644 l64-projection/src/analysis.rs create mode 100644 l64-projection/src/atlas.rs create mode 100644 l64-projection/src/certification.rs create mode 100644 l64-projection/src/lib.rs create mode 100644 l64-projection/src/order.rs create mode 100644 l64-projection/src/replay.rs create mode 100644 l64-projection/src/report.rs create mode 100644 l64-projection/src/research.rs create mode 100644 l64-projection/src/set.rs create mode 100644 l64-projection/src/source.rs create mode 100644 l64-projection/tests/architecture.rs create mode 100644 l64-projection/tests/projection.rs delete mode 100644 l64-registry/.gitignore delete mode 100644 l64-registry/Cargo.toml delete mode 100644 l64-registry/data/seed.v1.json delete mode 100644 l64-registry/src/lib.rs create mode 100644 l64-release/Cargo.toml create mode 100644 l64-release/src/lib.rs create mode 100644 l64-release/tests/release.rs delete mode 100644 l64-research/Cargo.toml delete mode 100644 l64-research/src/lib.rs delete mode 100644 l64-runtime/.gitignore delete mode 100644 l64-runtime/Cargo.toml delete mode 100644 l64-runtime/src/lib.rs delete mode 100644 l64-selector/.gitignore delete mode 100644 l64-selector/Cargo.toml delete mode 100644 l64-selector/src/lib.rs create mode 100644 l64-symbolic/Cargo.toml create mode 100644 l64-symbolic/DESIGN.md create mode 100644 l64-symbolic/README.md create mode 100644 l64-symbolic/examples/symbolic_audit.rs create mode 100644 l64-symbolic/examples/symbolic_commitment.rs create mode 100644 l64-symbolic/src/lib.rs create mode 100644 l64-symbolic/tests/algebra.rs create mode 100644 l64-symbolic/tests/architecture.rs delete mode 100644 l64-testkit/src/lib.rs create mode 100644 l64-transport/Cargo.toml create mode 100644 l64-transport/README.md create mode 100644 l64-transport/src/lib.rs create mode 100644 l64-transport/src/stream.rs create mode 100644 l64-transport/tests/architecture.rs create mode 100644 l64-transport/tests/transport.rs delete mode 100644 samples/chain_rule_bundle.dna delete mode 100644 samples/chain_rule_integrated_bundle.dna create mode 100644 samples/golden/certified_triangle.rna create mode 100644 samples/golden/equality_chain.rna create mode 100644 samples/golden/expected/certified_triangle.certify.txt create mode 100644 samples/golden/expected/certified_triangle.dna.hex create mode 100644 samples/golden/expected/certified_triangle.normalized.rna create mode 100644 samples/golden/expected/certified_triangle.run.txt create mode 100644 samples/golden/expected/equality_chain.certify.txt create mode 100644 samples/golden/expected/equality_chain.dna.hex create mode 100644 samples/golden/expected/equality_chain.normalized.rna create mode 100644 samples/golden/expected/equality_chain.run.txt create mode 100644 samples/golden/expected/invalid_child_context.certify.txt create mode 100644 samples/golden/expected/invalid_child_context.dna.hex create mode 100644 samples/golden/expected/invalid_child_context.normalized.rna create mode 100644 samples/golden/expected/invalid_child_context.run.txt create mode 100644 samples/golden/expected/matrix_multiply.certify.txt create mode 100644 samples/golden/expected/matrix_multiply.dna.hex create mode 100644 samples/golden/expected/matrix_multiply.normalized.rna create mode 100644 samples/golden/expected/matrix_multiply.run.txt create mode 100644 samples/golden/expected/mixed_bundle.certify.txt create mode 100644 samples/golden/expected/mixed_bundle.observe.txt create mode 100644 samples/golden/expected/mixed_bundle.run.txt create mode 100644 samples/golden/expected/open_obligation.certify.txt create mode 100644 samples/golden/expected/open_obligation.dna.hex create mode 100644 samples/golden/expected/open_obligation.normalized.rna create mode 100644 samples/golden/expected/open_obligation.run.txt create mode 100644 samples/golden/expected/triangle.release.authority.dna.hex create mode 100644 samples/golden/expected/triangle.release.projection.txt create mode 100644 samples/golden/expected/triangle.release.record create mode 100644 samples/golden/expected/triangle_to_equality.compare.txt create mode 100644 samples/golden/invalid_child_context.rna create mode 100644 samples/golden/matrix_multiply.rna create mode 100644 samples/golden/open_obligation.rna delete mode 100644 samples/imported_claim_bundle.dna delete mode 100644 samples/imported_claim_stress_gap_bundle.dna create mode 100644 samples/native_equality.rna create mode 100644 samples/native_triangle.rna delete mode 100644 samples/research/claim_chain_rule.json delete mode 100644 samples/research/coverage_chain_rule.json delete mode 100644 samples/research/export_capability_truth.json delete mode 100644 samples/research/export_explain_execution.json delete mode 100644 samples/research/export_namespace_contract.json delete mode 100644 samples/research/export_predict_impact_contract.json delete mode 100644 samples/research/export_validate_inspection_report.json delete mode 100644 samples/research/producer_host_chain_rule.json delete mode 100644 samples/research/promotion_chain_rule.json delete mode 100644 samples/research/remediation_explain_execution.json delete mode 100644 samples/research/repro_chain_rule.json delete mode 100644 samples/research/signature_full_compound_completion.json delete mode 100644 samples/research/signature_operational_truth.json delete mode 100644 samples/research/task_full_compound_completion.json delete mode 100644 samples/research/task_operational_truth.json create mode 100755 scripts/run-native-demo.sh delete mode 100644 scripts/torture-test.ps1 create mode 100755 scripts/verify-cli-hardening.sh create mode 100755 scripts/verify-documentation-coherence.sh create mode 100755 scripts/verify-golden-portability.sh create mode 100755 scripts/verify-legacy-authority-island-deletion.sh create mode 100755 scripts/verify-native-carrier.sh create mode 100755 scripts/verify-native-scale.sh create mode 100755 scripts/verify-portability-receipts.sh create mode 100755 scripts/verify-process-contract.sh create mode 100755 scripts/write-portability-receipt.sh diff --git a/.github/workflows/native-core.yml b/.github/workflows/native-core.yml new file mode 100644 index 0000000..3b5aa72 --- /dev/null +++ b/.github/workflows/native-core.yml @@ -0,0 +1,116 @@ +name: Native core gate + +on: + pull_request: + branches: [main, 'chatgpt/**'] + paths: + - Cargo.toml + - Cargo.lock + - l64-symbolic/** + - l64-native/** + - l64-projection/** + - l64-release/** + - l64-execution/** + - l64-transport/** + - l64-certification/** + - l64-observation/** + - l64-change/** + - l64-cli/** + - l64/** + - scripts/verify-native-carrier.sh + - scripts/verify-cli-hardening.sh + - scripts/verify-process-contract.sh + - scripts/verify-native-scale.sh + - scripts/verify-documentation-coherence.sh + - scripts/verify-golden-portability.sh + - scripts/write-portability-receipt.sh + - scripts/verify-portability-receipts.sh + - samples/golden/** + - '**/*.md' + - scripts/run-native-demo.sh + - scripts/verify-legacy-authority-island-deletion.sh + - samples/native_triangle.rna + - samples/native_equality.rna + - LOCUS64_*_RAIL.athens + - LOCUS64_*_CHANGE_CHAIN.athens + - .github/workflows/native-core.yml + workflow_dispatch: + +permissions: + contents: read + +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - name: Check formatting + run: cargo fmt --all --check + - name: Verify legacy authority island deletion + run: ./scripts/verify-legacy-authority-island-deletion.sh + - name: Verify dependency-free native carrier + run: ./scripts/verify-native-carrier.sh + - name: Verify hardened CLI boundary + run: ./scripts/verify-cli-hardening.sh + - name: Verify process outcomes, RNA spans, and streaming bundles + run: ./scripts/verify-process-contract.sh + - name: Verify measured native scale boundaries + run: ./scripts/verify-native-scale.sh + - name: Verify current documentation coherence + run: ./scripts/verify-documentation-coherence.sh + - name: Verify golden workloads and portability contract + run: ./scripts/verify-golden-portability.sh + - name: Test complete workspace offline + run: cargo test --locked --offline --workspace + - name: Lint complete workspace offline + run: cargo clippy --locked --offline --workspace --all-targets -- -D warnings + + portable-rust: + name: Portable Rust workspace (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - name: Test complete dependency-free workspace + run: cargo test --locked --offline --workspace + - name: Write source-bound portability receipt + shell: bash + env: + L64_SOURCE_REF: ${{ github.sha }} + run: ./scripts/write-portability-receipt.sh "portability-receipt/l64-portability-${{ matrix.os }}.json" "${{ matrix.os }}" + - name: Upload host portability receipt + uses: actions/upload-artifact@v4 + with: + name: locus64-portability-receipt-${{ matrix.os }} + path: portability-receipt/l64-portability-${{ matrix.os }}.json + if-no-files-found: error + retention-days: 30 + + portable-receipts: + name: Verify combined portability receipts + needs: portable-rust + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Download host receipts + uses: actions/download-artifact@v4 + with: + pattern: locus64-portability-receipt-* + path: portability-receipts + merge-multiple: true + - name: Verify exact source-bound host set + run: ./scripts/verify-portability-receipts.sh portability-receipts "${{ github.sha }}" + - name: Upload verified receipt set + uses: actions/upload-artifact@v4 + with: + name: locus64-portability-receipts + path: portability-receipts/*.json + if-no-files-found: error + retention-days: 30 diff --git a/Cargo.lock b/Cargo.lock index 10deab3..a97b1ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,814 +2,92 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys", -] - -[[package]] -name = "anyhow" -version = "1.0.102" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" - -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - -[[package]] -name = "arrayvec" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" - -[[package]] -name = "assert_cmd" -version = "2.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" -dependencies = [ - "anstyle", - "bstr", - "libc", - "predicates", - "predicates-core", - "predicates-tree", - "wait-timeout", -] - -[[package]] -name = "bincode" -version = "1.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" -dependencies = [ - "serde", -] - -[[package]] -name = "bitflags" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" - -[[package]] -name = "blake3" -version = "1.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if", - "constant_time_eq", - "cpufeatures", -] - -[[package]] -name = "bstr" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" -dependencies = [ - "memchr", - "regex-automata", - "serde", -] - -[[package]] -name = "cc" -version = "1.2.62" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "constant_time_eq" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" - -[[package]] -name = "cpufeatures" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" -dependencies = [ - "libc", -] - -[[package]] -name = "difflib" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" - -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-executor" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-util" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - [[package]] name = "l64" -version = "0.1.0" -dependencies = [ - "anyhow", -] - -[[package]] -name = "l64-admin" -version = "0.1.0" -dependencies = [ - "anyhow", - "assert_cmd", - "clap", - "l64-atlas", - "l64-bundle", - "l64-cert", - "l64-command", - "l64-core", - "l64-locus", - "l64-observe", - "l64-policy", - "l64-registry", - "serde_json", - "serial_test", -] - -[[package]] -name = "l64-atlas" -version = "0.1.0" -dependencies = [ - "l64-core", - "l64-kernel", - "l64-policy", - "l64-registry", - "serde", - "thiserror", -] - -[[package]] -name = "l64-bundle" -version = "0.1.0" -dependencies = [ - "anyhow", - "l64-core", - "l64-locus", - "l64-registry", - "serde", - "serde_json", - "thiserror", -] +version = "0.1.3" [[package]] -name = "l64-canon" -version = "0.1.0" +name = "l64-certification" +version = "0.1.3" dependencies = [ - "l64-core", - "l64-registry", - "l64-runtime", - "thiserror", + "l64-native", + "l64-projection", ] [[package]] -name = "l64-cert" -version = "0.1.0" +name = "l64-change" +version = "0.1.3" dependencies = [ - "bincode", - "l64-atlas", - "l64-bundle", - "l64-core", - "l64-kernel", - "l64-locus", - "l64-policy", - "l64-registry", - "l64-runtime", - "serde", - "serde_json", - "serial_test", - "thiserror", + "l64-certification", + "l64-native", + "l64-observation", + "l64-transport", ] [[package]] name = "l64-cli" -version = "0.1.0" -dependencies = [ - "anyhow", - "assert_cmd", - "bincode", - "clap", - "hex", - "l64-atlas", - "l64-bundle", - "l64-canon", - "l64-cert", - "l64-command", - "l64-core", - "l64-kernel", - "l64-locus", - "l64-policy", - "l64-registry", - "l64-research", - "l64-runtime", - "l64-selector", - "serde_json", -] - -[[package]] -name = "l64-command" -version = "0.1.0" -dependencies = [ - "clap", - "l64-core", -] - -[[package]] -name = "l64-core" -version = "0.1.0" -dependencies = [ - "bincode", - "blake3", - "serde", - "serde_json", -] - -[[package]] -name = "l64-kernel" -version = "0.1.0" -dependencies = [ - "l64-core", - "l64-testkit", - "serde", - "thiserror", -] - -[[package]] -name = "l64-locus" -version = "0.1.0" -dependencies = [ - "bincode", - "l64-core", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "l64-observe" -version = "0.1.0" -dependencies = [ - "anyhow", - "bincode", - "l64-atlas", - "l64-bundle", - "l64-cert", - "l64-core", - "l64-locus", - "l64-policy", - "serde", - "serde_json", -] - -[[package]] -name = "l64-policy" -version = "0.1.0" -dependencies = [ - "l64-core", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "l64-registry" -version = "0.1.0" -dependencies = [ - "l64-core", - "serde_json", - "thiserror", -] - -[[package]] -name = "l64-research" -version = "0.1.0" -dependencies = [ - "anyhow", - "bincode", - "l64-cert", - "l64-core", - "l64-locus", - "serde", - "serde_json", -] - -[[package]] -name = "l64-runtime" -version = "0.1.0" -dependencies = [ - "bincode", - "l64-core", - "l64-registry", - "serde", - "thiserror", -] - -[[package]] -name = "l64-selector" -version = "0.1.0" -dependencies = [ - "l64-core", - "l64-kernel", - "l64-testkit", -] - -[[package]] -name = "l64-testkit" -version = "0.1.0" -dependencies = [ - "l64-core", -] - -[[package]] -name = "libc" -version = "0.2.186" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" - -[[package]] -name = "memchr" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "predicates" -version = "3.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" -dependencies = [ - "anstyle", - "difflib", - "predicates-core", -] - -[[package]] -name = "predicates-core" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" - -[[package]] -name = "predicates-tree" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" -dependencies = [ - "predicates-core", - "termtree", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +version = "0.1.3" dependencies = [ - "unicode-ident", + "l64-certification", + "l64-change", + "l64-execution", + "l64-native", + "l64-observation", + "l64-projection", + "l64-release", + "l64-transport", ] [[package]] -name = "quote" -version = "1.0.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +name = "l64-execution" +version = "0.1.3" dependencies = [ - "proc-macro2", + "l64-certification", + "l64-native", + "l64-projection", ] [[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +name = "l64-native" +version = "0.1.3" dependencies = [ - "bitflags", + "l64-symbolic", ] [[package]] -name = "regex-automata" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" - -[[package]] -name = "scc" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46e6f046b7fef48e2660c57ed794263155d713de679057f2d0c169bfc6e756cc" +name = "l64-observation" +version = "0.1.3" dependencies = [ - "sdd", + "l64-certification", + "l64-native", + "l64-projection", + "l64-transport", ] [[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "sdd" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca" - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +name = "l64-projection" +version = "0.1.3" dependencies = [ - "serde_core", - "serde_derive", + "l64-native", ] [[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +name = "l64-release" +version = "0.1.3" dependencies = [ - "serde_derive", + "l64-native", + "l64-projection", ] [[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] +name = "l64-symbolic" +version = "0.1.3" [[package]] -name = "serde_json" -version = "1.0.150" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +name = "l64-transport" +version = "0.1.3" dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", + "l64-certification", + "l64-execution", + "l64-native", ] - -[[package]] -name = "serial_test" -version = "3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "911bd979bf1070a3f3aa7b691a3b3e9968f339ceeec89e08c280a8a22207a32f" -dependencies = [ - "futures-executor", - "futures-util", - "log", - "once_cell", - "parking_lot", - "scc", - "serial_test_derive", -] - -[[package]] -name = "serial_test_derive" -version = "3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a7d91949b85b0d2fb687445e448b40d322b6b3e4af6b44a29b21d9a5f33e6d9" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "syn" -version = "2.0.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "termtree" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" - -[[package]] -name = "thiserror" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "wait-timeout" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" -dependencies = [ - "libc", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "zmij" -version = "1.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml index 3a7c67a..66de823 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,41 +1,24 @@ [workspace] +resolver = "2" members = [ - "l64-core", - "l64-locus", - "l64-research", - "l64-kernel", - "l64-registry", - "l64-selector", + "l64-symbolic", + "l64-native", + "l64-projection", + "l64-release", + "l64-execution", + "l64-transport", + "l64-certification", + "l64-observation", + "l64-change", "l64-cli", - "l64-runtime", - "l64-canon", - "l64-atlas", - "l64-cert", - "l64-bundle", - "l64-policy", - "l64-observe", - "l64-admin", - "l64-command", "l64", - "l64-testkit", ] -resolver = "2" [workspace.package] +version = "0.1.3" edition = "2024" -version = "0.1.0" license = "MIT" -[workspace.dependencies] -anyhow = "1.0" -clap = { version = "4.5", features = ["derive"] } -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -thiserror = "2.0" -bincode = "1.3" -hex = "0.4" -blake3 = "1.5" - [profile.release] opt-level = "z" lto = true diff --git a/EXPORT_STRESS_REMEDIATION_LEDGER.md b/EXPORT_STRESS_REMEDIATION_LEDGER.md index 29bbd95..30cf5f3 100644 --- a/EXPORT_STRESS_REMEDIATION_LEDGER.md +++ b/EXPORT_STRESS_REMEDIATION_LEDGER.md @@ -32,7 +32,7 @@ Every exported failure or friction signal should cash out into: ## Current machine absorption state -The remediation ledger is no longer only prose. It now coexists with warm-host routing, promotion-readiness, claim packets, and producer-host specs, so export-derived seams can participate in actual route choice and readiness gating rather than remaining detached notes. +The remediation ledger remains an explicit compatibility record beside route, claim, and producer-host records. Promotion-readiness and lineage stores were deleted; remediation notes cannot manufacture promotion state or authority. ## Current coherence checkpoint diff --git a/HANDOFF_STATUS.md b/HANDOFF_STATUS.md index 6c1437d..2e41727 100644 --- a/HANDOFF_STATUS.md +++ b/HANDOFF_STATUS.md @@ -1,108 +1,21 @@ -# Locus64 Handoff Status +# Handoff Status — Pass 30 -## Current State +Status: local residue closure and source-bound remote portability proof infrastructure complete. Authority, wire formats, runtime behavior, process law, and Linux runtime bytes are unchanged. -The workspace builds and tests as a Rust workspace with the unified `l64` wrapper, direct `l64-cli`, and direct `l64-admin` binaries. +The workspace contains eleven dependency-free native packages at version 0.1.3. Five representative authority workloads bind exact normalized RNA, canonical DNA, execution, certification, compare, transport, observation, and release behavior. -The source crate/package/binary prefix rename from `mf` to `l64` has been executed. Remaining `mf` mentions should be limited to historical rail notes or explicitly documented transitional residue. +Pass 30: -The active lower chain is the authority path: +- removes the obsolete live `scripts/torture-test.ps1` harness while retaining one external forensic copy; +- recomputes the source manifest and research/administration classification through the Pass 29 restore boundary; +- extends documentation coherence across every current script and current-facing document; +- emits one machine-readable `L64PORT1` receipt after each Linux, macOS, or Windows workspace test; +- verifies that the exact three-host receipt set binds one source commit, eleven packages, zero external dependencies, and the complete locked-offline workspace test; +- uploads both per-host receipts and one combined verified receipt artifact in CI; +- keeps all receipt machinery outside runtime and authority. -```text -Tokenization -> RnaNormalization -> StructuralResolution -> CanonicalNormalization -> DNA emission -``` +Restore boundary: Pass 29 source archive. The Pass 30 source changes verification, CI, and current documentation only; the Linux runtime is rebuilt and reverified for the handoff. -Implemented lower-chain substrates include: +Remote portability closure is established by a successful exact-source CI run and its retained combined receipt artifact. The source tree intentionally does not embed a transient run ID; the external receipt set names the exact commit it proves. -- token classes, token streams, tokenization receipts, token specs -- RNORM diagnostic specs and token-grounded normalization receipts -- SSR transition specs and ephemeral SSR receipts -- distinction, transition, and equivalence law tables consumed by CNORM -- versioned canonical instruction records used to derive canonical bytes and canonical identity -- DNA header receipts, section payload commitments, explicit decode modes, and validation reports -- duplex semantic/complement pair validation, domain closure reports, and deterministic authority merge records -- execution exactness and execution closure receipts -- proof coverage dispatch with reuse legality, reuse decisions, and residual verification receipts -- research lineage records that carry canonical hash, lowering receipt id, phase ids, and phase ledger -- report-derived claim packets classified as projection authority until replay-specific promotion exists -- named, scoped evaluator policy resolution and deterministic policy-precedence receipts - -The current `LINEAR_EXECUTION_RAIL.md` supersedes earlier completion framing. It now routes remaining transitional bundle/product/campaign paths through native authority products before further deletion or upper-stack expansion. - -## Shipping Entry Points - -- `l64`: canonical wrapper -- `l64-cli`: direct CLI binary for automation and lower-level debugging -- `l64-admin`: direct admin binary for automation and lower-level debugging - -Release packages include all three because `l64` dispatches to sibling `l64-cli` or `l64-admin`. - -## Verification Commands - -```powershell -cargo fmt --check -cargo test -q -cargo build --profile perfopt -p l64 -p l64-cli -p l64-admin -cargo build --profile compact -p l64 -p l64-cli -p l64-admin -powershell -ExecutionPolicy Bypass -File .\scripts\torture-test.ps1 -OuterRounds 1 -InnerNamespaces 1 -``` - -## Release Profiles - -- `perfopt`: `opt-level=3`, fat LTO, one codegen unit, stripped, abort panic -- `compact`: size optimization, LTO, one codegen unit, stripped, abort panic - -Linux target attempted by this release pass: `x86_64-unknown-linux-gnu`. The Rust target is installed, but packaging Linux binaries is blocked locally because the GNU linker `cc` is missing. - -Windows target used by this release pass: `x86_64-pc-windows-msvc`. - -## Known Constraints - -- The repo is a Git repository connected to GitHub. -- `.dna` is the machine authority artifact. Legacy packet decoding is explicit migration/forensic behavior only. -- Q-surface crates have been removed from the workspace. Public doctrine is RNA/DNA; remaining Q-surface mentions are historical notes, negative regressions, or documented tombstones only. -- SSR is intentionally ephemeral and must not become a persisted semantic authority layer. -- `sequence-dna` emits canonical reconstructable RNA; `inspect-dna` owns JSON inspection output. -- `compile-rna` rejects inspection reports, release projections, release records, receipts, and JSON report/projection text as source. -- Generated genome release artifacts now use source/canonical `.rna`, genome `.dna`, and role-specific `.projection`, `.record`, or receipt filenames. They no longer emit `.locus` projection files or an on-disk JSON manifest. -- Admin/cert artifact discovery no longer reads legacy JSON manifest/lock/report caches, legacy report `.locus` caches, or execution `reports.json`. -- Execution manifest and bundle-lock packet caches now use `.dna` filenames rather than `.locus` filenames. -- Certification execution cache entries now use `.dna` filenames rather than `.locus` filenames. Rebuild `l64-cli` and `l64-admin` together before running admin tests that use CLI-produced cache entries. -- Observe persistence entries now use `.dna` filenames rather than `.locus` filenames for observation/diff/prediction/plan/explanation/assessment/execution/reconciliation records. -- Bundle-entry authoring text now uses the native `!l64-bundle v1` header. `compile-bundle` rejects obsolete `!qc0`/`!qa0` headers. -- Bundle-entry authoring text must contain at least one entry. -- Bundle import rejects non-closed native substrate parity before persisting `BundleWorld`. -- Bundle substrate parity now carries duplex pair counts, locally valid pair counts, domain closure, and deterministic merge evidence. -- Report-derived research artifacts are warm-host projections unless replayed through a stronger authority path. `Integrated` or `Certified` report verdicts are retained as projection assumptions, not automatically promoted into evidence/benchmark authority. -- Evaluator behavior must resolve through named scoped `MechanizationPolicyObject` records. Equal-precedence policy candidates are ordered by stable policy identity so policy resolution IDs, applied policy order, and trace steps are deterministic. -- Under memory pressure, use the low-memory verification wrapper: - -```powershell -.\scripts\verify-low-memory.ps1 -Scope workspace -.\scripts\verify-low-memory.ps1 -Scope all -``` - -The wrapper sets `CARGO_BUILD_JOBS=1`, disables incremental compilation, strips dev/test debug info, and runs formatting plus `git diff --check` unless explicitly skipped. - -## Cleanup Policy Used - -Generated caches, old zips, transient scratch files, and previous release payloads are moved to: - -```text -C:\Users\Fresh\Projects\Locus64 Garbage -``` - -They are not hard-deleted. - -## Most Important Files - -- `README.md`: concise project overview and release layout -- `LOCUS64_LANGUAGE_SPEC.md`: RNA/DNA command and language reference, including source/inspection membrane rules -- `USAGE_GUIDE.md`: operator command guide -- `SEMANTIC_USAGE_GUIDE.md`: semantic usage guide for claim governance, branch/challenge tracking, and research-framework integration -- `LINEAR_EXECUTION_RAIL.md`: authoritative linear execution rail and phase sequence -- `L64_APPROVAL_GATES.md`: approval-gate ledger for candidate/proven/deferred/rejected architectural law -- `LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md`: mechanically proven architectural law only -- `scripts/torture-test.ps1`: regression/torture harness -- `scripts/verify-low-memory.ps1`: low-memory cargo verification wrapper for large `l64-core` rebuilds -- `Cargo.toml`: workspace members and release profiles +After that receipt exists, further work is optional capability or packaging expansion rather than unfinished native closure. diff --git a/L64_APPROVAL_GATES.md b/L64_APPROVAL_GATES.md index 64f9ce0..0e24399 100644 --- a/L64_APPROVAL_GATES.md +++ b/L64_APPROVAL_GATES.md @@ -1,94 +1,36 @@ -# Locus64 Approval Gate Ledger - -This file tracks candidate architectural law. A gate is only constitutional after it has executable evidence. - -Status values: - -- `Candidate`: accepted direction, not mechanically proven yet -- `Proven`: mechanically proven and eligible for constitution promotion -- `Deferred`: valid later concern outside the active dependency frontier -- `Rejected`: retained as an audited non-path - -Proof classes: - -- `CR`: compiler/category rejection -- `FP`: fixed-point reconstruction -- `DV`: DNA validation -- `MG`: strategic migration -- `PE`: deterministic parallel equivalence -- `PL`: projection-loss accounting -- `EA`: external-adapter witness -- `RI`: release/source integrity - -| Gate | Candidate ruling | Proof | Depends on | Status | Evidence | -|---|---|---:|---|---|---| -| L64-G001 | Duplex pair is the smallest locally authoritative unit | CR,DV | canonical encoding | Proven | `cargo test -p l64-core duplex_pair_validation_requires_semantic_and_complement_strands` | -| L64-G002 | Neither strand is independently promotable | CR | G001 | Proven | `cargo test -p l64-core duplex_pair_validation_requires_semantic_and_complement_strands` | -| L64-G003 | Pair-local validity does not imply domain closure | CR,DV | G001 | Proven | `cargo test -p l64-core domain_closure_blocks_promotion_on_open_frontier` | -| L64-G004 | Complement encodes admissibility burdens; receipts only discharge them | CR | G001 | Proven | `cargo test -p l64-core authority_complement_must_carry_burdens_not_receipt_only_claims` | -| L64-G005 | Duplex is native DNA structure, not a third public format | CR,RI | artifact roles | Candidate | pending | -| L64-G006 | Current molecular nouns are provisional role mappings | CR,MG | role model | Candidate | pending | -| L64-G007 | Codons compile to structural instructions, not semantic codebooks | CR,DV | symbolic law | Proven | `cargo test -p l64-core` (`codon_lexon_law_tables_are_unique_and_complete`, `codon_header_phase_controls_source_admission`) | -| L64-G008 | Lexons are scoped receipted bindings, not global meaning | CR,DV | scope law | Proven | `cargo test -p l64-core` (`lexon_aliases_resolve_to_scoped_canonical_targets`, `representative_lexons_bind_scoped_targets_with_receipts`) | -| L64-G009 | Macro-codons compile to reaction law, not workflow labels | CR,DV | G007 | Proven | `cargo test -p l64-core macro_codons_are_separate_from_lexons` | -| L64-G010 | Graphs are resolver, plan, diagnostic, or projection representations only | CR | graph roles | Candidate | pending | -| L64-G011 | Duplex pairing is logical and variable-length, not fixed-width syntax | DV,FP | canonical encoding | Candidate | pending | -| L64-G012 | Domain theorem/claim/proof classes remain above root substrate | CR,MG | substrate roles | Candidate | pending | -| L64-G013 | Generated-word bans are regression tripwires, not authority law | CR | typed admission | Proven | `cargo test -p l64-core generated_structural_word_ban_detects_old_label_payloads` | -| L64-G014 | Bincode is cache/transport only, not canonical DNA | DV,FP | canonical encoding | Candidate | pending | -| L64-G015 | Persistent authority identity derives from canonical structural bytes | FP,DV | distinction/equivalence | Proven | `cargo test -p l64-core` (`canonical_structure_erases_spacing_but_preserves_order`, `dna_packet_validation_checks_canonical_structure_digest`) | -| L64-G016 | Explicit canonical instructions replace token-hash authority | FP,DV | G015 | Proven | `cargo test -p l64-core canonical_structure_erases_spacing_but_preserves_order` | -| L64-G017 | Every authority section commitment binds its payload | DV | packet codec | Proven | `cargo test -p l64-core generic_dna_packet_validates_section_payload_commitment` | -| L64-G018 | Authority payload decode requires complete packet validation | DV | G017 | Proven | `cargo test -p l64-core` (`dna_packet_validation_checks_canonical_structure_digest`, `generic_dna_packet_validates_section_payload_commitment`) | -| L64-G019 | Legacy decoding requires explicit migration or forensic mode | DV,MG | decode roles | Proven | `cargo test -p l64-core legacy_packet_decode_requires_explicit_migration_or_forensic_mode` | -| L64-G020 | Authority decoding is bounded before allocation | DV | packet codec | Proven | `cargo test -p l64-core locus_packet_decode_rejects_oversized_fields_before_payload_copy` | -| L64-G021 | Authority tiers are typed law at DNA validation | CR,DV | role model | Proven | `cargo test -p l64-core dna_packet_validation_rejects_unknown_authority_tier` | -| L64-G022 | Capability summaries require witness coordinates | CR,DV | witness model | Candidate | pending | -| L64-G023 | Generated caches and ambiguous reports do not ship as source | RI | release gate | Proven | `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` | -| L64-G024 | Serial and parallel authoritative outputs are byte-equivalent | PE | closure scheduler | Proven | `cargo test -p l64-core deterministic_authority_merge_excludes_worker_count_and_input_order` | -| L64-G025 | Scheduler plans and telemetry are receipts, not authority | PE,CR | G024 | Proven | `cargo test -p l64-core deterministic_authority_merge_excludes_worker_count_and_input_order` | -| L64-G026 | Authored obligation status is intent, never evidence | CR,MG | evaluator model | Proven | `cargo test -p l64-cert authored_obligation_status_does_not_satisfy_evidence` | -| L64-G027 | Evaluator authority is explicit, named, and scoped | CR,MG | evaluator interface | Proven | `cargo test -p l64-policy evaluator_authority_is_named_and_scoped` | -| L64-G028 | Every certification verdict carries authority scope | CR,DV | scope law | Candidate | pending | -| L64-G029 | Report-derived research records are projections until replayed | CR,MG | artifact roles | Proven | `cargo test -p l64-research report_derivation_emits_lineage_record` | -| L64-G030 | Policy precedence emits deterministic receipts | PE,DV | policy law | Proven | `cargo test -p l64-policy policy_precedence_receipt_is_stable_across_registry_order` | -| L64-G031 | Namespace import is a receipted bridge, not string rewriting | MG,DV | bridge law | Candidate | pending | -| L64-G032 | RNA and DNA remain the only public authority surfaces | CR,RI | artifact roles | Proven | `cargo test -p l64-cli --test cli` (`rna_dna_primary_authority_commands_work`, `standalone_projection_leaf_commands_are_removed`, `inspect_dna_output_is_not_rna_source`) | -| L64-G033 | Bundle-entry JSON is deletion-bound migration ingress only | MG,RI | native bundle path | Proven | `cargo test -p l64-bundle` (`bundle_document_import_can_cross_explicit_migration_ingress`, `bundle_entry_text_rejects_deprecated_surface_schema_entries`) | -| L64-G034 | Remaining Qa/Qc types are migration ASTs, not core ontology | MG,CR | native bundle path | Candidate | pending | -| L64-G035 | Codebook/glyph/combo packs are projection or legacy machinery | MG,CR | projection boundary | Candidate | pending | -| L64-G036 | DNA reconstructs canonical RNA, not authored RNA | FP | canonical encoding | Proven | `cargo test -p l64-cli --test cli cki_registry_fixture_preserves_rna_dna_fixed_point` | -| L64-G037 | Grooves, folds, indexes, maps, and plans stay outside identity | FP,PE | G015 | Candidate | pending | -| L64-G038 | Release strings are renderers over witnessed products | MG,PL | expression layer | Proven | `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` | -| L64-G039 | Seed JSON is bootstrap source and compiles to DNA | MG,RI | native seed path | Candidate | pending | -| L64-G040 | Every sample artifact has an explicit source/migration/projection role | RI,CR | artifact roles | Proven | `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` | -| L64-G041 | External standards are dialects and witness providers | EA,CR | adapter law | Deferred | pending | -| L64-G042 | Every standards export carries a projection-loss receipt | PL,EA | G041 | Deferred | pending | -| L64-G043 | Proof assistants provide scoped external witnesses | EA,DV | evaluator interface | Deferred | pending | -| L64-G044 | SBOM/provenance standards are loss-accounted projections | PL,EA | G041 | Deferred | pending | -| L64-G045 | Constitutional rules require mechanical evidence | CR,FP,DV,MG,PE,PL,EA | this ledger | Proven | ledger promotion law | -| L64-G046 | New crates are justified only by enforceable authority membranes | CR | dependency audit | Candidate | pending | -| L64-G047 | Migration completes only after execution authority reroutes | MG | native execution path | Candidate | pending | -| L64-G048 | Reasoning cost and validation locality precede byte compactness | FP,DV | canonical path | Candidate | pending | -| L64-G049 | Authority tiers are earned through receipted transitions | CR,DV | G021 | Candidate | pending | -| L64-G050 | Product identity is witness-shaped; digest is its commitment | DV,MG | witness/product law | Candidate | pending | -| L64-G051 | Boollet is a transition-memory sidecar, not Locus64 authority | CR,MG | Bands B-E native authority path | Candidate | pending | -| L64-G052 | Boollet Rust embedding requires fixture parity with the Python reference | FP,MG | Boollet Rust port | Candidate | pending | -| L64-G053 | Boollet suggestions re-enter Locus64 only as proposals or witness coordinates | CR,MG | G051 | Candidate | pending | -| L64-G054 | Boollet replay identity may guide remediation ordering but cannot affect canonical identity | FP,CR | G015,G051 | Candidate | pending | -| L64-G055 | Locus64 admission/remediation sidecar fixtures prove usefulness without authority transfer | MG,DV | G051,G052,native Locus64 transition fixture | Candidate | pending | -| L64-G056 | No naked equality: structural equivalence requires explicit law specs and transition context | CR,FP | G015,distinction law | Proven | `cargo test -p l64-core` (`equivalence_law_makes_ordering_explicit_before_cnorm`, `distinction_law_classifies_collapse_before_equivalence`) | -| L64-G057 | K2 bridge/path comparability is a transport obligation over DNA authority, not root identity | CR,MG | G056,G031 | Candidate | pending | -| L64-G058 | K2 proof-shape success is a witness receipt and cannot override DNA admission or fixed-point failure | CR,DV | G018,G036,G056 | Candidate | pending | -| L64-G059 | Route selection is lexicographic by lawfulness, obligations, equivalence transport, loss, rollback, proof shape, complexity, then reuse payoff | MG,PE | domain closure | Candidate | pending | -| L64-G060 | Boollet replay identity is sidecar reproducibility evidence and cannot substitute for Locus64 canonical identity | CR,FP | G015,G051,G052 | Candidate | pending | - -## Promotion Law - -1. Add or identify executable evidence. -2. Record the exact test, fixture, or migration artifact in `Evidence`. -3. Verify all listed dependencies are `Proven`. -4. Change the row to `Proven` in the same change that lands the proof. -5. Promote the ruling into the constitution only after workspace conformance passes. - -No bulk status promotion is allowed. Evidence is gate-specific even when one test exercises multiple gates. +--- +document_status: current +view: live executable gates only +historical_ledger: L64_HISTORICAL_APPROVAL_LEDGER.md +--- + +# Locus64 Current Approval Gates + +This file contains only gates that constrain the live native workspace. The complete candidate, rejection, deferral, supersession, and migration history is preserved in [`L64_HISTORICAL_APPROVAL_LEDGER.md`](L64_HISTORICAL_APPROVAL_LEDGER.md). + +| Gate | Contact protected | Direct evidence | Current consequence | +|---|---|---|---| +| `native-constraint-core-green` | dimensional and guarded admission | `LOCUS64_CONSTRAINT_CORE_CHANGE_CHAIN.athens`; native constraint tests | inconsistent dimensions and refuted guards cannot commit | +| `proof-producing-congruence-green` | equality and congruence | `LOCUS64_PROOF_CONGRUENCE_CHANGE_CHAIN.athens`; equality tests | equality requires checked evidence and context scope | +| `incremental-closure-green` | context-relative closure | `LOCUS64_INCREMENTAL_CLOSURE_CHANGE_CHAIN.athens`; closure tests | change impact is derived without a second authority store | +| `native-upper-projection-green` | read-only upper views | `LOCUS64_NATIVE_UPPER_PROJECTION_CHANGE_CHAIN.athens`; projection tests | views remain reconstructible and non-authoritative | +| `legacy-authority-island-deletion-green` | deleted compatibility authority | `LOCUS64_LEGACY_AUTHORITY_ISLAND_DELETION_CHANGE_CHAIN.athens`; `scripts/verify-legacy-authority-island-deletion.sh` | deleted crates and executable legacy routes cannot return | +| `native-carrier-green` | RNA/DNA execution, release, transport, certification, observation, change | `scripts/verify-native-carrier.sh` | every product contact derives from exact native authority | +| `native-cli-hardening-green` | public command contact | `LOCUS64_NATIVE_CLI_HARDENING_CHANGE_CHAIN.athens`; `scripts/verify-cli-hardening.sh` | wrong formats fail locally; outputs are atomic and non-overwriting | +| `native-process-contract-green` | shell status, diagnostics, bounded bundle work | `LOCUS64_NATIVE_PROCESS_CONTRACT_CHANGE_CHAIN.athens`; `scripts/verify-process-contract.sh` | verdict output and process status remain stable and member-local | +| `native-scale-green` | measured structural performance | `LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens`; `scripts/verify-native-scale.sh` | optimization cannot weaken authority or retained-projection verification | +| `documentation-coherence-green` | current architecture reconstruction | `LOCUS64_DOCUMENTATION_COHERENCE_CHANGE_CHAIN.athens`; `scripts/verify-documentation-coherence.sh` | current docs, Cargo membership, live help, scripts, and historical markers agree | +| `golden-portability-green` | representative product behavior and host invariance | `LOCUS64_GOLDEN_PORTABILITY_CHANGE_CHAIN.athens`; `scripts/verify-golden-portability.sh` | canonical bytes, stable outputs, verdicts, bundles, releases, line endings, paths, and host builds cannot drift silently | +| `residue-remote-proof-green` | live-source residue and retained host proof | `LOCUS64_RESIDUE_REMOTE_PROOF_CHANGE_CHAIN.athens`; `scripts/verify-documentation-coherence.sh`; `scripts/verify-portability-receipts.sh`; combined CI receipt artifact | deleted commands cannot return through scripts and three-host success must remain bound to one exact source | +| `workspace-green` | complete source boundary | locked-offline workspace tests, Clippy, formatting, ShellCheck | no local gate may substitute for complete workspace proof | + +## Promotion law + +1. Name the operational contact and the law being changed. +2. Land or identify direct executable evidence. +3. Verify every dependent current gate. +4. Update [`LOCUS64_NATIVE_CONSTITUTION.md`](LOCUS64_NATIVE_CONSTITUTION.md) when the law changes. +5. Preserve superseded reasoning in the historical ledgers when it remains reconstructively useful. +6. Pass `documentation-coherence-green` and `workspace-green` in the same release boundary. + +No bulk promotion is allowed. A historical gate name, prior test, or narrative claim cannot authorize current behavior by resemblance. diff --git a/L64_HISTORICAL_APPROVAL_LEDGER.md b/L64_HISTORICAL_APPROVAL_LEDGER.md new file mode 100644 index 0000000..d1036e3 --- /dev/null +++ b/L64_HISTORICAL_APPROVAL_LEDGER.md @@ -0,0 +1,140 @@ +--- +document_status: historical +superseded_by: L64_APPROVAL_GATES.md +scope: legacy candidates, superseded gates, and migration approvals through Pass 27 +preservation_reason: correction history and evidence lineage +--- + +# Locus64 Historical Approval Ledger + +This ledger preserves the former mixed-era approval table as historical evidence. Candidate, rejected, deferred, superseded, and migration-era rows here do not define the live product. Current executable gates are listed in [`L64_APPROVAL_GATES.md`](L64_APPROVAL_GATES.md). + +## Preserved prior approval ledger + +# Locus64 Approval Gate Ledger + +This file tracks candidate architectural law. A gate is only constitutional after it has executable evidence. + +Status values: + +- `Candidate`: accepted direction, not mechanically proven yet +- `Proven`: mechanically proven and eligible for constitution promotion +- `Deferred`: valid later concern outside the active dependency frontier +- `Rejected`: retained as an audited non-path + +Proof classes: + +- `CR`: compiler/category rejection +- `FP`: fixed-point reconstruction +- `DV`: DNA validation +- `MG`: strategic migration +- `PE`: deterministic parallel equivalence +- `PL`: projection-loss accounting +- `EA`: external-adapter witness +- `RI`: release/source integrity + +| Gate | Candidate ruling | Proof | Depends on | Status | Evidence | +|---|---|---:|---|---|---| +| L64-G001 | Duplex pair is the smallest locally authoritative unit | CR,DV | canonical encoding | Proven | `cargo test -p l64-core duplex_pair_validation_requires_semantic_and_complement_strands` | +| L64-G002 | Neither strand is independently promotable | CR | G001 | Proven | `cargo test -p l64-core duplex_pair_validation_requires_semantic_and_complement_strands` | +| L64-G003 | Pair-local validity does not imply domain closure | CR,DV | G001 | Proven | `cargo test -p l64-core domain_closure_blocks_promotion_on_open_frontier` | +| L64-G004 | Complement encodes admissibility burdens; receipts only discharge them | CR | G001 | Proven | `cargo test -p l64-core authority_complement_must_carry_burdens_not_receipt_only_claims` | +| L64-G005 | Duplex is native DNA structure, not a third public format | CR,RI | artifact roles | Candidate | pending | +| L64-G006 | Current molecular nouns are provisional role mappings | CR,MG | role model | Candidate | pending | +| L64-G007 | Codons compile to structural instructions, not semantic codebooks | CR,DV | symbolic law | Proven | `cargo test -p l64-core` (`codon_lexon_law_tables_are_unique_and_complete`, `codon_header_phase_controls_source_admission`) | +| L64-G008 | Lexons are scoped receipted bindings, not global meaning | CR,DV | scope law | Proven | `cargo test -p l64-core` (`lexon_aliases_resolve_to_scoped_canonical_targets`, `representative_lexons_bind_scoped_targets_with_receipts`) | +| L64-G009 | Macro-codons compile to reaction law, not workflow labels | CR,DV | G007 | Proven | `cargo test -p l64-core macro_codons_are_separate_from_lexons` | +| L64-G010 | Graphs are resolver, plan, diagnostic, or projection representations only | CR | graph roles | Candidate | pending | +| L64-G011 | Duplex pairing is logical and variable-length, not fixed-width syntax | DV,FP | canonical encoding | Candidate | pending | +| L64-G012 | Domain theorem/claim/proof classes remain above root substrate | CR,MG | substrate roles | Candidate | pending | +| L64-G013 | Generated-word bans are regression tripwires, not authority law | CR | typed admission | Proven | `cargo test -p l64-core generated_structural_word_ban_detects_old_label_payloads` | +| L64-G014 | Bincode is cache/transport only, not canonical DNA | DV,FP | canonical encoding | Candidate | pending | +| L64-G015 | Persistent authority identity derives from canonical structural bytes | FP,DV | distinction/equivalence | Proven | `cargo test -p l64-core` (`canonical_structure_erases_spacing_but_preserves_order`, `dna_packet_validation_checks_canonical_structure_digest`) | +| L64-G016 | Explicit canonical instructions replace token-hash authority | FP,DV | G015 | Proven | `cargo test -p l64-core canonical_structure_erases_spacing_but_preserves_order` | +| L64-G017 | Every authority section commitment binds its payload | DV | packet codec | Proven | `cargo test -p l64-core generic_dna_packet_validates_section_payload_commitment` | +| L64-G018 | Authority payload decode requires complete packet validation | DV | G017 | Proven | `cargo test -p l64-core` (`dna_packet_validation_checks_canonical_structure_digest`, `generic_dna_packet_validates_section_payload_commitment`) | +| L64-G019 | Legacy decoding requires explicit migration or forensic mode | DV,MG | decode roles | Proven | `cargo test -p l64-core legacy_packet_decode_requires_explicit_migration_or_forensic_mode` | +| L64-G020 | Authority decoding is bounded before allocation | DV | packet codec | Proven | `cargo test -p l64-core locus_packet_decode_rejects_oversized_fields_before_payload_copy` | +| L64-G021 | Authority tiers are typed law at DNA validation | CR,DV | role model | Proven | `cargo test -p l64-core dna_packet_validation_rejects_unknown_authority_tier` | +| L64-G022 | Capability summaries require witness coordinates | CR,DV | witness model | Candidate | pending | +| L64-G023 | Generated caches and ambiguous reports do not ship as source | RI | release gate | Proven | `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` | +| L64-G024 | Serial and parallel authoritative outputs are byte-equivalent | PE | closure scheduler | Proven | `cargo test -p l64-core deterministic_authority_merge_excludes_worker_count_and_input_order` | +| L64-G025 | Scheduler plans and telemetry are receipts, not authority | PE,CR | G024 | Proven | `cargo test -p l64-core deterministic_authority_merge_excludes_worker_count_and_input_order` | +| L64-G026 | Authored obligation status is intent, never evidence | CR,MG | evaluator model | Proven | `cargo test -p l64-cert authored_obligation_status_does_not_satisfy_evidence` | +| L64-G027 | Evaluator authority is explicit, named, and scoped | CR,MG | evaluator interface | Rejected | superseded by direct execution and deletion law L64-G068 | +| L64-G028 | Every certification verdict carries authority scope | CR,DV | scope law | Proven | `scripts/verify-native-carrier.sh` (`canonical_native_authority_certifies_from_direct_burdens`, native CLI membrane gate) | +| L64-G029 | Persisted report-derived lineage/readiness records are a valid authority path | CR,MG | artifact roles | Rejected | superseded by deletion law L64-G067 | +| L64-G030 | Policy precedence emits deterministic receipts | PE,DV | policy law | Rejected | superseded by deletion law L64-G068; no live policy registry remains | +| L64-G031 | Namespace import is a receipted bridge, not string rewriting | MG,DV | bridge law | Candidate | pending | +| L64-G032 | RNA and DNA remain the only public authority surfaces | CR,RI | artifact roles | Proven | `cargo test -p l64-cli --test cli` (`rna_dna_primary_authority_commands_work`, `standalone_projection_leaf_commands_are_removed`, `inspect_dna_output_is_not_rna_source`) | +| L64-G033 | Bundle-entry JSON is deletion-bound migration ingress only | MG,RI | native bundle path | Rejected | migration ingress and overlay world deleted by L64-G068 | +| L64-G034 | Remaining Qa/Qc types are migration ASTs, not core ontology | MG,CR | native bundle path | Candidate | pending | +| L64-G035 | Codebook/glyph/combo packs are projection or legacy machinery | MG,CR | projection boundary | Candidate | pending | +| L64-G036 | DNA reconstructs canonical RNA, not authored RNA | FP | canonical encoding | Proven | `cargo test -p l64-cli --test cli cki_registry_fixture_preserves_rna_dna_fixed_point` | +| L64-G037 | Grooves, folds, indexes, maps, and plans stay outside identity | FP,PE | G015 | Candidate | pending | +| L64-G038 | Release strings are renderers over witnessed products | MG,PL | expression layer | Proven | `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` | +| L64-G039 | Seed JSON is bootstrap source and compiles to DNA | MG,RI | native seed path | Candidate | pending | +| L64-G040 | Every sample artifact has an explicit source/migration/projection role | RI,CR | artifact roles | Proven | `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` | +| L64-G041 | External standards are dialects and witness providers | EA,CR | adapter law | Deferred | pending | +| L64-G042 | Every standards export carries a projection-loss receipt | PL,EA | G041 | Deferred | pending | +| L64-G043 | Proof assistants provide scoped external witnesses | EA,DV | evaluator interface | Deferred | pending | +| L64-G044 | SBOM/provenance standards are loss-accounted projections | PL,EA | G041 | Deferred | pending | +| L64-G045 | Constitutional rules require mechanical evidence | CR,FP,DV,MG,PE,PL,EA | this ledger | Proven | ledger promotion law | +| L64-G046 | New crates are justified only by enforceable authority membranes | CR | dependency audit | Candidate | pending | +| L64-G047 | Migration completes only after execution authority reroutes | MG | native execution path | Candidate | pending | +| L64-G048 | Reasoning cost and validation locality precede byte compactness | FP,DV | canonical path | Candidate | pending | +| L64-G049 | Authority tiers are earned through receipted transitions | CR,DV | G021 | Candidate | pending | +| L64-G050 | Product identity is witness-shaped; digest is its commitment | DV,MG | witness/product law | Candidate | pending | +| L64-G051 | Boollet is a transition-memory sidecar, not Locus64 authority | CR,MG | Bands B-E native authority path | Candidate | pending | +| L64-G052 | Boollet Rust embedding requires fixture parity with the Python reference | FP,MG | Boollet Rust port | Candidate | pending | +| L64-G053 | Boollet suggestions re-enter Locus64 only as proposals or witness coordinates | CR,MG | G051 | Candidate | pending | +| L64-G054 | Boollet replay identity may guide remediation ordering but cannot affect canonical identity | FP,CR | G015,G051 | Candidate | pending | +| L64-G055 | Locus64 admission/remediation sidecar fixtures prove usefulness without authority transfer | MG,DV | G051,G052,native Locus64 transition fixture | Candidate | pending | +| L64-G056 | No naked equality: structural equivalence requires explicit law specs and transition context | CR,FP | G015,distinction law | Proven | `cargo test -p l64-core` (`equivalence_law_makes_ordering_explicit_before_cnorm`, `distinction_law_classifies_collapse_before_equivalence`) | +| L64-G057 | K2 bridge/path comparability is a transport obligation over DNA authority, not root identity | CR,MG | G056,G031 | Candidate | pending | +| L64-G058 | K2 proof-shape success is a witness receipt and cannot override DNA admission or fixed-point failure | CR,DV | G018,G036,G056 | Candidate | pending | +| L64-G059 | Route selection is lexicographic by lawfulness, obligations, equivalence transport, loss, rollback, proof shape, complexity, then reuse payoff | MG,PE | domain closure | Candidate | pending | +| L64-G060 | Boollet replay identity is sidecar reproducibility evidence and cannot substitute for Locus64 canonical identity | CR,FP | G015,G051,G052 | Candidate | pending | +| L64-G061 | Native bundle transport frames canonical DNA members without creating composite authority | CR,DV,RI | G018,G032 | Proven | `scripts/verify-native-carrier.sh` (`bundle_is_exact_ordered_dna_transport`, `execution_verifies_each_projection_without_composite_authority`, native membrane gate) | +| L64-G062 | Native certification derives only from exact DNA and verified per-context burdens; bundles have no composite certificate | CR,DV,RI | G028,G061 | Proven | `scripts/verify-native-carrier.sh` (`canonical_native_authority_certifies_from_direct_burdens`, `invalid_child_context_invalidates_the_authority_certification`, `bundle_members_are_certified_independently`) | +| L64-G063 | Native observation is reconstructible non-authoritative projection over exact DNA; bundles have no composite observation | CR,DV,RI | G028,G061,G062 | Proven | `scripts/verify-native-carrier.sh` (`canonical_authority_observation_binds_verified_native_surfaces`, `invalid_child_context_remains_visible_in_report_and_certification`, `bundle_members_are_observed_independently`, native membrane gate) | + +| L64-G064 | Native change analysis compares exact current authorities without creating diff authority or composite bundle verdict | CR,DV,RI | G061,G062,G063 | Proven | `scripts/verify-native-carrier.sh` (`identical_dna_is_exactly_unchanged`, `structural_and_verdict_movement_is_directly_visible`, `bundle_members_remain_independent_change_contacts`, native membrane gate) | + +| L64-G065 | Campaign/report cache storage may be deleted once native certification, observation, and change carry every productive contact | MG,RI | G062,G063,G064 | Proven | `scripts/verify-legacy-cache-deletion.sh` plus packaged historical export | +| L64-G066 | Prediction/recompute/execution-plan records and bundle-lock/execution-manifest storage may be deleted once direct native change and current carriers replace their productive contacts | MG,RI | G061,G062,G063,G064,G065 | Proven | `scripts/verify-legacy-plan-storage-deletion.sh` plus packaged historical export | +| L64-G067 | Report-derived lineage, readiness, promotion-queue, and handoff stores may be deleted once native certification, observation, and change carry their productive facts | MG,RI | G062,G063,G064,G065,G066 | Proven | `scripts/verify-legacy-lineage-readiness-deletion.sh` plus packaged historical export | +| L64-G068 | Registry-overlay bundle execution and stored policy resolution may be deleted once current transport and direct execution carry every productive contact | MG,RI | G061,G062,G063,G064,G065,G066,G067 | Proven | `scripts/verify-legacy-registry-overlay-policy-deletion.sh` plus packaged historical export | + +| L64-G073 | Large-authority optimization is admitted only from measured structural hot paths and may not weaken exact authority or retained-projection verification | FP,DV,PE | G069,G070,G071,G072 | Proven | `scripts/verify-native-scale.sh`, profile corpus, full offline workspace tests and Clippy | + +## Promotion Law + +1. Add or identify executable evidence. +2. Record the exact test, fixture, or migration artifact in `Evidence`. +3. Verify all listed dependencies are `Proven`. +4. Change the row to `Proven` in the same change that lands the proof. +5. Promote the ruling into the constitution only after workspace conformance passes. + +No bulk status promotion is allowed. Evidence is gate-specific even when one test exercises multiple gates. + +## G069 — Legacy authority island deletion + +Approved. The complete historical theorem/campaign/research/registry/tower execution island was externally exported and deleted. The live workspace has eleven dependency-free packages and passes full offline tests and Clippy. Evidence: `LOCUS64_LEGACY_AUTHORITY_ISLAND_DELETION_CHANGE_CHAIN.athens`. + +## G070 — Direct native execution carrier + +Approved. `l64-execution` provides direct, non-persistent RNA/DNA structural evaluation; bundle execution reuses the same member carrier. Full offline workspace tests, Clippy, and the end-to-end native demo pass. Evidence: `LOCUS64_NATIVE_EXECUTION_CHANGE_CHAIN.athens`. + +## G071 — Direct Native CLI Hardening + +Approved. The current CLI has no boolean compatibility fallback, rejects wrong carrier formats at the requested contact, exposes command-specific help and version output, emits stable human-readable diagnostics, rejects dead artifact-class routing, and creates authority/bundle files atomically without overwriting existing paths. Evidence: `LOCUS64_NATIVE_CLI_HARDENING_CHANGE_CHAIN.athens` and `scripts/verify-cli-hardening.sh`. + + +## G072 — Verdict-Aware Process and Bounded Transport + +Approved. Certification-bearing commands emit complete output and use stable member-local verdict process codes; RNA parser failures carry exact token spans; bundle creation and bundle-facing CLI operations process members sequentially while preserving exact ordered `L64B` transport. Evidence: `LOCUS64_NATIVE_PROCESS_CONTRACT_CHANGE_CHAIN.athens` and `scripts/verify-process-contract.sh`. + +## G073 — Measured Native Scale Law + +Approved. Profiling identified per-mutation whole-state recomputation, repeated closure memo allocation, whole-route scans, and whole-graph equality scans as structural hot paths. Canonical source compilation now bulk-constructs and derives its final state symbol once; routes are indexed per node; closure analysis is shared per context; equality traversal is edge-local; and freshly derived in-process projections are not immediately rederived. Exact RNA/DNA fixed points, tracked mutation journals, stale/forged projection rejection, packet bytes, bundle framing, and member-local authority remain unchanged. Evidence: `LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens`, `scripts/verify-native-scale.sh`, the Pass 27 benchmark corpus, and full offline tests/Clippy. diff --git a/LINEAR_EXECUTION_RAIL.md b/LINEAR_EXECUTION_RAIL.md index ff93bcb..adaa057 100644 --- a/LINEAR_EXECUTION_RAIL.md +++ b/LINEAR_EXECUTION_RAIL.md @@ -1,4 +1,13 @@ -# Locus64 Linear Execution Rail +--- +document_status: historical +superseded_by: LOCUS64_EXECUTION_COHERENCE_RAIL.athens +current_handoff: HANDOFF_STATUS.md +scope: migration and implementation trajectory through Pass 27 +--- + +> Historical trajectory only. This rail preserves the correction and migration path, including assumptions that were later deleted. Resume current work from `HANDOFF_STATUS.md`, `LOCUS64_NATIVE_CONSTITUTION.md`, and the closed current rail. + +# Historical Linear Execution Rail — Superseded This is the authoritative linear execution rail for Locus64. @@ -129,9 +138,12 @@ Use the following decision order: Current active selector output: ```text -Band F strategic migration membrane --> route remaining transitional bundle/product/campaign paths through native authority products --> remove or quarantine residual transitional fields once native products carry equivalent evidence +Post-quarantine native product hardening +-> exact RNA/DNA authority, execution, release, ordered transport, certification, observation, and change are live +-> legacy authority island and compatibility runtime are deleted +-> direct CLI boundary, stable verdict outcomes, exact RNA spans, and sequential L64B processing are complete +-> large native authorities and transport members are profiled; measured construction, route, closure, equality, and fresh-derivation hot paths are optimized +-> next performance work requires a new reproducible workload and measured causal bottleneck ``` Rationale: @@ -139,7 +151,10 @@ Rationale: - Digest-role separation, DNA payload commitments, and authority decode modes have landed as the current packet membrane. - Production authority paths now use current-authority decoding; migration/forensic decoding is explicit rather than ambient. - Node 07A/08, canonical instruction, duplex local admission, domain closure, deterministic merge, and first bundle migration slices have landed enough lower-chain law for the first real structure family: distinction classes, transition law, equivalence coupling, versioned canonical instruction bytes, local semantic/complement pair validation, promotion-blocking domain closure, worker-count-independent authority merge, and bundle parity evidence over native authority products now exist. -- The next burden reducer is routing remaining transitional bundle/product/campaign paths through native authority products because bundle parity now carries duplex, closure, and deterministic merge evidence. +- Native release export and ordered `L64B` transport now carry current output and bundle movement without manifests, overlays, or composite authority. +- Exact-DNA, all-context native certification carries lawful structural verdicts; native observation binds those verdicts to verified replay and closure/opcode projections without persistence. +- Direct DNA/bundle change analysis replaces report/lock/manifest comparison, drift explanation, impact prediction, and recompute planning. +- Pass 19 removed cache/admin storage. Pass 20 removed prediction/plan/lock/manifest storage. Pass 21 removed report-derived lineage/readiness/queue/handoff schemas and stores. Registry-overlay, policy, and remaining research-record stores remain explicit compatibility and deletion-bound. - Any migration slice must preserve capability but reject category errors exposed by the new role, distinction, duplex, closure, deterministic merge, and bundle parity law. If a future pass finds a higher-scoring slice, it must update this selector before implementing it. @@ -187,15 +202,15 @@ Do not cross these boundaries in one unclassified burst: Current slice classification: ```text -Node: Band F / Node 11D surface-schema replacement -Slice: deprecated surface-schema lookup/materialization/admission retirement -Role: authority-path -Authority impact: removes deprecated surface-schema lookup methods from the active registry trait and prevents surface-schema records from entering active bundle registries or generic bundle-entry JSON admission -Promotion status: load-bearing runtime behavior, not constitutional promotion -Expected files: l64-core/src/lib.rs, l64-registry/src/lib.rs, l64-bundle/src/lib.rs, l64-testkit/src/lib.rs, l64-policy/src/lib.rs, l64-selector/src/lib.rs, LINEAR_EXECUTION_RAIL.md -Required verification: cargo test -p l64-bundle; cargo check --workspace -Stop condition: deprecated surface-schema records remain deserializable storage residue but cannot be looked up, materialized into active local registries, or admitted through generic/bundle-entry text -Rollback trigger: active native registry lookup or bundle import behavior loses valid theorem/campaign/certificate/evidence functionality +Node: post-quarantine native hardening / Pass 26 +Slice: verdict-aware process outcomes, exact RNA spans, and sequential bundle I/O +Role: burden-reduction +Authority impact: none; all outcomes and diagnostics are projections over exact native authority +Promotion status: complete and mechanically proven +Expected files: l64-native RNA parser, l64-transport streaming carrier, l64-cli membrane, tests, gates, docs, CI +Required verification: exact span tests; process-code gate; streaming byte-equivalence and bounded-read tests; full offline tests and Clippy +Stop condition: verdict commands return stable status; malformed RNA points to one exact token; bundle commands retain one member/graph at a time +Rollback trigger: output is suppressed on non-certified verdicts, status changes authority, source spans become heuristic, or L64B bytes/order change ``` ## Persistent Execution Mandate @@ -3402,6 +3417,8 @@ Downstream payoff: ### Node 11F - Legacy Quarantine +Pass 17 status: native `L64B` transport, exact-DNA certification, and certification/replay/report observation are implemented; legacy campaign/report contacts are explicit compatibility ingress. Research/admin JSON promotion and residual report/cache deletion remain open. + Purpose: - remove or quarantine transitional release/bundle paths after replacement authority is proven @@ -4451,7 +4468,7 @@ The rail is implemented when: - Q-surface crates are removed and no longer shape the architecture - public command/crate naming does not mislead users, implementation, authority boundaries, or deletion sequencing - compatibility imports are removed unless backed by a concrete active requirement and deletion condition -- persisted cross-binary cache/report/lock keys use the shared cache-hash policy rather than ad hoc local hashers +- deleted cache/report/lock/overlay/policy storage remains absent and cannot return through a replacement keying layer - public documentation does not recommend QC0, QA0, QM0, or QK0 as public languages or active authority routes - wrapper commands do not route deleted or retired commands as live behavior - conformance, fuzz, torture, replay, migration, and cross-platform determinism tests pass @@ -4461,7 +4478,7 @@ The rail is implemented when: - every digest/cache key resolves to a witness form in the product index - no release artifact can be ingested by `compile-rna` unless it has an explicit source/reconstruction role over RNA or canonical RNA - inspection reports, generated views, receipts, `.pep`, `.prot`, `.ptome`, `.cell` product text, claim pages, closure maps, stress maps, replay records, and lineages are rejected as source -- release gates include dependency closure, parent-before-child constructive order, explicit open obligations, validation receipts, replay records, status propagation, and projection/authority separation +- release gates preserve exact authority, explicit open obligations, constructive order, and projection/authority separation without recreating deleted report, replay, lineage, overlay, or policy stores ## 34. Final System Definition @@ -4475,3 +4492,43 @@ structure is authority canonical form is identity reuse is proven rather than assumed ``` + + +## Pass 22 Registry Overlay and Policy Deletion + +The registry-overlay and stored-policy compatibility layer is closed: + +1. `l64-bundle` and `l64-policy` were exported and deleted. +2. `BundleWorld`, overlay merge, namespace import, conflict policy, bundle-world caching, and overlay-only execution are permanently rejected. +3. Registry admission no longer accepts policy objects, bindings, or resolutions. +4. Certification uses one direct in-process execution profile and emits no policy ID, hash, precedence trace, or persistent policy record. +5. The workspace contains 22 packages. +6. The next deletion slice is surviving research registry/producer-host/tower persistence, followed by seed theorem/campaign registry retirement. + +## Pass 23 closure + +Slice: surviving research/producer-host/tower persistence and seed theorem/campaign registry retirement. + +Result: the complete twelve-crate legacy authority island and included dispatcher were externally archived and deleted. The workspace collapsed from 22 packages to 10, external dependencies from the live graph fell to zero, and full offline workspace tests and Clippy passed. `legacy-authority-quarantine` is complete; no further compatibility runtime remains. + +## Pass 25 — Native CLI hardening + +- Removed the obsolete boolean fallback membrane after final legacy deletion. +- Wrong L64R1/L64D/L64B contacts now fail directly with path-specific diagnostics. +- Added stable `Display` diagnostics across the public native error chain. +- Added `--version`, grouped help, and command-specific help. +- `compile-rna` and `compile-bundle` now use atomic create-new promotion and never overwrite existing outputs. +- Removed silent `--artifact-class gene` acceptance. +- Added `scripts/verify-cli-hardening.sh` and CI coverage. + +## 34. Measured Native Scale Closure + +1. The pre-change source compiler recomputed the complete state symbol after every instruction: 500 linear atoms required 3.17 seconds, 1,000 required 12.78 seconds, and 100,000 did not finish within the bounded profile. +2. Canonical RNA compilation now uses bulk graph construction, records no intermediate journal, and computes the exact final state symbol once. Direct graph mutation remains tracked and journaled. +3. Per-node route lookup is a derived exact index rather than a route-map scan. The index is excluded from authority and rebuilt from canonical state. +4. Projection derivation computes visible closure states once per context and shares the result across atlas, certification, report, replay, and research views. +5. Equality canonicalization traverses actual equality edges through the reverse index rather than scanning the full graph for every operation. +6. Fresh in-process projections are graph-bound by construction and are not immediately rederived. Retained and external projections retain explicit stale/forgery verification. +7. `scripts/verify-native-scale.sh` rejects reintroduction of the measured structural hot paths and executes bounded large linear and operation-heavy workloads. +8. No authority bytes, packet framing, bundle ordering, verdict law, or public projection content changed. +9. Further optimization requires a new measured workload and causal profile; speculative performance abstraction is prohibited. diff --git a/LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md b/LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md index 30c8c66..cf5c3d9 100644 --- a/LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md +++ b/LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md @@ -1,429 +1,15 @@ -# Locus64 Architectural Constitution v1 +--- +document_status: historical +superseded_by: LOCUS64_NATIVE_CONSTITUTION.md +scope: compatibility pointer +--- -This file is an index of mechanically demonstrated architectural law. It is not a wishlist, roadmap, branding document, or substitute for executable evidence. +# Superseded Locus64 Architectural Constitution v1 -Rules enter this constitution only after their corresponding approval gate is marked `Proven` in `L64_APPROVAL_GATES.md`. +The former mixed-era constitution has been separated so historical laws cannot be mistaken for current architecture. -## Authority Rule +- Current native constitution: [`LOCUS64_NATIVE_CONSTITUTION.md`](LOCUS64_NATIVE_CONSTITUTION.md) +- Preserved historical law ledger: [`LOCUS64_HISTORICAL_LAW_LEDGER.md`](LOCUS64_HISTORICAL_LAW_LEDGER.md) +- Current executable gates: [`L64_APPROVAL_GATES.md`](L64_APPROVAL_GATES.md) -Runtime authority is earned by closed transitions, validated packet structure, stable commitments, deterministic merge behavior, and receipted lineage. Names, projections, reports, caches, legacy formats, display IDs, scheduler choices, and migration objects do not become authority by existing in the repository. - -## Proven Gates - -### L64-G001 - Duplex Pair Local Authority Unit - -Duplex pair is the smallest locally authoritative unit. - -Evidence: - -- `cargo test -p l64-core duplex_pair_validation_requires_semantic_and_complement_strands` - -Constitutional effect: - -- A semantic strand without its authority complement is not locally valid. -- Local authority begins at the paired structure, not at either strand alone. - -### L64-G002 - No Strand-Only Promotion - -Neither strand is independently promotable. - -Evidence: - -- `cargo test -p l64-core duplex_pair_validation_requires_semantic_and_complement_strands` - -Constitutional effect: - -- Semantic-only or complement-only material must fail local admission. -- Promotion logic must consume paired authority structure rather than single-lane meaning. - -### L64-G003 - Local Validity Is Not Domain Closure - -Pair-local validity does not imply domain closure. - -Evidence: - -- `cargo test -p l64-core domain_closure_blocks_promotion_on_open_frontier` - -Constitutional effect: - -- A locally valid pair may still be non-promotable when open obligations or external burdens remain. -- Domain closure is a separate gate above pair admission. - -### L64-G004 - Complement Burden Law - -Complement encodes admissibility burdens; receipts only discharge them. - -Evidence: - -- `cargo test -p l64-core authority_complement_must_carry_burdens_not_receipt_only_claims` - -Constitutional effect: - -- Authority complements must carry invariant and witness-form requirements. -- Receipt-only complement claims are malformed and cannot become local authority. - -### L64-G007 - Codon Structural Law - -Codons compile to structural instructions, not semantic codebooks. - -Evidence: - -- `cargo test -p l64-core` -- Proving tests: `codon_lexon_law_tables_are_unique_and_complete`, `codon_header_phase_controls_source_admission` - -Constitutional effect: - -- Codon tables define structural phase/admission law. -- Codon names are not semantic authority and must not become lookup-mediated meaning. - -### L64-G008 - Lexon Scoped Binding Law - -Lexons are scoped receipted bindings, not global meaning. - -Evidence: - -- `cargo test -p l64-core` -- Proving tests: `lexon_aliases_resolve_to_scoped_canonical_targets`, `representative_lexons_bind_scoped_targets_with_receipts` - -Constitutional effect: - -- Lexon aliases resolve into scoped canonical targets. -- Bindings require receipts and cannot become global semantic aliases. - -### L64-G009 - Macro-Codon Reaction Law - -Macro-codons compile to reaction law, not workflow labels. - -Evidence: - -- `cargo test -p l64-core macro_codons_are_separate_from_lexons` - -Constitutional effect: - -- Macro-codons are separate reaction-law structures. -- Workflow labels do not define executable law. - -### L64-G013 - Generated-Word Regression Boundary - -Generated-word bans are regression tripwires, not authority law. - -Evidence: - -- `cargo test -p l64-core generated_structural_word_ban_detects_old_label_payloads` - -Constitutional effect: - -- Generated-word bans may prevent old label payloads from leaking into structural regions. -- The ban list is diagnostic enforcement, not a source of meaning. - -### L64-G015 - Canonical Structural Identity - -Persistent authority identity derives from canonical structural bytes. - -Evidence: - -- `cargo test -p l64-core` -- Proving tests: `canonical_structure_erases_spacing_but_preserves_order`, `dna_packet_validation_checks_canonical_structure_digest` - -Constitutional effect: - -- Formatting variation cannot define authority identity. -- Authority identity must bind canonical structure, not authored source text. - -### L64-G016 - Canonical Instruction Stream - -Explicit canonical instructions replace token-hash authority. - -Evidence: - -- `cargo test -p l64-core canonical_structure_erases_spacing_but_preserves_order` - -Constitutional effect: - -- Canonical structure is encoded through versioned instructions. -- Token hash shortcuts cannot be promoted as authority identity. - -### L64-G017 - Section Payload Commitment - -Every authority section commitment binds its payload. - -Evidence: - -- `cargo test -p l64-core generic_dna_packet_validates_section_payload_commitment` - -Constitutional effect: - -- DNA validation must compare section payloads against payload commitments before authority decode can be trusted. -- Payload commitments are authority-adjacent validation material, not display identifiers. - -### L64-G018 - Complete Authority Decode Validation - -Authority payload decode requires complete packet validation. - -Evidence: - -- `cargo test -p l64-core` -- Proving tests: `dna_packet_validation_checks_canonical_structure_digest`, `generic_dna_packet_validates_section_payload_commitment` - -Constitutional effect: - -- Authority decode must validate payload commitment and canonical structure digest requirements. -- Partial packet success cannot promote a payload into authority. - -### L64-G019 - Explicit Legacy Decode Mode - -Legacy decoding requires explicit migration or forensic mode. - -Evidence: - -- `cargo test -p l64-core legacy_packet_decode_requires_explicit_migration_or_forensic_mode` - -Constitutional effect: - -- Current authority decode must not silently fall back to legacy packet decoding. -- Migration and forensic decode paths are intentional subordinate modes, not ambient compatibility. - -### L64-G020 - Bounded Authority Decode - -Authority decoding is bounded before allocation. - -Evidence: - -- `cargo test -p l64-core locus_packet_decode_rejects_oversized_fields_before_payload_copy` - -Constitutional effect: - -- Sized packet fields must pass a hard length cap before payload copy. -- Authority decoding cannot allocate unbounded field payloads from attacker-controlled lengths. - -### L64-G021 - Authority Tier Validation - -Authority tiers are typed law at DNA validation. - -Evidence: - -- `cargo test -p l64-core dna_packet_validation_rejects_unknown_authority_tier` - -Constitutional effect: - -- DNA validation must reject unknown authority tier values. -- The packet byte remains layout-compatible, but valid tier meaning is closed by the typed tier table. - -### L64-G023 - Source Release Hygiene - -Generated caches and ambiguous reports do not ship as source. - -Evidence: - -- `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` - -Constitutional effect: - -- Release products must distinguish source, projection, record, receipt, and view roles. -- Generated views and reports may be shipped as products, but not as source authority. - -### L64-G024 - Deterministic Parallel Equivalence - -Serial and parallel authoritative outputs are byte-equivalent. - -Evidence: - -- `cargo test -p l64-core deterministic_authority_merge_excludes_worker_count_and_input_order` - -Constitutional effect: - -- Worker count and input completion order must not affect authoritative merge output. -- Canonical ordering must be derived from structural coordinates and payload commitments. - -### L64-G025 - Scheduler Non-Authority - -Scheduler plans and telemetry are receipts, not authority. - -Evidence: - -- `cargo test -p l64-core deterministic_authority_merge_excludes_worker_count_and_input_order` - -Constitutional effect: - -- Worker count, timing, lane assignment, and scheduling plan data are excluded from authority identity. -- Scheduler details may be recorded as diagnostics or receipts only. - -### L64-G026 - Authored Obligation Status Is Intent - -Authored obligation status is intent, never evidence. - -Evidence: - -- `cargo test -p l64-cert authored_obligation_status_does_not_satisfy_evidence` - -Constitutional effect: - -- An authored `Certified` obligation does not satisfy evidence by itself. -- Unsupported obligations must remain unsupported or blocked unless executable evaluation or native stored evidence exists. - -### L64-G027 - Scoped Evaluator Authority - -Evaluator authority is explicit, named, and scoped. - -Evidence: - -- `cargo test -p l64-policy evaluator_authority_is_named_and_scoped` - -Constitutional effect: - -- Evaluator behavior must be selected through a named `MechanizationPolicyObject`. -- The resolved evaluator authority must carry a concrete policy scope; implicit ambient evaluator behavior cannot claim scoped authority. - -### L64-G029 - Report-Derived Research Projection - -Report-derived research records are projections until replayed. - -Evidence: - -- `cargo test -p l64-research report_derivation_emits_lineage_record` - -Constitutional effect: - -- Claim packets derived from certification reports must be classified as projection authority, even when the report verdict is `Integrated` or `Certified`. -- Report verdicts may be retained as projection assumptions, but they cannot upgrade report-derived research records into evidence or benchmark authority without a replay-specific promotion path. - -### L64-G030 - Deterministic Policy Precedence Receipts - -Policy precedence emits deterministic receipts. - -Evidence: - -- `cargo test -p l64-policy policy_precedence_receipt_is_stable_across_registry_order` - -Constitutional effect: - -- Equal-precedence policy candidates must be ordered by stable policy identity rather than registry insertion order. -- Policy resolution IDs, applied policy ID order, and trace steps must remain stable for equivalent policy sets. - -### L64-G032 - RNA/DNA Public Authority Surfaces - -RNA and DNA remain the only public authority surfaces. - -Evidence: - -- `cargo test -p l64-cli --test cli` -- Proving tests: `rna_dna_primary_authority_commands_work`, `standalone_projection_leaf_commands_are_removed`, `inspect_dna_output_is_not_rna_source` - -Constitutional effect: - -- Public authority workflows must pass through source/canonical RNA or DNA. -- Projection, inspection, and removed legacy commands cannot define public authority surfaces. - -### L64-G033 - Bundle-Entry Migration Ingress - -Bundle-entry JSON is deletion-bound migration ingress only. - -Evidence: - -- `cargo test -p l64-bundle` -- Proving tests: `bundle_document_import_can_cross_explicit_migration_ingress`, `bundle_entry_text_rejects_deprecated_surface_schema_entries` - -Constitutional effect: - -- Bundle-entry text may cross an explicit migration membrane. -- Bundle-entry JSON cannot become a public authority syntax or native ontology source. - -### L64-G036 - Canonical RNA Reconstruction - -DNA reconstructs canonical RNA, not authored RNA. - -Evidence: - -- `cargo test -p l64-cli --test cli cki_registry_fixture_preserves_rna_dna_fixed_point` - -Constitutional effect: - -- DNA-to-RNA reconstruction targets canonical RNA. -- Original authored RNA remains lineage/source material, not a required inverse of DNA. - -### L64-G038 - Release Renderer Law - -Release strings are renderers over witnessed products. - -Evidence: - -- `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` - -Constitutional effect: - -- Release strings, claim pages, maps, views, and rendered records must be derived from witnessed authority products. -- Rendered release artifacts do not become source authority. - -### L64-G040 - Artifact Role Explicitness - -Every sample artifact has an explicit source, migration, projection, record, receipt, or view role. - -Evidence: - -- `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` - -Constitutional effect: - -- Release and sample artifacts must advertise their role through type, filename, content marker, or command boundary. -- Ambiguous artifacts must fail source admission or be classified before use. - -### L64-G056 - Explicit Structural Equivalence Law - -Structural equivalence requires explicit law specs and transition context. - -Evidence: - -- `cargo test -p l64-core` -- Proving tests: `equivalence_law_makes_ordering_explicit_before_cnorm`, `distinction_law_classifies_collapse_before_equivalence` - -Constitutional effect: - -- CNORM cannot claim sameness from naked equality strings, graph shape, or source text alone. -- Equivalence must reference transition law and distinction law before collapse is allowed. - -### L64-G045 - Mechanical Evidence Requirement - -Constitutional rules require mechanical evidence. - -Evidence: - -- `L64_APPROVAL_GATES.md` promotion law - -Constitutional effect: - -- Candidate rulings remain outside this constitution until their executable proof is landed and recorded. -- Documentation alone cannot promote runtime law. - -## Explicit Non-Promotions - -The following are not constitutional authority in v1: - -- `QaDocument` as ontology source. -- Bundle-entry JSON as public authority syntax. -- Bincode as canonical DNA. -- Projection/report/view artifacts as source. -- Legacy Q-surface syntax or Q-surface policy objects. -- Graph, arena, map, index, fold, or scheduler representation as substrate authority. -- Current molecular names unless promoted by a future proven gate. - -## Current Blockers - -The following gates remain candidate or deferred and must not be treated as proven law: - -- Duplex-pair promotion law beyond local first-slice tests. -- Full canonical structural identity replacing every token-hash fallback. -- Bundle semantic reroute as native authority rather than parity scaffold. -- Seed JSON replacement by native DNA bootstrap. -- Boollet integration as a sidecar transition-memory module. -- External standards and proof assistants as scoped witness providers. - -## Maintenance Rule - -Every future constitution edit must include: - -1. The promoted gate ID. -2. The exact evidence command, fixture, or proof artifact. -3. The authority effect. -4. The non-authority boundary it preserves. - -If any of those are missing, the ruling belongs in `L64_APPROVAL_GATES.md`, not here. +This compatibility filename carries no independent architectural authority. diff --git a/LOCUS64_CONSTRAINT_CORE_CHANGE_CHAIN.athens b/LOCUS64_CONSTRAINT_CORE_CHANGE_CHAIN.athens new file mode 100644 index 0000000..44d1a06 --- /dev/null +++ b/LOCUS64_CONSTRAINT_CORE_CHANGE_CHAIN.athens @@ -0,0 +1,39 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=projection_authority;value=non_authoritative +field=key=rail_version;value=6 +field=key=schema_version;value=1 +gate=id=constraint-core-closure-green +gate=id=context-consistency-green +gate=id=dimension-algebra-green +gate=id=guarded-obligation-green +gate=id=native-surface-green +stage=id=dimension-algebra +stage_field=stage=dimension-algebra;key=required_gates;value=dimension-algebra-green +stage_field=stage=dimension-algebra;key=status;value=complete +stage=id=context-consistency +stage_field=stage=context-consistency;key=depends_on;value=dimension-algebra +stage_field=stage=context-consistency;key=required_gates;value=context-consistency-green +stage_field=stage=context-consistency;key=status;value=complete +stage=id=guarded-obligation +stage_field=stage=guarded-obligation;key=depends_on;value=context-consistency +stage_field=stage=guarded-obligation;key=required_gates;value=guarded-obligation-green +stage_field=stage=guarded-obligation;key=status;value=complete +stage=id=native-surface +stage_field=stage=native-surface;key=depends_on;value=guarded-obligation +stage_field=stage=native-surface;key=required_gates;value=native-surface-green +stage_field=stage=native-surface;key=status;value=complete +stage=id=constraint-core-closure +stage_field=stage=constraint-core-closure;key=depends_on;value=native-surface +stage_field=stage=constraint-core-closure;key=required_gates;value=constraint-core-closure-green +stage_field=stage=constraint-core-closure;key=status;value=complete +history=from_status=current;gates=dimension-algebra-green;mode=linear_advance;stage_id=dimension-algebra;to_status=complete +history=evidence=local%3A22-tests%2Bclippy%3Bdimension-law%2Bdecoder-recheck;kind=dogfood_promotion_receipt;stage_id=dimension-algebra +history=from_status=current;gates=context-consistency-green;mode=linear_advance;stage_id=context-consistency;to_status=complete +history=evidence=local%3A24-tests%2Bclippy%3Bcontradiction-atomic%2Bdecode-recheck;kind=dogfood_promotion_receipt;stage_id=context-consistency +history=from_status=current;gates=guarded-obligation-green;mode=linear_advance;stage_id=guarded-obligation;to_status=complete +history=evidence=local%3A28-tests%2Bclippy%3Bsqrt-witness%7Cobligation%7Crejection%2Bforgery-refusal;kind=dogfood_promotion_receipt;stage_id=guarded-obligation +history=from_status=current;gates=native-surface-green;mode=linear_advance;stage_id=native-surface;to_status=complete +history=evidence=local%3A32-tests%2Bclippy%3Bconstraint-rna-dna-fixed-point%2Binvalid-refusal;kind=dogfood_promotion_receipt;stage_id=native-surface +history=from_status=current;gates=constraint-core-closure-green;mode=linear_advance;stage_id=constraint-core-closure;to_status=complete +history=evidence=github-cbcbfe5d9c4f34baf0ca54306c77a85ac970bd26-run-29990484222;kind=dogfood_promotion_receipt;stage_id=constraint-core-closure +END diff --git a/LOCUS64_DOCUMENTATION_COHERENCE_CHANGE_CHAIN.athens b/LOCUS64_DOCUMENTATION_COHERENCE_CHANGE_CHAIN.athens new file mode 100644 index 0000000..b3df43d --- /dev/null +++ b/LOCUS64_DOCUMENTATION_COHERENCE_CHANGE_CHAIN.athens @@ -0,0 +1,23 @@ +ATHENS_CHANGE_CHAIN v1 +field=key=pass;value=28 +field=key=name;value=documentation-coherence +field=key=authority_effect;value=none +field=key=wire_effect;value=none +field=key=runtime_effect;value=none +field=key=document_status;value=current +stage=id=current-source-map;status=complete;effect=current_docs_and_historical_surfaces_classified +stage=id=stale-claim-repair;status=complete;effect=live_native_readme_and_legacy_state_corrected +stage=id=constitution-separation;status=complete;effect=current_native_law_separated_from_historical_ledger +stage=id=gate-separation;status=complete;effect=current_executable_gates_separated_from_historical_approval_ledger +stage=id=historical-marking;status=complete;effect=linear_rail_and_compatibility_paths_marked_historical +stage=id=binary-surface-documentation;status=complete;effect=l64_cli_and_l64_wrapper_contacts_explicit +stage=id=script-repair;status=complete;effect=dead_low_memory_crate_contacts_removed +stage=id=documentation-gate;status=complete;effect=cargo_help_docs_and_script_contacts_verified_directly +gate=id=documentation-coherence-green;status=complete;evidence=scripts/verify-documentation-coherence.sh +gate=id=workspace-green;status=complete;evidence=locked_offline_test_clippy_fmt_shellcheck +completion=condition=no_live_legacy_claims;status=complete +completion=condition=no_deleted_crate_commands;status=complete +completion=condition=current_package_count_matches_cargo;status=complete +completion=condition=command_spec_matches_live_help;status=complete +completion=condition=historical_laws_recoverable_and_visibly_historical;status=complete +END diff --git a/LOCUS64_EXECUTION_COHERENCE_RAIL.athens b/LOCUS64_EXECUTION_COHERENCE_RAIL.athens new file mode 100644 index 0000000..fb174d3 --- /dev/null +++ b/LOCUS64_EXECUTION_COHERENCE_RAIL.athens @@ -0,0 +1,61 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=current_stage;value=complete +field=key=next_stage;value=none +field=key=projection_authority;value=non_authoritative +field=key=rail_version;value=11 +field=key=schema_version;value=1 +field=key=native_identity;value=exact_symbolic +field=key=native_compact_seal;value=non_authoritative +field=key=legacy_digest_boundary;value=removed_from_workspace +field=key=live_workspace_packages;value=11 +field=key=ambient_legacy_authority;value=deleted_tombstones_only +field=key=native_bundle_transport;value=ordered_l64d_no_composite_authority +field=key=native_execution;value=direct_nonpersistent_rna_dna_bundle_members +field=key=native_observation;value=verified_projection_no_persistence_no_composite_observation +field=key=native_change;value=exact_authority_projection_no_persistence +field=key=native_scale;value=measured-bulk-indexed-shared-analysis +field=key=legacy_research_admin_json;value=deleted +field=key=legacy_lineage_readiness_storage;value=deleted_after_external_export +gate=id=incremental-closure-green +gate=id=legacy-authority-quarantine-green +gate=id=native-constraint-core-green +gate=id=native-upper-projection-green +gate=id=native-execution-carrier-green +gate=id=native-observation-carrier-green +gate=id=native-change-carrier-green +gate=id=native-scale-green +gate=id=proof-producing-congruence-green +stage=id=native-constraint-core +stage_field=stage=native-constraint-core;key=required_gates;value=native-constraint-core-green +stage_field=stage=native-constraint-core;key=status;value=complete +stage=id=proof-producing-congruence +stage_field=stage=proof-producing-congruence;key=depends_on;value=native-constraint-core +stage_field=stage=proof-producing-congruence;key=required_gates;value=proof-producing-congruence-green +stage_field=stage=proof-producing-congruence;key=status;value=complete +stage=id=incremental-closure +stage_field=stage=incremental-closure;key=depends_on;value=proof-producing-congruence +stage_field=stage=incremental-closure;key=required_gates;value=incremental-closure-green +stage_field=stage=incremental-closure;key=status;value=complete +stage=id=native-upper-projection +stage_field=stage=native-upper-projection;key=depends_on;value=incremental-closure +stage_field=stage=native-upper-projection;key=required_gates;value=native-upper-projection-green +stage_field=stage=native-upper-projection;key=status;value=complete +stage=id=legacy-authority-quarantine +stage_field=stage=legacy-authority-quarantine;key=depends_on;value=native-upper-projection +stage_field=stage=legacy-authority-quarantine;key=required_gates;value=legacy-authority-quarantine-green +stage_field=stage=legacy-authority-quarantine;key=status;value=complete +history=from_status=current;gates=native-constraint-core-green;mode=linear_advance;stage_id=native-constraint-core;to_status=complete +history=evidence=github-cbcbfe5d9c4f34baf0ca54306c77a85ac970bd26-run-29990484222;kind=dogfood_promotion_receipt;stage_id=native-constraint-core +history=from_status=current;gates=proof-producing-congruence-green;mode=linear_advance;stage_id=proof-producing-congruence;to_status=complete +history=evidence=github-0a84bdd3dc232a0db1b79009c3bf99cfd4fb40cd-run-29997066639;kind=dogfood_promotion_receipt;stage_id=proof-producing-congruence +history=from_status=current;gates=incremental-closure-green;mode=linear_advance;stage_id=incremental-closure;to_status=complete +history=evidence=github-fd90966af2191e6d9ca5e14e17f0bcaca431c260-run-30009891592;kind=dogfood_promotion_receipt;stage_id=incremental-closure +history=from_status=current;gates=native-upper-projection-green;mode=linear_advance;stage_id=native-upper-projection;to_status=complete +history=evidence=github-0ad8acc52f35362262c383efd02cc455e6778489-run-30139859138;kind=dogfood_promotion_receipt;stage_id=native-upper-projection +history=evidence=local%3Acertification-replay-report-projection%2Bno-persistence%2Bno-composite-observation;kind=implementation_receipt;stage_id=legacy-authority-quarantine +history=evidence=local%3Aexact-authority-change-projection%2Bno-prediction-plan-cache%2Bexplicit-research-admin-json;kind=implementation_receipt;stage_id=legacy-authority-quarantine +history=evidence=local%3Alineage-readiness-queue-handoff-schema-and-store-deletion%2Bnative-carrier-green;kind=implementation_receipt;stage_id=legacy-authority-quarantine +history=evidence=local%3Alegacy-authority-island-deleted%2B10-package-dependency-free-offline-workspace-green;kind=dogfood_promotion_receipt;stage_id=legacy-authority-quarantine +history=evidence=local%3A11-package-offline-test-clippy%2Brna-dna-bundle-execution-demo;kind=dogfood_promotion_receipt;stage_id=legacy-authority-quarantine +history=evidence=local%3Aprofile-corpus%2Bbulk-rna%2Bindexed-routes%2Bshared-closure%2Bedge-local-equality%2Bscale-gate;kind=dogfood_promotion_receipt;stage_id=legacy-authority-quarantine +END diff --git a/LOCUS64_GOLDEN_PORTABILITY_CHANGE_CHAIN.athens b/LOCUS64_GOLDEN_PORTABILITY_CHANGE_CHAIN.athens new file mode 100644 index 0000000..62ed7f0 --- /dev/null +++ b/LOCUS64_GOLDEN_PORTABILITY_CHANGE_CHAIN.athens @@ -0,0 +1,26 @@ +ATHENS_CHANGE_CHAIN v1 +field=key=pass;value=29 +field=key=name;value=golden-workload-portability +field=key=authority_effect;value=none +field=key=wire_effect;value=none +field=key=runtime_effect;value=none +field=key=document_status;value=current +field=key=supported_hosts;value=linux_macos_windows +stage=id=workload-selection;status=complete;effect=five_minimal_authority_cases_cover_proof_equality_open_invalid_and_matrix_contacts +stage=id=exact-snapshots;status=complete;effect=canonical_rna_dna_execution_and_certification_bytes_bound +stage=id=product-journey;status=complete;effect=compare_transport_observation_certification_and_release_contacts_bound +stage=id=line-ending-path-portability;status=complete;effect=lf_crlf_unicode_and_space_paths_produce_identical_authority +stage=id=wrapper-host-selection;status=complete;effect=platform_specific_sibling_binary_candidates_tested +stage=id=host-matrix;status=receipt_enabled;effect=complete_rust_workspace_configured_for_linux_macos_windows_ci_with_source_bound_receipts +stage=id=direct-gate;status=complete;effect=golden_and_portability_contacts_verified_without_parallel_runtime +stage=id=target-directory-portability;status=complete;effect=forge_and_execution_share_CARGO_TARGET_DIR +gate=id=golden-portability-green;status=local_complete_remote_evidence_external;evidence=scripts/verify-golden-portability.sh-plus-source-bound-three-host-receipts +gate=id=workspace-green;status=complete;evidence=locked_offline_test_clippy_fmt_shellcheck_actionlint +completion=condition=canonical_bytes_are_host_invariant;status=complete +completion=condition=text_and_verdict_snapshots_are_exact;status=complete +completion=condition=lf_crlf_equivalence_is_executable;status=complete +completion=condition=unicode_and_space_paths_are_executable;status=complete +completion=condition=transport_and_release_journey_is_exact;status=complete +completion=condition=three_host_ci_matrix_exists;status=complete +completion=condition=macos_windows_execution_receipts;status=emitted_by_successful_exact_source_ci_run +END diff --git a/LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md b/LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md new file mode 100644 index 0000000..722ff36 --- /dev/null +++ b/LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md @@ -0,0 +1,62 @@ +--- +document_status: current +contract_scope: golden workload and host portability +supported_hosts: Linux, macOS, Windows +--- + +# Locus64 Golden Workload and Portability Contract + +This contract fixes the smallest representative workload set that can detect drift across authority, execution, verdict, transport, release, text, path, and host boundaries. It does not create a second specification or promote snapshots into authority. Canonical RNA and DNA remain the only source-authority surfaces; the snapshots are executable comparison evidence. + +## Golden authority workloads + +| Workload | Native contact exercised | Required verdict | Distinction protected | +|---|---|---:|---| +| `certified_triangle.rna` | typed function composition with native witness | `CERTIFIED` / `0` | proof-producing operation and exact fixed point | +| `equality_chain.rna` | reflexive, symmetric, and transitive equality evidence | `CERTIFIED` / `0` | equality replay and canonical ordering | +| `open_obligation.rna` | unresolved guarded square root | `OPEN` / `10` | open burden remains visible and non-fatal | +| `invalid_child_context.rna` | child context with refuted non-negative guard | `INVALID` / `12` | context-local invalidity propagates without rewriting the root | +| `matrix_multiply.rna` | valid matrix shape admission | `CERTIFIED` / `0` | typed shape law and witness production | + +For every workload, the repository retains exact snapshots of: + +- canonical normalized RNA; +- canonical `L64D` bytes rendered as lowercase hexadecimal; +- direct RNA execution text; +- direct DNA certification text. + +The product-journey workload additionally fixes: + +- exact DNA comparison output; +- ordered mixed-verdict bundle execution, certification, and observation; +- the four-file native release contents and exact release record. + +## Portability law + +1. The same canonical RNA yields the same canonical DNA bytes on every supported host. +2. LF and CRLF RNA normalize to the same LF canonical RNA and the same DNA bytes. +3. Stable text outputs use `\n` and must match the golden snapshots byte-for-byte. +4. Paths containing spaces and valid Unicode must work through direct `Path`/`OsString` contacts without text round-tripping. +5. Wire integers, lengths, ordering, and symbolic coordinates are explicitly encoded; host pointer width and host endianness cannot enter authority identity. +6. `l64` selects the platform-appropriate sibling `l64-cli` executable without changing the forwarded argument vector or exit code. +7. The complete dependency-free Rust workspace must compile and execute its tests on Linux, macOS, and Windows in CI. +8. Each successful host must emit one `L64PORT1` receipt bound to the exact tested commit. Portability closes only when the combined verifier accepts the exact three-host set. +9. Portability receipts remain external execution evidence and cannot become runtime or authority state. +10. Unix shell gates remain release-orchestration contacts, not runtime requirements. Product behavior is proven by host-neutral Rust tests beneath them. +11. Build-and-execute gates on both Unix and Windows must honor `CARGO_TARGET_DIR`; forge and execution cannot silently resolve different binary locations. + +## What the snapshots may and may not do + +A snapshot may reject an unintended behavioral change. It cannot prove that the behavior is mathematically sufficient, cryptographically secure, or semantically complete. A deliberate snapshot change requires the same named operational contact, law change, current documentation update, and full workspace proof as any other promoted behavior. + +## Direct evidence + +- `samples/golden/*.rna` +- `samples/golden/expected/*` +- `l64-cli/src/golden_tests.rs` +- `l64/src/main.rs` portability test +- `scripts/verify-golden-portability.sh` +- `LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md` +- `scripts/write-portability-receipt.sh` +- `scripts/verify-portability-receipts.sh` +- `.github/workflows/native-core.yml` host matrix and retained receipt artifacts diff --git a/LOCUS64_HISTORICAL_LAW_LEDGER.md b/LOCUS64_HISTORICAL_LAW_LEDGER.md new file mode 100644 index 0000000..61539e0 --- /dev/null +++ b/LOCUS64_HISTORICAL_LAW_LEDGER.md @@ -0,0 +1,608 @@ +--- +document_status: historical +superseded_by: LOCUS64_NATIVE_CONSTITUTION.md +scope: pre-native and migration-era architectural laws through Pass 27 +preservation_reason: correction history and forensic reconstruction +--- + +# Locus64 Historical Architectural Law Ledger + +This ledger preserves the former mixed-era constitution exactly as trajectory evidence. It is not a current architecture source. Current authority law lives in [`LOCUS64_NATIVE_CONSTITUTION.md`](LOCUS64_NATIVE_CONSTITUTION.md); current executable gates live in [`L64_APPROVAL_GATES.md`](L64_APPROVAL_GATES.md). + +## Preserved prior constitution + +# Locus64 Architectural Constitution v1 + +This file is an index of mechanically demonstrated architectural law. It is not a wishlist, roadmap, branding document, or substitute for executable evidence. + +Rules enter this constitution only after their corresponding approval gate is marked `Proven` in `L64_APPROVAL_GATES.md`. + +## Authority Rule + +Runtime authority is earned by closed transitions, validated packet structure, stable commitments, deterministic merge behavior, and receipted lineage. Names, projections, reports, caches, legacy formats, display IDs, scheduler choices, and migration objects do not become authority by existing in the repository. + +## Proven Gates + +### L64-G001 - Duplex Pair Local Authority Unit + +Duplex pair is the smallest locally authoritative unit. + +Evidence: + +- `cargo test -p l64-core duplex_pair_validation_requires_semantic_and_complement_strands` + +Constitutional effect: + +- A semantic strand without its authority complement is not locally valid. +- Local authority begins at the paired structure, not at either strand alone. + +### L64-G002 - No Strand-Only Promotion + +Neither strand is independently promotable. + +Evidence: + +- `cargo test -p l64-core duplex_pair_validation_requires_semantic_and_complement_strands` + +Constitutional effect: + +- Semantic-only or complement-only material must fail local admission. +- Promotion logic must consume paired authority structure rather than single-lane meaning. + +### L64-G003 - Local Validity Is Not Domain Closure + +Pair-local validity does not imply domain closure. + +Evidence: + +- `cargo test -p l64-core domain_closure_blocks_promotion_on_open_frontier` + +Constitutional effect: + +- A locally valid pair may still be non-promotable when open obligations or external burdens remain. +- Domain closure is a separate gate above pair admission. + +### L64-G004 - Complement Burden Law + +Complement encodes admissibility burdens; receipts only discharge them. + +Evidence: + +- `cargo test -p l64-core authority_complement_must_carry_burdens_not_receipt_only_claims` + +Constitutional effect: + +- Authority complements must carry invariant and witness-form requirements. +- Receipt-only complement claims are malformed and cannot become local authority. + +### L64-G007 - Codon Structural Law + +Codons compile to structural instructions, not semantic codebooks. + +Evidence: + +- `cargo test -p l64-core` +- Proving tests: `codon_lexon_law_tables_are_unique_and_complete`, `codon_header_phase_controls_source_admission` + +Constitutional effect: + +- Codon tables define structural phase/admission law. +- Codon names are not semantic authority and must not become lookup-mediated meaning. + +### L64-G008 - Lexon Scoped Binding Law + +Lexons are scoped receipted bindings, not global meaning. + +Evidence: + +- `cargo test -p l64-core` +- Proving tests: `lexon_aliases_resolve_to_scoped_canonical_targets`, `representative_lexons_bind_scoped_targets_with_receipts` + +Constitutional effect: + +- Lexon aliases resolve into scoped canonical targets. +- Bindings require receipts and cannot become global semantic aliases. + +### L64-G009 - Macro-Codon Reaction Law + +Macro-codons compile to reaction law, not workflow labels. + +Evidence: + +- `cargo test -p l64-core macro_codons_are_separate_from_lexons` + +Constitutional effect: + +- Macro-codons are separate reaction-law structures. +- Workflow labels do not define executable law. + +### L64-G013 - Generated-Word Regression Boundary + +Generated-word bans are regression tripwires, not authority law. + +Evidence: + +- `cargo test -p l64-core generated_structural_word_ban_detects_old_label_payloads` + +Constitutional effect: + +- Generated-word bans may prevent old label payloads from leaking into structural regions. +- The ban list is diagnostic enforcement, not a source of meaning. + +### L64-G015 - Canonical Structural Identity + +Persistent authority identity derives from canonical structural bytes. + +Evidence: + +- `cargo test -p l64-core` +- Proving tests: `canonical_structure_erases_spacing_but_preserves_order`, `dna_packet_validation_checks_canonical_structure_digest` + +Constitutional effect: + +- Formatting variation cannot define authority identity. +- Authority identity must bind canonical structure, not authored source text. + +### L64-G016 - Canonical Instruction Stream + +Explicit canonical instructions replace token-hash authority. + +Evidence: + +- `cargo test -p l64-core canonical_structure_erases_spacing_but_preserves_order` + +Constitutional effect: + +- Canonical structure is encoded through versioned instructions. +- Token hash shortcuts cannot be promoted as authority identity. + +### L64-G017 - Section Payload Commitment + +Every authority section commitment binds its payload. + +Evidence: + +- `cargo test -p l64-core generic_dna_packet_validates_section_payload_commitment` + +Constitutional effect: + +- DNA validation must compare section payloads against payload commitments before authority decode can be trusted. +- Payload commitments are authority-adjacent validation material, not display identifiers. + +### L64-G018 - Complete Authority Decode Validation + +Authority payload decode requires complete packet validation. + +Evidence: + +- `cargo test -p l64-core` +- Proving tests: `dna_packet_validation_checks_canonical_structure_digest`, `generic_dna_packet_validates_section_payload_commitment` + +Constitutional effect: + +- Authority decode must validate payload commitment and canonical structure digest requirements. +- Partial packet success cannot promote a payload into authority. + +### L64-G019 - Explicit Legacy Decode Mode + +Legacy decoding requires explicit migration or forensic mode. + +Evidence: + +- `cargo test -p l64-core legacy_packet_decode_requires_explicit_migration_or_forensic_mode` + +Constitutional effect: + +- Current authority decode must not silently fall back to legacy packet decoding. +- Migration and forensic decode paths are intentional subordinate modes, not ambient compatibility. + +### L64-G020 - Bounded Authority Decode + +Authority decoding is bounded before allocation. + +Evidence: + +- `cargo test -p l64-core locus_packet_decode_rejects_oversized_fields_before_payload_copy` + +Constitutional effect: + +- Sized packet fields must pass a hard length cap before payload copy. +- Authority decoding cannot allocate unbounded field payloads from attacker-controlled lengths. + +### L64-G021 - Authority Tier Validation + +Authority tiers are typed law at DNA validation. + +Evidence: + +- `cargo test -p l64-core dna_packet_validation_rejects_unknown_authority_tier` + +Constitutional effect: + +- DNA validation must reject unknown authority tier values. +- The packet byte remains layout-compatible, but valid tier meaning is closed by the typed tier table. + +### L64-G023 - Source Release Hygiene + +Generated caches and ambiguous reports do not ship as source. + +Evidence: + +- `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` + +Constitutional effect: + +- Release products must distinguish source, projection, record, receipt, and view roles. +- Generated views and reports may be shipped as products, but not as source authority. + +### L64-G024 - Deterministic Parallel Equivalence + +Serial and parallel authoritative outputs are byte-equivalent. + +Evidence: + +- `cargo test -p l64-core deterministic_authority_merge_excludes_worker_count_and_input_order` + +Constitutional effect: + +- Worker count and input completion order must not affect authoritative merge output. +- Canonical ordering must be derived from structural coordinates and payload commitments. + +### L64-G025 - Scheduler Non-Authority + +Scheduler plans and telemetry are receipts, not authority. + +Evidence: + +- `cargo test -p l64-core deterministic_authority_merge_excludes_worker_count_and_input_order` + +Constitutional effect: + +- Worker count, timing, lane assignment, and scheduling plan data are excluded from authority identity. +- Scheduler details may be recorded as diagnostics or receipts only. + +### L64-G026 - Authored Obligation Status Is Intent + +Authored obligation status is intent, never evidence. + +Evidence: + +- `cargo test -p l64-cert authored_obligation_status_does_not_satisfy_evidence` + +Constitutional effect: + +- An authored `Certified` obligation does not satisfy evidence by itself. +- Unsupported obligations must remain unsupported or blocked unless executable evaluation or native stored evidence exists. + +### L64-G027 - Scoped Evaluator Authority (Superseded) + +The registry-scoped evaluator-policy path is rejected. Direct certification owns one explicit in-process execution profile and emits no policy object, binding, resolution ID, precedence trace, or persistent policy receipt. See L64-G068. + +### L64-G030 - Deterministic Policy Precedence Receipts (Superseded) + +Policy precedence is no longer a live authority path. The policy registry and stored resolution machinery were deleted after historical export. Determinism now belongs to direct execution and exact native authority, not ordering policy records. See L64-G068. + +### L64-G032 - RNA/DNA Public Authority Surfaces + +RNA and DNA remain the only public authority surfaces. + +Evidence: + +- `cargo test -p l64-cli --test cli` +- Proving tests: `rna_dna_primary_authority_commands_work`, `standalone_projection_leaf_commands_are_removed`, `inspect_dna_output_is_not_rna_source` + +Constitutional effect: + +- Public authority workflows must pass through source/canonical RNA or DNA. +- Projection, inspection, and removed legacy commands cannot define public authority surfaces. + +### L64-G033 - Bundle-Entry Migration Ingress (Superseded) + +Bundle-entry JSON, `BundleWorld`, overlay merging, namespace import, and conflict-policy execution were deleted after historical export. Current bundle transport is exact ordered `L64B` over canonical `L64D` members. See L64-G061 and L64-G068. + +### L64-G036 - Canonical RNA Reconstruction + +DNA reconstructs canonical RNA, not authored RNA. + +Evidence: + +- `cargo test -p l64-cli --test cli cki_registry_fixture_preserves_rna_dna_fixed_point` + +Constitutional effect: + +- DNA-to-RNA reconstruction targets canonical RNA. +- Original authored RNA remains lineage/source material, not a required inverse of DNA. + +### L64-G038 - Release Renderer Law + +Release strings are renderers over witnessed products. + +Evidence: + +- `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` + +Constitutional effect: + +- Release strings, claim pages, maps, views, and rendered records must be derived from witnessed authority products. +- Rendered release artifacts do not become source authority. + +### L64-G040 - Artifact Role Explicitness + +Every sample artifact has an explicit source, migration, projection, record, receipt, or view role. + +Evidence: + +- `cargo test -p l64-cli --test cli genome_release_exports_coordinate_spine_and_rejects_views_as_source` + +Constitutional effect: + +- Release and sample artifacts must advertise their role through type, filename, content marker, or command boundary. +- Ambiguous artifacts must fail source admission or be classified before use. + +### L64-G056 - Explicit Structural Equivalence Law + +Structural equivalence requires explicit law specs and transition context. + +Evidence: + +- `cargo test -p l64-core` +- Proving tests: `equivalence_law_makes_ordering_explicit_before_cnorm`, `distinction_law_classifies_collapse_before_equivalence` + +Constitutional effect: + +- CNORM cannot claim sameness from naked equality strings, graph shape, or source text alone. +- Equivalence must reference transition law and distinction law before collapse is allowed. + +### L64-G045 - Mechanical Evidence Requirement + +Constitutional rules require mechanical evidence. + +Evidence: + +- `L64_APPROVAL_GATES.md` promotion law + +Constitutional effect: + +- Candidate rulings remain outside this constitution until their executable proof is landed and recorded. +- Documentation alone cannot promote runtime law. + +### L64-G028 - Certification Scope Law + +Every certification verdict carries an explicit authority scope. + +Evidence: + +- `scripts/verify-native-carrier.sh` +- Proving tests: `canonical_native_authority_certifies_from_direct_burdens`, native CLI membrane gate + +Constitutional effect: + +- A verdict cannot silently broaden from native structural closure into theorem, campaign, benchmark, policy, or external truth. +- The authority bytes and the non-authoritative diagnostic symbol must remain distinguishable in certification output. + +### L64-G061 - Native Bundle Transport Law + +Native bundle transport frames canonical DNA members without creating composite authority. + +Evidence: + +- `scripts/verify-native-carrier.sh` +- Proving tests: `bundle_is_exact_ordered_dna_transport`, `execution_verifies_each_projection_without_composite_authority` + +Constitutional effect: + +- `L64B` may preserve order and exact member boundaries only. +- Bundle transport cannot merge registries, resolve semantic conflicts, or invent bundle-level truth. + +### L64-G062 - Native Certification Derivation Law + +Native certification derives only from exact DNA and verified per-context burdens; bundles have no composite certificate. + +Evidence: + +- `scripts/verify-native-carrier.sh` +- Proving tests: `canonical_native_authority_certifies_from_direct_burdens`, `invalid_child_context_invalidates_the_authority_certification`, `bundle_members_are_certified_independently` + +Constitutional effect: + +- Every native context must be evaluated; an invalid child context invalidates the authority certification. +- `OPEN`, `INCOMPLETE`, and `INVALID` remain distinct from `CERTIFIED`. +- `L64B` members retain independent verdicts; no bundle-level verdict or certificate may be emitted. + +### L64-G063 - Native Observation Projection Law + +Native observation is reconstructible non-authoritative projection over exact DNA; bundles have no composite observation. + +Evidence: + +- `scripts/verify-native-carrier.sh` +- Proving tests: `canonical_authority_observation_binds_verified_native_surfaces`, `invalid_child_context_remains_visible_in_report_and_certification`, `bundle_members_are_observed_independently`, native CLI membrane gate + +Constitutional effect: + +- Observation may bind direct certification to verified replay and closure/opcode report projections only. +- Observation cannot persist a second authority, campaign, report cache, policy result, or fabricated replay history. +- `L64B` members remain independently observed; no bundle-level observation or verdict may be emitted. + +### L64-G064 - Native Change Projection Law + +Native change analysis compares exact current authorities without creating diff authority or a composite bundle verdict. + +Evidence: + +- `scripts/verify-native-carrier.sh` +- Proving tests: `identical_dna_is_exactly_unchanged`, `structural_and_verdict_movement_is_directly_visible`, `bundle_members_remain_independent_change_contacts`, native CLI membrane gate + +Constitutional effect: + +- Exact canonical DNA bytes determine equality; symbolic section differences and projection movements remain diagnostics. +- Change analysis cannot persist predictions, plans, locks, manifests, policy resolutions, report caches, campaigns, or receipts. +- Ordered bundle members are compared independently by transport index; no bundle-level change authority or verdict may be emitted. + +### L64-G065 - Legacy Cache Deletion Law + +Campaign/report storage may be deleted after every productive current contact is carried directly by native authority projections and an external historical export exists. + +Evidence: + +- `scripts/verify-legacy-cache-deletion.sh` +- Pass 19 historical export archive and Pass 18 restore source +- packaged native carrier verification after deletion + +Constitutional effect: + +- `l64-observe`, `l64-admin`, certification execution caches, report-cache paths, report-ID replay, and invalidation lookup are not live runtime surfaces. +- Certification computes fresh from its current inputs. Native observation and change remain reconstructible and non-persistent. +- Deleted storage schemas must not be recreated inside native crates. Historical decoding belongs to external archives or explicit file contacts only. + +## Explicit Non-Promotions + +The following are not constitutional authority in v1: + +- `QaDocument` as ontology source. +- Bundle-entry JSON as public authority syntax. +- Bincode as canonical DNA. +- Projection/report/view artifacts as source. +- Legacy Q-surface syntax or Q-surface policy objects. +- Graph, arena, map, index, fold, or scheduler representation as substrate authority. +- Current molecular names unless promoted by a future proven gate. + +### L64-G066 - Legacy Plan, Lock, and Manifest Deletion Law + +Stored prediction, recomputation, execution-plan, bundle-lock, and execution-manifest records are obsolete once exact native authorities and direct projections carry their productive contacts. + +Evidence: + +- `scripts/verify-legacy-plan-storage-deletion.sh` +- Pass 20 historical export archive and Pass 19 restore source +- packaged dependency-free native carrier verification after deletion + +Constitutional effect: + +- Prediction, semantic-drift, recomputation-plan, plan-execution, assessment, reconciliation, bundle-lock, replay-lock, lock-receipt, lock-diff, policy-manifest, and execution-manifest record types are not live schemas. +- QA/registry admission, bundle import/export, packet-store paths, policy builders, certification enrichment, and command routes for those records are deleted. +- Numeric packet-kind tombstones may remain only to preserve unrelated discriminant numbering; they may have no constructors or live references. +- Deleted storage schemas must not be recreated inside native crates. Historical reconstruction belongs to the external archive. + + +### L64-G067 - Legacy Lineage, Readiness, Queue, and Handoff Deletion Law + +Persisted report-derived lineage, promotion-readiness, promotion-queue, and governed-handoff records are obsolete once exact native certification, observation, and change expose their productive facts directly. + +Evidence: + +- `scripts/verify-legacy-lineage-readiness-deletion.sh` +- Pass 21 historical export archive and Pass 20 restore source +- packaged dependency-free native carrier verification after deletion + +Constitutional effect: + +- `ResearchLineageRecord`, `PromotionReadinessReport`, `PromotionQueueEntry`, `PromotionQueueStatus`, and `HandoffPacket` are not live schemas. +- Research bundle fields, report-derived constructors, persistence paths, import/export/list routes, status aggregation, and compile-RNA lineage persistence for those records are deleted. +- Live certification output must not manufacture references to deleted lineage records. +- Deleted schemas must not be recreated inside native crates. Historical reconstruction belongs to the external archive. + + +### L64-G068 - Registry Overlay and Stored Policy Deletion Law + +Registry-overlay bundle worlds and stored policy resolution are obsolete once current native transport, certification, observation, and change carry every productive contact directly. + +Evidence: + +- `scripts/verify-legacy-registry-overlay-policy-deletion.sh` +- Pass 22 historical export archive and Pass 21 restore source +- packaged dependency-free native carrier verification after deletion + +Constitutional effect: + +- `l64-bundle` and `l64-policy` are not live crates. +- `BundleWorld`, overlay registries, bundle manifests, merge reports, conflict policies, namespace import, and bundle-world caches are not live schemas or execution paths. +- `MechanizationPolicyObject`, `PolicyBinding`, `PolicyResolution`, policy precedence traces, policy IDs, and policy hashes are not live schemas or report coordinates. +- The seed registry may retain surviving theorem/campaign records temporarily, but it admits no evaluator-policy objects or overlay-local authority. +- Certification uses one direct in-process execution profile and emits no persistent policy object, binding, resolution, or receipt. +- Current `L64B` transport orders independent canonical `L64D` authorities and creates no composite authority. +- Deleted overlay and policy machinery must not be recreated inside native crates. Historical reconstruction belongs to the external archive. + +## Current Blockers + +The following gates remain candidate or deferred and must not be treated as proven law: + +- Duplex-pair promotion law beyond local first-slice tests. +- Full canonical structural identity replacing every token-hash fallback. +- The historical theorem/campaign/research/registry authority island is deleted; no compatibility runtime remains. +- Seed JSON replacement by native DNA bootstrap. +- Boollet integration as a sidecar transition-memory module. +- External standards and proof assistants as scoped witness providers. + +## Maintenance Rule + +Every future constitution edit must include: + +1. The promoted gate ID. +2. The exact evidence command, fixture, or proof artifact. +3. The authority effect. +4. The non-authority boundary it preserves. + +If any of those are missing, the ruling belongs in `L64_APPROVAL_GATES.md`, not here. + +## L64-G069 — Delete the Superseded Authority Island + +Once every productive current contact is carried directly by exact native authority and verified projections, historical theorem/campaign/research/registry execution machinery must be exported and removed rather than retained as a compatibility runtime. + +Proving boundary: +- `scripts/verify-legacy-authority-island-deletion.sh` +- `cargo test --locked --offline --workspace` +- `cargo clippy --locked --offline --workspace --all-targets -- -D warnings` + +Authority effect: +- the live workspace is eleven dependency-free native packages; +- no seed registry, research store, producer host, tower store, campaign engine, or legacy dispatcher remains; +- deleted commands fail as permanent tombstones and cannot touch the filesystem. + +## Native execution carrier + +Direct execution is non-persistent structural authority evaluation. `run-rna` compiles canonical RNA transiently; `run-dna` validates canonical DNA. Both verify the root projection, certify every context, mutate no authority, and create no run record. Ordered bundle execution reuses the same member carrier and creates no composite execution authority. + +## L64-G071 — Direct Native CLI Boundary + +The native operator boundary must dispatch current commands directly. A wrong carrier format is an error at the requested command contact, not a compatibility-fallback signal. + +Proving boundary: +- `scripts/verify-cli-hardening.sh` +- `cargo test --locked --offline --workspace` +- `cargo clippy --locked --offline --workspace --all-targets -- -D warnings` + +Constitutional effect: +- no `Result` command membrane or `Ok(false)` fallback may return; +- public carrier errors must render stable human-readable diagnostics rather than Rust debug syntax; +- `compile-rna` and `compile-bundle` create new files atomically and refuse replacement; +- no-op legacy selectors such as `--artifact-class` must fail explicitly; +- command discovery must include `--help`, `help `, and `--version` without external dependencies. + + +## L64-G072 — Verdict-Aware Process and Bounded Transport Law + +Native commands that compute certification must preserve the full derived result while returning a stable process status for the worst member-local verdict. RNA parse failures must identify the exact source token span. Ordered bundle processing must not require retaining the complete transport and all decoded member graphs simultaneously. + +Proving boundary: +- `scripts/verify-process-contract.sh` +- `streaming_encoder_matches_exact_transport_and_decoder_releases_members_sequentially` +- `streaming_decoder_never_requests_the_whole_bundle_buffer` +- `rna_diagnostic_renders_exact_token_span` +- full locked offline workspace tests and Clippy + +Constitutional effect: +- `0`, `10`, `11`, and `12` represent `CERTIFIED`, `OPEN`, `INCOMPLETE`, and `INVALID` successful computations; operational failure remains `2`; +- process status is a projection over certification and never authority; +- RNA diagnostics preserve exact line, column, and token length without introducing a diagnostic registry; +- bundle encoding and bundle-facing CLI operations process one member at a time and preserve exact `L64B` bytes, member order, and member-local authority. + +## L64-G073 — Measured Native Scale Law + +Performance work must begin with a reproducible authority-shaped workload and a measured causal hot path. Canonical source compilation may suppress intermediate journals and state-symbol recomputation only while constructing a transient graph that is finalized once before publication. Public graph mutations remain tracked. Derived indexes and shared analysis may accelerate exact queries but cannot enter canonical authority bytes. Fresh in-process projections may be accepted by construction; any retained, transported, cached, or externally supplied projection must still be explicitly verified against exact authority. + +Proving boundary: +- `scripts/verify-native-scale.sh` +- exact RNA/DNA fixed-point and journal tests +- stale and forged projection rejection tests +- full locked offline workspace tests and Clippy diff --git a/LOCUS64_INCREMENTAL_CLOSURE_CHANGE_CHAIN.athens b/LOCUS64_INCREMENTAL_CLOSURE_CHANGE_CHAIN.athens new file mode 100644 index 0000000..0e6cd16 --- /dev/null +++ b/LOCUS64_INCREMENTAL_CLOSURE_CHANGE_CHAIN.athens @@ -0,0 +1,46 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=projection_authority;value=non_authoritative +field=key=rail_version;value=7 +field=key=schema_version;value=1 +gate=id=closure-state-evaluator-green +gate=id=context-refinement-impact-green +gate=id=exact-affected-recompute-green +gate=id=incremental-closure-green +gate=id=local-global-closure-green +gate=id=reverse-incidence-green +stage=id=reverse-incidence +stage_field=stage=reverse-incidence;key=required_gates;value=reverse-incidence-green +stage_field=stage=reverse-incidence;key=status;value=complete +stage=id=closure-state-evaluator +stage_field=stage=closure-state-evaluator;key=depends_on;value=reverse-incidence +stage_field=stage=closure-state-evaluator;key=required_gates;value=closure-state-evaluator-green +stage_field=stage=closure-state-evaluator;key=status;value=complete +stage=id=context-refinement-impact +stage_field=stage=context-refinement-impact;key=depends_on;value=closure-state-evaluator +stage_field=stage=context-refinement-impact;key=required_gates;value=context-refinement-impact-green +stage_field=stage=context-refinement-impact;key=status;value=complete +stage=id=exact-affected-recompute +stage_field=stage=exact-affected-recompute;key=depends_on;value=context-refinement-impact +stage_field=stage=exact-affected-recompute;key=required_gates;value=exact-affected-recompute-green +stage_field=stage=exact-affected-recompute;key=status;value=complete +stage=id=local-global-closure +stage_field=stage=local-global-closure;key=depends_on;value=exact-affected-recompute +stage_field=stage=local-global-closure;key=required_gates;value=local-global-closure-green +stage_field=stage=local-global-closure;key=status;value=complete +stage=id=incremental-closure-closure +stage_field=stage=incremental-closure-closure;key=depends_on;value=local-global-closure +stage_field=stage=incremental-closure-closure;key=required_gates;value=incremental-closure-green +stage_field=stage=incremental-closure-closure;key=status;value=complete +history=from_status=current;gates=reverse-incidence-green;mode=linear_advance;stage_id=reverse-incidence;to_status=complete +history=evidence=local%3A43-tests%2Breverse-index%2Bdecode-rebuild%2Bexact-independent-exclusion;kind=dogfood_promotion_receipt;stage_id=reverse-incidence +history=from_status=current;gates=closure-state-evaluator-green;mode=linear_advance;stage_id=closure-state-evaluator;to_status=complete +history=evidence=local%3Aclosure-closed-open-invalid%2Bevidence-propagation%2Bclippy;kind=dogfood_promotion_receipt;stage_id=closure-state-evaluator +history=from_status=current;gates=context-refinement-impact-green;mode=linear_advance;stage_id=context-refinement-impact;to_status=complete +history=evidence=local%3Adirect-child-constraint-refinement%2Bpositive-discharge%2Bnegative-refusal;kind=dogfood_promotion_receipt;stage_id=context-refinement-impact +history=from_status=current;gates=exact-affected-recompute-green;mode=linear_advance;stage_id=exact-affected-recompute;to_status=complete +history=evidence=local%3Areverse-reachable-only%2Bdownstream-equality%2Bindependent-stability;kind=dogfood_promotion_receipt;stage_id=exact-affected-recompute +history=from_status=current;gates=local-global-closure-green;mode=linear_advance;stage_id=local-global-closure;to_status=complete +history=evidence=local%3Aroot-open%2Bchild-closed-or-invalid%2Bglobal-aggregate;kind=dogfood_promotion_receipt;stage_id=local-global-closure +history=from_status=current;gates=incremental-closure-green;mode=linear_advance;stage_id=incremental-closure-closure;to_status=complete +history=evidence=github-fd90966af2191e6d9ca5e14e17f0bcaca431c260-run-30009891592;kind=dogfood_promotion_receipt;stage_id=incremental-closure-closure +END diff --git a/LOCUS64_LANGUAGE_SPEC.md b/LOCUS64_LANGUAGE_SPEC.md index 38ea966..46fe719 100644 --- a/LOCUS64_LANGUAGE_SPEC.md +++ b/LOCUS64_LANGUAGE_SPEC.md @@ -1,719 +1,54 @@ -# Locus64 Interaction Language Specification +# Locus64 Native Language Specification -Status note: RNA and DNA are the active public surfaces. Bundle-entry text remains an authoring convenience for generating `.dna` bundle packets, but QC0/QA0/QM0/QK0 are no longer public interaction languages or workspace crates. +## Authority surfaces -This is the concrete syntax and record-shape specification for interacting with Locus64. +- `L64R1` is canonical textual RNA. +- `L64D` is canonical binary DNA. +- RNA normalization is deterministic. +- RNA → DNA → RNA → DNA is an exact fixed point. +- DNA decoding revalidates structure, constraints, equality proofs, contexts, operation law, canonical ordering, and exact re-encoding. -There are three practical interaction forms: +## Transport -1. **Command language**: shell commands accepted by `l64`. -2. **RNA language**: small symbolic input compiled into DNA. -3. **Bundle-entry text**: one record-kind plus one JSON object per line, compiled into `.dna`. +`L64B` is a versioned ordered frame containing length-prefixed canonical `L64D` members. It has no bundle registry, names, overlays, conflict policy, composite certificate, or composite authority. -If you are driving Locus64 indirectly from ChatGPT or another system, generate RNA or bundle-entry text, compile it into DNA, and then use the `.dna` artifact for certification/execution. +## Derived surfaces -Native structural law is moving toward codon/lexon governance: +Projection, certification, observation, and change outputs are verified read-only derivatives. They may reject or expose invalid authority, but they never become source authority. -- **Codons** are finite structural operators/classes with arity, phase/admission law, and opcode identity. -- **Lexons** are scoped symbolic bindings for domain-local objects such as chain rule, derivative, composition, and bridge-sector patterns. -- **Macro-codons** are recurring structural/reaction patterns such as roundtrip, closure frontier, view receipt, integration receipt, and expression receipt. They are not lexons and do not share the lexon registry. -- Aliases are ingress-only. Generated native artifacts should emit canonical symbols, not structural aliases as words. -- Header truth and codon phase law outrank filename extensions. A source/product/receipt/view decision must come from the native header and phase table, not from `.rna`, `.pep`, `.prot`, JSON shape, or command habit. -- Opcode allocation is stable law: never reuse an opcode, deprecate by tombstone, migrate by receipt, and do not rely on Rust enum variant order for persisted numeric meaning. -- Generated-word bans apply to native structural regions only. Words such as `claim_page`, `dependency_spine`, `theorem`, or `campaign` may appear in gloss/comments/views, but must not survive as generated native structural tokens. -- Digests and hashes are machine memo bindings, not public proof identity. -- Products, views, receipts, and projections remain rejected as source unless explicitly reconstructed into canonical RNA. -- Report-derived research records are projection authority until replay-specific promotion exists. Authored/imported `claim-packet` records may declare `authority_state`, but report-derived claim packets must not upgrade report verdicts into evidence or benchmark authority. -- Evaluator authority is selected by named scoped `policy-object` records. Equal-precedence policies are resolved by stable policy identity so policy receipts are deterministic. +## Binary surfaces -This law exists to prevent future bundle/product records from becoming JSON with different punctuation. Bundle-entry text remains transitional until representative workflows are rerouted through substrate-native records. +- `l64-cli` owns the complete native command grammar and executes every current command directly. +- `l64` adds only `authority-audit`. Every other argument is forwarded unchanged to the sibling `l64-cli`, and the child process status is preserved. +- The wrapper is not a second parser, execution layer, authority path, or compatibility fallback. -Current representative registries: +## `l64-cli` commands -- Codon module: `l64-core/src/codons.rs` -- Lexon module: `l64-core/src/lexons.rs` -- Macro-codon module: `l64-core/src/macro_codons.rs` +- `normalize-rna` +- `compile-rna` +- `sequence-dna` +- `inspect-dna` +- `verify-roundtrip` +- `export-genome-release` +- `run-rna` +- `run-dna` +- `compile-bundle` +- `run-bundle` +- `certify-dna` +- `certify-bundle` +- `observe-dna` +- `observe-bundle` +- `compare-dna` +- `compare-bundle` -The controlled CKI registry fixture lives at `fixtures/cki_registry.genome.rna`. It is a regression fixture for the RNA/DNA fixed-point membrane, not independent authority and not a third public surface. +## `l64`-local command -## 1. Command Language +- `authority-audit` -Primary executable: +All historical theorem, campaign, research, registry, producer-host, tower, packet, policy, cache, planning, administration, and `legacy` execution commands are permanently deleted tombstones. -```text -l64 [args...] -``` +## Process semantics -`l64` is a wrapper. Keep `l64`, `l64-cli`, and `l64-admin` in the same directory. +Certification-bearing commands are successful computations even when their structural verdict is not certified. They emit the complete result and return `0` for `CERTIFIED`, `10` for `OPEN`, `11` for `INCOMPLETE`, and `12` for `INVALID`. Operational failure returns `2`. These codes are process projections and do not alter authority. -Core commands: - -```text -l64 normalize-rna -l64 compile-rna [--out ] [--artifact-class gene|haplotype|chromosome|genome] [--persist-lineage] -l64 sequence-dna -l64 inspect-dna -l64 verify-roundtrip [--artifact-class gene|haplotype|chromosome|genome] -l64 export-genome-release --rna --out [--artifact-class gene|haplotype|chromosome|genome] - -l64 compile-bundle [--out ] -l64 certify-bundle --file --conflict-policy exact-match -l64 certify-derived --campaign -l64 observe-run --report -l64 export-report-dna --report-id --out .dna -l64 export-validation-dna-bundle --id --out .validation.dna - -l64 research-derive-from-report --report-id --persist -l64 research-promotion-readiness -l64 research-status - -l64 dispatch-coverage --report-id -l64 derive-frontier --report-id -l64 tower-step --report-id -``` - -## 2. RNA Language - -RNA is a symbolic input language for lower-chain identity/structure roots. - -Pipeline: - -```text -raw RNA -> TOKENIZE -> RNORM -> SSR -> CNORM -> DNA -``` - -### 2.1 Token Classes - -The tokenizer classifies characters into: - -| Class | Characters / rule | -| --- | --- | -| `Atom` | lowercase, digits, Greek/non-control symbolic characters not otherwise classified | -| `Binder` | ASCII uppercase `A-Z` | -| `Operator` | `_`, `|`, `:`, `=`, `+`, `-`, `*`, `/`, `^`, `≔`, `‖`, `→` | -| `GroupLeft` | `(`, `[`, `{` | -| `GroupRight` | `)`, `]`, `}` | -| `Separator` | `,`, `;` | -| `StrandRef` | `.` | -| `Meta` | whitespace | - -Non-whitespace control characters are invalid. - -### 2.2 Current Practical RNA Form - -The current implementation preserves tokens and normalizes whitespace/group/splice structure. It does **not** parse full mathematical notation as a theorem language. - -Safe forms: - -```text -i := s || k -ι ≔ σ ‖ κ -A.x := y -(a := b) -``` - -Splice markers: - -```text -iei eie -``` - -Unclosed splice regions fail. - -### 2.3 RNA Commands - -```powershell -l64 normalize-rna .\claim_root.gene.rna -l64 compile-rna .\claim_root.gene.rna --out .\claim_root.gene.dna --artifact-class gene --persist-lineage -l64 sequence-dna .\claim_root.gene.dna -l64 inspect-dna .\claim_root.gene.dna -l64 verify-roundtrip .\claim_root.gene.rna --artifact-class gene -l64 export-genome-release --rna .\claim_root.gene.rna --out .\claim_root.release --artifact-class gene -``` - -### 2.4 RNA Output Guarantees - -`compile-rna` accepts source RNA only. It rejects inspection reports, receipts, views, closure maps, claim pages, stress maps, replay records, and JSON report/projection text before lower-chain tokenization. - -Successful `compile-rna` returns an inspection report containing: - -- byte count -- packet summary -- normalized RNA -- tokenization/RNORM/SSR/CNORM receipts -- DNA validation report -- lineage record - -`sequence-dna` emits canonical reconstructable RNA, not JSON. - -`inspect-dna` emits a JSON inspection report for humans and tooling. Inspection output is not source and must not be passed to `compile-rna`. - -`verify-roundtrip` proves the public fixed-point law: - -```text -RNA -> DNA -> canonical RNA -> DNA -``` - -The canonical hash must be preserved. Packet bytes may differ when intentionally variable metadata changes, but same-subject library roundtrips are expected to stabilize byte-for-byte. - -Use RNA/DNA for identity and canonicalization. Bundle-entry text remains a transitional authoring convenience compiled into `.dna`; it is not a public authority surface. - -`export-genome-release` creates derived review artifacts from the same RNA/DNA authority spine. Its manifest, claim pages, dependency spine, closure map, closure frontier, stress map, lineage, replay record, views, and view receipts are projections or records. They use role-specific projection/record/receipt filenames, are not source RNA, and are rejected by `compile-rna`; generated source RNA and canonical RNA are the re-compilable text artifacts. - -## 3. Bundle-Entry Authoring Text - -Bundle-entry text is a transitional authoring convenience for generating `.dna` bundle packets. It is not a public authority surface and is not accepted by normal bundle execution without first compiling it through `compile-bundle`. - -### 3.1 File Structure - -Bundle-entry text is line-oriented: - -```text -!l64-bundle v1 - - -... -``` - -Rules: - -- First non-empty line must be `!l64-bundle v1`. -- Each later non-empty line must contain one entry kind, one space, and one JSON object. -- JSON must be valid on a single line. -- Entry order can matter operationally for readability, but parsing accepts entries by kind. -- Comments are not part of bundle-entry projection syntax. Do not emit comments inside projection entry files. - -Header: - -```text -!l64-bundle v1 -``` - -`capability_id` may be `null`. - -### 3.2 Accepted Entry Kinds - -The parser accepts these entry kind strings: - -```text -object -regime -bridge -proof -mechanization -theorem -obligation -target -ledger -certificate -campaign -portfolio -route-class -diagnostic -policy-object -adequacy -burden-pack -claim-packet -evidence-contract -benchmark-receipt -challenge-receipt -reproducibility-packet -``` - -Deprecated surface-schema entries are rejected by generic bundle-entry JSON admission and by `compile-bundle`: - -```text -surface-policy -transform-receipt -roundtrip-report -capability -capability-matrix -surface-budget -surface-deficiency -``` - -These names remain historical schema residue only where needed for binary/storage compatibility. They do not enter active bundle registries and cannot discharge certification obligations. - -For most semantic/governance workflows, use: - -```text -proof -bridge -atlas -theorem -obligation -target -ledger -campaign -burden-pack -claim-packet -evidence-contract -benchmark-receipt -challenge-receipt -reproducibility-packet -adequacy -``` - -Note: `atlas` is accepted by the broader surface parser in the current samples and certification flow. - -## 4. Core Record Shapes - -All enum values are case-sensitive. - -### 4.1 `claim-packet` - -Use for a governed claim. - -```text -claim-packet {"id":"CLM_ID","claim_class":"Kernel","authority_state":"Evidence","target_sector":"cosmology","statement":"claim text","assumptions":["A1","A2"],"open_caveats":["gap"]} -``` - -Fields: - -| Field | Type | Required | -| --- | --- | --- | -| `id` | string | yes | -| `claim_class` | `Kernel` \| `Interoperability` \| `Host` | yes | -| `authority_state` | `Derived` \| `Benchmark` \| `Evidence` \| `Projection` | yes | -| `target_sector` | string | yes | -| `statement` | string | yes | -| `assumptions` | string array | no, default `[]` | -| `open_caveats` | string array | no, default `[]` | - -Use `Projection` for report-derived research records unless a replay-specific promotion path has produced stronger authority. Use `Evidence` or `Benchmark` only when the authored/imported claim is backed by the corresponding evidence contracts, receipts, reproducibility packets, adequacy clauses, and certification path. - -### 4.2 `evidence-contract` - -Use to define required evidence before promotion. - -```text -evidence-contract {"id":"ECT_ID","required_evidence_kinds":["derivation","observation"],"required_benchmark_roles":["TargetCase","Stress"],"requires_stress":true,"requires_challenge":true,"admissibility_thresholds":["reproducible"],"promotion_ceiling":"Certified"} -``` - -Fields: - -| Field | Type | -| --- | --- | -| `id` | string | -| `required_evidence_kinds` | string array | -| `required_benchmark_roles` | `TargetCase` \| `Control` \| `Stress` \| `Trace` array | -| `requires_stress` | bool | -| `requires_challenge` | bool | -| `admissibility_thresholds` | string array | -| `promotion_ceiling` | certification verdict | - -### 4.3 `benchmark-receipt` - -Use for an observational/computational/stress result. - -```text -benchmark-receipt {"id":"BMR_ID","claim_packet_id":"CLM_ID","role":"TargetCase","verdict":"Certified","metrics":{"score":"1.0","dataset":"tolman"},"reproducibility_ref":"RPK_ID"} -``` - -Fields: - -| Field | Type | -| --- | --- | -| `id` | string | -| `claim_packet_id` | string | -| `role` | `TargetCase` \| `Control` \| `Stress` \| `Trace` | -| `verdict` | certification verdict | -| `metrics` | object with string values | -| `reproducibility_ref` | string | - -### 4.4 `challenge-receipt` - -Use for objections, anomalies, failed branches, or required responses. - -```text -challenge-receipt {"id":"CHR_ID","claim_packet_id":"CLM_ID","grounds":["Etherington duality failure"],"required_response":"replace endpoint-only branch","status":"Open"} -``` - -Fields: - -| Field | Type | -| --- | --- | -| `id` | string | -| `claim_packet_id` | string | -| `grounds` | string array | -| `required_response` | string | -| `status` | `Open` \| `Addressed` \| `Retired` | - -### 4.5 `reproducibility-packet` - -Use for replay/audit references. - -```text -reproducibility-packet {"id":"RPK_ID","claim_packet_id":"CLM_ID","derivation_path":["D1","D2"],"code_refs":["notebook.ipynb"],"benchmark_refs":["BMR_ID"],"artifact_refs":["claim_root.gene.dna"]} -``` - -Fields: - -| Field | Type | -| --- | --- | -| `id` | string | -| `claim_packet_id` | string | -| `derivation_path` | string array | -| `code_refs` | string array | -| `benchmark_refs` | string array | -| `artifact_refs` | string array | - -### 4.6 `burden-pack` - -Use to bind obligations, adequacy clauses, and evidence contracts into one certifiable burden. - -```text -burden-pack {"id":"BPK_ID","allowed_host_cluster":["R_TOP","R_CALC"],"obligation_ids":["OBL_ID"],"adequacy_clause_ids":["ADQ_ID"],"required_proof_shape_family":"Square","route_class_constraints":[],"evidence_contract_ids":["ECT_ID"],"promotion_ceiling":"Certified","blocker_taxonomy":["DEvidenceContract","DBenchmarkGap","DStressGap","DChallengeGap"]} -``` - -Fields: - -| Field | Type | -| --- | --- | -| `id` | string | -| `allowed_host_cluster` | string array | -| `obligation_ids` | string array | -| `adequacy_clause_ids` | string array | -| `required_proof_shape_family` | proof shape family | -| `route_class_constraints` | string array | -| `evidence_contract_ids` | string array | -| `promotion_ceiling` | certification verdict | -| `blocker_taxonomy` | deficiency class array | - -### 4.7 `adequacy` - -Use to connect claim/evidence/challenge objects to certification adequacy. - -```text -adequacy {"id":"ADQ_ID","kind":"EvidenceContractInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_ID"],"burden_pack_ids":["BPK_ID"],"claim_packet_ids":["CLM_ID"],"evidence_contract_ids":["ECT_ID"],"benchmark_receipt_ids":[],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_ID"],"description":"evidence contract present","blocking":true} -``` - -`kind` values: - -```text -ObjectInterpretation -ThreadInterpretation -EquivalenceInterpretation -TollInterpretation -KnotInterpretation -BridgeSoundness -ProjectionInterpretation -ContainmentInterpretation -ClosureInterpretation -RunningLawInterpretation -EvidenceContractInterpretation -BenchmarkInterpretation -StressInterpretation -ChallengeInterpretation -``` - -### 4.8 `theorem` - -Use as the central certifiable statement. - -```text -theorem {"id":"THS_ID","statement":"claim statement","hosts":["R_TOP","R_CALC"],"bridges":["B_ID"],"operators":["OPR.ID"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_ID"]} -``` - -Fields: - -| Field | Type | -| --- | --- | -| `id` | string | -| `statement` | string | -| `hosts` | string array | -| `bridges` | string array | -| `operators` | string array | -| `target_equivalence` | string | -| `obligations` | obligation kind array | -| `primary_zone` | proof mechanism zone | -| `verdict` | certification verdict | -| `proof_shapes` | string array | - -### 4.9 `obligation` - -```text -obligation {"id":"OBL_ID","kind":"OblAdm","description":"admissibility check","status":"Benchmarked"} -``` - -`kind` values: - -```text -OblEq -OblAdm -OblLoc -OblGlu -OblTol -OblRed -OblBrg -OblRbk -OblAde -OblFin -OblObs -OblKnt -``` - -### 4.10 `target` - -```text -target {"id":"TGT_ID","burden_class":"ImportedKernelClaim","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"OpenBlocked","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]} -``` - -### 4.11 `ledger` - -```text -ledger {"id":"TRL_ID","theorem":"THS_ID","paths":[["B_ID"]],"budget":{"max_loss":1,"allow_lossy_supported":false,"require_proof":true},"losses":[],"receipts":["Trace_ID"],"normalized_path":["B_ID"]} -``` - -### 4.12 `campaign` - -```text -campaign {"id":"CPG_ID","theorem":"THS_ID","target_profile":"TGT_ID","route_ledger":"TRL_ID","obligations":["OBL_ID"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["claim"]} -``` - -### 4.13 `policy-object` - -Use to select named scoped optimizer, evaluator, replay-cache, report, or scheduler policy. - -```text -policy-object {"id":"MOP_LOCAL_EVAL","kind":"Evaluator","scope":{"Theorem":"THS_ID"},"extends":null,"optimizer":null,"evaluator":{"evidence_preference":"RecomputeIfSupported","allow_approximation":false,"unsupported_mode":"StrictFail","require_symbolic_fidelity_route":false,"prefer_comp_replay":true},"replay_cache":null,"report":null,"scheduler":null,"canonicalizer_mode":null,"merge_policy":null,"notes":["strict theorem-scoped evaluator"]} -``` - -Rules: - -- `kind` must match the config it carries in strict policy resolution. -- `scope` may be `Global`, `Bundle`, `Theorem`, `Campaign`, or `TargetProfile`. -- Equal-precedence policy candidates resolve in stable policy-id order; registry insertion order is not authority. -- Policy resolution receipts carry the applied policy IDs, trace, scope, and verdict. - -## 5. Common Enum Values - -### Certification Verdict - -```text -Invalid -Underspecified -RouteFound -Benchmarked -Certified -Integrated -BlockedOpen -BlockedContradiction -``` - -### Proof Shape Family - -```text -Minimal -Triangle -Square -Diamond -Pentagon -Hexagon -MixedBattery -``` - -### Proof Mechanism Zone - -```text -PmzStructural -PmzBridge -PmzLocalToGlobal -PmzAggregation -PmzReduction -PmzCanonicalization -PmzSemantic -PmzSpectral -PmzObstruction -PmzProbabilistic -PmzOperational -``` - -### Campaign Class - -```text -CBasic -CBridge -CWelded -COperator -CAtlas -COpen -``` - -### Burden Class - -```text -ExtensionalCarrierReasoning -ProofRelevantAlgebra -DerivativeLocalWitnessExtraction -MeasurableNormalizedBranching -ProbabilisticJudgment -SimulationExecutableInference -CertifiedPropertyWitness -ImportedKernelClaim -ProjectionClosure -Containment -RunningLaw -General -``` - -### Reversibility Class - -```text -Exact -Conservative -Enriching -Forgetting -LossySupported -Invalid -``` - -### Promotion Goal - -```text -PromoteOperator -PromoteBridge -PromoteRouteClass -Retire -OpenBlocked -``` - -### Deficiency Class - -```text -DNoRoute -DHighLoss -DBadEqTransport -DRollbackCliff -DNoAdequacy -DBridge -DEq -DSelector -DRoundtrip -DPromo -DNoCommutingProof -DNoOperatorPayoff -DOpenConjectural -DProjection -DContainment -DClosure -DRunningLaw -DEvidenceContract -DBenchmarkGap -DStressGap -DChallengeGap -DHostPackMissing -``` - -## 6. Minimal Complete Imported Claim Bundle - -This is the smallest practical semantic bundle shape for a governed external claim: - -```text -!l64-bundle v1 -proof {"id":"PS_COSMO","kind":"Square","nodes":["a","b","c","d"],"edges":[{"from":"a","to":"b","label":"derive"},{"from":"b","to":"d","label":"observe"},{"from":"a","to":"c","label":"project"},{"from":"c","to":"d","label":"compare"}],"equations":["observable=projection(assumption)"],"target_equivalence":"observational-equivalence","receipts":["RCP_COSMO"],"gate":"Pass"} -bridge {"id":"B_COSMO","src":"R_TOP","tgt":"R_CALC","id_pres":"preserved","eq_pres":"observational","forget":[],"enrich":["observable"],"loss":[],"reversibility":"Enriching","receipts":["RCP_COSMO"],"rollback":"allowed"} -atlas {"id":"A_COSMO","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"ImportedKernelClaim","proof_target":"cosmology-claim","candidate_paths":[["B_COSMO"]],"normalized_winner":["B_COSMO"],"winner_state":"Candidate","loss_profile":{"items":[]},"proof_shapes_checked":["PS_COSMO"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}} -theorem {"id":"THS_COSMO","statement":"distributed density renormalization preserves Tolman scaling","hosts":["R_TOP","R_CALC"],"bridges":["B_COSMO"],"operators":["OPR.Cosmo"],"target_equivalence":"observational-equivalence","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_COSMO"]} -obligation {"id":"OBL_COSMO","kind":"OblAdm","description":"claim is admissible under stated assumptions","status":"Benchmarked"} -target {"id":"TGT_COSMO","burden_class":"ImportedKernelClaim","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"observational-equivalence","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"OpenBlocked","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]} -ledger {"id":"TRL_COSMO","theorem":"THS_COSMO","paths":[["B_COSMO"]],"budget":{"max_loss":1,"allow_lossy_supported":false,"require_proof":true},"losses":[],"receipts":["Trace_COSMO"],"normalized_path":["B_COSMO"]} -campaign {"id":"CPG_COSMO","theorem":"THS_COSMO","target_profile":"TGT_COSMO","route_ledger":"TRL_COSMO","obligations":["OBL_COSMO"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["cosmology-claim"]} -burden-pack {"id":"BPK_COSMO","allowed_host_cluster":["R_TOP","R_CALC"],"obligation_ids":["OBL_COSMO"],"adequacy_clause_ids":["ADQ_COSMO_EVID","ADQ_COSMO_BENCH","ADQ_COSMO_STRESS","ADQ_COSMO_CHALLENGE"],"required_proof_shape_family":"Square","route_class_constraints":[],"evidence_contract_ids":["ECT_COSMO"],"promotion_ceiling":"Certified","blocker_taxonomy":["DEvidenceContract","DBenchmarkGap","DStressGap","DChallengeGap"]} -claim-packet {"id":"CLM_COSMO","claim_class":"Kernel","authority_state":"Evidence","target_sector":"cosmology","statement":"distributed density renormalization preserves Tolman scaling","assumptions":["observed metric is density-renormalized","redshift accumulates along path"],"open_caveats":["acoustic peaks unresolved"]} -evidence-contract {"id":"ECT_COSMO","required_evidence_kinds":["derivation","observation"],"required_benchmark_roles":["TargetCase","Stress"],"requires_stress":true,"requires_challenge":true,"admissibility_thresholds":["reproducible"],"promotion_ceiling":"Certified"} -benchmark-receipt {"id":"BMR_COSMO_TARGET","claim_packet_id":"CLM_COSMO","role":"TargetCase","verdict":"Certified","metrics":{"tolman_scaling":"pass"},"reproducibility_ref":"RPK_COSMO"} -benchmark-receipt {"id":"BMR_COSMO_STRESS","claim_packet_id":"CLM_COSMO","role":"Stress","verdict":"Benchmarked","metrics":{"cmb_acoustic_peaks":"unresolved"},"reproducibility_ref":"RPK_COSMO"} -challenge-receipt {"id":"CHR_COSMO","claim_packet_id":"CLM_COSMO","grounds":["acoustic peak structure unresolved"],"required_response":"attach CMB benchmark or leave residual obligation open","status":"Open"} -reproducibility-packet {"id":"RPK_COSMO","claim_packet_id":"CLM_COSMO","derivation_path":["A1","D1","D2"],"code_refs":[],"benchmark_refs":["BMR_COSMO_TARGET","BMR_COSMO_STRESS"],"artifact_refs":["CLM_COSMO"]} -adequacy {"id":"ADQ_COSMO_EVID","kind":"EvidenceContractInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_COSMO"],"burden_pack_ids":["BPK_COSMO"],"claim_packet_ids":["CLM_COSMO"],"evidence_contract_ids":["ECT_COSMO"],"benchmark_receipt_ids":[],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_COSMO"],"description":"evidence contract present","blocking":true} -adequacy {"id":"ADQ_COSMO_BENCH","kind":"BenchmarkInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_COSMO"],"burden_pack_ids":["BPK_COSMO"],"claim_packet_ids":["CLM_COSMO"],"evidence_contract_ids":["ECT_COSMO"],"benchmark_receipt_ids":["BMR_COSMO_TARGET","BMR_COSMO_STRESS"],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_COSMO"],"description":"benchmark receipts attached","blocking":true} -adequacy {"id":"ADQ_COSMO_STRESS","kind":"StressInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_COSMO"],"burden_pack_ids":["BPK_COSMO"],"claim_packet_ids":["CLM_COSMO"],"evidence_contract_ids":["ECT_COSMO"],"benchmark_receipt_ids":["BMR_COSMO_STRESS"],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_COSMO"],"description":"stress benchmark attached","blocking":true} -adequacy {"id":"ADQ_COSMO_CHALLENGE","kind":"ChallengeInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_COSMO"],"burden_pack_ids":["BPK_COSMO"],"claim_packet_ids":["CLM_COSMO"],"evidence_contract_ids":["ECT_COSMO"],"benchmark_receipt_ids":[],"challenge_receipt_ids":["CHR_COSMO"],"reproducibility_packet_ids":["RPK_COSMO"],"description":"challenge record attached","blocking":true} -``` - -Run it: - -```powershell -l64 compile-bundle .\cosmo.locus.rna --out .\cosmo.dna -l64 certify-bundle --file .\cosmo.dna --conflict-policy exact-match -``` - -Then inspect the generated report id: - -```powershell -l64 observe-run --report REPORT_THS_COSMO_CPG_COSMO -l64 research-derive-from-report --report-id REPORT_THS_COSMO_CPG_COSMO --persist -l64 research-promotion-readiness REPORT_THS_COSMO_CPG_COSMO -``` - -## 7. ChatGPT Output Contract - -When asking ChatGPT to generate something for Locus64, ask for exactly one of: - -```text -1. A .gene.rna file body. -2. A complete bundle-entry text body that can be compiled with `l64 compile-bundle`. -3. A single bundle entry line. -4. A patch to an existing bundle-entry text body. -``` - -For semantic claims, prefer: - -```text -Generate a complete Locus64 bundle-entry text body. -Do not include comments. -Use one JSON object per line. -Include claim-packet, evidence-contract, benchmark-receipt, challenge-receipt, reproducibility-packet, adequacy, theorem, obligation, target, ledger, campaign, bridge, proof, and atlas entries. -``` - -Do not ask ChatGPT for “Locus64 prose.” Ask for valid bundle entry lines, compile them with `l64 compile-bundle`, and certify the resulting `.dna`. - -## 8. Validation Loop - -After generating bundle entry text: - -```powershell -l64 compile-bundle .\file.locus.rna --out .\file.dna -l64 certify-bundle --file .\file.dna --conflict-policy exact-match -l64 import-bundle .\file.dna --conflict-policy exact-match -``` - -If validation fails: - -- fix projection syntax first -- then regenerate the `.dna` -- then re-run certification/import checks -- then fix missing referenced ids -- then fix adequacy/evidence gaps - -## 9. Common Failure Causes - -- Missing `!l64-bundle v1` header. -- Multi-line JSON payloads. -- Wrong enum casing, e.g. `certified` instead of `Certified`. -- Referencing an id that has no entry. -- Claim has `requires_stress: true` but no `Stress` benchmark receipt. -- Claim has `requires_challenge: true` but no addressed/open challenge receipt. -- `metrics` values are not strings. -- Comments inserted into projection entry files. - -## 10. Practical Rule - -Use: - -- RNA for canonical symbolic roots. -- Bundle-entry text only as a transitional authoring convenience that must be compiled with `l64 compile-bundle`. -- DNA as the generated machine authority artifact. -- Inspection, projection, record, receipt, report, and release artifacts only in their declared non-source roles. - -Do not use QC0, QA0, QM0, or QK0 as public interaction languages. Their useful structure has been ported into RNA/DNA authority, bundle-entry authoring, inspection/projection outputs, receipts, policies, and deficiencies. - -For indirect integration, the active route is: - -```text -authored bundle-entry text --> l64 compile-bundle --> .dna bundle packet --> l64 certify-bundle / import-bundle / run-bundle -``` +RNA syntax failures carry one exact byte span `(line, column, length)`. Diagnostics render that span against the supplied source. `L64B` framing remains unchanged; sequential readers and writers are implementation carriers over the same exact ordered bytes. diff --git a/LOCUS64_LEGACY_AUTHORITY_ISLAND_DELETION_CHANGE_CHAIN.athens b/LOCUS64_LEGACY_AUTHORITY_ISLAND_DELETION_CHANGE_CHAIN.athens new file mode 100644 index 0000000..26b5515 --- /dev/null +++ b/LOCUS64_LEGACY_AUTHORITY_ISLAND_DELETION_CHANGE_CHAIN.athens @@ -0,0 +1,22 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_version;value=1 +field=key=schema_version;value=1 +field=key=restore_boundary;value=pass22-source +field=key=historical_export;value=locus64-legacy-authority-island-history-pass23-v1 +field=key=live_workspace_packages;value=10 +field=key=external_dependencies;value=0 +gate=id=historical-export-green +gate=id=legacy-island-absent-green +gate=id=native-workspace-green +stage=id=historical-export +stage_field=stage=historical-export;key=status;value=complete +stage=id=legacy-island-deletion +stage_field=stage=legacy-island-deletion;key=depends_on;value=historical-export +stage_field=stage=legacy-island-deletion;key=status;value=complete +stage=id=native-workspace-closure +stage_field=stage=native-workspace-closure;key=depends_on;value=legacy-island-deletion +stage_field=stage=native-workspace-closure;key=status;value=complete +history=evidence=local%3Aforensic-archive-plus-vault-byte-match;kind=dogfood_promotion_receipt;stage_id=historical-export +history=evidence=local%3A12-legacy-crates-plus-seed-registry-and-dispatcher-deleted;kind=dogfood_promotion_receipt;stage_id=legacy-island-deletion +history=evidence=local%3A10-package-offline-test-and-clippy-green;kind=dogfood_promotion_receipt;stage_id=native-workspace-closure +END diff --git a/LOCUS64_LEGACY_AUTHORITY_QUARANTINE_CHANGE_CHAIN.athens b/LOCUS64_LEGACY_AUTHORITY_QUARANTINE_CHANGE_CHAIN.athens new file mode 100644 index 0000000..bb50b63 --- /dev/null +++ b/LOCUS64_LEGACY_AUTHORITY_QUARANTINE_CHANGE_CHAIN.athens @@ -0,0 +1,58 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=ambient_legacy_authority;value=forbidden +field=key=default_packet_decode;value=current_authority +field=key=explicit_legacy_recovery;value=compatibility_forensic_only +field=key=legacy_upper_stack_dispatch;value=transitional +field=key=legacy_bundle_record_ingress;value=explicit_only +field=key=native_bundle_shape;value=ordered_current_dna_frames +field=key=native_bundle_composite_authority;value=none +field=key=native_certification_scope;value=native_structural_closure +field=key=native_observation_scope;value=certification_replay_report_projection +field=key=native_observation_authority;value=non_authoritative +field=key=native_bundle_composite_observation;value=none +field=key=native_change_scope;value=exact_authority_projection +field=key=native_bundle_composite_change_verdict;value=none +field=key=legacy_research_admin_json;value=explicit_compatibility_only +field=key=legacy_lineage_readiness_storage;value=deleted_after_external_export +field=key=legacy_admin_dispatch;value=explicit_only +field=key=legacy_campaign_report_observation;value=explicit_compatibility +field=key=native_bundle_composite_certificate;value=none +field=key=legacy_certification_engine;value=explicit_compatibility +field=key=native_carrier_gate;value=dependency_free +field=key=native_release_shape;value=source_authority_projection_record +field=key=rail_version;value=8 +field=key=schema_version;value=1 +gate=id=ambient-authority-rejection-green +gate=id=explicit-recovery-green +gate=id=non-authority-dispatch-green +gate=id=native-inspection-carrier-green +gate=id=native-release-carrier-green +gate=id=native-bundle-transport-green +gate=id=native-certification-carrier-green +gate=id=native-observation-carrier-green +gate=id=native-change-carrier-green +gate=id=legacy-upper-stack-classified-green +gate=id=legacy-authority-quarantine-green +stage=id=ambient-authority-ingress-cut +stage_field=stage=ambient-authority-ingress-cut;key=required_gates;value=ambient-authority-rejection-green,explicit-recovery-green,non-authority-dispatch-green +stage_field=stage=ambient-authority-ingress-cut;key=status;value=complete +stage=id=legacy-upper-stack-classification +stage_field=stage=legacy-upper-stack-classification;key=depends_on;value=ambient-authority-ingress-cut +stage_field=stage=legacy-upper-stack-classification;key=required_gates;value=legacy-upper-stack-classified-green +stage_field=stage=legacy-upper-stack-classification;key=status;value=complete +stage=id=legacy-authority-quarantine-closure +stage_field=stage=legacy-authority-quarantine-closure;key=depends_on;value=legacy-upper-stack-classification +stage_field=stage=legacy-authority-quarantine-closure;key=required_gates;value=legacy-authority-quarantine-green +stage_field=stage=legacy-authority-quarantine-closure;key=status;value=current +history=evidence=local%3Asource-cut%2Bexplicit-recovery-retained%2Bfmt-clean;kind=implementation_receipt;stage_id=ambient-authority-ingress-cut +history=evidence=local%3Adefault-decode-current-authority%2Bmigration-forensic-explicit;kind=implementation_receipt;stage_id=ambient-authority-ingress-cut +history=evidence=local%3Arustc-native-carrier%2Bsample-fixed-point%2Bverified-projection;kind=implementation_receipt;stage_id=ambient-authority-ingress-cut +history=evidence=local%3Aatomic-four-contact-native-release%2Boverwrite-refusal%2Bdependency-free-gate;kind=implementation_receipt;stage_id=legacy-upper-stack-classification +history=from_status=current;gates=ambient-authority-rejection-green,explicit-recovery-green,non-authority-dispatch-green;mode=linear_advance;stage_id=ambient-authority-ingress-cut;to_status=complete +history=evidence=local%3Al64b-exact-framing%2Bcanonical-member-validation%2Bper-member-projection-verification%2Bno-composite-authority;kind=implementation_receipt;stage_id=legacy-upper-stack-classification +history=evidence=local%3Aexact-l64d%2Ball-context-certification-projection-verification%2Bdistinct-open-incomplete-invalid%2Bindependent-l64b-member-verdicts%2Bno-composite-certificate;kind=implementation_receipt;stage_id=legacy-upper-stack-classification +history=evidence=local%3Acertification%2Breplay%2Breport-projection-verification%2Bno-persistence%2Bindependent-l64b-member-observation%2Bexplicit-legacy-campaign-report-ingress;kind=implementation_receipt;stage_id=legacy-upper-stack-classification +history=evidence=local%3Aexact-dna-change%2Bsection-and-verdict-movement%2Bindependent-l64b-member-change%2Bno-persistence%2Bexplicit-research-admin-json-ingress;kind=implementation_receipt;stage_id=legacy-upper-stack-classification +history=from_status=current;gates=legacy-upper-stack-classified-green,native-change-carrier-green;mode=linear_advance;stage_id=legacy-upper-stack-classification;to_status=complete +history=evidence=local%3Areport-derived-lineage-readiness-queue-handoff-deleted%2Bpermanent-tombstones;kind=implementation_receipt;stage_id=legacy-authority-quarantine-closure +END diff --git a/LOCUS64_LEGACY_CACHE_DELETION_CHANGE_CHAIN.athens b/LOCUS64_LEGACY_CACHE_DELETION_CHANGE_CHAIN.athens new file mode 100644 index 0000000..c60837e --- /dev/null +++ b/LOCUS64_LEGACY_CACHE_DELETION_CHANGE_CHAIN.athens @@ -0,0 +1,41 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_version;value=2 +field=key=schema_version;value=1 +field=key=authority_replacement;value=native_certification_observation_change +field=key=historical_export;value=external_archive_before_deletion +field=key=native_replacement_schema;value=none +gate=id=historical-export-green +gate=id=leaf-storage-deletion-green +gate=id=cert-cache-severance-green +gate=id=retired-ingress-green +gate=id=legacy-cache-deletion-green +stage=id=historical-export +stage_field=stage=historical-export;key=status;value=complete +stage_field=stage=historical-export;key=required_gates;value=historical-export-green +stage=id=leaf-storage-deletion +stage_field=stage=leaf-storage-deletion;key=depends_on;value=historical-export +stage_field=stage=leaf-storage-deletion;key=status;value=complete +stage_field=stage=leaf-storage-deletion;key=required_gates;value=leaf-storage-deletion-green +stage=id=cert-cache-severance +stage_field=stage=cert-cache-severance;key=depends_on;value=leaf-storage-deletion +stage_field=stage=cert-cache-severance;key=status;value=complete +stage_field=stage=cert-cache-severance;key=required_gates;value=cert-cache-severance-green +stage=id=retired-ingress +stage_field=stage=retired-ingress;key=depends_on;value=cert-cache-severance +stage_field=stage=retired-ingress;key=status;value=complete +stage_field=stage=retired-ingress;key=required_gates;value=retired-ingress-green +stage=id=legacy-cache-deletion-closure +stage_field=stage=legacy-cache-deletion-closure;key=depends_on;value=retired-ingress +stage_field=stage=legacy-cache-deletion-closure;key=status;value=complete +stage_field=stage=legacy-cache-deletion-closure;key=required_gates;value=legacy-cache-deletion-green +history=from_status=current;gates=historical-export-green;mode=linear_advance;stage_id=historical-export;to_status=complete +history=evidence=external%3Apass18-source-plus-cache-storage-history-archive;kind=dogfood_promotion_receipt;stage_id=historical-export +history=from_status=current;gates=leaf-storage-deletion-green;mode=linear_advance;stage_id=leaf-storage-deletion;to_status=complete +history=evidence=local%3Al64-admin-and-l64-observe-removed;kind=dogfood_promotion_receipt;stage_id=leaf-storage-deletion +history=from_status=current;gates=cert-cache-severance-green;mode=linear_advance;stage_id=cert-cache-severance;to_status=complete +history=evidence=local%3Acertification-always-fresh-plus-no-report-cache-writes;kind=dogfood_promotion_receipt;stage_id=cert-cache-severance +history=from_status=current;gates=retired-ingress-green;mode=linear_advance;stage_id=retired-ingress;to_status=complete +history=evidence=local%3Awrapper-and-cli-permanent-deletion-errors;kind=dogfood_promotion_receipt;stage_id=retired-ingress +history=from_status=current;gates=legacy-cache-deletion-green;mode=linear_advance;stage_id=legacy-cache-deletion-closure;to_status=complete +history=evidence=local%3Adeleted-storage-gate%2B24-package-locked-graph%2Bdependency-free-native-carrier;kind=dogfood_promotion_receipt;stage_id=legacy-cache-deletion-closure +END diff --git a/LOCUS64_LEGACY_LINEAGE_READINESS_DELETION_CHANGE_CHAIN.athens b/LOCUS64_LEGACY_LINEAGE_READINESS_DELETION_CHANGE_CHAIN.athens new file mode 100644 index 0000000..252650d --- /dev/null +++ b/LOCUS64_LEGACY_LINEAGE_READINESS_DELETION_CHANGE_CHAIN.athens @@ -0,0 +1,41 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_version;value=1 +field=key=schema_version;value=1 +field=key=authority_replacement;value=native_certification_observation_change +field=key=historical_export;value=external_archive_before_deletion +field=key=native_replacement_schema;value=none +gate=id=historical-export-green +gate=id=record-schema-deletion-green +gate=id=storage-reference-deletion-green +gate=id=retired-ingress-green +gate=id=legacy-lineage-readiness-deletion-green +stage=id=historical-export +stage_field=stage=historical-export;key=status;value=complete +stage_field=stage=historical-export;key=required_gates;value=historical-export-green +stage=id=record-schema-deletion +stage_field=stage=record-schema-deletion;key=depends_on;value=historical-export +stage_field=stage=record-schema-deletion;key=status;value=complete +stage_field=stage=record-schema-deletion;key=required_gates;value=record-schema-deletion-green +stage=id=storage-reference-deletion +stage_field=stage=storage-reference-deletion;key=depends_on;value=record-schema-deletion +stage_field=stage=storage-reference-deletion;key=status;value=complete +stage_field=stage=storage-reference-deletion;key=required_gates;value=storage-reference-deletion-green +stage=id=retired-ingress +stage_field=stage=retired-ingress;key=depends_on;value=storage-reference-deletion +stage_field=stage=retired-ingress;key=status;value=complete +stage_field=stage=retired-ingress;key=required_gates;value=retired-ingress-green +stage=id=legacy-lineage-readiness-deletion-closure +stage_field=stage=legacy-lineage-readiness-deletion-closure;key=depends_on;value=retired-ingress +stage_field=stage=legacy-lineage-readiness-deletion-closure;key=status;value=complete +stage_field=stage=legacy-lineage-readiness-deletion-closure;key=required_gates;value=legacy-lineage-readiness-deletion-green +history=from_status=current;gates=historical-export-green;mode=linear_advance;stage_id=historical-export;to_status=complete +history=evidence=external%3Apass20-source-plus-lineage-readiness-history-archive;kind=dogfood_promotion_receipt;stage_id=historical-export +history=from_status=current;gates=record-schema-deletion-green;mode=linear_advance;stage_id=record-schema-deletion;to_status=complete +history=evidence=local%3Alineage-readiness-queue-handoff-types-and-bundle-fields-removed;kind=dogfood_promotion_receipt;stage_id=record-schema-deletion +history=from_status=current;gates=storage-reference-deletion-green;mode=linear_advance;stage_id=storage-reference-deletion;to_status=complete +history=evidence=local%3Astores-constructors-status-and-synthetic-record-references-removed;kind=dogfood_promotion_receipt;stage_id=storage-reference-deletion +history=from_status=current;gates=retired-ingress-green;mode=linear_advance;stage_id=retired-ingress;to_status=complete +history=evidence=local%3Acompile-lineage-and-research-record-permanent-deletion-errors;kind=dogfood_promotion_receipt;stage_id=retired-ingress +history=from_status=current;gates=legacy-lineage-readiness-deletion-green;mode=linear_advance;stage_id=legacy-lineage-readiness-deletion-closure;to_status=complete +history=evidence=local%3Apass21-deletion-gate%2B24-package-path-graph%2Bdependency-free-native-carrier;kind=dogfood_promotion_receipt;stage_id=legacy-lineage-readiness-deletion-closure +END diff --git a/LOCUS64_LEGACY_PLAN_STORAGE_DELETION_CHANGE_CHAIN.athens b/LOCUS64_LEGACY_PLAN_STORAGE_DELETION_CHANGE_CHAIN.athens new file mode 100644 index 0000000..89afb91 --- /dev/null +++ b/LOCUS64_LEGACY_PLAN_STORAGE_DELETION_CHANGE_CHAIN.athens @@ -0,0 +1,41 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_version;value=1 +field=key=schema_version;value=1 +field=key=authority_replacement;value=native_change_plus_release_transport_certification_observation +field=key=historical_export;value=external_archive_before_deletion +field=key=native_replacement_schema;value=none +gate=id=historical-export-green +gate=id=record-schema-deletion-green +gate=id=packet-store-deletion-green +gate=id=retired-ingress-green +gate=id=legacy-plan-storage-deletion-green +stage=id=historical-export +stage_field=stage=historical-export;key=status;value=complete +stage_field=stage=historical-export;key=required_gates;value=historical-export-green +stage=id=record-schema-deletion +stage_field=stage=record-schema-deletion;key=depends_on;value=historical-export +stage_field=stage=record-schema-deletion;key=status;value=complete +stage_field=stage=record-schema-deletion;key=required_gates;value=record-schema-deletion-green +stage=id=packet-store-deletion +stage_field=stage=packet-store-deletion;key=depends_on;value=record-schema-deletion +stage_field=stage=packet-store-deletion;key=status;value=complete +stage_field=stage=packet-store-deletion;key=required_gates;value=packet-store-deletion-green +stage=id=retired-ingress +stage_field=stage=retired-ingress;key=depends_on;value=packet-store-deletion +stage_field=stage=retired-ingress;key=status;value=complete +stage_field=stage=retired-ingress;key=required_gates;value=retired-ingress-green +stage=id=legacy-plan-storage-deletion-closure +stage_field=stage=legacy-plan-storage-deletion-closure;key=depends_on;value=retired-ingress +stage_field=stage=legacy-plan-storage-deletion-closure;key=status;value=complete +stage_field=stage=legacy-plan-storage-deletion-closure;key=required_gates;value=legacy-plan-storage-deletion-green +history=from_status=current;gates=historical-export-green;mode=linear_advance;stage_id=historical-export;to_status=complete +history=evidence=external%3Apass19-source-plus-plan-lock-manifest-history-archive;kind=dogfood_promotion_receipt;stage_id=historical-export +history=from_status=current;gates=record-schema-deletion-green;mode=linear_advance;stage_id=record-schema-deletion;to_status=complete +history=evidence=local%3Aretired-record-types-plus-qa-and-registry-admission-removed;kind=dogfood_promotion_receipt;stage_id=record-schema-deletion +history=from_status=current;gates=packet-store-deletion-green;mode=linear_advance;stage_id=packet-store-deletion;to_status=complete +history=evidence=local%3Amanifest-lock-cache-paths-builders-and-enrichment-removed;kind=dogfood_promotion_receipt;stage_id=packet-store-deletion +history=from_status=current;gates=retired-ingress-green;mode=linear_advance;stage_id=retired-ingress;to_status=complete +history=evidence=local%3Awrapper-and-direct-cli-permanent-deletion-errors;kind=dogfood_promotion_receipt;stage_id=retired-ingress +history=from_status=current;gates=legacy-plan-storage-deletion-green;mode=linear_advance;stage_id=legacy-plan-storage-deletion-closure;to_status=complete +history=evidence=local%3Alegacy-plan-storage-deletion-gate%2B24-package-path-graph%2Bdependency-free-native-carrier;kind=dogfood_promotion_receipt;stage_id=legacy-plan-storage-deletion-closure +END diff --git a/LOCUS64_LEGACY_REGISTRY_OVERLAY_POLICY_DELETION_CHANGE_CHAIN.athens b/LOCUS64_LEGACY_REGISTRY_OVERLAY_POLICY_DELETION_CHANGE_CHAIN.athens new file mode 100644 index 0000000..549a93a --- /dev/null +++ b/LOCUS64_LEGACY_REGISTRY_OVERLAY_POLICY_DELETION_CHANGE_CHAIN.athens @@ -0,0 +1,48 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_version;value=1 +field=key=schema_version;value=1 +field=key=authority_replacement;value=native_transport_plus_direct_execution +field=key=historical_export;value=external_archive_before_deletion +field=key=native_replacement_schema;value=none +gate=id=historical-export-green +gate=id=overlay-crate-deletion-green +gate=id=policy-admission-deletion-green +gate=id=direct-execution-green +gate=id=retired-ingress-green +gate=id=legacy-registry-overlay-policy-deletion-green +stage=id=historical-export +stage_field=stage=historical-export;key=status;value=complete +stage_field=stage=historical-export;key=required_gates;value=historical-export-green +stage=id=overlay-crate-deletion +stage_field=stage=overlay-crate-deletion;key=depends_on;value=historical-export +stage_field=stage=overlay-crate-deletion;key=status;value=complete +stage_field=stage=overlay-crate-deletion;key=required_gates;value=overlay-crate-deletion-green +stage=id=policy-admission-deletion +stage_field=stage=policy-admission-deletion;key=depends_on;value=overlay-crate-deletion +stage_field=stage=policy-admission-deletion;key=status;value=complete +stage_field=stage=policy-admission-deletion;key=required_gates;value=policy-admission-deletion-green +stage=id=direct-execution +stage_field=stage=direct-execution;key=depends_on;value=policy-admission-deletion +stage_field=stage=direct-execution;key=status;value=complete +stage_field=stage=direct-execution;key=required_gates;value=direct-execution-green +stage=id=retired-ingress +stage_field=stage=retired-ingress;key=depends_on;value=direct-execution +stage_field=stage=retired-ingress;key=status;value=complete +stage_field=stage=retired-ingress;key=required_gates;value=retired-ingress-green +stage=id=legacy-registry-overlay-policy-deletion-closure +stage_field=stage=legacy-registry-overlay-policy-deletion-closure;key=depends_on;value=retired-ingress +stage_field=stage=legacy-registry-overlay-policy-deletion-closure;key=status;value=complete +stage_field=stage=legacy-registry-overlay-policy-deletion-closure;key=required_gates;value=legacy-registry-overlay-policy-deletion-green +history=from_status=current;gates=historical-export-green;mode=linear_advance;stage_id=historical-export;to_status=complete +history=evidence=external%3Apass21-source-plus-registry-overlay-policy-history-archive;kind=dogfood_promotion_receipt;stage_id=historical-export +history=from_status=current;gates=overlay-crate-deletion-green;mode=linear_advance;stage_id=overlay-crate-deletion;to_status=complete +history=evidence=local%3Al64-bundle-plus-BundleWorld-overlay-cache-and-merge-removed;kind=dogfood_promotion_receipt;stage_id=overlay-crate-deletion +history=from_status=current;gates=policy-admission-deletion-green;mode=linear_advance;stage_id=policy-admission-deletion;to_status=complete +history=evidence=local%3Al64-policy-plus-policy-object-binding-resolution-and-seed-admission-removed;kind=dogfood_promotion_receipt;stage_id=policy-admission-deletion +history=from_status=current;gates=direct-execution-green;mode=linear_advance;stage_id=direct-execution;to_status=complete +history=evidence=local%3Adirect-in-process-execution-profile-without-policy-records;kind=dogfood_promotion_receipt;stage_id=direct-execution +history=from_status=current;gates=retired-ingress-green;mode=linear_advance;stage_id=retired-ingress;to_status=complete +history=evidence=local%3Aoverlay-and-policy-arguments-permanently-rejected;kind=dogfood_promotion_receipt;stage_id=retired-ingress +history=from_status=current;gates=legacy-registry-overlay-policy-deletion-green;mode=linear_advance;stage_id=legacy-registry-overlay-policy-deletion-closure;to_status=complete +history=evidence=local%3Apass22-deletion-gate%2B22-package-path-graph%2Bdependency-free-native-carrier;kind=dogfood_promotion_receipt;stage_id=legacy-registry-overlay-policy-deletion-closure +END diff --git a/LOCUS64_NATIVE_CLI_HARDENING_CHANGE_CHAIN.athens b/LOCUS64_NATIVE_CLI_HARDENING_CHANGE_CHAIN.athens new file mode 100644 index 0000000..0a45518 --- /dev/null +++ b/LOCUS64_NATIVE_CLI_HARDENING_CHANGE_CHAIN.athens @@ -0,0 +1,35 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_id;value=locus64-native-cli-hardening-pass25 +field=key=rail_version;value=1 +field=key=schema_version;value=1 +field=key=restore_boundary;value=pass24-source-archive +field=key=authority_effect;value=none +field=key=operator_boundary;value=direct-current-native-commands +field=key=output_policy;value=atomic-create-new-no-overwrite +field=key=diagnostic_policy;value=stable-display-no-debug-enums +field=key=compatibility_fallback;value=none +gate=id=direct-dispatch-green +gate=id=stable-diagnostics-green +gate=id=atomic-output-green +gate=id=command-discovery-green +gate=id=workspace-green +stage=id=direct-dispatch +stage_field=stage=direct-dispatch;key=status;value=complete +stage_field=stage=direct-dispatch;key=evidence;value=scripts/verify-cli-hardening.sh +stage=id=stable-diagnostics +stage_field=stage=stable-diagnostics;key=depends_on;value=direct-dispatch +stage_field=stage=stable-diagnostics;key=status;value=complete +stage_field=stage=stable-diagnostics;key=evidence;value=public-error-display-implementations-plus-malformed-input-gate +stage=id=atomic-output +stage_field=stage=atomic-output;key=depends_on;value=stable-diagnostics +stage_field=stage=atomic-output;key=status;value=complete +stage_field=stage=atomic-output;key=evidence;value=create-new-stage-sync-hard-link-promotion-plus-overwrite-regression +stage=id=command-discovery +stage_field=stage=command-discovery;key=depends_on;value=atomic-output +stage_field=stage=command-discovery;key=status;value=complete +stage_field=stage=command-discovery;key=evidence;value=help-command-help-version-regressions +stage=id=workspace-closure +stage_field=stage=workspace-closure;key=depends_on;value=command-discovery +stage_field=stage=workspace-closure;key=status;value=complete +stage_field=stage=workspace-closure;key=evidence;value=offline-tests-clippy-native-demo-cli-hardening-gate +END diff --git a/LOCUS64_NATIVE_CONSTITUTION.md b/LOCUS64_NATIVE_CONSTITUTION.md new file mode 100644 index 0000000..15edfc4 --- /dev/null +++ b/LOCUS64_NATIVE_CONSTITUTION.md @@ -0,0 +1,121 @@ +--- +document_status: current +constitution_scope: live dependency-free native workspace +workspace_packages: 11 +external_dependencies: 0 +--- + +# Locus64 Native Constitution + +This is the current architecture law for the live Locus64 workspace. It is derived from current code, wire formats, product gates, and direct command behavior. Historical laws remain recoverable in [`LOCUS64_HISTORICAL_LAW_LEDGER.md`](LOCUS64_HISTORICAL_LAW_LEDGER.md), but they cannot authorize current behavior. + +## 1. Authority + +1. Canonical `L64R1` RNA and canonical `L64D` DNA are the only source-authority surfaces. +2. Positive authority equality is exact equality of the domain-qualified canonical representation. A compact symbolic seal may prove fast inequality, but a matching seal never proves equality. +3. Canonical decoding must revalidate structure, contexts, constraints, equality evidence, operation law, ordering, framing, and exact re-encoding before authority is accepted. +4. Admission is transactional: a failed transition does not mutate authority, context, route indexes, or journal state. +5. Names, projections, reports, process codes, CLI formatting, caches, package topology, and historical ledgers are not authority. + +Evidence: `l64-symbolic`, `l64-native`, `scripts/verify-native-carrier.sh`, full locked-offline workspace tests. + +## 2. Native structure and proof + +1. Routes, nodes, ports, contexts, constraints, judgments, witnesses, obligations, and the transition journal share one native graph authority. +2. Dimensions and guarded operations are checked at admission. Proven guards receive native evidence; refuted guards reject; unresolved guards create native obligations. +3. Equality is proof-producing and context-scoped. Reflexivity, exact identity, symmetry, transitivity, and congruence are re-executed during decode. +4. Equivalence classes, representative caches, reverse indexes, route indexes, and closure memoization are derived accelerators. They do not serialize into RNA or DNA and do not participate in authority identity. +5. Closure is context-relative and may be `Closed`, `Open`, or `Invalid`; assumption changes create child-context refinements rather than rewriting prior authority. + +Evidence: `LOCUS64_CONSTRAINT_CORE_CHANGE_CHAIN.athens`, `LOCUS64_PROOF_CONGRUENCE_CHANGE_CHAIN.athens`, `LOCUS64_INCREMENTAL_CLOSURE_CHANGE_CHAIN.athens`. + +## 3. Transport + +1. `L64B` is an ordered frame of exact canonical `L64D` members. +2. A bundle preserves order and member boundaries but creates no composite authority, certificate, observation, change verdict, registry, name resolution, overlay, or conflict policy. +3. Bundle readers and writers process members sequentially so transport scale does not require retaining the complete bundle and all decoded graphs simultaneously. + +Evidence: `l64-transport`, `scripts/verify-native-carrier.sh`, `scripts/verify-process-contract.sh`. + +## 4. Execution and derivation + +1. `l64-execution` evaluates canonical RNA or DNA directly and non-persistently. +2. Execution does not mutate authority, invent runtime authority, or persist scheduler state. +3. Projection, certification, observation, and change are verified read-only derivatives over exact authority. +4. Fresh in-process projections may be trusted by construction only inside the deriving operation. Retained or externally supplied projections require explicit rederive-and-compare verification. +5. Certification scope is structural and context-local. It cannot silently broaden into theorem truth, campaign truth, policy truth, or external truth. + +Evidence: `l64-projection`, `l64-execution`, `l64-certification`, `l64-observation`, `l64-change`, current native carrier gates. + +## 5. Release + +1. A native release contains exactly four direct contacts: canonical RNA, canonical DNA, one verified projection, and one small release record binding them. +2. Release rendering does not create a second authority schema. +3. File-producing commands stage output atomically and refuse to overwrite an existing destination. + +Evidence: `l64-release`, `scripts/verify-native-carrier.sh`, `scripts/verify-cli-hardening.sh`. + +## 6. Command surfaces + +1. `l64-cli` owns the complete native command grammar and executes every current authoring, execution, derivation, transport, and release command directly. +2. `l64` is a small sibling-binary wrapper. It adds only `authority-audit`; every other argument vector is forwarded unchanged to the colocated `l64-cli`, and the exact child exit code is preserved. +3. The wrapper is not a second dispatcher, parser, authority layer, fallback membrane, or compatibility runtime. +4. Wrong carrier formats fail at the requested command contact. Dead commands remain permanent tombstones and cannot route to executable compatibility behavior. +5. Process results are projections over completed computation: `0` success/certified, `10` open, `11` incomplete, `12` invalid, and `2` usage/input/filesystem/processing failure. + +Evidence: `l64-cli`, `l64`, `LOCUS64_LANGUAGE_SPEC.md`, `scripts/verify-cli-hardening.sh`, `scripts/verify-process-contract.sh`. + +## 7. Historical boundary + +1. The legacy theorem, campaign, research, registry, tower, packet, policy, cache, planning, administration, and compatibility execution island was externally recovered and deleted. +2. No live compatibility dispatcher remains. The token `legacy` is a rejection tombstone only. +3. Historical documents may preserve deleted models when explicitly marked `document_status: historical`; they cannot be used as current source-of-truth without current-code verification. +4. Reintroducing a deleted authority contact requires a new explicit authority law and proof. Historical familiarity is not evidence. + +Evidence: `LOCUS64_LEGACY_AUTHORITY_ISLAND_DELETION_CHANGE_CHAIN.athens`, `scripts/verify-legacy-authority-island-deletion.sh`. + +## 8. Scale and performance + +1. Performance changes require a measured structural cause. +2. Optimization may remove repeated derivation, allocation, scanning, or transient journaling only when exact authority, wire bytes, member order, verdict law, stale/forged projection rejection, and public mutation semantics remain unchanged. +3. Canonical source compilation may bulk-construct and derive the final state once; public graph mutation remains fully tracked. +4. No generic digest service, schema router, cache bureaucracy, or alternate graph may be introduced to conceal local work. +5. The live workspace contains eleven packages, zero external Rust dependencies, and must remain buildable and testable with locked offline Cargo. + +Evidence: `LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens`, `scripts/verify-native-scale.sh`, full workspace tests and Clippy. + +## 9. Documentation law + +1. Current-facing documentation must reconstruct the live package graph, command surface, authority boundary, process law, and deletion state. +2. Historical material must be visibly historical before its first substantive claim. +3. Current scripts may not invoke deleted crates or removed commands. +4. Every command listed in the native language specification must appear in live CLI help, except the wrapper-local `authority-audit`, which must execute through `l64` only. +5. Documentation validation must remain a direct contact check over files, Cargo membership, and live help. It may not become a document registry or a parallel architecture database. + +Evidence: `LOCUS64_DOCUMENTATION_COHERENCE_CHANGE_CHAIN.athens`, `scripts/verify-documentation-coherence.sh`. + +## 10. Golden workload and portability law + +1. Representative workload snapshots are executable compatibility evidence, not authority. +2. Canonical RNA, canonical DNA bytes, stable derivative text, verdict status, ordered transport behavior, and native release contents must remain identical across supported hosts unless their governing law is deliberately changed. +3. LF and CRLF textual inputs must normalize to the same LF canonical RNA and exact DNA. +4. Valid paths containing spaces and Unicode must pass through native path contacts without lossy string conversion. +5. The dependency-free Rust workspace must execute its complete tests on Linux, macOS, and Windows. Host-specific shell orchestration cannot become a runtime dependency. +6. Each successful host execution must emit one machine-readable receipt bound to the exact source commit; the three-host set must be verified as one source before portability is called closed. +7. Portability receipts are external execution evidence only. They cannot enter native authority, transport, runtime persistence, certification, observation, or change. +8. A golden snapshot may block accidental drift but cannot promote a new authority law by itself. + +Evidence: `LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md`, `LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md`, `l64-cli/src/golden_tests.rs`, `scripts/verify-golden-portability.sh`, `scripts/verify-portability-receipts.sh`, host-matrix CI artifacts. + +## 11. Promotion law + +A new architectural law becomes current only when: + +1. the operational contact it governs is named; +2. executable evidence is identified; +3. the change preserves or explicitly replaces every dependent law; +4. the relevant direct gate passes; +5. full locked-offline workspace tests and Clippy pass; +6. current-facing documentation and the historical ledger are updated in the same change. + +Documentation alone cannot promote behavior. Passing code alone cannot leave contradictory current documentation behind. diff --git a/LOCUS64_NATIVE_EXECUTION_CHANGE_CHAIN.athens b/LOCUS64_NATIVE_EXECUTION_CHANGE_CHAIN.athens new file mode 100644 index 0000000..a76b28e --- /dev/null +++ b/LOCUS64_NATIVE_EXECUTION_CHANGE_CHAIN.athens @@ -0,0 +1,21 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_version;value=1 +field=key=schema_version;value=1 +field=key=authority_mutation;value=none +field=key=persistence;value=none +field=key=bundle_composite_execution;value=none +gate=id=execution-carrier-green +gate=id=execution-cli-green +gate=id=execution-demo-green +stage=id=single-authority-execution +stage_field=stage=single-authority-execution;key=status;value=complete +stage=id=bundle-member-reuse +stage_field=stage=bundle-member-reuse;key=depends_on;value=single-authority-execution +stage_field=stage=bundle-member-reuse;key=status;value=complete +stage=id=end-to-end-demo +stage_field=stage=end-to-end-demo;key=depends_on;value=bundle-member-reuse +stage_field=stage=end-to-end-demo;key=status;value=complete +history=evidence=local%3Arun-rna-run-dna-same-symbol-fixed-point-projection-certification;kind=dogfood_promotion_receipt;stage_id=single-authority-execution +history=evidence=local%3Atransport-reuses-authority-execution-per-member-no-composite-execution;kind=dogfood_promotion_receipt;stage_id=bundle-member-reuse +history=evidence=local%3Aoffline-release-build-plus-two-authority-demo-output;kind=dogfood_promotion_receipt;stage_id=end-to-end-demo +END diff --git a/LOCUS64_NATIVE_PROCESS_CONTRACT_CHANGE_CHAIN.athens b/LOCUS64_NATIVE_PROCESS_CONTRACT_CHANGE_CHAIN.athens new file mode 100644 index 0000000..295e2fb --- /dev/null +++ b/LOCUS64_NATIVE_PROCESS_CONTRACT_CHANGE_CHAIN.athens @@ -0,0 +1,30 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_id;value=locus64-native-process-contract-pass26 +field=key=rail_version;value=1 +field=key=schema_version;value=1 +field=key=restore_boundary;value=pass25-source-archive +field=key=authority_effect;value=none +field=key=process_projection;value=certified-0-open-10-incomplete-11-invalid-12-operational-error-2 +field=key=rna_diagnostic;value=exact-line-column-length-source-caret +field=key=bundle_memory;value=one-member-plus-one-graph +field=key=bundle_authority;value=member-local-only +gate=id=verdict-status-green +gate=id=rna-span-green +gate=id=streaming-transport-green +gate=id=workspace-green +stage=id=verdict-status +stage_field=stage=verdict-status;key=status;value=complete +stage_field=stage=verdict-status;key=evidence;value=scripts/verify-process-contract.sh +stage=id=rna-span +stage_field=stage=rna-span;key=depends_on;value=verdict-status +stage_field=stage=rna-span;key=status;value=complete +stage_field=stage=rna-span;key=evidence;value=rna_diagnostic_renders_exact_token_span-plus-malformed-cli-gate +stage=id=streaming-transport +stage_field=stage=streaming-transport;key=depends_on;value=rna-span +stage_field=stage=streaming-transport;key=status;value=complete +stage_field=stage=streaming-transport;key=evidence;value=BundleDecoder-plus-BundleEncoder-plus-streaming-memory-tests +stage=id=workspace-closure +stage_field=stage=workspace-closure;key=depends_on;value=streaming-transport +stage_field=stage=workspace-closure;key=status;value=complete +stage_field=stage=workspace-closure;key=evidence;value=offline-tests-clippy-native-carrier-process-contract-gates +END diff --git a/LOCUS64_NATIVE_RAIL.athens b/LOCUS64_NATIVE_RAIL.athens new file mode 100644 index 0000000..7d4ce78 --- /dev/null +++ b/LOCUS64_NATIVE_RAIL.athens @@ -0,0 +1,25 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=projection_authority;value=non_authoritative +field=key=rail_version;value=8 +field=key=schema_version;value=1 +gate=id=legacy-demotion-green +gate=id=native-cli-membrane-green +gate=id=native-rna-pilot-green +stage=id=native-rna-pilot +stage_field=stage=native-rna-pilot;key=required_gates;value=native-rna-pilot-green +stage_field=stage=native-rna-pilot;key=status;value=complete +stage=id=native-cli-membrane +stage_field=stage=native-cli-membrane;key=depends_on;value=native-rna-pilot +stage_field=stage=native-cli-membrane;key=required_gates;value=native-cli-membrane-green +stage_field=stage=native-cli-membrane;key=status;value=complete +stage=id=legacy-demotion +stage_field=stage=legacy-demotion;key=depends_on;value=native-cli-membrane +stage_field=stage=legacy-demotion;key=required_gates;value=legacy-demotion-green +stage_field=stage=legacy-demotion;key=status;value=complete +history=from_status=current;gates=native-rna-pilot-green;mode=linear_advance;stage_id=native-rna-pilot;to_status=complete +history=evidence=github-ad80a8c344a92a857170994ac0dd0f52a41abfc5-run-29982693189;kind=dogfood_promotion_receipt;stage_id=native-rna-pilot +history=from_status=current;gates=native-cli-membrane-green;mode=linear_advance;stage_id=native-cli-membrane;to_status=complete +history=evidence=github-4c2a5fcaa50400e08e421c4a16ee55b662728fd4-run-29983336925;kind=dogfood_promotion_receipt;stage_id=native-cli-membrane +history=from_status=current;gates=legacy-demotion-green;mode=linear_advance;stage_id=legacy-demotion;to_status=complete +history=evidence=github-ce1dd6a3713d0dfaa3daf27b20e99116ebcc67aa-run-29983720943;kind=dogfood_promotion_receipt;stage_id=legacy-demotion +END diff --git a/LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens b/LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens new file mode 100644 index 0000000..c32d094 --- /dev/null +++ b/LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens @@ -0,0 +1,41 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=rail_id;value=locus64-native-scale-pass27 +field=key=rail_version;value=1 +field=key=schema_version;value=1 +field=key=restore_boundary;value=pass26-source-archive +field=key=authority_effect;value=none +field=key=optimization_law;value=measured-hot-paths-only +field=key=rna_construction;value=bulk-final-symbol-once +field=key=route_lookup;value=exact-per-node-index +field=key=closure_analysis;value=one-context-memo +field=key=equality_projection;value=edge-local +field=key=fresh_projection_validation;value=verified-by-construction +field=key=retained_projection_validation;value=explicit-rederive-and-compare +field=key=external_dependencies;value=none +gate=id=bulk-rna-green +gate=id=indexed-route-green +gate=id=shared-closure-green +gate=id=edge-local-equality-green +gate=id=fresh-derivation-green +gate=id=scale-workload-green +gate=id=workspace-green +stage=id=profile-baseline +stage_field=stage=profile-baseline;key=status;value=complete +stage_field=stage=profile-baseline;key=evidence;value=500-atoms-3.17s-plus-1000-atoms-12.78s-plus-100k-timeout +stage=id=bulk-rna +stage_field=stage=bulk-rna;key=depends_on;value=profile-baseline +stage_field=stage=bulk-rna;key=status;value=complete +stage_field=stage=bulk-rna;key=evidence;value=Graph-new_bulk-finish_bulk-plus-zero-journal-fixed-point-test +stage=id=indexed-native-analysis +stage_field=stage=indexed-native-analysis;key=depends_on;value=bulk-rna +stage_field=stage=indexed-native-analysis;key=status;value=complete +stage_field=stage=indexed-native-analysis;key=evidence;value=primary-route-index-plus-context-closure-analysis-plus-edge-local-equality +stage=id=projection-execution-deduplication +stage_field=stage=projection-execution-deduplication;key=depends_on;value=indexed-native-analysis +stage_field=stage=projection-execution-deduplication;key=status;value=complete +stage_field=stage=projection-execution-deduplication;key=evidence;value=fresh-derived-projections-not-immediately-rederived-plus-retained-stale-rejection-tests +stage=id=scale-closure +stage_field=stage=scale-closure;key=depends_on;value=projection-execution-deduplication +stage_field=stage=scale-closure;key=status;value=complete +stage_field=stage=scale-closure;key=evidence;value=scripts/verify-native-scale.sh-plus-offline-workspace-tests-clippy-plus-profile-corpus +END diff --git a/LOCUS64_NATIVE_UPPER_PROJECTION_CHANGE_CHAIN.athens b/LOCUS64_NATIVE_UPPER_PROJECTION_CHANGE_CHAIN.athens new file mode 100644 index 0000000..c5f3344 --- /dev/null +++ b/LOCUS64_NATIVE_UPPER_PROJECTION_CHANGE_CHAIN.athens @@ -0,0 +1,60 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=projection_authority;value=non_authoritative +field=key=rail_version;value=2 +field=key=schema_version;value=1 +gate=id=projection-contract-green +gate=id=read-only-query-green +gate=id=atlas-view-green +gate=id=certification-view-green +gate=id=replay-view-green +gate=id=report-research-view-green +gate=id=deterministic-regeneration-green +gate=id=native-upper-projection-green +stage=id=projection-contract +stage_field=stage=projection-contract;key=required_gates;value=projection-contract-green +stage_field=stage=projection-contract;key=status;value=complete +stage=id=read-only-native-query +stage_field=stage=read-only-native-query;key=depends_on;value=projection-contract +stage_field=stage=read-only-native-query;key=required_gates;value=read-only-query-green +stage_field=stage=read-only-native-query;key=status;value=complete +stage=id=atlas-candidate-view +stage_field=stage=atlas-candidate-view;key=depends_on;value=read-only-native-query +stage_field=stage=atlas-candidate-view;key=required_gates;value=atlas-view-green +stage_field=stage=atlas-candidate-view;key=status;value=complete +stage=id=certification-burden-view +stage_field=stage=certification-burden-view;key=depends_on;value=atlas-candidate-view +stage_field=stage=certification-burden-view;key=required_gates;value=certification-view-green +stage_field=stage=certification-burden-view;key=status;value=complete +stage=id=replay-causal-view +stage_field=stage=replay-causal-view;key=depends_on;value=certification-burden-view +stage_field=stage=replay-causal-view;key=required_gates;value=replay-view-green +stage_field=stage=replay-causal-view;key=status;value=complete +stage=id=report-research-view +stage_field=stage=report-research-view;key=depends_on;value=replay-causal-view +stage_field=stage=report-research-view;key=required_gates;value=report-research-view-green +stage_field=stage=report-research-view;key=status;value=complete +stage=id=deterministic-regeneration +stage_field=stage=deterministic-regeneration;key=depends_on;value=report-research-view +stage_field=stage=deterministic-regeneration;key=required_gates;value=deterministic-regeneration-green +stage_field=stage=deterministic-regeneration;key=status;value=complete +stage=id=native-upper-projection-closure +stage_field=stage=native-upper-projection-closure;key=depends_on;value=deterministic-regeneration +stage_field=stage=native-upper-projection-closure;key=required_gates;value=native-upper-projection-green +stage_field=stage=native-upper-projection-closure;key=status;value=complete +history=from_status=current;gates=projection-contract-green;mode=linear_advance;stage_id=projection-contract;to_status=complete +history=evidence=local%3Aprojection-source-binding%2Bnonmutation%2Bno-storage%2Bsingle-native-dependency;kind=dogfood_promotion_receipt;stage_id=projection-contract +history=from_status=current;gates=read-only-query-green;mode=linear_advance;stage_id=read-only-native-query;to_status=complete +history=evidence=local%3Acontext%2Bvisible-node%2Broute%2Bequality-evidence-read-surface;kind=dogfood_promotion_receipt;stage_id=read-only-native-query +history=from_status=current;gates=atlas-view-green;mode=linear_advance;stage_id=atlas-candidate-view;to_status=complete +history=evidence=local%3Atyped-operation-and-equality-candidates%2Bnative-route-resolution;kind=dogfood_promotion_receipt;stage_id=atlas-candidate-view +history=from_status=current;gates=certification-view-green;mode=linear_advance;stage_id=certification-burden-view;to_status=complete +history=evidence=local%3Aclosed-open-invalid%2Bcontext-discharge-without-authority-rewrite;kind=dogfood_promotion_receipt;stage_id=certification-burden-view +history=from_status=current;gates=replay-view-green;mode=linear_advance;stage_id=replay-causal-view;to_status=complete +history=evidence=local%3Ajournal-bound-replay%2Bsource-route-causality%2Bjournal-divergence-rejection;kind=dogfood_promotion_receipt;stage_id=replay-causal-view +history=from_status=current;gates=report-research-view-green;mode=linear_advance;stage_id=report-research-view;to_status=complete +history=evidence=local%3Adeterministic-counts%2Bobligation-and-invalid-routes%2Baffected-set-ranking;kind=dogfood_promotion_receipt;stage_id=report-research-view +history=from_status=current;gates=deterministic-regeneration-green;mode=linear_advance;stage_id=deterministic-regeneration;to_status=complete +history=evidence=local%3A56-tests%2Bstrict-clippy%2Bformat%2Blive-projection-execution%2Bforged-and-stale-rejection;kind=dogfood_promotion_receipt;stage_id=deterministic-regeneration +history=from_status=current;gates=native-upper-projection-green;mode=linear_advance;stage_id=native-upper-projection-closure;to_status=complete +history=evidence=github-0ad8acc52f35362262c383efd02cc455e6778489-run-30139859138;kind=dogfood_promotion_receipt;stage_id=native-upper-projection-closure +END diff --git a/LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md b/LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md new file mode 100644 index 0000000..07cce0a --- /dev/null +++ b/LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md @@ -0,0 +1,39 @@ +--- +document_status: current +contract_scope: source-bound remote portability evidence +receipt_schema: L64PORT1 +--- + +# Locus64 Portability Receipt Contract + +The host matrix proves portability only when each runner emits a machine-readable receipt bound to the exact source commit it tested. Workflow configuration and transient logs are not substitutes for retained evidence. + +## Receipt law + +Each successful host produces exactly one `L64PORT1` JSON receipt containing: + +- the exact Git commit in `source_ref`; +- repository, workflow-run, and attempt coordinates; +- the declared GitHub runner label; +- the actual Rust host triple, `rustc`, and Cargo versions; +- the live Cargo-derived package count; +- the external-dependency count; +- the exact test command and a `passed` result. + +The supported set is exactly: + +- `ubuntu-latest`; +- `macos-latest`; +- `windows-latest`. + +A combined verifier accepts the set only when all three receipts exist, bind the same source, retain eleven workspace packages, retain zero external Rust dependencies, and report the complete locked-offline workspace test as passed. + +## Authority boundary + +A portability receipt is execution evidence. It is not mathematical authority, canonical RNA, canonical DNA, a transport member, a runtime registry, or a substitute for exact product outputs. It may prove that a named source executed on a named host; it cannot promote behavior or change authority law. + +## Direct contacts + +- `scripts/write-portability-receipt.sh` writes one receipt after a successful host test. +- `scripts/verify-portability-receipts.sh` verifies the exact three-host set and provides a local self-test. +- `.github/workflows/native-core.yml` uploads each host receipt, combines the three artifacts, verifies the common source, and uploads the accepted set. diff --git a/LOCUS64_PROOF_CONGRUENCE_CHANGE_CHAIN.athens b/LOCUS64_PROOF_CONGRUENCE_CHANGE_CHAIN.athens new file mode 100644 index 0000000..5447b02 --- /dev/null +++ b/LOCUS64_PROOF_CONGRUENCE_CHANGE_CHAIN.athens @@ -0,0 +1,46 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=projection_authority;value=non_authoritative +field=key=rail_version;value=7 +field=key=schema_version;value=1 +gate=id=canonical-representative-green +gate=id=congruence-lifting-green +gate=id=equality-judgment-green +gate=id=evidence-path-validation-green +gate=id=forged-merge-closure-green +gate=id=primitive-equality-witness-green +stage=id=equality-judgment +stage_field=stage=equality-judgment;key=required_gates;value=equality-judgment-green +stage_field=stage=equality-judgment;key=status;value=complete +stage=id=primitive-equality-witness +stage_field=stage=primitive-equality-witness;key=depends_on;value=equality-judgment +stage_field=stage=primitive-equality-witness;key=required_gates;value=primitive-equality-witness-green +stage_field=stage=primitive-equality-witness;key=status;value=complete +stage=id=congruence-lifting +stage_field=stage=congruence-lifting;key=depends_on;value=primitive-equality-witness +stage_field=stage=congruence-lifting;key=required_gates;value=congruence-lifting-green +stage_field=stage=congruence-lifting;key=status;value=complete +stage=id=evidence-path-validation +stage_field=stage=evidence-path-validation;key=depends_on;value=congruence-lifting +stage_field=stage=evidence-path-validation;key=required_gates;value=evidence-path-validation-green +stage_field=stage=evidence-path-validation;key=status;value=complete +stage=id=canonical-representative +stage_field=stage=canonical-representative;key=depends_on;value=evidence-path-validation +stage_field=stage=canonical-representative;key=required_gates;value=canonical-representative-green +stage_field=stage=canonical-representative;key=status;value=complete +stage=id=forged-merge-closure +stage_field=stage=forged-merge-closure;key=depends_on;value=canonical-representative +stage_field=stage=forged-merge-closure;key=required_gates;value=forged-merge-closure-green +stage_field=stage=forged-merge-closure;key=status;value=complete +history=from_status=current;gates=equality-judgment-green;mode=linear_advance;stage_id=equality-judgment;to_status=complete +history=evidence=local%3A41-tests%3Btyped-equality-judgment%2Battached-witness;kind=dogfood_promotion_receipt;stage_id=equality-judgment +history=from_status=current;gates=primitive-equality-witness-green;mode=linear_advance;stage_id=primitive-equality-witness;to_status=complete +history=evidence=local%3A41-tests%3Breflexive%2Bstructural%2Bsymmetry%2Btransitivity;kind=dogfood_promotion_receipt;stage_id=primitive-equality-witness +history=from_status=current;gates=congruence-lifting-green;mode=linear_advance;stage_id=congruence-lifting;to_status=complete +history=evidence=local%3A41-tests%3Bconstructor%2Boperation-congruence;kind=dogfood_promotion_receipt;stage_id=congruence-lifting +history=from_status=current;gates=evidence-path-validation-green;mode=linear_advance;stage_id=evidence-path-validation;to_status=complete +history=evidence=local%3A41-tests%3Bdeterministic-path%2Bcontext-scope%2Bdecode-recheck;kind=dogfood_promotion_receipt;stage_id=evidence-path-validation +history=from_status=current;gates=canonical-representative-green;mode=linear_advance;stage_id=canonical-representative;to_status=complete +history=evidence=local%3A41-tests%3Broute-minimal-representative-no-persisted-index;kind=dogfood_promotion_receipt;stage_id=canonical-representative +history=from_status=current;gates=forged-merge-closure-green;mode=linear_advance;stage_id=forged-merge-closure;to_status=complete +history=evidence=github-0a84bdd3dc232a0db1b79009c3bf99cfd4fb40cd-run-29997066639;kind=dogfood_promotion_receipt;stage_id=forged-merge-closure +END diff --git a/LOCUS64_RESEARCH_ADMIN_CLASSIFICATION.md b/LOCUS64_RESEARCH_ADMIN_CLASSIFICATION.md new file mode 100644 index 0000000..486b897 --- /dev/null +++ b/LOCUS64_RESEARCH_ADMIN_CLASSIFICATION.md @@ -0,0 +1,11 @@ +# Research and Administration Classification + +All legacy research, registry, producer-host, tower, theorem, campaign, policy, overlay, cache, planning, lineage, readiness, and administration stores are deleted from the live workspace. + +Productive contacts are carried directly by current native authority, certification, observation, and change. Historical implementations exist only in the Pass 19–23 forensic archives. No live import, export, registry admission, campaign execution, compatibility dispatcher, or legacy torture harness remains. + +## Current boundary through Pass 30 + +Passes 24–30 introduced no research or administration authority. Native execution, CLI hardening, process statuses, RNA spans, sequential transport, measured scale, documentation coherence, golden workloads, and source-bound portability receipts are direct product or verification contacts. They are non-persistent and create no research host, registry, queue, policy world, receipt registry, or composite authority. + +The `L64PORT1` portability files are external execution evidence bound to a source commit. They do not enter RNA, DNA, transport, certification, observation, change, or runtime state. diff --git a/LOCUS64_RESIDUE_REMOTE_PROOF_CHANGE_CHAIN.athens b/LOCUS64_RESIDUE_REMOTE_PROOF_CHANGE_CHAIN.athens new file mode 100644 index 0000000..5d9b15a --- /dev/null +++ b/LOCUS64_RESIDUE_REMOTE_PROOF_CHANGE_CHAIN.athens @@ -0,0 +1,19 @@ +ATHENS_CHANGE_CHAIN v1 +field=key=pass;value=30 +field=key=name;value=residue-and-remote-proof-closure +field=key=authority_effect;value=none +field=key=wire_effect;value=none +field=key=runtime_effect;value=none +field=key=document_status;value=current +stage=id=legacy-script-residue;status=complete;effect=dead_torture_harness_removed_from_live_source_and_preserved_forensically +stage=id=current-document-residue;status=complete;effect=restore_boundary_research_classification_and_handoff_recomputed_from_pass29 +stage=id=whole-live-source-scan;status=complete;effect=retired_commands_and_stale_restore_language_rejected_across_current_scripts_and_documents +stage=id=source-bound-host-receipts;status=complete;effect=each_ci_host_emits_one_L64PORT1_receipt_bound_to_exact_commit +stage=id=three-host-receipt-verification;status=complete;effect=combined_ci_job_requires_linux_macos_windows_receipts_with_one_source_ref +stage=id=receipt-contract-self-test;status=complete;effect=writer_and_combined_verifier_execute_locally_without_registry_or_runtime_authority +stage=id=external-host-execution;status=external_evidence;effect=github_actions_run_artifacts_supply_exact_host_receipts +completion=condition=no_live_legacy_torture_surface;status=complete +completion=condition=current_documents_name_current_restore_and_research_boundary;status=complete +completion=condition=ci_receipts_are_machine_readable_and_source_bound;status=complete +completion=condition=macos_windows_remote_execution;status=requires_successful_exact_source_ci_run +END diff --git a/LOCUS64_STACK.md b/LOCUS64_STACK.md index a1d5abb..bac2456 100644 --- a/LOCUS64_STACK.md +++ b/LOCUS64_STACK.md @@ -1,69 +1,34 @@ # Locus64 Stack -## Core identity +Locus64 is a dependency-free native workspace with eleven packages and zero external Rust dependencies. -Locus64 is the current architectural stack for the Locus Kernel, RNA/DNA lower chain, governed research host, and closure-safe reuse/tower work. +## Authority and product carriers -- **Locus Kernel** is the cold sovereign core that carries canonical mathematical truth, campaign execution, adequacy, deficiencies, certification, and promotion/block truth. -- **Locus Genome** is the binary-first packet/layout/runtime substrate that carries compact machine-native artifacts and projects them outward into readable views only when needed. -- **Locus Research Host** is the warm intake/routing/challenge/registry/distillate shell that decides what work should happen, why it should happen, and what reusable residue remains afterward. -- **Locus Tower** is the vertical compounding layer: proof coverage, payoff, distress, search compartments, crystallization, promotion candidates, and self-strengthening search objects. +- `l64-symbolic`: exact identity envelope and non-authoritative compact seal. +- `l64-native`: canonical `L64R1`/`L64D` authority and checked admission. +- `l64-projection`: verified read-only projections. +- `l64-execution`: direct non-persistent evaluation of canonical RNA/DNA with verified projection and certification. +- `l64-release`: atomic four-contact release carrier. +- `l64-transport`: ordered `L64B` transport without composite authority. +- `l64-certification`: structural certification over exact native authority. +- `l64-observation`: verified certification/replay/report observation. +- `l64-change`: ephemeral exact-authority comparison. +- `l64-cli`: complete native command grammar and direct command execution. +- `l64`: sibling-binary convenience wrapper; adds `authority-audit` and otherwise forwards unchanged to `l64-cli`. -## Design law +The wrapper is not a second parser, execution engine, authority layer, or compatibility membrane. -1. Keep canonical truth small. -2. Keep the certifier cold. -3. Make artifacts machine-cheap and human-legible only by projection. -4. Make challenges and blocked states first-class. -5. Convert repeated successful work into reusable law. -6. Allow expansion only when live blockers force it. +## Deleted historical island -## Immediate implementation focus +The legacy core, locus packet layer, research host, kernel, registry, selector, runtime, canonicalizer, atlas, theorem/campaign certifier, command adapter, and testkit were externally recovered and deleted in Pass 23. Their commands are permanent tombstones. They are not compatibility runtime. -1. operational truth hardening -2. shared packet-runtime unification -3. warm research-host persistence and routing -4. registry/distillate/repro substrate -5. producer-host placement -6. coverage/payoff/tower compounding +## Public boundaries +- Wrong carrier formats fail at the requested command contact. +- File-producing commands create new outputs atomically and refuse replacement. +- Verdict-bearing commands preserve complete output and return stable status codes. +- RNA parser errors carry exact source spans. +- Bundle readers and writers retain one member contact at a time. +- Large-authority optimization is admitted only from measured structural causes and cannot weaken exact authority. -## Recent slice - -The Locus Research Host now lifts cold certification outputs into warm control-state artifacts: `FrameworkRegistryEntry`, `OperatorRecord`, `StrengtheningArtifact`, `ReproducibilityPacket`, `ReviewReceipt`, and optional `ChallengeRecord`. This is the first direct report-to-research compounding bridge. - - -## Current implemented stack slice - -- **Locus Kernel**: cold certification, adequacy, verdicts, receipts -- **Locus Genome**: shared packet/runtime substrate and binary-first machine artifacts -- **Locus Research Host**: tasks, signatures, reviews, challenges, registry, remediation, repro, claims, reductions, projections, benchmark runs, handoff packets, producer-host specs, promotion queue -- **Locus Tower (partial)**: coverage dispatch, distress/help, recipes, promotion candidates, calibration pressure - -## Current authority membrane - -The current coherence point is stricter than the warm-host object list might imply: - -- Report-derived research objects are projections until a replay-specific path promotes them. -- Evaluator authority is explicit, named, and scoped through `MechanizationPolicyObject`. -- Policy precedence emits deterministic receipts; equivalent policy sets must resolve the same way even when registry input order differs. -- Candidate approval gates are not constitutional law until executable evidence lands in `L64_APPROVAL_GATES.md` and the rule is promoted into `LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md`. - -This membrane prevents the warm host from becoming a second authority source beside RNA/DNA. - - -## Producer-host realization slice - -The stack now carries explicit persisted producer-host specs for: -- Reduction -- Projection -- Benchmark -- ChallengeResolution -- Handoff - -These are still skeletal, but they are now first-class objects in the warm host rather than only a future phase heading. - - -## Governing warm-host layer - -Locus Research Host now lifts cold certification results into governed task/signature/route/readiness/handoff state. The intended default is: cold result -> governed research bundle -> persisted warm objects -> route/promotion/handoff surfaces consume those objects by default. +Current law: [`LOCUS64_NATIVE_CONSTITUTION.md`](LOCUS64_NATIVE_CONSTITUTION.md). Current gates: [`L64_APPROVAL_GATES.md`](L64_APPROVAL_GATES.md). diff --git a/LOCUS64_SYMBOLIC_COMMITMENT_CHANGE_CHAIN.athens b/LOCUS64_SYMBOLIC_COMMITMENT_CHANGE_CHAIN.athens new file mode 100644 index 0000000..855896c --- /dev/null +++ b/LOCUS64_SYMBOLIC_COMMITMENT_CHANGE_CHAIN.athens @@ -0,0 +1,62 @@ +ATHENS_DEVELOPMENT_RAIL v1 +field=key=compact_seal_authority;value=non_authoritative +field=key=exact_identity_authority;value=domain_plus_canonical_bytes +field=key=legacy_blake3_boundary;value=removed_from_workspace +field=key=rail_version;value=3 +field=key=schema_version;value=1 +gate=id=exact-identity-envelope-green +gate=id=seal-coordinate-algebra-green +gate=id=composition-grammar-green +gate=id=native-section-symbol-green +gate=id=dna-v2-symbolic-frame-green +gate=id=projection-symbol-binding-green +gate=id=developer-surface-green +gate=id=symbolic-commitment-green +stage=id=exact-identity-envelope +stage_field=stage=exact-identity-envelope;key=required_gates;value=exact-identity-envelope-green +stage_field=stage=exact-identity-envelope;key=status;value=complete +stage=id=seal-coordinate-algebra +stage_field=stage=seal-coordinate-algebra;key=depends_on;value=exact-identity-envelope +stage_field=stage=seal-coordinate-algebra;key=required_gates;value=seal-coordinate-algebra-green +stage_field=stage=seal-coordinate-algebra;key=status;value=complete +stage=id=composition-grammar +stage_field=stage=composition-grammar;key=depends_on;value=seal-coordinate-algebra +stage_field=stage=composition-grammar;key=required_gates;value=composition-grammar-green +stage_field=stage=composition-grammar;key=status;value=complete +stage=id=native-section-symbol +stage_field=stage=native-section-symbol;key=depends_on;value=composition-grammar +stage_field=stage=native-section-symbol;key=required_gates;value=native-section-symbol-green +stage_field=stage=native-section-symbol;key=status;value=complete +stage=id=dna-v2-symbolic-frame +stage_field=stage=dna-v2-symbolic-frame;key=depends_on;value=native-section-symbol +stage_field=stage=dna-v2-symbolic-frame;key=required_gates;value=dna-v2-symbolic-frame-green +stage_field=stage=dna-v2-symbolic-frame;key=status;value=complete +stage=id=projection-symbol-binding +stage_field=stage=projection-symbol-binding;key=depends_on;value=dna-v2-symbolic-frame +stage_field=stage=projection-symbol-binding;key=required_gates;value=projection-symbol-binding-green +stage_field=stage=projection-symbol-binding;key=status;value=complete +stage=id=developer-surface +stage_field=stage=developer-surface;key=depends_on;value=projection-symbol-binding +stage_field=stage=developer-surface;key=required_gates;value=developer-surface-green +stage_field=stage=developer-surface;key=status;value=complete +stage=id=symbolic-commitment-closure +stage_field=stage=symbolic-commitment-closure;key=depends_on;value=developer-surface +stage_field=stage=symbolic-commitment-closure;key=required_gates;value=symbolic-commitment-green +stage_field=stage=symbolic-commitment-closure;key=status;value=complete +history=from_status=current;gates=exact-identity-envelope-green;mode=linear_advance;stage_id=exact-identity-envelope;to_status=complete +history=evidence=local%3Al64s1-self-delimiting-domain-plus-canonical-bytes%2Bexact-roundtrip;kind=dogfood_promotion_receipt;stage_id=exact-identity-envelope +history=from_status=current;gates=seal-coordinate-algebra-green;mode=linear_advance;stage_id=seal-coordinate-algebra;to_status=complete +history=evidence=local%3Asigma-pi-delta-omega%2Bprime-field%2Btyped-axis-law%2Bmillion-sample-audit;kind=dogfood_promotion_receipt;stage_id=seal-coordinate-algebra +history=from_status=current;gates=composition-grammar-green;mode=linear_advance;stage_id=composition-grammar;to_status=complete +history=evidence=local%3Adomain-qualification%2Bordered%2Bcommutative%2Bderivation-composition;kind=dogfood_promotion_receipt;stage_id=composition-grammar +history=from_status=current;gates=native-section-symbol-green;mode=linear_advance;stage_id=native-section-symbol;to_status=complete +history=evidence=local%3Anodes-ports-contexts-routes-localization%2Bexact-state-identity;kind=dogfood_promotion_receipt;stage_id=native-section-symbol +history=from_status=current;gates=dna-v2-symbolic-frame-green;mode=linear_advance;stage_id=dna-v2-symbolic-frame;to_status=complete +history=evidence=local%3A44-byte-frame%2Bv1-explicit-rejection%2Bstale-seal-rejection%2Bexact-fixed-point;kind=dogfood_promotion_receipt;stage_id=dna-v2-symbolic-frame +history=from_status=current;gates=projection-symbol-binding-green;mode=linear_advance;stage_id=projection-symbol-binding;to_status=complete +history=evidence=local%3Aprojection-source-and-replay-bind-native-state-symbol%2Bstale-rejection;kind=dogfood_promotion_receipt;stage_id=projection-symbol-binding +history=from_status=current;gates=developer-surface-green;mode=linear_advance;stage_id=developer-surface;to_status=complete +history=evidence=local%3Aone-line-helpers%2Bparser-safe-ascii%2Breadable-unicode%2Baxis-change-explanations;kind=dogfood_promotion_receipt;stage_id=developer-surface +history=from_status=current;gates=symbolic-commitment-green;mode=linear_advance;stage_id=symbolic-commitment-closure;to_status=complete +history=evidence=github-66e09837ff96e2d10bee30232346e57f9bf7cec9-run-30146463330;kind=dogfood_promotion_receipt;stage_id=symbolic-commitment-closure +END diff --git a/README.md b/README.md index a92ab1c..cf248be 100644 --- a/README.md +++ b/README.md @@ -1,113 +1,81 @@ # Locus64 -Locus64 is a Rust command-line certification framework for routed mathematical campaigns, lower-chain RNA/DNA compilation, adequacy checking, replayable execution, proof coverage, and governed research artifacts. - -The primary binary is `l64`. It routes commands to the CLI or admin implementation as needed. `l64-cli` and `l64-admin` are still shipped as direct entry points for automation and lower-level debugging. - -## Current Architecture - -- **Locus Kernel**: cold semantic authority for certification, adequacy, replay, and promotion decisions. -- **RNA/DNA lower chain**: `TOKENIZE -> RNORM -> SSR -> CNORM -> DNA` is the active authority path. SSR remains ephemeral; CNORM now consumes explicit distinction/equivalence law and emits versioned canonical instructions. -- **Locus Genome**: `.dna` is the machine authority artifact. Legacy packet decoding is explicit migration/forensic behavior, not an ambient authority fallback. -- **Bundle substrate migration**: `.dna` bundle imports must pass native molecular-envelope parity, duplex local validation, domain closure, and deterministic merge evidence before persistence. -- **Research Host**: governed task, signature, review, challenge, lineage, promotion, handoff, and remediation surfaces. Research objects derived from reports are projection-class until a replay-specific authority path promotes them. -- **Tower/Coverage**: proof coverage dispatch, lawful reuse receipts, residual verification, distress/help, recipes, and promotion candidates. -- **Policy authority**: evaluator behavior is selected through named, scoped policy objects. Policy precedence emits deterministic receipts independent of registry insertion order. - -## Quick Start - -```powershell -cargo test -q -cargo build --release -p l64 -p l64-cli -p l64-admin -.\target\release\l64.exe clear-cache --scope all -.\target\release\l64.exe certify-derived --campaign CPG_CHAIN_RULE -.\target\release\l64.exe observe-run --report REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE -``` - -If the local machine is under memory pressure during a full rebuild, use the low-memory verifier: - -```powershell -.\scripts\verify-low-memory.ps1 -Scope workspace -.\scripts\verify-low-memory.ps1 -Scope all +Locus64 is a compact, dependency-free native authority and execution system. + +Current authority is canonical `L64R1` RNA and `L64D` DNA. `L64B` transports ordered DNA members without creating composite authority. Execution evaluates current authority directly without mutation or persistence. Certification, observation, change, and projection are verified read-only derivatives. + +## Verify the workspace + +```bash +cargo test --locked --offline --workspace +cargo clippy --locked --offline --workspace --all-targets -- -D warnings +cargo fmt --all --check +./scripts/verify-legacy-authority-island-deletion.sh +./scripts/verify-native-carrier.sh +./scripts/verify-cli-hardening.sh +./scripts/verify-process-contract.sh +./scripts/verify-native-scale.sh +./scripts/verify-documentation-coherence.sh +./scripts/verify-golden-portability.sh ``` -Expected seeded verdicts: +## Command surfaces -- `Integrated`: `CPG_CHAIN_RULE`, `CPG_CHAIN_RULE_RECIPE`, `CPG_CHAIN_RULE_TRANSPORT` -- `Certified`: `CPG_BAYES_BRACE`, `CPG_EXEC_INFER`, `CPG_PROB_JUDG`, `CPG_CERT_PROP`, `CPG_CH_NORM`, `CPG_CH_INH` +`l64-cli` owns the complete native command grammar. `l64` is a small sibling-binary wrapper: it adds `authority-audit`, forwards every other argument unchanged to `l64-cli`, and preserves the child exit code. It is not a second parser, execution layer, or compatibility route. -## RNA/DNA Flow - -```powershell -Set-Content .\sample.gene.rna "ι ≔ σ ‖ κ" -Encoding UTF8 -.\target\release\l64.exe normalize-rna .\sample.gene.rna -.\target\release\l64.exe compile-rna .\sample.gene.rna --out .\sample.gene.dna --artifact-class gene --persist-lineage -.\target\release\l64.exe sequence-dna .\sample.gene.dna -.\target\release\l64.exe inspect-dna .\sample.gene.dna -.\target\release\l64.exe verify-roundtrip .\sample.gene.rna --artifact-class gene -.\target\release\l64.exe export-genome-release --rna .\sample.gene.rna --out .\sample-release --artifact-class gene +```bash +cargo run -p l64-cli -- --help +cargo run -p l64-cli -- help run-rna +cargo run -p l64-cli -- --version +cargo run -p l64 -- authority-audit ``` -`sequence-dna` emits canonical reconstructable RNA. `inspect-dna` emits inspection JSON. `compile-rna` rejects inspection/report/projection text as source. -`export-genome-release` emits a coordinate-bearing release spine from RNA/DNA authority: genome, source sequence, claim page, dependency spine, closure map, frontier, stress map, replay record, views, and view receipts. Only generated source/canonical RNA are re-compilable; the other release artifacts use projection/record/receipt roles and extensions. - -RNA is the human symbolic surface. DNA is the machine artifact surface. SSR is ephemeral and must not be treated as public authority. +Primary commands: -## Sample Bundles - -```powershell -.\target\release\l64.exe certify-bundle --file samples/chain_rule_bundle.dna --conflict-policy exact-match -.\target\release\l64.exe certify-bundle --file samples/chain_rule_integrated_bundle.dna --conflict-policy exact-match -.\target\release\l64.exe certify-bundle --file samples/imported_claim_bundle.dna --conflict-policy exact-match -.\target\release\l64.exe certify-bundle --file samples/imported_claim_stress_gap_bundle.dna --conflict-policy exact-match +```bash +cargo run -p l64-cli -- run-rna samples/native_triangle.rna +cargo run -p l64-cli -- compile-rna samples/native_triangle.rna --out triangle.dna +# New authority and bundle outputs are created atomically and never overwrite existing paths. +cargo run -p l64-cli -- run-dna triangle.dna +cargo run -p l64-cli -- certify-dna triangle.dna +cargo run -p l64-cli -- observe-dna triangle.dna +cargo run -p l64-cli -- inspect-dna triangle.dna ``` -The imported-claim samples exercise evidence contracts, benchmark receipts, challenge receipts, reproducibility packets, and sharp stress-gap blocking. +The legacy theorem, campaign, research, registry, producer-host, tower, policy, overlay, cache, planning, and administration execution island was historically exported and deleted. No live compatibility dispatcher remains. -If you have bundle-entry text, compile it into a `.dna` packet before using it as a certification input: +Run the complete offline demonstration: -```powershell -.\target\release\l64.exe compile-bundle .\bundle.locus.rna --out .\bundle.dna +```bash +./scripts/run-native-demo.sh /tmp/l64-demo ``` -Bundle-entry text must start with `!l64-bundle v1` and contain at least one entry. Obsolete `!qc0`/`!qa0` headers and header-only bundles are rejected. +## Process and memory contract -## Torture Test +Verdict-bearing commands keep their output and return stable process codes: `0` certified/success, `10` open, `11` incomplete, `12` invalid, and `2` for usage/input/filesystem/processing failure. RNA parse failures include exact line, column, source excerpt, and caret span. Bundle creation and bundle-facing commands process one canonical DNA member at a time rather than retaining the complete transport and every graph simultaneously. -```powershell -powershell -ExecutionPolicy Bypass -File .\scripts\torture-test.ps1 -``` +## Measured scale contract -The harness builds release binaries, runs the full test suite, exercises seeded campaigns, sample bundles, report DNA export/import, validation DNA bundle export/import, lock/replay, research reconnect, and RNA/DNA normalize/compile/sequence checks. Output lands in `release\torture` unless overridden. +Large-authority work is optimized only after profiling. Canonical RNA source compilation uses a bulk graph-construction path that suppresses per-instruction whole-state symbol and journal recomputation, then derives the exact final state once. Direct interactive graph mutations remain journaled. Route lookup is indexed per node; closure analysis is shared per context; equality canonicalization traverses real equality edges; retained/external projections remain explicitly reverified. -## Release Layout -Prepared release artifacts are generated under: +## Golden workload and portability contract -- `release\perfopt`: speed-optimized Windows and Linux binaries plus docs -- `release\compact`: footprint-minimized Windows and Linux binaries plus docs -- `release\src`: source release with usage and developer docs +Five representative authority fixtures bind exact normalized RNA, canonical DNA bytes, execution text, certification text, mixed-verdict transport behavior, and native release contents. The host-neutral Rust tests also prove LF/CRLF equivalence and paths containing spaces and Unicode. CI runs the complete Rust workspace on Linux, macOS, and Windows; Unix shell gates remain release orchestration rather than runtime dependencies. -Zip files for all five release packages are placed directly under `release`. +Run the direct local gate: -## Development References - -- `LINEAR_EXECUTION_RAIL.md`: authoritative linear rail; compounding change chains are trajectory-preserving changes to this file -- `L64_APPROVAL_GATES.md`: candidate/proven architectural laws and their executable evidence -- `LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md`: proven constitutional rules only; do not treat candidate gates as implemented law -- `LOCUS64_LANGUAGE_SPEC.md`: RNA/DNA command and language reference -- `USAGE_GUIDE.md`: command guide -- `SEMANTIC_USAGE_GUIDE.md`: semantic/claim-governance guide for research frameworks and indirect ChatGPT workflows -- `HANDOFF_STATUS.md`: developer handoff and verification notes -- `LOCUS64_STACK.md`: stack overview - -## Current Coherence Checkpoint +```bash +./scripts/verify-golden-portability.sh +``` -The latest verified authority gates prove that: +## Current source-of-truth documents -- authored obligation status is intent, not evidence -- evaluator authority is named and scoped through policy objects -- report-derived research records are projections until replayed -- policy precedence receipts are deterministic across equivalent registry orderings +- [`LOCUS64_NATIVE_CONSTITUTION.md`](LOCUS64_NATIVE_CONSTITUTION.md): live architecture law. +- [`L64_APPROVAL_GATES.md`](L64_APPROVAL_GATES.md): live executable gates. +- [`LOCUS64_LANGUAGE_SPEC.md`](LOCUS64_LANGUAGE_SPEC.md): authority, transport, binary, command, and process specification. +- [`LOCUS64_STACK.md`](LOCUS64_STACK.md): current eleven-package contact map. +- [`LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md`](LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md): exact workload and host-portability law. +- [`HANDOFF_STATUS.md`](HANDOFF_STATUS.md): current pass boundary. -Use these rules when adapting Locus64 patterns to other projects: derive views freely, but promote only through explicit replay, scope, lineage, and receipt gates. +Historical trajectory is retained in explicitly marked ledgers and rails; it is not a current architecture source. diff --git a/SEMANTIC_USAGE_GUIDE.md b/SEMANTIC_USAGE_GUIDE.md index 545bd53..070f0e3 100644 --- a/SEMANTIC_USAGE_GUIDE.md +++ b/SEMANTIC_USAGE_GUIDE.md @@ -1,374 +1,7 @@ -# Locus64 Semantic Usage Guide +# Semantic Usage Guide -This guide explains how to use Locus64 as semantic governance infrastructure for evolving derivational frameworks, especially speculative or research-heavy systems where assumptions, branches, observational constraints, and unresolved pressure points must stay traceable. - -The intended use is not to turn Locus64 into a physics engine or a generic theorem prover. The intended use is: - -```text -closure-constrained derivational infrastructure -``` - -Locus64 should govern derivational legitimacy, lineage, challenge state, adequacy, reuse, and promotion/deprecation. Domain-specific symbolic algebra, tensor manipulation, numerical simulation, and paper writing can remain external tools whose outputs are imported as governed artifacts. - -## Core Mental Model - -Use Locus64 to convert an evolving body of ideas into a governed graph: - -```text -human symbolic work -> RNA -> canonical lower chain -> DNA -> claims/evidence/challenges/lineage -``` - -The semantic split is: - -- `RNA`: human-authored symbolic surface for equations, derivation statements, branch notes, and claim authoring. -- `DNA`: canonical machine artifact carrying normalized structure and lineage references. -- `ClaimPacket`: a governed claim with assumptions, target sector, caveats, and authority state. -- `EvidenceContract`: what evidence must exist before the claim can be promoted. -- `BenchmarkReceipt`: observational, computational, or stress-test evidence. -- `ChallengeReceipt` or `ChallengeRecord`: an unresolved or resolved objection/failure surface. -- `ReproducibilityPacket`: derivation/code/artifact refs needed to replay or audit the claim. -- `ResearchLineageRecord`: the causal chain linking lower-chain truth, reports, and research artifacts. - -Important current boundary: claim packets authored/imported as part of a governed bundle can carry their declared `authority_state`, but claim packets derived from certification reports are projection-class until replay-specific promotion exists. Do not treat a report verdict as research-object evidence by itself. - -## Cosmology Mapping - -For a cosmological framework, use this mapping: - -| Framework object | Locus64 representation | -| --- | --- | -| primitive substrate assumption | canonical RNA/DNA root plus claim assumption | -| derived operational observable | benchmark target or projection artifact | -| gauge-equivalent description | transport-equivalent coverage or claim relation | -| unresolved pressure point | challenge record, remediation entry, or residual obligation | -| derivation chain | lineage receipt plus reproducibility packet | -| observational consistency check | benchmark receipt and adequacy clause | -| branch split | governed route, challenge, promotion, or deprecation state | -| surviving invariant equation | canonical normalized form | -| emergent effective description | warm-host research projection | -| equivalence-class ambiguity | conflict-resolution and transport legality surface | -| predictive test | benchmark packet | -| under-modeled anomaly | distress vector or residual verification receipt | - -## Recommended Workflow - -### 1. Author Symbolic RNA - -Write a compact `.gene.rna` file for each claim root or derivation fragment. - -Example: - -```text -distributed_density_renormalization_preserves_tolman_scaling -``` - -Current RNA syntax is structural and intentionally minimal. If the equation is too rich for current RNA syntax, store the readable equation in a claim/reproducibility artifact and use RNA as the stable symbolic identity or derivation root. - -### 2. Compile RNA To DNA - -```powershell -l64 normalize-rna .\distributed_tolman.gene.rna -l64 compile-rna .\distributed_tolman.gene.rna --out .\distributed_tolman.gene.dna --artifact-class gene --persist-lineage -l64 sequence-dna .\distributed_tolman.gene.dna -l64 inspect-dna .\distributed_tolman.gene.dna -l64 verify-roundtrip .\distributed_tolman.gene.rna --artifact-class gene -l64 export-genome-release --rna .\distributed_tolman.gene.rna --out .\distributed_tolman.release --artifact-class gene -``` - -`sequence-dna` returns canonical reconstructable RNA for fixed-point checks. `inspect-dna` returns inspection JSON and cannot be used as source RNA. -`export-genome-release` emits coordinate-bearing review artifacts from RNA/DNA authority. Generated source/canonical RNA can be recompiled; generated views, claim pages, closure maps, stress maps, lineages, replay records, manifests, and receipts remain projection/record artifacts, use role-specific filenames, and are rejected as source. - -This creates a lower-chain record: - -```text -Tokenization -> RnaNormalization -> StructuralResolution -> CanonicalNormalization -``` - -The DNA packet is the machine-facing artifact. Do not treat prose, filenames, or notebook cells as canonical authority. - -### 3. Create A Claim Packet - -A claim packet should capture: - -- stable claim id -- claim class -- authority state -- target sector -- theorem-style statement -- assumptions -- caveats - -Template: - -```text -CLAIM: -Distributed density renormalization preserves Tolman scaling. - -ASSUMPTIONS: -A1: observed metric is density-renormalized from absolute metric. -A2: photon propagation accumulates distributed density response. -A3: surface brightness is evaluated through the observed projection. - -DERIVATION: -D1: define density response along null path. -D2: derive redshift accumulation. -D3: compute surface-brightness scaling. - -OBSERVABLE: -B(z) proportional to (1+z)^-4. - -STATUS: -constrained-surviving - -FAILURE SURFACES: -acoustic peak structure unresolved -structure growth unresolved - -DEPENDENCIES: -metric conformal renormalization -photon propagation renormalization - -LINEAGE: -distributed_tolman.gene.dna -``` - -If using bundle-entry authoring text, represent these with `claim-packet`, `evidence-contract`, `benchmark-receipt`, `challenge-receipt`, `reproducibility-packet`, and `adequacy` entries, then compile the bundle text into `.dna` before certification. - -### 4. Attach Evidence Contracts - -An evidence contract states what must be true before promotion. - -Typical cosmology evidence contract fields: - -- required evidence kinds: derivation, benchmark, stress, observational comparison -- benchmark roles: target case, control, stress, trace -- admissibility thresholds: exact, bounded approximation, reproducible, independently checked -- promotion ceiling: exploratory, constrained, certified, integrated - -Use evidence contracts to prevent claims from being promoted because they are rhetorically convincing. - -### 5. Attach Benchmark Receipts - -Use benchmark receipts for observational or computational checks: - -- CMB acoustic peaks -- BAO scale -- SN1a distance-redshift relation -- lensing -- rotation curves -- Tolman surface-brightness tests -- Hubble tension -- structure formation -- nucleosynthesis - -Each benchmark should declare: - -- role: target case, control, stress, or trace -- verdict -- metrics -- reproducibility reference -- tolerance or exactness class - -### 6. Persist Challenges - -Do not delete failed branches. Persist them. - -Examples: - -| Challenge | Suggested state | -| --- | --- | -| endpoint-only renormalization violates Etherington duality | blocked or deprecated | -| distributed renormalization preserves Tolman scaling | constrained-surviving | -| acoustic peak recovery unresolved | open challenge | -| nucleosynthesis compatibility unresolved | open challenge | -| MOND-like scaling exploratory | exploratory challenge | -| residual geometric expansion unresolved | residual obligation | - -This preserves derivational memory and prevents accidental reintroduction of broken branches. - -### 7. Derive Research Lineage - -After certification or report generation: - -```powershell -l64 research-derive-from-report --report-id REPORT_ID --persist -l64 research-promotion-readiness REPORT_ID -l64 research-status -``` - -Lineage should answer: - -- what claim or report is this derived from? -- what lower-chain DNA or canonical hash grounds it? -- what evidence is attached? -- what challenges remain open? -- what promotion state is justified? - -Derived research lineage is a warm-host projection over cold results. It is useful for routing, review, handoff, and readiness planning, but it must not be mistaken for a second source of authority. Replay, scoped evaluator policy, closure state, and receipt coordinates determine whether a derived object can be promoted later. - -### 8. Use Coverage And Reuse Carefully - -Locus64 can skip repeated work only when reuse is lawful. - -Reuse requires: - -- canonical identity match or declared transport-equivalence -- valid lineage -- replay legality -- matching policy/tolerance envelope -- residual obligations explicitly recorded - -For cosmology, this matters when two branches are observationally equivalent under a projection but not ontologically identical. - -### 9. Use Scoped Evaluator Policy - -When a claim needs stricter evidence behavior, encode that as a named policy object with a concrete scope. This avoids hidden evaluator assumptions. - -```text -policy-object {"id":"MOP_COSMO_EVAL","kind":"Evaluator","scope":{"Theorem":"THS_COSMO"},"extends":null,"optimizer":null,"evaluator":{"evidence_preference":"RecomputeIfSupported","allow_approximation":false,"unsupported_mode":"StrictFail","require_symbolic_fidelity_route":false,"prefer_comp_replay":true},"replay_cache":null,"report":null,"scheduler":null,"canonicalizer_mode":null,"merge_policy":null,"notes":["cosmology evaluator scope"]} -``` - -Policy resolution is deterministic: equal-precedence candidates are ordered by stable policy identity, not registry insertion order. - -## Promotion States - -Use these semantic states consistently: - -| State | Meaning | -| --- | --- | -| exploratory | authored but weakly constrained | -| constrained | partial observational or derivational support | -| challenged | live inconsistency or unresolved blocker | -| integrated | compatible with current closure/evidence requirements | -| blocked | contradiction or failed adequacy | -| deprecated | superseded by a stronger branch | - -Do not collapse `challenged`, `blocked`, and `deprecated`; they mean different things operationally. - -## Example: Branch Governance - -For branch splits, create separate claim packets and link them by challenge/promotion records. - -```text -Branch A: -endpoint-only renormalization -Status: -blocked -Challenge: -Etherington duality failure - -Branch B: -distributed renormalization -Status: -constrained-surviving -Challenge: -acoustic peaks unresolved - -Branch C: -residual geometric expansion -Status: -exploratory -Challenge: -not yet benchmarked against BAO/CMB -``` - -This is better than replacing old notes because it preserves why a branch failed or survived. - -## What Not To Do - -Do not use Locus64 as: - -- a symbolic algebra replacement -- a tensor calculus engine -- a numerical cosmology simulator -- a prose database -- an ontology freezer - -Use it as: - -- claim governance -- derivation lineage -- adequacy routing -- challenge persistence -- benchmark accounting -- promotion/deprecation control -- canonical artifact conversion - -## Practical File Layout For A Research Project - -Suggested external project layout: - -```text -cosmology-work/ - rna/ - distributed_tolman.gene.rna - endpoint_renorm.gene.rna - dna/ - distributed_tolman.gene.dna - claims/ - distributed_tolman.claim.locus.rna - distributed_tolman.claim.dna - benchmarks/ - tolman_surface_brightness.benchmark.json - hubble_tension.benchmark.json - challenges/ - etherington_endpoint.challenge.json - acoustic_peaks.challenge.json - repro/ - distributed_tolman.repro.json - exports/ - reports/ -``` - -Locus64 can live separately and be called by scripts or ChatGPT-generated workflows. - -## Minimal Command Loop - -```powershell -# 1. Compile identity/derivation root. -l64 compile-rna .\rna\distributed_tolman.gene.rna --out .\dna\distributed_tolman.gene.dna --artifact-class gene --persist-lineage - -# 2. Compile and certify the claim bundle. -l64 compile-bundle .\claims\distributed_tolman.claim.locus.rna --out .\claims\distributed_tolman.claim.dna -l64 certify-bundle --file .\claims\distributed_tolman.claim.dna --conflict-policy exact-match - -# 3. Inspect report. -l64 observe-run --report REPORT_ID - -# 4. Persist research lineage. -l64 research-derive-from-report --report-id REPORT_ID --persist - -# 5. Check promotion readiness. -l64 research-promotion-readiness REPORT_ID - -# 6. Export DNA-backed artifacts for review or ChatGPT handoff. -l64 export-report-dna --report-id REPORT_ID --out .\exports\reports\REPORT_ID.dna -``` - -## ChatGPT Integration Pattern - -When moving between ChatGPT and Locus64: - -1. Draft claim/derivation in natural language. -2. Collapse it into a claim packet template. -3. Create or update the RNA identity/root. -4. Compile RNA to DNA. -5. Attach evidence, benchmark, challenge, and reproducibility records. -6. Certify or validate. -7. Export report back to ChatGPT for interpretation. -8. Convert ChatGPT critique into new challenge records or remediation entries, not silent edits. - -This keeps iterative reasoning from mutating assumptions invisibly. - -## Key Principle - -Locus64 should preserve the difference between: - -- what is canonical -- what is projected -- what is observed -- what is challenged -- what is merely useful -- what is promoted - -That distinction is the main value of the system for evolving semantic frameworks. +- Treat canonical `L64R1`/`L64D` bytes as authority. +- Treat `L64B` as ordered transport only. +- Treat projections, certification, observation, and change as verified non-authoritative views. +- Do not recreate registry, campaign, research-host, tower, policy, cache, planning, or receipt schemas. +- Historical archives are forensic evidence, not runtime inputs. diff --git a/SOURCE_REFERENCE_MANIFEST.md b/SOURCE_REFERENCE_MANIFEST.md index e5920c6..156dbea 100644 --- a/SOURCE_REFERENCE_MANIFEST.md +++ b/SOURCE_REFERENCE_MANIFEST.md @@ -1,71 +1,60 @@ -# Locus64 Source Reference Manifest - -This repository snapshot is intended to be usable as a source-only reference for Locus64 patterns in other projects. - -## What This Snapshot Represents - -The current coherent state is: - -```text -RNA/DNA public authority --> lower-chain canonical structure --> DNA validation and fixed-point reconstruction --> duplex/domain closure gates --> deterministic policy and parallel receipts --> warm-host research projections -``` - -The important distinction is that projections, reports, rendered views, release products, cache records, and research-host derivatives may guide work, but they are not authority by default. - -## Core Documents - -- `README.md`: project overview, quick start, command examples, and current coherence checkpoint. -- `USAGE_GUIDE.md`: operational command guide. -- `SEMANTIC_USAGE_GUIDE.md`: claim-governance and research-framework integration guide. -- `LOCUS64_LANGUAGE_SPEC.md`: concrete RNA/DNA, bundle-entry, and policy-object syntax. -- `LINEAR_EXECUTION_RAIL.md`: path-optimized development dependency rail. -- `L64_APPROVAL_GATES.md`: candidate/proven architectural law and required proof classes. -- `LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md`: mechanically proven architectural law only. -- `LOCUS64_STACK.md`: architectural stack overview. -- `HANDOFF_STATUS.md`: developer handoff and verification notes. -- `EXPORT_STRESS_REMEDIATION_LEDGER.md`: exported-finding remediation doctrine. - -## Latest Proven Authority Rules - -- Authored obligation status is intent, not evidence. -- Evaluator authority is explicit, named, and scoped. -- Report-derived research records are projections until replayed. -- Policy precedence emits deterministic receipts. -- RNA and DNA remain the only public authority surfaces. -- Generated release artifacts are role-marked views, records, receipts, or projections unless explicitly reconstructed into canonical RNA. - -## Source-Only Archive Policy - -A clean reference archive should include: - -- Rust source crates -- scripts -- samples -- fixtures -- documentation -- `Cargo.toml` and `Cargo.lock` - -It should exclude: - -- `.git` -- `target` -- `.l64-cache` -- `release` -- generated zip files -- transient logs -- local garbage/scratch directories - -## Verification Baseline - -At the time this manifest was added, the workspace passed: - -```powershell -cargo test --workspace -``` - -Use `scripts/verify-low-memory.ps1` if full workspace verification is too heavy for the machine. +# Source Reference Manifest + +## Live source + +- `l64-symbolic` +- `l64-native` +- `l64-projection` +- `l64-release` +- `l64-execution` +- `l64-transport` +- `l64-certification` +- `l64-observation` +- `l64-change` +- `l64-cli` +- `l64` + +## Governing closure + +- `LOCUS64_LEGACY_AUTHORITY_ISLAND_DELETION_CHANGE_CHAIN.athens` +- `LOCUS64_NATIVE_EXECUTION_CHANGE_CHAIN.athens` +- `LOCUS64_NATIVE_CLI_HARDENING_CHANGE_CHAIN.athens` +- `LOCUS64_NATIVE_PROCESS_CONTRACT_CHANGE_CHAIN.athens` +- `LOCUS64_NATIVE_SCALE_CHANGE_CHAIN.athens` +- `LOCUS64_DOCUMENTATION_COHERENCE_CHANGE_CHAIN.athens` +- `LOCUS64_GOLDEN_PORTABILITY_CHANGE_CHAIN.athens` +- `LOCUS64_RESIDUE_REMOTE_PROOF_CHANGE_CHAIN.athens` +- `LOCUS64_EXECUTION_COHERENCE_RAIL.athens` + +## Restore and historical recovery + +The removed legacy source is external to the live workspace in the Pass 19–23 forensic archives. The complete Pass 29 source archive is the restore boundary for Pass 30. The removed pre-native torture harness is retained only in the external Pass 30 forensic backup; it is not a live verification contact. + +## Direct verification + +- `scripts/verify-legacy-authority-island-deletion.sh` +- `scripts/verify-native-carrier.sh` +- `scripts/verify-cli-hardening.sh` +- `scripts/verify-process-contract.sh` +- `scripts/verify-native-scale.sh` +- `scripts/verify-documentation-coherence.sh` +- `scripts/verify-golden-portability.sh` +- `scripts/verify-portability-receipts.sh --self-test` +- `scripts/run-native-demo.sh` + +## Current product evidence + +- `samples/native_triangle.rna` +- `samples/native_equality.rna` +- `samples/golden/*.rna` +- `samples/golden/expected/*` +- `LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md` +- `LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md` + +## Pass 30 residue and remote-proof surfaces + +- `scripts/write-portability-receipt.sh` emits one source-bound host receipt after the complete host-neutral workspace test passes. +- `scripts/verify-portability-receipts.sh` requires the exact Linux, macOS, and Windows receipt set and provides a local contract self-test. +- `.github/workflows/native-core.yml` retains per-host and combined receipt artifacts. +- `scripts/verify-documentation-coherence.sh` rejects a returned torture harness, retired-command use in current scripts, stale restore-boundary prose, and missing receipt contacts. +- `LOCUS64_RESIDUE_REMOTE_PROOF_CHANGE_CHAIN.athens` records the bounded closure. diff --git a/USAGE_GUIDE.md b/USAGE_GUIDE.md index 5bacbff..ffa3da1 100644 --- a/USAGE_GUIDE.md +++ b/USAGE_GUIDE.md @@ -1,165 +1,70 @@ -# Locus64 Usage Guide +# Usage Guide -Use `l64` as the primary command. On Windows release bundles, run `l64.exe` from the release directory. On Linux release bundles, run `./l64`. +## Binary choice -## Verify Installation +Use `l64-cli` for the complete command grammar. Use `l64` as the installed convenience entrypoint when both sibling binaries are packaged together. `l64` forwards every ordinary command unchanged to `l64-cli` and preserves its exit code; it adds only one local diagnostic command: -```powershell -l64 dump-runtime-roots -l64 clear-cache --scope all +```bash +l64 authority-audit ``` -If running from source on Windows: +The wrapper does not parse or reinterpret authority and is not a second execution layer. -```powershell -cargo build --release -p l64 -p l64-cli -p l64-admin -.\target\release\l64.exe dump-runtime-roots -``` +## Discovery -## Campaign Certification - -```powershell -l64 certify-derived --campaign CPG_CHAIN_RULE -l64 certify-derived --campaign CPG_CHAIN_RULE_RECIPE -l64 certify-derived --campaign CPG_CHAIN_RULE_TRANSPORT -l64 certify-derived --campaign CPG_BAYES_BRACE -l64 certify-derived --campaign CPG_EXEC_INFER -l64 certify-derived --campaign CPG_PROB_JUDG -l64 certify-derived --campaign CPG_CERT_PROP -l64 certify-derived --campaign CPG_CH_NORM -l64 certify-derived --campaign CPG_CH_INH +```bash +cargo run -p l64-cli -- --help +cargo run -p l64-cli -- help compile-rna +cargo run -p l64-cli -- --version +cargo run -p l64 -- authority-audit ``` -Use `observe-run` after certification: +## Authoring, execution, derivation, and transport -```powershell -l64 observe-run --report REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE +```bash +cargo run -p l64-cli -- normalize-rna samples/native_triangle.rna +cargo run -p l64-cli -- run-rna samples/native_triangle.rna +cargo run -p l64-cli -- compile-rna samples/native_triangle.rna --out triangle.dna +cargo run -p l64-cli -- run-dna triangle.dna +cargo run -p l64-cli -- sequence-dna triangle.dna +cargo run -p l64-cli -- inspect-dna triangle.dna +cargo run -p l64-cli -- certify-dna triangle.dna +cargo run -p l64-cli -- observe-dna triangle.dna +cargo run -p l64-cli -- compare-dna before.dna after.dna +cargo run -p l64-cli -- compile-bundle first.dna second.dna --out work.l64b +cargo run -p l64-cli -- run-bundle --file work.l64b ``` -## Bundle Certification - -```powershell -l64 certify-bundle --file samples/chain_rule_bundle.dna --conflict-policy exact-match -l64 certify-bundle --file samples/chain_rule_integrated_bundle.dna --conflict-policy exact-match -l64 certify-bundle --file samples/imported_claim_bundle.dna --conflict-policy exact-match -l64 certify-bundle --file samples/imported_claim_stress_gap_bundle.dna --conflict-policy exact-match -``` - -## RNA/DNA Commands - -```powershell -l64 normalize-rna sample.gene.rna -l64 compile-rna sample.gene.rna --out sample.gene.dna --artifact-class gene --persist-lineage -l64 sequence-dna sample.gene.dna -l64 inspect-dna sample.gene.dna -l64 verify-roundtrip sample.gene.rna --artifact-class gene -l64 export-genome-release --rna sample.gene.rna --out sample-release --artifact-class gene -``` +Former `legacy`, theorem, campaign, research, registry, and tower commands are permanent deletion tombstones. -The lower chain is ledgered as: +End-to-end offline demo: -```text -Tokenization -> RnaNormalization -> StructuralResolution -> CanonicalNormalization +```bash +./scripts/run-native-demo.sh /tmp/l64-demo ``` -DNA emission validates header truth, structural opcode law, and symbol-table non-authority before writing the artifact. - -`compile-rna` accepts source RNA only. It rejects inspection reports, receipts, generated views, closure maps, claim pages, stress maps, replay records, and JSON report/projection text. +`compile-rna`, `compile-bundle`, and `export-genome-release` refuse existing outputs. Choose a new path or remove the old output deliberately; there is no implicit force mode. -`sequence-dna` emits canonical reconstructable RNA suitable for recompilation. `inspect-dna` emits JSON inspection output and is not source. `verify-roundtrip` checks the fixed-point path: +Wrong carrier formats fail at the requested command contact, and malformed RNA/DNA diagnostics use stable human-readable messages rather than Rust debug syntax. -```text -RNA -> DNA -> canonical RNA -> DNA -``` +## Process outcomes -`export-genome-release` creates a derived release directory with: - -```text -genome/ -spine/ -claims/ -frontier/ -replay/ -views/ -``` +Verdict-bearing commands emit their normal text before returning: -Generated manifest, claim pages, dependency spines, closure maps, closure frontiers, stress maps, lineage records, replay records, views, and receipts are projection/record artifacts and are rejected by `compile-rna`. Generated source RNA and canonical RNA are the only release text artifacts intended to re-enter `compile-rna`; generated non-source artifacts use role-specific `.projection`, `.record`, or receipt filenames rather than `.locus` authority hints. - -## Export, Import, Validate - -```powershell -l64 export-validation-dna-bundle --id REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE --out chain-rule.validation.dna -l64 import-bundle chain-rule.validation.dna -l64 export-report-dna --report-id REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE --out chain-rule.dna -l64 import-report-dna chain-rule.dna -``` - -## Lock and Replay - -```powershell -l64 lock-bundle samples/chain_rule_integrated_bundle.dna --optimizer-policy conservative --conflict-policy exact-match -l64 replay-with-lock --parallel-obligations --max-obligation-workers 3 -``` - -## Research Host - -```powershell -l64 research-import --kind task samples/research/task_operational_truth.json -l64 research-import --kind signature samples/research/signature_operational_truth.json -l64 research-route --task-id TASK_OPERATIONAL_TRUTH_HARDENING --signature-id SIG_OPERATIONAL_TRUTH_HARDENING -l64 research-derive-from-report --report-id REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE --persist -l64 research-promotion-readiness REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE -l64 research-status -``` - -`research-derive-from-report` creates warm-host projection records unless a later replay-specific path promotes them. A report verdict such as `Integrated` or `Certified` is preserved as an assumption on the derived claim packet; it is not automatically evidence authority for the research object. - -For exact syntax and record shapes, see `LOCUS64_LANGUAGE_SPEC.md`. - -For semantic claim governance, branch tracking, derivation lineage, and cosmology-style workflows, see `SEMANTIC_USAGE_GUIDE.md`. - -## Policy Authority - -Evaluator behavior comes from named, scoped policy objects rather than ambient defaults or report prose. Equivalent policy sets resolve deterministically even if registry ordering changes. - -Use policy objects in bundle text when you need scoped evaluator behavior: - -```text -policy-object {"id":"MOP_LOCAL_EVAL","kind":"Evaluator","scope":{"Theorem":"THS_LOCAL"},"extends":null,"optimizer":null,"evaluator":{"evidence_preference":"RecomputeIfSupported","allow_approximation":false,"unsupported_mode":"StrictFail","require_symbolic_fidelity_route":false,"prefer_comp_replay":true},"replay_cache":null,"report":null,"scheduler":null,"canonicalizer_mode":null,"merge_policy":null,"notes":["strict local evaluator"]} -``` - -## Coverage and Tower - -```powershell -l64 dispatch-coverage --report-id REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE -l64 derive-frontier --report-id REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE -l64 tower-step --report-id REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE -l64 derive-distress --report-id REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE -``` - -Reuse is lawful only when canonical identity or declared transport-equivalence, closure-valid lineage, replay legality, and residual-obligation accounting all pass. - -## Torture Harness - -```powershell -powershell -ExecutionPolicy Bypass -File .\scripts\torture-test.ps1 -``` - -Useful smaller smoke pass: - -```powershell -powershell -ExecutionPolicy Bypass -File .\scripts\torture-test.ps1 -OuterRounds 1 -InnerNamespaces 1 -``` +- `0`: command succeeded; certification is `CERTIFIED` when applicable +- `10`: `OPEN` burdens remain +- `11`: certification is `INCOMPLETE` because evidence is missing +- `12`: certification is `INVALID` +- `2`: usage, input, filesystem, or processing failure -Artifacts land in `release\torture` by default. +Malformed RNA diagnostics identify the exact token span. `L64B` commands decode, execute, certify, observe, and compare members sequentially; bundle creation writes members sequentially into the atomic staging output. -## Cache Isolation +## Golden portability verification -Set `MF_CACHE_NAMESPACE` to isolate runs: +The repository carries five exact authority workloads plus a complete compare, bundle, and release journey. Run the host-neutral snapshot tests through the direct gate: -```powershell -$env:MF_CACHE_NAMESPACE='demo' -l64 clear-cache --scope all +```bash +./scripts/verify-golden-portability.sh ``` -Release users can delete `.l64-cache` safely when no run needs cached reports or research artifacts. +The same Rust workspace tests run in CI on Linux, macOS, and Windows. LF and CRLF sources must compile to identical authority bytes, and valid paths containing spaces or Unicode must not change command behavior. See [`LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md`](LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md). diff --git a/bin/l64-admin.cmd b/bin/l64-admin.cmd deleted file mode 100644 index a5b52bd..0000000 --- a/bin/l64-admin.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@echo off -set "ROOT=%~dp0.." -if exist "%ROOT%\target\debug\l64-admin.exe" ( - "%ROOT%\target\debug\l64-admin.exe" %* -) else ( - cargo run -q -p l64-admin -- %* -) diff --git a/fixtures/README.md b/fixtures/README.md deleted file mode 100644 index 8629dc7..0000000 --- a/fixtures/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Locus64 Fixtures - -Fixtures are controlled test inputs, not authority by themselves. - -## `cki_registry.genome.rna` - -Classification: fixture candidate promoted to controlled regression fixture. - -Role: - -- exercises a nontrivial authored RNA source through the public RNA/DNA membrane -- proves `RNA -> DNA -> canonical RNA -> DNA` fixed-point stability over a dependency-heavy external proving slice -- remains source input only; generated DNA, products, reports, and views must be derived by commands during tests or release generation - -Restrictions: - -- do not treat this file as semantic authority outside the RNA/DNA pipeline -- do not hand-edit generated outputs into fixtures without a matching command-level reproduction test -- do not use this fixture to justify new public surfaces diff --git a/fixtures/cki_registry.genome.rna b/fixtures/cki_registry.genome.rna deleted file mode 100644 index 43da979..0000000 --- a/fixtures/cki_registry.genome.rna +++ /dev/null @@ -1,277 +0,0 @@ - -:registry( -:meta( -:title(cki_tkcoaat_vnext_typed_registry), -:version(v0_1_0), -:principle(stable_spectral_residue_of_recursively_constrained_relational_transport) -); - -:nodes( - -:node(p1,:label(causal_substrate),:kind(primitive),:status(assumed), -:parents(),:consumes(),:produces(causal_substrate_tuple), -:constrains(local_finiteness,acyclic_causality,finite_alexandrov_intervals,no_primitive_metric_gauge_spin), -:enables(),:proof_deps(),:equations(causal_substrate_tuple),:notes()); - -:node(p2,:label(kineton_transport_support),:kind(primitive),:status(assumed), -:parents(),:consumes(causal_substrate_tuple),:produces(kineton_tuple,omega_domain), -:constrains(),:enables(),:proof_deps(), -:equations(kineton_tuple,omega_membership), -:notes(omega_domain_abstract_until_kinematic_geometry_reconstructs_direction_space)); - -:node(o1,:label(density_operator),:kind(operator),:status(constructed), -:parents(p1,p2),:consumes(causal_substrate_tuple,kineton),:produces(rho,rho4,rho_perp), -:constrains(),:enables(),:proof_deps(), -:equations(rho_sum_alpha_delta,rho4_dim_l4,rho_perp_dim_l2),:notes()); - -:node(o2,:label(projected_valence_lock),:kind(operator),:status(proved), -:parents(o1),:consumes(rho_perp),:produces(ell_k,nu0,script_n), -:constrains(),:enables(),:proof_deps(projected_causal_link_density_not_4d_bulk_density), -:equations(script_n_equals_rho_perp_ell_k2,rho_perp_ell_k2_equals_nu0,ell_k_sqrt_nu0_over_rho_perp,ell_k_prop_rho_perp_minus_half),:notes()); - -:node(o4,:label(gaussian_compensation_kernel),:kind(operator),:status(conditional), -:parents(o1,o2),:consumes(rho,ell_k,script_n,e1kin_tangent_diffusion_domain),:produces(h_t,sigma_x,chi), -:constrains(),:enables(),:proof_deps(markov_semigroup,isotropy,positivity,normalization,finite_variance,kinematic_local_domain), -:equations(hs_ht_equals_hs_plus_t,heat_kernel,hat_h_exp_minus_dtk2,t_trace_sigma_over_6d),:notes()); - -:node(o3,:label(relational_readout),:kind(operator),:status(constructed), -:parents(o1,o4),:consumes(rho,h_t),:produces(tau,chi), -:constrains(),:enables(),:proof_deps(), -:equations(tau_equals_rho_minus_h_convolve_rho,chi_k_equals_one_minus_hhat),:notes()); - -:node(o5,:label(projected_transport_flow),:kind(operator),:status(enabled), -:parents(p2,o2,o4),:consumes(k,ell_k,h_t),:produces(projected_flow,holonomy,norm_continuity), -:constrains(),:enables(),:proof_deps(), -:equations(dkdt_projected_gradient_flow,p_k_projector,energy_gamma_lambda), -:notes(norm_preservation_not_identical_to_quantum_unitarity)); - -:node(o6,:label(dynamo_operator),:kind(operator),:status(constructed), -:parents(o3,o4,o5),:consumes(tau,h_t,k),:produces(dynamo,sigma,pi,xi,sigma_scalar,chi,omega), -:constrains(),:enables(),:proof_deps(), -:equations(dynamo_maps_rho_to_transport,dynamo_rho_equals_h_convolve_rho,q_exp_minus_d_over_6_less_than_1),:notes()); - -:node(o7,:label(recursive_transport_return_operator),:kind(operator),:status(enabled), -:parents(o5,o6),:consumes(transport_trajectories,redistribution_sector),:produces(return_operator,lambda_k,m_k,q_topological), -:constrains(),:enables(),:proof_deps(), -:equations(return_maps_transport_to_transport_return,lambda_k_cycle,m_k2_gamma_lambda_k_plus_lambda,q_integer),:notes()); - -:node(d1,:label(microscopic_transport_gauge_action),:kind(dynamics),:status(constructed), -:parents(o5,o6,o7),:consumes(k,u_xy),:produces(action_s,gauge_curvature), -:constrains(),:enables(),:proof_deps(), -:equations(action_k_u),:notes()); - -:node(d2,:label(matter_gauge_hessian),:kind(dynamics),:status(constructed), -:parents(d1),:consumes(action_s),:produces(hessian,sigma_k,t_k), -:constrains(),:enables(),:proof_deps(), -:equations(sigma_hessian_schur,t_minus_g2_over_k2_plus_ma2,g2_scaling,ma2_scaling),:notes()); - -:node(d5a,:label(positive_manifold_selector_ensemble),:kind(dynamics),:status(conditional), -:parents(p1,d1),:consumes(causal_set,manifold_indicator),:produces(mu_n_plus,f_man), -:constrains(),:enables(),:proof_deps(selector_positive_all_non_manifold_ldp_directions,global_uniqueness_phi_a), -:equations(f_man_quadratic,mu_n_plus_gibbs,two_a_minus_h_positive),:notes()); - -:node(e6,:label(manifold_dominance),:kind(emergent),:status(conditional), -:parents(d5a),:consumes(mu_n_plus),:produces(manifold_4), -:constrains(),:enables(),:proof_deps(full_rank_selector,global_ldp_dominance), -:equations(mu_non_manifold_bound,mu_converges_to_manifold),:notes()); - -:node(c_rec,:label(causal_reconstruction_bridge),:kind(consistency),:status(bridge), -:parents(p1,e6),:consumes(causal_substrate,manifold_4),:produces(manifold_metric_mod_diff), -:constrains(),:enables(),:proof_deps(faithful_embedding,hauptvermutung_uniqueness,causal_order_plus_volume_reconstruction), -:equations(causal_order_to_conformal_metric,counting_to_volume),:notes()); - -:node(e1kin,:label(kinematic_lorentzian_geometry),:kind(emergent),:status(conditional), -:parents(p1,e6,c_rec),:consumes(causal_substrate,manifold_4),:produces(kinematic_metric_mod_diff), -:constrains(),:enables(),:proof_deps(), -:equations(e1kin_metric_mod_diff),:notes()); - -:node(d3,:label(adm_closure_dynamics),:kind(dynamics),:status(conditional), -:parents(e1kin),:consumes(gamma_ij,pi_ij,refoliation_algebra),:produces(adm_hamiltonian,a_plus_2b_zero), -:constrains(),:enables(),:proof_deps(micro_relabeling_to_refoliation_descent), -:equations(adm_hamiltonian,hamiltonian_constraint_bracket,a_plus_2b_zero),:notes()); - -:node(e2,:label(dewitt_supermetric),:kind(emergent),:status(proved), -:parents(d3),:consumes(a_plus_2b_zero),:produces(dewitt_metric), -:constrains(),:enables(),:proof_deps(), -:equations(dewitt_supermetric_formula),:notes()); - -:node(i2,:label(scalar_sector_elimination_and_trace_suppression),:kind(invariant),:status(conditional), -:parents(d3,o3,o4),:consumes(dirac_closure,chi_k),:produces(tt_dominant_ir_sector), -:constrains(),:enables(),:proof_deps(d3_removes_independent_scalar_graviton,o3_o4_suppress_scalar_leakage), -:equations(chi_k_order_k2,scalar_leakage_order_k6,omega2_k2_plus_order_k6),:notes()); - -:node(e1obs,:label(observable_metric),:kind(emergent),:status(constructed), -:parents(o1,d3,d5a),:consumes(rho,h_munu),:produces(g_obs), -:constrains(),:enables(),:proof_deps(), -:equations(g_obs_equals_rho_inverse_h),:notes()); - -:node(c_spin,:label(spin_structure_bridge),:kind(consistency),:status(bridge), -:parents(e1kin),:consumes(e1kin),:produces(spin_representation_domain), -:constrains(),:enables(),:proof_deps(orientability,time_orientability,spin_structure), -:equations(),:notes()); - -:node(e3,:label(clifford_carrier),:kind(emergent),:status(conditional), -:parents(e1kin,c_spin),:consumes(metric),:produces(psi_c4,chiral_decomposition), -:constrains(),:enables(),:proof_deps(), -:equations(clifford_relation,clifford_complex_is_m4c,c4_left_right_decomposition),:notes()); - -:node(c_tri,:label(triadic_gauge_bridge),:kind(consistency),:status(bridge), -:parents(o5,o6,o7),:consumes(triadic_persistence,k_in_c3),:produces(su3), -:constrains(),:enables(),:proof_deps(triadic_persistence_forces_k_in_c3), -:equations(u3_decomposes_su3_plus_u1,su3_antihermitian_traceless,lie_bracket_su3),:notes()); - -:node(e5,:label(su3_color_compensator_sector),:kind(emergent),:status(conditional), -:parents(c_tri),:consumes(su3),:produces(su3_group), -:constrains(),:enables(),:proof_deps(), -:equations(dim_su3_equals_8),:notes()); - -:node(c_chiral,:label(chiral_representation_bridge),:kind(consistency),:status(bridge), -:parents(e3,e5),:consumes(psi_c4,su3),:produces(sm_one_generation_chiral_table), -:constrains(),:enables(),:proof_deps(), -:equations(q_l_3_2_1_6,u_rc_3bar_1_minus_2_3,d_rc_3bar_1_1_3,l_l_1_2_minus_1_2,e_rc_1_1_1),:notes()); - -:node(i4,:label(anomaly_cancellation),:kind(invariant),:status(proved), -:parents(c_chiral),:consumes(sm_one_generation_chiral_table),:produces(anomaly_free_chiral_sector), -:constrains(),:enables(),:proof_deps(), -:equations(a_33y_zero,a_22y_zero,a_yyy_zero,a_gravgravy_zero),:notes()); - -:node(c_mass,:label(spectral_generation_bridge),:kind(consistency),:status(bridge), -:parents(o7,d2),:consumes(lambda_k,hessian_sector),:produces(generation_mass_law,mixing_matrix), -:constrains(),:enables(),:proof_deps(spectral_generation_law_remains_bridge_theorem), -:equations(m_n_mass_law,v_ij_fourier_phase,j_cp_sine),:notes()); - -:node(e7,:label(spectral_generation_locking),:kind(emergent),:status(bridge), -:parents(c_mass),:consumes(c_mass),:produces(generation_hierarchy), -:constrains(),:enables(),:proof_deps(), -:equations(m_n2_prop_lambda_n_return),:notes()); - -:node(d4,:label(rg_fixed_point_flow),:kind(dynamics),:status(conditional), -:parents(d1,d2,d3),:consumes(action_k_u,adm_sector),:produces(gamma_star,beta_z,lorentz_attractor_flow), -:constrains(),:enables(),:proof_deps(), -:equations(beta_lambda_equation,gamma_star_equation,beta_z_minus_zomega_f),:notes()); - -:node(a1,:label(lorentz_restoration_attractor),:kind(attractor),:status(conditional), -:parents(d4),:consumes(beta_z_minus_zomega_f),:produces(z_to_1,zomega_to_0,delta_star_to_0), -:constrains(),:enables(),:proof_deps(), -:equations(zomega_decay_flow),:notes()); - -:node(b1,:label(signal_velocity),:kind(observable),:status(proved), -:parents(o4,a1),:consumes(lambda,mu2,nu0),:produces(c), -:constrains(),:enables(),:proof_deps(), -:equations(c_lambda_mu2_over_6,mu2_mg_ell_k2,lambda_lambda0_rho_perp,c_lambda0_mg_nu0_over_6),:notes()); - -:node(b2,:label(soliton_spectrum),:kind(observable),:status(constructed), -:parents(o7,e7),:consumes(lambda_k),:produces(e_n_k), -:constrains(),:enables(),:proof_deps(), -:equations(soliton_energy_spectrum),:notes()); - -:node(b3,:label(fine_structure_fixed_point_relation),:kind(observable),:status(open), -:parents(d4),:consumes(kappa,pf),:produces(alpha_star), -:constrains(),:enables(),:proof_deps(derive_kappa_star_independently), -:equations(alpha_star_kappa_relation,alpha_inverse_relation),:notes()); - -:node(d5b,:label(quantum_decoherence_functional),:kind(dynamics),:status(open), -:parents(p1,d1),:consumes(causal_set,action_of_c,kernel_c_cp),:produces(z_functional,decoherence_functional), -:constrains(),:enables(),:proof_deps(trace_class_convergence,hilbert_reconstruction), -:equations(path_sum_z,decoherence_functional_sum),:notes()); - -:node(c_hilb,:label(hilbert_branch_reconstruction_bridge),:kind(consistency),:status(open), -:parents(d5b),:consumes(decoherent_histories),:produces(psi_state,branch_projectors), -:constrains(),:enables(),:proof_deps(nonperturbative_convergence,orthonormal_branch_records), -:equations(),:notes()); - -:node(c_q,:label(quantum_measure_compatibility_bridge),:kind(consistency),:status(open), -:parents(d5a,d5b,c_hilb),:consumes(mu_n_plus,decoherence_functional,hilbert_branches),:produces(born_probabilities), -:constrains(),:enables(),:proof_deps(), -:equations(decoherent_histories_diagonal,p_i_decoherence_diagonal),:notes()); - -:node(b4,:label(born_rule),:kind(observable),:status(conditional), -:parents(c_q),:consumes(psi_superposition),:produces(p_k), -:constrains(),:enables(),:proof_deps(), -:equations(born_rule_projector_expectation),:notes()); - -:node(b5,:label(density_redshift_and_alignment_anisotropy),:kind(observable),:status(constructed), -:parents(e1obs),:consumes(g_obs,rho),:produces(redshift,alignment_anisotropy), -:constrains(),:enables(),:proof_deps(), -:equations(redshift_density_relation,alignment_anisotropy_gradient),:notes()) -); - -:edges( -:edge(p1,o1,constructs,constructed); -:edge(p2,o1,constructs,constructed); -:edge(o1,o2,constructs,constructed); -:edge(o1,o4,constructs,constructed); -:edge(o2,o4,constructs,constructed); -:edge(e1kin,o4,enables,conditional); -:edge(o1,o3,constructs,constructed); -:edge(o4,o3,constructs,constructed); -:edge(p2,o5,enables,constructed); -:edge(o2,o5,enables,constructed); -:edge(o4,o5,enables,constructed); -:edge(o3,o6,constructs,constructed); -:edge(o4,o6,constructs,constructed); -:edge(o5,o6,constructs,constructed); -:edge(o5,o7,enables,constructed); -:edge(o6,o7,enables,constructed); -:edge(o5,d1,constructs,constructed); -:edge(o6,d1,constructs,constructed); -:edge(o7,d1,constructs,constructed); -:edge(d1,d2,constructs,constructed); -:edge(p1,d5a,constructs,constructed); -:edge(d1,d5a,constructs,constructed); -:edge(d5a,e6,constructs,constructed); -:edge(p1,c_rec,constructs,constructed); -:edge(e6,c_rec,constructs,constructed); -:edge(p1,e1kin,constructs,constructed); -:edge(e6,e1kin,constructs,constructed); -:edge(c_rec,e1kin,constructs,constructed); -:edge(e1kin,d3,enables,constructed); -:edge(d3,e2,constructs,constructed); -:edge(d3,i2,proves,constructed); -:edge(o3,i2,proves,constructed); -:edge(o4,i2,proves,constructed); -:edge(o1,e1obs,constructs,constructed); -:edge(d3,e1obs,constructs,constructed); -:edge(d5a,e1obs,constructs,constructed); -:edge(e1kin,c_spin,constructs,constructed); -:edge(e1kin,e3,constructs,constructed); -:edge(c_spin,e3,constructs,constructed); -:edge(o5,c_tri,constructs,constructed); -:edge(o6,c_tri,constructs,constructed); -:edge(o7,c_tri,constructs,constructed); -:edge(c_tri,e5,proves,constructed); -:edge(e3,c_chiral,constructs,constructed); -:edge(e5,c_chiral,constructs,constructed); -:edge(c_chiral,i4,proves,constructed); -:edge(o7,c_mass,constructs,constructed); -:edge(d2,c_mass,constructs,constructed); -:edge(c_mass,e7,proves,constructed); -:edge(d1,d4,constructs,constructed); -:edge(d2,d4,constructs,constructed); -:edge(d3,d4,constructs,constructed); -:edge(d4,a1,flows_to,constructed); -:edge(o4,b1,constructs,constructed); -:edge(a1,b1,constructs,constructed); -:edge(o7,b2,constructs,constructed); -:edge(e7,b2,constructs,constructed); -:edge(d4,b3,constructs,constructed); -:edge(p1,d5b,constructs,constructed); -:edge(d1,d5b,constructs,constructed); -:edge(d5b,c_hilb,constructs,constructed); -:edge(d5a,c_q,constructs,constructed); -:edge(d5b,c_q,constructs,constructed); -:edge(c_hilb,c_q,constructs,constructed); -:edge(c_q,b4,proves,constructed); -:edge(e1obs,b5,constructs,constructed) -); - -:validation( -:nodes(37), -:edges(66), -:errors(0), -:warnings(0), -:projection_authority(false), -:parent_order(parent_aware), -:source(cki_registry_vnext) -) -) \ No newline at end of file diff --git a/l64-admin/Cargo.toml b/l64-admin/Cargo.toml deleted file mode 100644 index 5422ee5..0000000 --- a/l64-admin/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "l64-admin" -version = "0.1.0" -edition = "2024" - -[dependencies] -anyhow = { workspace = true } -clap = { workspace = true } -l64-core = { path = "../l64-core" } -l64-locus = { path = "../l64-locus" } -l64-bundle = { path = "../l64-bundle" } -l64-command = { path = "../l64-command" } -l64-cert = { path = "../l64-cert" } -l64-atlas = { path = "../l64-atlas" } -l64-policy = { path = "../l64-policy" } -l64-observe = { path = "../l64-observe" } -l64-registry = { path = "../l64-registry" } -serde_json = { workspace = true } - -[dev-dependencies] -assert_cmd = "2.0" -serial_test = "3.2" diff --git a/l64-admin/src/main.rs b/l64-admin/src/main.rs deleted file mode 100644 index a456460..0000000 --- a/l64-admin/src/main.rs +++ /dev/null @@ -1,1521 +0,0 @@ -use anyhow::{Context, Result, anyhow}; -use clap::{Parser, Subcommand, ValueEnum}; -use l64_bundle::{BundleWorld, import_bundle_file, load_bundle_world}; -use l64_cert::{ - CertificationOptions, certify_derived_campaign_with_options, - certify_derived_theorem_with_options, encode_locus_packet_for_report, replay_report, - report_cache_path, report_id, -}; -use l64_command::{BundlePolicyArg, OptimizerPolicyArg}; -use l64_core::{ - ArtifactContract, ArtifactKind, ArtifactLocator, BundleLock, CapabilityReadiness, - CertificationReport, CommandContract, LockDiff, LockReceipt, MechanizationPolicyObject, - NamespaceScope, OptimizerPolicy, RegistryLookup, cache_hash_v1_bytes, cache_hash_v1_str, - locate_artifact, runtime_root_report, -}; -use l64_locus::{ - load_bundle_lock, load_execution_manifest, manifest_cache_root, persist_bundle_lock, - persist_execution_manifest, -}; -use l64_observe::{ - ExecutePlanOptions, assess_prediction, compare_executions, compare_locks, compare_manifests, - compare_report_manifest, compare_reports, drift_report, execute_plan, explain_drift, load_diff, - load_execution, load_plan, load_prediction, observe_report, plan_recompute_from_diff, - plan_recompute_from_prediction, predict_from_bundle_change, predict_from_policy_override, - reconcile_prediction_to_report, -}; -use l64_policy::{build_execution_manifest, build_replay_lock_manifest, resolve_policy_graph}; -use l64_registry::SeedRegistry; -use std::{fs, path::Path}; - -#[derive(Debug, Clone, ValueEnum)] -enum CompareKindArg { - Report, - Manifest, - Lock, -} - -#[derive(Debug, Parser)] -#[command(name = "l64-admin")] -struct Cli { - #[command(subcommand)] - command: Command, -} - -#[derive(Debug, Subcommand)] -enum Command { - LockBundle { - file: String, - #[arg(long, value_enum, default_value = "reject")] - conflict_policy: BundlePolicyArg, - #[arg(long, value_enum, default_value = "conservative")] - optimizer_policy: OptimizerPolicyArg, - #[arg(long)] - evaluator_policy: Option, - #[arg(long)] - cache_policy: Option, - #[arg(long, default_value_t = false)] - strict_policy: bool, - }, - DumpExecutionManifest { - id: String, - }, - DumpRuntimeRoots, - ReplayWithLock { - id: String, - #[arg(long, default_value_t = false)] - parallel_obligations: bool, - #[arg(long)] - max_obligation_workers: Option, - }, - ObserveRun { - #[arg(long)] - report: Option, - #[arg(long)] - lock: Option, - }, - CompareLocks { - left: String, - right: String, - }, - CompareReports { - left: String, - right: String, - }, - CompareManifests { - left: String, - right: String, - }, - CompareReportManifest { - report_id: String, - manifest_id: String, - }, - PredictImpact { - #[arg(long)] - report: Option, - #[arg(long)] - lock: Option, - #[arg(long)] - bundle_file: Option, - #[arg(long)] - policy: Option, - #[arg(long, value_enum, default_value = "reject")] - conflict_policy: BundlePolicyArg, - }, - PlanRecompute { - #[arg(long)] - prediction: Option, - #[arg(long)] - diff: Option, - }, - ExecutePlan { - #[arg(long)] - prediction: Option, - #[arg(long)] - plan: Option, - #[arg(long, default_value_t = false)] - dry_run: bool, - #[arg(long, default_value_t = false)] - strict: bool, - #[arg(long, default_value_t = false)] - no_cache: bool, - #[arg(long, default_value_t = false)] - parallel: bool, - #[arg(long, default_value_t = false)] - parallel_obligations: bool, - #[arg(long, default_value_t = false)] - serialized: bool, - #[arg(long)] - max_workers: Option, - #[arg(long)] - max_obligation_workers: Option, - #[arg(long, default_value_t = false)] - strict_determinism: bool, - }, - ExplainExecution { - id: String, - }, - DumpExecutionDag { - id: String, - }, - DumpLanePlan { - id: String, - }, - ExplainObligationPlan { - id: String, - }, - DumpObligationDag { - id: String, - }, - DumpObligationLanes { - id: String, - }, - CompareObligationExecutions { - left: String, - right: String, - }, - CompareSchedules { - left: String, - right: String, - }, - ExplainPlan { - id: String, - }, - ExplainDrift { - left: String, - right: String, - #[arg(long, value_enum, default_value = "report")] - kind: CompareKindArg, - }, - CompareExecutions { - left: String, - right: String, - }, - AssessPrediction { - prediction_id: String, - actual_report_id: String, - }, - ReconcileRun { - #[arg(long)] - prediction: String, - #[arg(long = "actual-report")] - actual_report: String, - }, - DumpPolicyGraph { - #[arg(long)] - bundle: Option, - }, - ExplainPolicyResolution { - #[arg(long)] - bundle: Option, - #[arg(long)] - policy: Option, - }, - ResolveArtifactPath { - id: String, - }, - ClassifyArtifact { - id: String, - }, - CheckCommandInput { - #[arg(long)] - command: String, - #[arg(long)] - id: String, - }, - DumpCommandContracts, - DumpArtifactContracts, - DumpCapabilityReadiness, - DumpCacheNamespaces, -} - -fn main() -> Result<()> { - std::thread::Builder::new() - .name("l64-admin-main".into()) - .stack_size(32 * 1024 * 1024) - .spawn(real_main) - .map_err(|err| anyhow!("failed to start l64-admin main thread: {err}"))? - .join() - .map_err(|_| anyhow!("l64-admin main thread panicked"))? -} - -fn real_main() -> Result<()> { - let cli = Cli::parse(); - let registry = SeedRegistry::load().context("failed to load seed registry")?; - match cli.command { - Command::LockBundle { - file, - conflict_policy, - optimizer_policy, - evaluator_policy, - cache_policy, - strict_policy, - } => { - let world = import_bundle_file(Path::new(&file), None, conflict_policy.into(), None)?; - let options = build_cert_options( - optimizer_policy.into(), - &file, - &world.manifest.id, - evaluator_policy, - cache_policy, - strict_policy, - )?; - let resolved = resolve_for_world(&world, &options)?; - let reports = certify_bundle_world(&world, &options)?; - let route_winner_ids = reports - .iter() - .filter_map(|report| report.selected_atlas_cell.clone()) - .collect::>(); - let report_ids = reports.iter().map(report_id).collect::>(); - let manifest = build_execution_manifest( - &world.manifest.id, - &options.bundle_hash, - world.manifest.dependencies.clone(), - &resolved.resolution, - route_winner_ids, - vec!["l64-cert-obl-v7".into()], - vec!["v7-surfaces".into()], - report_ids.clone(), - ); - persist_execution_manifest(&manifest)?; - let lock = BundleLock { - id: format!("BLK_{}", cache_hash_v1_str(&manifest.id)), - bundle_id: world.manifest.id.clone(), - bundle_hash: options.bundle_hash.clone(), - policy_resolution_id: resolved.resolution.id.clone(), - report_ids: report_ids.clone(), - manifest_id: manifest.id.clone(), - }; - persist_bundle_lock(&lock)?; - for report in reports { - persist_report_document_with_lock(&report, &manifest.id, &lock.id)?; - } - let replay_manifest = build_replay_lock_manifest( - report_ids.first().map(String::as_str).unwrap_or(&lock.id), - &manifest.policy_manifest.policy_hash, - &manifest.route_winner_ids.join("|"), - &manifest.policy_manifest.policy_hash, - &manifest.bundle_hash, - ); - let receipt = LockReceipt { - id: format!("LRC_{}", cache_hash_v1_str(&lock.id)), - lock_id: lock.id.clone(), - manifest_id: manifest.id.clone(), - bundle_id: world.manifest.id.clone(), - receipt_ids: Vec::new(), - verdict: resolved.resolution.verdict.clone(), - }; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "lock": lock, - "manifest": manifest, - "replay_lock": replay_manifest, - "receipt": receipt - }))? - ); - } - Command::DumpExecutionManifest { id } => { - let manifest = load_execution_manifest(&id)?; - println!("{}", serde_json::to_string_pretty(&manifest)?); - } - Command::DumpRuntimeRoots => { - let report = runtime_root_report(&[]).map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&report)?); - } - Command::ReplayWithLock { - id, - parallel_obligations: _parallel_obligations, - max_obligation_workers: _max_obligation_workers, - } => { - let lock = load_bundle_lock(&id)?; - let manifest = load_execution_manifest(&lock.manifest_id)?; - let world = load_bundle_world(&lock.bundle_id)?; - let options = CertificationOptions { - optimizer_policy: OptimizerPolicy::Conservative, - bundle_hash: manifest.bundle_hash.clone(), - policy_hash: manifest.policy_manifest.policy_hash.clone(), - bundle_id: Some(lock.bundle_id.clone()), - evaluator_policy: None, - cache_policy: None, - no_cache: false, - replay_only: true, - strict_derived: false, - strict_policy: false, - force_parallel_obligations: _parallel_obligations, - max_obligation_workers: _max_obligation_workers, - }; - let reports = certify_bundle_world(&world, &options)?; - let replayed_ids = reports.iter().map(report_id).collect::>(); - if replayed_ids != lock.report_ids { - return Err(anyhow!("locked report set changed during replay")); - } - let replayed_winners = reports - .iter() - .filter_map(|report| report.selected_atlas_cell.clone()) - .collect::>(); - if replayed_winners != manifest.route_winner_ids { - return Err(anyhow!("locked route winner set changed during replay")); - } - let reports = reports - .into_iter() - .map(|mut report| { - if let Some(envelope) = &mut report.execution_envelope { - envelope.manifest_id = Some(manifest.id.clone()); - envelope.lock_id = Some(lock.id.clone()); - } - report - }) - .collect::>(); - println!("{}", serde_json::to_string_pretty(&reports)?); - } - Command::ObserveRun { report, lock } => { - let reports = if let Some(report_id) = report { - vec![replay_report(&report_id).map_err(anyhow::Error::msg)?] - } else if let Some(lock_id) = lock { - let lock = load_bundle_lock(&lock_id)?; - lock.report_ids - .iter() - .map(|id| replay_report(id).map_err(anyhow::Error::msg)) - .collect::>>()? - } else { - return Err(anyhow!("use --report or --lock ")); - }; - let observations = reports - .iter() - .map(|report| { - let manifest = report - .execution_envelope - .as_ref() - .and_then(|item| item.manifest_id.as_ref()) - .and_then(|id| load_execution_manifest(id).ok()); - let lock = report - .execution_envelope - .as_ref() - .and_then(|item| item.lock_id.as_ref()) - .and_then(|id| load_bundle_lock(id).ok()); - observe_report(report, manifest.as_ref(), lock.as_ref()) - }) - .collect::>>()?; - println!("{}", serde_json::to_string_pretty(&observations)?); - } - Command::CompareLocks { left, right } => { - let left_lock = load_bundle_lock(&left)?; - let right_lock = load_bundle_lock(&right)?; - let left_manifest = load_execution_manifest(&left_lock.manifest_id)?; - let right_manifest = load_execution_manifest(&right_lock.manifest_id)?; - let mut changed_fields = Vec::new(); - let semantic = compare_locks(&left_lock, &left_manifest, &right_lock, &right_manifest)?; - if left_lock.bundle_hash != right_lock.bundle_hash { - changed_fields.push("bundle_hash".into()); - } - if left_manifest.policy_manifest.policy_hash - != right_manifest.policy_manifest.policy_hash - { - changed_fields.push("policy_hash".into()); - } - if left_manifest.route_winner_ids != right_manifest.route_winner_ids { - changed_fields.push("route_winner_ids".into()); - } - if left_manifest.report_ids != right_manifest.report_ids { - changed_fields.push("report_ids".into()); - } - let diff = LockDiff { - id: format!("LDF_{}", cache_hash_v1_str(&(left.clone() + &right))), - left_lock_id: left, - right_lock_id: right, - changed_fields, - semantic_changes: semantic.summary, - }; - println!("{}", serde_json::to_string_pretty(&diff)?); - } - Command::CompareReports { left, right } => { - let left_report = replay_report(&left).map_err(anyhow::Error::msg)?; - let right_report = replay_report(&right).map_err(anyhow::Error::msg)?; - let diff = compare_reports(&left_report, &right_report)?; - println!("{}", serde_json::to_string_pretty(&diff)?); - } - Command::CompareManifests { left, right } => { - let left_manifest = load_execution_manifest(&left)?; - let right_manifest = load_execution_manifest(&right)?; - let diff = compare_manifests(&left_manifest, &right_manifest)?; - println!("{}", serde_json::to_string_pretty(&diff)?); - } - Command::CompareReportManifest { - report_id, - manifest_id, - } => { - let report = replay_report(&report_id).map_err(anyhow::Error::msg)?; - let manifest = load_execution_manifest(&manifest_id)?; - let diff = compare_report_manifest(&report, &manifest)?; - println!("{}", serde_json::to_string_pretty(&diff)?); - } - Command::PredictImpact { - report, - lock, - bundle_file, - policy, - conflict_policy, - } => { - if report.is_some() && lock.is_some() { - return Err(anyhow!( - "predict-impact accepts exactly one baseline selector: --report or --lock " - )); - } - if bundle_file.is_some() && policy.is_some() { - return Err(anyhow!( - "predict-impact accepts exactly one proposed-change selector: --bundle-file or --policy " - )); - } - let baseline_report = if let Some(report_id) = report { - replay_report(&report_id).map_err(anyhow::Error::msg)? - } else if let Some(lock_id) = lock { - let lock = load_bundle_lock(&lock_id)?; - let report_id = lock - .report_ids - .first() - .ok_or_else(|| anyhow!("lock has no report ids"))?; - replay_report(report_id).map_err(anyhow::Error::msg)? - } else { - return Err(anyhow!( - "predict-impact requires one baseline selector: --report or --lock ; use dump-command-contracts for details" - )); - }; - let prediction = if let Some(bundle_file) = bundle_file { - let proposed = import_bundle_file( - Path::new(&bundle_file), - None, - conflict_policy.into(), - None, - )?; - let baseline_bundle = baseline_report - .execution_envelope - .as_ref() - .and_then(|item| item.bundle_id.as_ref()) - .and_then(|id| load_bundle_world(id).ok()); - let resolved = resolve_policy_graph( - &proposed.overlay, - Some(&proposed.manifest.id), - proposed - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.as_str()), - proposed - .overlay - .local - .campaigns - .first() - .map(|item| item.id.as_str()), - proposed - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.as_str()), - false, - baseline_report - .route_explanation - .as_ref() - .map(|item| item.optimizer_policy.clone()) - .unwrap_or(OptimizerPolicy::Conservative), - ) - .map_err(anyhow::Error::msg)?; - predict_from_bundle_change( - &baseline_report, - baseline_bundle.as_ref(), - &proposed, - Some(&resolved.resolution), - )? - } else if let Some(policy_id) = policy { - let policy = registry - .get_policy_object(&policy_id) - .ok_or_else(|| anyhow!("unknown policy `{policy_id}`"))?; - predict_from_policy_object(&baseline_report, &policy)? - } else { - return Err(anyhow!( - "predict-impact requires one proposed-change selector: --bundle-file or --policy ; use dump-command-contracts for details" - )); - }; - println!("{}", serde_json::to_string_pretty(&prediction)?); - } - Command::PlanRecompute { prediction, diff } => { - let plan = if let Some(prediction_id) = prediction { - let prediction = load_prediction(&prediction_id)?; - plan_recompute_from_prediction(&prediction)? - } else if let Some(diff_id) = diff { - let diff = load_diff(&diff_id)?; - plan_recompute_from_diff(&diff)? - } else { - return Err(anyhow!("use --prediction or --diff ")); - }; - println!("{}", serde_json::to_string_pretty(&plan)?); - } - Command::ExecutePlan { - prediction, - plan, - dry_run, - strict, - no_cache, - parallel, - parallel_obligations, - serialized, - max_workers, - max_obligation_workers, - strict_determinism, - } => { - let plan = if let Some(prediction_id) = prediction { - let prediction = load_prediction(&prediction_id)?; - plan_recompute_from_prediction(&prediction)? - } else if let Some(plan_id) = plan { - load_plan(&plan_id)? - } else { - return Err(anyhow!("use --prediction or --plan ")); - }; - let execution = execute_plan( - &plan, - &ExecutePlanOptions { - dry_run, - no_cache, - strict, - force_parallel: parallel, - force_parallel_obligations: parallel_obligations, - force_serialized: serialized, - max_workers, - max_obligation_workers, - strict_determinism, - }, - )?; - println!("{}", serde_json::to_string_pretty(&execution)?); - } - Command::ExplainExecution { id } => match resolve_execution_record(&id) { - Ok(execution) => { - let explanation = serde_json::json!({ - "kind": "full-execution-record", - "id": execution.id, - "scheduler_policy": execution.scheduler_policy, - "scope": execution.execution_scope, - "lanes": execution.lane_records, - "obligation_lanes": execution.obligation_lanes, - "obligation_ordering": execution.obligation_ordering_receipts, - "ordering": execution.ordering_receipt, - "coherence": execution.coherence_receipts, - "notes": execution.explanation, - }); - println!("{}", serde_json::to_string_pretty(&explanation)?); - } - Err(primary_err) => { - let fallback = explain_execution_fallback(&id)?; - let explanation = serde_json::json!({ - "kind": "surrogate-execution-context", - "id": id, - "resolution": fallback, - "warning": primary_err.to_string(), - }); - println!("{}", serde_json::to_string_pretty(&explanation)?); - } - }, - Command::DumpExecutionDag { id } => { - let execution = resolve_execution_record(&id)?; - let nodes = execution - .outcomes - .iter() - .map(|item| { - serde_json::json!({ - "id": item.step_id, - "kind": item.kind, - "status": item.status - }) - }) - .collect::>(); - let edges = execution - .outcomes - .windows(2) - .map(|pair| { - serde_json::json!({ - "from": pair[0].step_id, - "to": pair[1].step_id, - "relation": "ordered-before" - }) - }) - .collect::>(); - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({"nodes": nodes, "edges": edges}))? - ); - } - Command::DumpLanePlan { id } => { - let execution = resolve_execution_record(&id)?; - println!("{}", serde_json::to_string_pretty(&execution.lane_records)?); - } - Command::ExplainObligationPlan { id } => { - let execution = resolve_execution_record(&id)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "plans": execution.obligation_plans, - "lanes": execution.obligation_lanes, - "ordering": execution.obligation_ordering_receipts, - "merge": execution.obligation_merge_receipts, - "replay_legality": execution.replay_legality_checks, - "barriers": execution.replay_barrier_receipts, - "obligation_statuses": execution - .resulting_reports - .iter() - .map(|report| serde_json::json!({ - "theorem_id": report.theorem_id, - "campaign_id": report.campaign_id, - "obligations": report.obligations, - })) - .collect::>(), - }))? - ); - } - Command::DumpObligationDag { id } => { - let execution = resolve_execution_record(&id)?; - let dags = execution - .obligation_plans - .iter() - .map(|plan| { - serde_json::json!({ - "plan_id": plan.id, - "theorem_id": plan.theorem_id, - "campaign_id": plan.campaign_id, - "nodes": plan.nodes, - "edges": plan.edges, - }) - }) - .collect::>(); - println!("{}", serde_json::to_string_pretty(&dags)?); - } - Command::DumpObligationLanes { id } => { - let execution = resolve_execution_record(&id)?; - println!( - "{}", - serde_json::to_string_pretty(&execution.obligation_lanes)? - ); - } - Command::CompareObligationExecutions { left, right } => { - let left = resolve_execution_record(&left)?; - let right = resolve_execution_record(&right)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "left": { - "plans": left.obligation_plans, - "lanes": left.obligation_lanes, - "reports": left.resulting_reports, - }, - "right": { - "plans": right.obligation_plans, - "lanes": right.obligation_lanes, - "reports": right.resulting_reports, - }, - "same": left.obligation_plans == right.obligation_plans && left.obligation_lanes == right.obligation_lanes, - }))? - ); - } - Command::CompareSchedules { left, right } => { - let left = resolve_execution_record(&left)?; - let right = resolve_execution_record(&right)?; - let output = serde_json::json!({ - "left": { - "schedule_hash": left.schedule_hash, - "lanes": left.lane_records, - }, - "right": { - "schedule_hash": right.schedule_hash, - "lanes": right.lane_records, - }, - "same_schedule": left.schedule_hash == right.schedule_hash && left.lane_records == right.lane_records, - }); - println!("{}", serde_json::to_string_pretty(&output)?); - } - Command::ExplainPlan { id } => { - let plan = load_plan(&id)?; - let explanation = serde_json::json!({ - "id": plan.id, - "prediction_id": plan.prediction_id, - "diff_id": plan.diff_id, - "reusable_artifacts": plan.reusable_artifacts, - "invalidated_artifacts": plan.invalidated_artifacts, - "steps": plan.steps, - "hints": plan.steps.iter().map(|step| serde_json::json!({ - "step_id": step.id, - "kind": step.kind, - "target_id": step.target_id, - "reason": step.reason - })).collect::>(), - "explanation": plan.explanation, - }); - println!("{}", serde_json::to_string_pretty(&explanation)?); - } - Command::ExplainDrift { left, right, kind } => { - let diff = match kind { - CompareKindArg::Report => { - let left_report = replay_report(&left).map_err(anyhow::Error::msg)?; - let right_report = replay_report(&right).map_err(anyhow::Error::msg)?; - compare_reports(&left_report, &right_report)? - } - CompareKindArg::Manifest => { - let left_manifest = load_execution_manifest(&left)?; - let right_manifest = load_execution_manifest(&right)?; - compare_manifests(&left_manifest, &right_manifest)? - } - CompareKindArg::Lock => { - let left_lock = load_bundle_lock(&left)?; - let right_lock = load_bundle_lock(&right)?; - let left_manifest = load_execution_manifest(&left_lock.manifest_id)?; - let right_manifest = load_execution_manifest(&right_lock.manifest_id)?; - compare_locks(&left_lock, &left_manifest, &right_lock, &right_manifest)? - } - }; - let explanation = explain_drift(&diff)?; - let drift = drift_report(&diff)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "diff": diff, - "drift": drift, - "explanation": explanation - }))? - ); - } - Command::CompareExecutions { left, right } => { - let left = resolve_execution_record(&left)?; - let right = resolve_execution_record(&right)?; - let diff = compare_executions(&left, &right)?; - println!("{}", serde_json::to_string_pretty(&diff)?); - } - Command::AssessPrediction { - prediction_id, - actual_report_id, - } => { - let prediction = load_prediction(&prediction_id)?; - let actual_report = replay_report(&actual_report_id).map_err(anyhow::Error::msg)?; - let assessment = assess_prediction(&prediction, &actual_report)?; - println!("{}", serde_json::to_string_pretty(&assessment)?); - } - Command::ReconcileRun { - prediction, - actual_report, - } => { - let prediction = load_prediction(&prediction)?; - let actual_report = replay_report(&actual_report).map_err(anyhow::Error::msg)?; - let reconciliation = reconcile_prediction_to_report(&prediction, &actual_report)?; - println!("{}", serde_json::to_string_pretty(&reconciliation)?); - } - Command::DumpPolicyGraph { bundle } => { - let resolution = if let Some(bundle_id) = bundle { - let world = load_bundle_world(&bundle_id)?; - resolve_policy_graph( - &world.overlay, - Some(&bundle_id), - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .campaigns - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.as_str()), - false, - OptimizerPolicy::Conservative, - ) - .map_err(anyhow::Error::msg)? - } else { - resolve_policy_graph( - ®istry, - None, - None, - None, - None, - false, - OptimizerPolicy::Conservative, - ) - .map_err(anyhow::Error::msg)? - }; - println!("{}", serde_json::to_string_pretty(&resolution)?); - } - Command::ExplainPolicyResolution { bundle, policy } => { - let resolved = if let Some(bundle_id) = bundle { - let world = load_bundle_world(&bundle_id)?; - resolve_policy_graph( - &world.overlay, - Some(&bundle_id), - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .campaigns - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.as_str()), - true, - OptimizerPolicy::Conservative, - ) - .map_err(anyhow::Error::msg)? - } else { - resolve_policy_graph( - ®istry, - None, - None, - None, - None, - true, - OptimizerPolicy::Conservative, - ) - .map_err(anyhow::Error::msg)? - }; - let output = if let Some(policy_id) = policy { - serde_json::json!({ - "policy": policy_id, - "applied": resolved.resolution.applied_policy_ids.iter().any(|id| id == &policy_id), - "trace": resolved.resolution.trace.steps, - "conflicts": resolved.resolution.conflicts, - }) - } else { - serde_json::to_value(&resolved.resolution)? - }; - println!("{}", serde_json::to_string_pretty(&output)?); - } - Command::ResolveArtifactPath { id } => { - let locator = locate_known_artifact(&id)?; - println!("{}", serde_json::to_string_pretty(&locator)?); - } - Command::ClassifyArtifact { id } => { - let info = classify_artifact(&id)?; - println!("{}", serde_json::to_string_pretty(&info)?); - } - Command::CheckCommandInput { command, id } => { - let info = classify_artifact(&id)?; - let contract = command_contract_by_name(&command).ok_or_else(|| { - anyhow!("unknown command `{command}`; use dump-command-contracts") - })?; - let accepted = info - .get("kind") - .and_then(|v| v.as_str()) - .map(|kind| { - contract - .accepted_inputs - .iter() - .any(|item| format!("{:?}", item) == kind) - }) - .unwrap_or(false); - let output = serde_json::json!({ - "command": contract.command, - "artifact": info, - "accepted": accepted, - "reason": if accepted { - "artifact kind is accepted by command contract" - } else { - "artifact kind is not accepted by command contract" - }, - "command_contract": contract, - }); - println!("{}", serde_json::to_string_pretty(&output)?); - } - Command::DumpCommandContracts => { - println!("{}", serde_json::to_string_pretty(&command_contracts())?); - } - Command::DumpArtifactContracts => { - println!("{}", serde_json::to_string_pretty(&artifact_contracts())?); - } - Command::DumpCapabilityReadiness => { - let mut readiness = std::collections::BTreeMap::new(); - for contract in command_contracts() { - let bucket = format!("{:?}", contract.readiness); - readiness - .entry(bucket) - .or_insert_with(Vec::new) - .push(contract.command); - } - println!( - "{}", - serde_json::to_string_pretty( - &serde_json::json!({"readiness": readiness, "count": command_contracts().len()}) - )? - ); - } - Command::DumpCacheNamespaces => { - println!( - "{}", - serde_json::to_string_pretty(&dump_cache_namespaces()?)? - ); - } - } - Ok(()) -} - -fn build_cert_options( - optimizer_policy: OptimizerPolicy, - file: &str, - bundle_id: &str, - evaluator_policy: Option, - cache_policy: Option, - strict_policy: bool, -) -> Result { - let input = fs::read(file).with_context(|| format!("failed to read `{file}`"))?; - Ok(CertificationOptions { - optimizer_policy: optimizer_policy.clone(), - bundle_hash: cache_hash_v1_bytes(&input), - policy_hash: cache_hash_v1_str(&format!( - "{optimizer_policy:?}|evaluator={:?}|cache={:?}|strict={strict_policy}", - evaluator_policy, cache_policy - )), - bundle_id: Some(bundle_id.to_string()), - evaluator_policy, - cache_policy, - no_cache: false, - replay_only: false, - strict_derived: false, - strict_policy, - force_parallel_obligations: false, - max_obligation_workers: None, - }) -} - -fn resolve_for_world( - world: &BundleWorld, - options: &CertificationOptions, -) -> Result { - resolve_policy_graph( - &world.overlay, - Some(&world.manifest.id), - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .campaigns - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.as_str()), - options.strict_policy, - options.optimizer_policy.clone(), - ) - .map_err(anyhow::Error::msg) -} - -fn certify_bundle_world( - world: &BundleWorld, - options: &CertificationOptions, -) -> Result> { - let mut reports = Vec::new(); - if world.overlay.local.campaigns.is_empty() { - for theorem in &world.overlay.local.theorem_specs { - let target = world.overlay.local.target_profiles.first().ok_or_else(|| { - anyhow!("bundle theorem execution requires at least one target profile") - })?; - let atlas = - l64_atlas::CompiledAtlas::compile(&world.overlay).map_err(anyhow::Error::msg)?; - let report = certify_derived_theorem_with_options( - &world.overlay, - &atlas, - &theorem.id, - &target.id, - None, - options, - ) - .map_err(anyhow::Error::msg)?; - reports.push(report); - } - } else { - let atlas = - l64_atlas::CompiledAtlas::compile(&world.overlay).map_err(anyhow::Error::msg)?; - for campaign in &world.overlay.local.campaigns { - let report = certify_derived_campaign_with_options( - &world.overlay, - &atlas, - &campaign.id, - options, - ) - .map_err(anyhow::Error::msg)?; - reports.push(report); - } - } - Ok(reports) -} - -fn persist_report_document_with_lock( - report: &CertificationReport, - manifest_id: &str, - lock_id: &str, -) -> Result<()> { - let path = report_cache_path(&report_id(report))?; - let mut report = report.clone(); - if let Some(envelope) = &mut report.execution_envelope { - envelope.manifest_id = Some(manifest_id.to_string()); - envelope.lock_id = Some(lock_id.to_string()); - } - let bytes = encode_locus_packet_for_report(&report).map_err(anyhow::Error::msg)?; - fs::write(path, bytes)?; - Ok(()) -} - -fn predict_from_policy_object( - baseline_report: &CertificationReport, - policy: &MechanizationPolicyObject, -) -> Result { - let kind = match policy.kind { - l64_core::PolicyKind::Optimizer => "Optimizer", - l64_core::PolicyKind::Evaluator => "Evaluator", - l64_core::PolicyKind::ReplayCache => "ReplayCache", - _ => "Other", - }; - predict_from_policy_override(baseline_report, &policy.id, kind, policy.notes.clone()) -} - -fn locate_known_artifact(id: &str) -> Result { - let manifest = manifest_cache_root()?.join(format!("{id}.dna")); - if manifest.exists() { - return Ok(locate_artifact(id, "manifest", &manifest).map_err(anyhow::Error::msg)?); - } - let lock = manifest_cache_root()?.join(format!("{id}.lock.dna")); - if lock.exists() { - return Ok(locate_artifact(id, "lock", &lock).map_err(anyhow::Error::msg)?); - } - let report = report_cache_path(id)?; - if report.exists() { - return Ok(locate_artifact(id, "report", &report).map_err(anyhow::Error::msg)?); - } - let roots = runtime_root_report(&[]).map_err(anyhow::Error::msg)?; - Err(anyhow!( - "artifact `{id}` not found under {} or {}", - roots.project_root.absolute_path, - roots.cache_root.absolute_path - )) -} - -fn command_contracts() -> Vec { - vec![ - CommandContract { - command: "explain-execution".into(), - accepted_inputs: vec![ArtifactKind::PlanExecution, ArtifactKind::Report, ArtifactKind::ExecutionManifest, ArtifactKind::BundleLock, ArtifactKind::ObservationRecord], - produces: vec![ArtifactKind::ForensicBundle], - readiness: CapabilityReadiness::ContractKnown, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["execution-centric admin command; resolves through report/manifest/lock/observe references before scanning executions".into()], - }, - CommandContract { - command: "predict-impact".into(), - accepted_inputs: vec![ArtifactKind::Report, ArtifactKind::BundleLock], - produces: vec![ArtifactKind::PredictionRecord], - readiness: CapabilityReadiness::ContractKnown, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["requires exactly one baseline selector (--report or --lock) and exactly one proposed change selector (--bundle-file or --policy)".into()], - }, - CommandContract { - command: "dump-execution-manifest".into(), - accepted_inputs: vec![ArtifactKind::ExecutionManifest], - produces: vec![ArtifactKind::ExecutionManifest], - readiness: CapabilityReadiness::FullyExercised, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["manifest id only".into()], - }, - CommandContract { - command: "compare-executions".into(), - accepted_inputs: vec![ArtifactKind::PlanExecution], - produces: vec![ArtifactKind::ForensicBundle], - readiness: CapabilityReadiness::SmokeExecuted, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["compare realized execution records, not plan ids".into()], - }, - CommandContract { - command: "classify-artifact".into(), - accepted_inputs: vec![ArtifactKind::Report, ArtifactKind::ExecutionManifest, ArtifactKind::BundleLock, ArtifactKind::ObservationRecord, ArtifactKind::PlanExecution], - produces: vec![ArtifactKind::ForensicBundle], - readiness: CapabilityReadiness::SmokeExecuted, - namespace_scope: NamespaceScope::Any, - notes: vec!["artifact self-inspection surface for operational truth".into()], - }, - CommandContract { - command: "check-command-input".into(), - accepted_inputs: vec![ArtifactKind::Report, ArtifactKind::ExecutionManifest, ArtifactKind::BundleLock, ArtifactKind::ObservationRecord, ArtifactKind::PlanExecution, ArtifactKind::PredictionRecord, ArtifactKind::RecomputationPlan], - produces: vec![ArtifactKind::ForensicBundle], - readiness: CapabilityReadiness::SmokeExecuted, - namespace_scope: NamespaceScope::Any, - notes: vec!["checks whether a specific artifact id is lawful input for a command contract".into()], - }, - ] -} - -fn artifact_contracts() -> Vec { - vec![ - ArtifactContract { - kind: ArtifactKind::InspectionReport, - class: "inspection".into(), - standalone_validation_complete: false, - namespace_scope: NamespaceScope::Any, - notes: vec!["optimized for inspection/export; may omit theorem/route context needed for full standalone validation".into()], - }, - ArtifactContract { - kind: ArtifactKind::ValidationBundle, - class: "validation".into(), - standalone_validation_complete: true, - namespace_scope: NamespaceScope::Any, - notes: vec!["self-contained export intended for validate/replay-style standalone checking".into()], - }, - ArtifactContract { - kind: ArtifactKind::PlanExecution, - class: "execution".into(), - standalone_validation_complete: false, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["execution records are namespace-local operational artifacts".into()], - }, - ArtifactContract { - kind: ArtifactKind::Report, - class: "report".into(), - standalone_validation_complete: false, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["live report ids may resolve into execution, manifest, and observation context inside the same namespace".into()], - }, - ArtifactContract { - kind: ArtifactKind::ExecutionManifest, - class: "manifest".into(), - standalone_validation_complete: false, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["execution manifests are operational context artifacts and may lead to execution reports but are not themselves validation bundles".into()], - }, - ArtifactContract { - kind: ArtifactKind::BundleLock, - class: "lock".into(), - standalone_validation_complete: false, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["bundle locks pin replay and report sets inside one namespace".into()], - }, - ArtifactContract { - kind: ArtifactKind::ObservationRecord, - class: "observation".into(), - standalone_validation_complete: false, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["observation records expose execution context indirectly through report linkage".into()], - }, - ArtifactContract { - kind: ArtifactKind::PredictionRecord, - class: "prediction".into(), - standalone_validation_complete: false, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["prediction records are advisory frontier artifacts, not validation-complete truth".into()], - }, - ArtifactContract { - kind: ArtifactKind::RecomputationPlan, - class: "plan".into(), - standalone_validation_complete: false, - namespace_scope: NamespaceScope::SameNamespace, - notes: vec!["recomputation plans are executable within one cache/runtime context".into()], - }, - ] -} - -fn command_contract_by_name(command: &str) -> Option { - command_contracts() - .into_iter() - .find(|item| item.command == command) -} - -fn artifact_contract_for_kind(kind: ArtifactKind) -> Option { - artifact_contracts() - .into_iter() - .find(|item| item.kind == kind) -} - -fn classify_artifact(id: &str) -> Result { - if let Ok(record) = load_execution(id) { - let locator = locate_known_artifact(id).ok(); - let contract = artifact_contract_for_kind(ArtifactKind::PlanExecution); - return Ok(serde_json::json!({ - "id": id, - "kind": format!("{:?}", ArtifactKind::PlanExecution), - "locator": locator, - "contract": contract, - "linked_reports": record.resulting_report_ids, - "linked_manifests": record.manifest_ids, - "linked_locks": record.lock_ids, - })); - } - if let Ok(observation) = l64_observe::load_observation(id) { - let locator = locate_known_artifact(id).ok(); - let contract = artifact_contract_for_kind(ArtifactKind::ObservationRecord); - return Ok(serde_json::json!({ - "id": id, - "kind": format!("{:?}", ArtifactKind::ObservationRecord), - "locator": locator, - "contract": contract, - "linked_report": observation.record.report_id, - })); - } - if let Ok(report) = replay_report(id).map_err(anyhow::Error::msg) { - let locator = locate_known_artifact(id).ok(); - let contract = artifact_contract_for_kind(ArtifactKind::Report); - return Ok(serde_json::json!({ - "id": id, - "kind": format!("{:?}", ArtifactKind::Report), - "locator": locator, - "contract": contract, - "execution_envelope": report.execution_envelope, - "selected_atlas_cell": report.selected_atlas_cell, - })); - } - if let Ok(manifest) = load_execution_manifest(id) { - let locator = locate_known_artifact(id).ok(); - let contract = artifact_contract_for_kind(ArtifactKind::ExecutionManifest); - return Ok(serde_json::json!({ - "id": id, - "kind": format!("{:?}", ArtifactKind::ExecutionManifest), - "locator": locator, - "contract": contract, - "report_ids": manifest.report_ids, - "rerun_artifacts": manifest.rerun_artifacts, - })); - } - if let Ok(lock) = load_bundle_lock(id) { - let locator = locate_known_artifact(id).ok(); - let contract = artifact_contract_for_kind(ArtifactKind::BundleLock); - return Ok(serde_json::json!({ - "id": id, - "kind": format!("{:?}", ArtifactKind::BundleLock), - "locator": locator, - "contract": contract, - "manifest_id": lock.manifest_id, - "report_ids": lock.report_ids, - })); - } - if let Ok(locator) = locate_known_artifact(id) { - return Ok(serde_json::json!({ - "id": id, - "kind": "UnclassifiedLocatedArtifact", - "locator": locator, - "warning": "artifact path exists but no typed loader classified it" - })); - } - Err(anyhow!("artifact `{id}` could not be classified")) -} - -fn resolve_execution_record(id: &str) -> Result { - if let Ok(record) = load_execution(id) { - return Ok(record); - } - if let Ok(observation) = l64_observe::load_observation(id) { - return resolve_execution_record_from_report_id(&observation.record.report_id); - } - if let Ok(report) = replay_report(id).map_err(anyhow::Error::msg) { - return resolve_execution_record_from_report(&report); - } - if let Ok(manifest) = load_execution_manifest(id) { - if let Some(record) = scan_execution_records(|item| { - item.manifest_ids - .iter() - .any(|manifest_id| manifest_id == &manifest.id) - })? { - return Ok(record); - } - } - if let Ok(lock) = load_bundle_lock(id) { - if let Some(record) = - scan_execution_records(|item| item.lock_ids.iter().any(|lock_id| lock_id == &lock.id))? - { - return Ok(record); - } - for report_id in &lock.report_ids { - if let Ok(record) = resolve_execution_record_from_report_id(report_id) { - return Ok(record); - } - } - } - Err(anyhow!( - "no execution record could be resolved from `{id}`; use dump-command-contracts for accepted inputs" - )) -} - -fn resolve_execution_record_from_report_id( - report_id: &str, -) -> Result { - let report = replay_report(report_id).map_err(anyhow::Error::msg)?; - resolve_execution_record_from_report(&report) -} - -fn resolve_execution_record_from_report( - report: &CertificationReport, -) -> Result { - if let Some(execution_id) = report - .execution_envelope - .as_ref() - .and_then(|item| item.executed_plan_id.as_ref()) - { - if let Ok(record) = load_execution(execution_id) { - return Ok(record); - } - } - if let Some(record) = scan_execution_records(|item| { - item.resulting_report_ids - .iter() - .any(|id| id == &report_id(report)) - })? { - return Ok(record); - } - if let Some(manifest_id) = report - .execution_envelope - .as_ref() - .and_then(|item| item.manifest_id.as_ref()) - { - if let Some(record) = - scan_execution_records(|item| item.manifest_ids.iter().any(|id| id == manifest_id))? - { - return Ok(record); - } - } - if let Some(lock_id) = report - .execution_envelope - .as_ref() - .and_then(|item| item.lock_id.as_ref()) - { - if let Some(record) = - scan_execution_records(|item| item.lock_ids.iter().any(|id| id == lock_id))? - { - return Ok(record); - } - } - Err(anyhow!( - "no execution record linked to report `{}`", - report_id(report) - )) -} - -fn explain_execution_fallback(id: &str) -> Result { - let classified = classify_artifact(id).ok(); - if let Ok(observation) = l64_observe::load_observation(id) { - let route_events = observation - .record - .events - .iter() - .filter(|event| matches!(event.kind, l64_core::ExecutionEventKind::RouteSelected)) - .count(); - let obligation_traces = observation - .record - .events - .iter() - .filter(|event| { - matches!( - event.kind, - l64_core::ExecutionEventKind::ObligationEvaluated - ) - }) - .count(); - return Ok(serde_json::json!({ - "artifact_class": "observation-record", - "classification": classified, - "report_id": observation.record.report_id, - "record_id": observation.record.id, - "available": { - "decision_nodes": observation.graph.nodes.len(), - "route_events": route_events, - "obligation_traces": obligation_traces, - }, - "next_best_inputs": [observation.record.report_id.clone()], - "notes": ["full execution record unavailable; observation-derived execution context returned"] - })); - } - if let Ok(report) = replay_report(id).map_err(anyhow::Error::msg) { - let mut next = Vec::new(); - if let Some(env) = &report.execution_envelope { - if let Some(mid) = &env.manifest_id { - next.push(mid.clone()); - } - if let Some(lid) = &env.lock_id { - next.push(lid.clone()); - } - if let Some(eid) = &env.executed_plan_id { - next.push(eid.clone()); - } - } - return Ok(serde_json::json!({ - "artifact_class": "report", - "classification": classified, - "report_id": report_id(&report), - "execution_envelope": report.execution_envelope, - "selected_path": report.selected_path, - "next_best_inputs": next, - "notes": ["full execution record unavailable; report-linked execution envelope returned"] - })); - } - if let Ok(manifest) = load_execution_manifest(id) { - return Ok(serde_json::json!({ - "artifact_class": "execution-manifest", - "classification": classified, - "manifest_id": manifest.id, - "report_ids": manifest.report_ids, - "rerun_artifacts": manifest.rerun_artifacts, - "notes": ["full execution record unavailable; manifest-derived execution context returned"] - })); - } - if let Ok(lock) = load_bundle_lock(id) { - return Ok(serde_json::json!({ - "artifact_class": "bundle-lock", - "classification": classified, - "lock_id": lock.id, - "report_ids": lock.report_ids, - "manifest_id": lock.manifest_id, - "notes": ["full execution record unavailable; lock-derived execution context returned"] - })); - } - Err(anyhow!( - "no explainable execution context could be resolved from `{id}`; use dump-command-contracts for accepted inputs" - )) -} - -fn scan_execution_records( - mut predicate: impl FnMut(&l64_core::PlanExecutionRecord) -> bool, -) -> Result> { - let root = l64_core::resolve_cache_root().map_err(anyhow::Error::msg)?; - let dir = Path::new(&root.absolute_path).join("executions"); - if !dir.exists() { - return Ok(None); - } - for entry in fs::read_dir(dir)? { - let entry = entry?; - let path = entry.path(); - if path.extension().and_then(|item| item.to_str()) != Some("locus") - && path.extension().and_then(|item| item.to_str()) != Some("json") - { - continue; - } - let stem = match path.file_stem().and_then(|item| item.to_str()) { - Some(stem) => stem.to_string(), - None => continue, - }; - if let Ok(record) = load_execution(&stem) { - if predicate(&record) { - return Ok(Some(record)); - } - } - } - Ok(None) -} - -fn dump_cache_namespaces() -> Result> { - let project = l64_core::resolve_project_root().map_err(anyhow::Error::msg)?; - let root = Path::new(&project.absolute_path) - .join(".l64-cache") - .join("namespaces"); - if !root.exists() { - return Ok(Vec::new()); - } - let mut items = fs::read_dir(root)? - .filter_map(|entry| entry.ok()) - .filter(|entry| entry.path().is_dir()) - .map(|entry| entry.file_name().to_string_lossy().to_string()) - .collect::>(); - items.sort(); - Ok(items) -} diff --git a/l64-admin/tests/admin.rs b/l64-admin/tests/admin.rs deleted file mode 100644 index 74b154e..0000000 --- a/l64-admin/tests/admin.rs +++ /dev/null @@ -1,1908 +0,0 @@ -use assert_cmd::cargo::cargo_bin; -use l64_core::{LocusCapabilityMask, LocusOpcode, LocusPacketKind, QaDocument, QaEntry}; -use serde_json::Value; -use serial_test::serial; -use std::{ - cell::RefCell, - fs, - path::PathBuf, - process::Command, - time::{SystemTime, UNIX_EPOCH}, -}; - -thread_local! { - static TEST_NAMESPACE: RefCell> = const { RefCell::new(None) }; -} - -fn workspace_root() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .to_path_buf() -} - -fn test_namespace() -> String { - TEST_NAMESPACE.with(|slot| { - let mut slot = slot.borrow_mut(); - if slot.is_none() { - *slot = Some(format!( - "test_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - } - slot.clone().unwrap() - }) -} - -fn temp_dir() -> PathBuf { - let root = std::env::temp_dir().join("l64_admin_tests").join( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - .to_string(), - ); - fs::create_dir_all(&root).unwrap(); - root -} - -fn write_bundle(path: &PathBuf, content: &str) { - if path.extension().and_then(|ext| ext.to_str()) == Some("dna") { - let document = bundle_document_from_text(content); - let bytes = l64_locus::encode_section_packet( - LocusPacketKind::CanonicalTransfer, - LocusOpcode::CanonicalPayload, - "BND_ADMIN_TEST", - "bundle_document.v1", - &document, - LocusCapabilityMask::default(), - 1, - ) - .unwrap(); - fs::write(path, bytes).unwrap(); - } else { - fs::write(path, content).unwrap(); - } -} - -fn bundle_document_from_text(bundle: &str) -> QaDocument { - let entries = bundle - .lines() - .filter_map(|line| { - let line = line.trim(); - if line.is_empty() || line.starts_with("!l64-bundle") { - return None; - } - let (kind, payload) = line.split_once(' ').unwrap(); - Some(QaEntry::from_surface_json(kind, payload).unwrap()) - }) - .collect(); - QaDocument { entries } -} - -fn run_json(bin: &str, args: &[&str]) -> Value { - let output = Command::new(cargo_bin(bin)) - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", test_namespace()) - .args(args) - .output() - .unwrap(); - assert!( - output.status.success(), - "stderr={}", - String::from_utf8_lossy(&output.stderr) - ); - serde_json::from_slice(&output.stdout).unwrap() -} - -fn run_json_ns(namespace: &str, bin: &str, args: &[&str]) -> Value { - let output = Command::new(cargo_bin(bin)) - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", namespace) - .args(args) - .output() - .unwrap(); - assert!( - output.status.success(), - "bin={bin} args={args:?} stderr={}", - String::from_utf8_lossy(&output.stderr) - ); - serde_json::from_slice(&output.stdout).unwrap() -} - -fn clear_cache() { - let output = Command::new(cargo_bin("l64-cli")) - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", test_namespace()) - .args(["clear-cache", "--scope", "all"]) - .output() - .unwrap(); - assert!( - output.status.success(), - "stderr={}", - String::from_utf8_lossy(&output.stderr) - ); - let _ = fs::remove_dir_all( - workspace_root() - .join(".l64-cache") - .join("namespaces") - .join(test_namespace()), - ); -} - -fn route_bundle(stem: &str, optimizer_policy: &str) -> String { - route_bundle_named(stem, optimizer_policy, "THS_LOCAL_ROUTE", "CPG_LOCAL_ROUTE") -} - -fn route_bundle_named( - stem: &str, - optimizer_policy: &str, - theorem_id: &str, - campaign_id: &str, -) -> String { - let bundle_id = format!("BND_{}", stem.to_ascii_uppercase().replace('-', "_")); - let axes = if optimizer_policy == "ExecutionFirst" { - r#"["ExecutionCost","LossCompliance","Lawfulness","BundleResolution","SymbolicFidelity"]"# - } else { - r#"["SymbolicFidelity","SurfaceTransitionPenalty","IdentityPreservation","LossCompliance","ProofShapeSatisfiability","ExecutionCost"]"# - }; - format!( - r#"!l64-bundle v1 -policy-object {{"id":"MOP_{bundle_id}_OPT","kind":"Optimizer","scope":{{"Bundle":"{bundle_id}"}},"extends":null,"optimizer":{{"optimizer_policy":"{optimizer_policy}","backend":"Lexicographic","active_axes":{axes},"route_explanation_verbosity":"standard","symbolic_fidelity_preferred":{symbolic},"tie_break_rules":["shorter-path"]}},"evaluator":null,"replay_cache":null,"report":null,"canonicalizer_mode":null,"merge_policy":null,"notes":["bundle local optimizer"]}} -proof {{"id":"PS_LOCAL","kind":"Square","nodes":["a","b","c","d"],"edges":[{{"from":"a","to":"b","label":"f"}},{{"from":"b","to":"d","label":"g"}},{{"from":"a","to":"c","label":"h"}},{{"from":"c","to":"d","label":"i"}}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"}} -bridge {{"id":"B_FAST","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":["symbolic"],"reversibility":"LossySupported","receipts":["r"],"rollback":"conditional"}} -bridge {{"id":"B_FAITHFUL_1","src":"R_TOP","tgt":"R_SET","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":[],"loss":[],"reversibility":"Conservative","receipts":["r"],"rollback":"allowed"}} -bridge {{"id":"B_FAITHFUL_2","src":"R_SET","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"}} -atlas {{"id":"A_FAST","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"General","proof_target":"route","candidate_paths":[["B_FAST"]],"normalized_winner":["B_FAST"],"winner_state":"Candidate","loss_profile":{{"items":["symbolic-loss"]}},"proof_shapes_checked":["PS_LOCAL"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{{"compatibility":"DebugMirrorOnly","penalties":[{{"reason":"debug-collapse","amount":4}}],"total_penalty":4}}}} -atlas {{"id":"A_FAITHFUL","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"General","proof_target":"route","candidate_paths":[["B_FAITHFUL_1","B_FAITHFUL_2"]],"normalized_winner":["B_FAITHFUL_1","B_FAITHFUL_2"],"winner_state":"Candidate","loss_profile":{{"items":[]}},"proof_shapes_checked":["PS_LOCAL"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{{"compatibility":"SymbolicFidelityPreserving","penalties":[],"total_penalty":0}}}} -theorem {{"id":"{theorem_id}","statement":"local route","hosts":["R_TOP","R_CALC"],"bridges":["B_FAST","B_FAITHFUL_1","B_FAITHFUL_2"],"operators":["OPR.Local"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_LOCAL"]}} -obligation {{"id":"OBL_LOCAL_ADM","kind":"OblAdm","description":"adm","status":"Benchmarked"}} -target {{"id":"TGT_LOCAL_ROUTE","burden_class":"General","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["LossySupported","Conservative","Enriching"],"loss_ceiling":4,"rollback_ceiling":4,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]}} -ledger {{"id":"TRL_LOCAL_ROUTE","theorem":"{theorem_id}","paths":[["B_FAST"],["B_FAITHFUL_1","B_FAITHFUL_2"]],"budget":{{"max_loss":4,"allow_lossy_supported":true,"require_proof":true}},"losses":[],"receipts":[],"normalized_path":["B_FAST"]}} -campaign {{"id":"{campaign_id}","theorem":"{theorem_id}","target_profile":"TGT_LOCAL_ROUTE","route_ledger":"TRL_LOCAL_ROUTE","obligations":["OBL_LOCAL_ADM"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["route"]}} -"#, - symbolic = if optimizer_policy == "SymbolicFidelityFirst" { - "true" - } else { - "false" - }, - axes = axes, - theorem_id = theorem_id, - campaign_id = campaign_id, - ) -} - -fn evaluator_bundle(stem: &str, strict: bool) -> String { - let bundle_id = format!("BND_{}", stem.to_ascii_uppercase().replace('-', "_")); - let policy_line = if strict { - format!( - r#"policy-object {{"id":"MOP_{bundle_id}_EVAL","kind":"Evaluator","scope":{{"Bundle":"{bundle_id}"}},"extends":null,"optimizer":null,"evaluator":{{"evidence_preference":"RecomputeIfSupported","allow_approximation":false,"unsupported_mode":"StrictFail","require_symbolic_fidelity_route":false,"prefer_comp_replay":false}},"replay_cache":null,"report":null,"canonicalizer_mode":null,"merge_policy":null,"notes":["strict evaluator"]}}"# - ) - } else { - String::new() - }; - format!( - r#"!l64-bundle v1 -{policy_line} -proof {{"id":"PS_EVAL","kind":"Square","nodes":["a","b","c","d"],"edges":[{{"from":"a","to":"b","label":"f"}},{{"from":"b","to":"d","label":"g"}},{{"from":"a","to":"c","label":"h"}},{{"from":"c","to":"d","label":"i"}}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"}} -bridge {{"id":"B_EVAL","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"}} -atlas {{"id":"A_EVAL","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"General","proof_target":"eval","candidate_paths":[["B_EVAL"]],"normalized_winner":["B_EVAL"],"winner_state":"Candidate","loss_profile":{{"items":[]}},"proof_shapes_checked":["PS_EVAL"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}}}} -theorem {{"id":"THS_LOCAL_EVAL","statement":"local eval","hosts":["R_TOP","R_CALC"],"bridges":["B_EVAL"],"operators":["OPR.Local"],"target_equivalence":"eq","obligations":["OblEq"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_EVAL"]}} -obligation {{"id":"OBL_LOCAL_EQ","kind":"OblEq","description":"unsupported eq","status":"Benchmarked"}} -target {{"id":"TGT_LOCAL_EVAL","burden_class":"General","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]}} -ledger {{"id":"TRL_LOCAL_EVAL","theorem":"THS_LOCAL_EVAL","paths":[["B_EVAL"]],"budget":{{"max_loss":1,"allow_lossy_supported":false,"require_proof":true}},"losses":[],"receipts":[],"normalized_path":["B_EVAL"]}} -campaign {{"id":"CPG_LOCAL_EVAL","theorem":"THS_LOCAL_EVAL","target_profile":"TGT_LOCAL_EVAL","route_ledger":"TRL_LOCAL_EVAL","obligations":["OBL_LOCAL_EQ"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["eval"]}} -"# - ) -} - -fn replay_bundle(stem: &str, replay_allowed: bool) -> String { - let bundle_id = format!("BND_{}", stem.to_ascii_uppercase().replace('-', "_")); - let policy_line = format!( - r#"policy-object {{"id":"MOP_{bundle_id}_REPLAY","kind":"ReplayCache","scope":{{"Bundle":"{bundle_id}"}},"extends":null,"optimizer":null,"evaluator":null,"replay_cache":{{"replay_allowed":{replay_allowed},"exact_policy_match_required":true,"survive_surface_only_changes":false,"reuse_approximate_results":true,"optimizer_change_invalidates":true,"surface_pack_change_invalidates":true,"trust_class":"ExactPolicyOnly"}},"report":null,"canonicalizer_mode":null,"merge_policy":null,"notes":["replay policy"]}}"# - ); - format!( - r#"!l64-bundle v1 -{policy_line} -proof {{"id":"PS_REPLAY","kind":"Square","nodes":["a","b","c","d"],"edges":[{{"from":"a","to":"b","label":"f"}},{{"from":"b","to":"d","label":"g"}},{{"from":"a","to":"c","label":"h"}},{{"from":"c","to":"d","label":"i"}}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"}} -bridge {{"id":"B_REPLAY","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"}} -atlas {{"id":"A_REPLAY","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"General","proof_target":"replay","candidate_paths":[["B_REPLAY"]],"normalized_winner":["B_REPLAY"],"winner_state":"Candidate","loss_profile":{{"items":[]}},"proof_shapes_checked":["PS_REPLAY"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}}}} -theorem {{"id":"THS_LOCAL_REPLAY","statement":"local replay","hosts":["R_TOP","R_CALC"],"bridges":["B_REPLAY"],"operators":["OPR.Local"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_REPLAY"]}} -obligation {{"id":"OBL_LOCAL_REPLAY","kind":"OblAdm","description":"adm","status":"Benchmarked"}} -target {{"id":"TGT_LOCAL_REPLAY","burden_class":"General","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]}} -ledger {{"id":"TRL_LOCAL_REPLAY","theorem":"THS_LOCAL_REPLAY","paths":[["B_REPLAY"]],"budget":{{"max_loss":1,"allow_lossy_supported":false,"require_proof":true}},"losses":[],"receipts":[],"normalized_path":["B_REPLAY"]}} -campaign {{"id":"CPG_LOCAL_REPLAY","theorem":"THS_LOCAL_REPLAY","target_profile":"TGT_LOCAL_REPLAY","route_ledger":"TRL_LOCAL_REPLAY","obligations":["OBL_LOCAL_REPLAY"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["replay"]}} -"# - ) -} - -fn parallel_campaign_bundle(stem: &str) -> String { - let bundle_id = format!("BND_{}", stem.to_ascii_uppercase().replace('-', "_")); - format!( - r#"!l64-bundle v1 -policy-object {{"id":"MOP_{bundle_id}_SCHED","kind":"ReportExport","scope":{{"Bundle":"{bundle_id}"}},"extends":null,"optimizer":null,"evaluator":null,"replay_cache":null,"report":{{"export_surfaces":[],"include_policy_trace":true,"include_route_explanation":true,"include_obligation_logs":true}},"scheduler":{{"parallelization":"ParallelIndependent","max_workers":2,"allow_parallel_replay":false,"allow_parallel_certification":true,"allow_parallel_exports":true,"deterministic_ordering":true}},"canonicalizer_mode":null,"merge_policy":null,"notes":["parallel scheduler policy"]}} -proof {{"id":"PS_PAR","kind":"Square","nodes":["a","b","c","d"],"edges":[{{"from":"a","to":"b","label":"f"}},{{"from":"b","to":"d","label":"g"}},{{"from":"a","to":"c","label":"h"}},{{"from":"c","to":"d","label":"i"}}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"}} -bridge {{"id":"B_PAR","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"}} -atlas {{"id":"A_PAR","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"General","proof_target":"parallel","candidate_paths":[["B_PAR"]],"normalized_winner":["B_PAR"],"winner_state":"Candidate","loss_profile":{{"items":[]}},"proof_shapes_checked":["PS_PAR"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}}}} -theorem {{"id":"THS_PAR_A","statement":"parallel A","hosts":["R_TOP","R_CALC"],"bridges":["B_PAR"],"operators":["OPR.ParA"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_PAR"]}} -theorem {{"id":"THS_PAR_B","statement":"parallel B","hosts":["R_TOP","R_CALC"],"bridges":["B_PAR"],"operators":["OPR.ParB"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_PAR"]}} -obligation {{"id":"OBL_PAR","kind":"OblAdm","description":"adm","status":"Benchmarked"}} -target {{"id":"TGT_PAR","burden_class":"General","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]}} -ledger {{"id":"TRL_PAR_A","theorem":"THS_PAR_A","paths":[["B_PAR"]],"budget":{{"max_loss":1,"allow_lossy_supported":false,"require_proof":true}},"losses":[],"receipts":[],"normalized_path":["B_PAR"]}} -ledger {{"id":"TRL_PAR_B","theorem":"THS_PAR_B","paths":[["B_PAR"]],"budget":{{"max_loss":1,"allow_lossy_supported":false,"require_proof":true}},"losses":[],"receipts":[],"normalized_path":["B_PAR"]}} -campaign {{"id":"CPG_PAR_A","theorem":"THS_PAR_A","target_profile":"TGT_PAR","route_ledger":"TRL_PAR_A","obligations":["OBL_PAR"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["parallel"]}} -campaign {{"id":"CPG_PAR_B","theorem":"THS_PAR_B","target_profile":"TGT_PAR","route_ledger":"TRL_PAR_B","obligations":["OBL_PAR"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["parallel"]}} -"# - ) -} - -fn parallel_campaign_bundle_with_optimizer(stem: &str, optimizer: &str) -> String { - let bundle_id = format!("BND_{}", stem.to_ascii_uppercase().replace('-', "_")); - let axes = if optimizer == "ExecutionFirst" { - r#"["ExecutionCost","LossCompliance","Lawfulness","BundleResolution","SymbolicFidelity"]"# - } else { - r#"["SymbolicFidelity","SurfaceTransitionPenalty","IdentityPreservation","LossCompliance","ExecutionCost"]"# - }; - let mut bundle = parallel_campaign_bundle(stem); - bundle.push_str(&format!( - "policy-object {{\"id\":\"MOP_{bundle_id}_OPT\",\"kind\":\"Optimizer\",\"scope\":{{\"Bundle\":\"{bundle_id}\"}},\"extends\":null,\"optimizer\":{{\"optimizer_policy\":\"{optimizer}\",\"backend\":\"Lexicographic\",\"active_axes\":{axes},\"route_explanation_verbosity\":\"standard\",\"symbolic_fidelity_preferred\":true,\"tie_break_rules\":[\"shorter-path\"]}},\"evaluator\":null,\"replay_cache\":null,\"report\":null,\"scheduler\":null,\"canonicalizer_mode\":null,\"merge_policy\":null,\"notes\":[\"optimizer override\"]}}\n" - )); - bundle -} - -fn obligation_parallel_bundle(stem: &str, allow_parallel: bool) -> String { - let bundle_id = format!("BND_{}", stem.to_ascii_uppercase().replace('-', "_")); - let workers = if allow_parallel { 3 } else { 1 }; - format!( - r#"!l64-bundle v1 -policy-object {{"id":"MOP_{bundle_id}_SCHED","kind":"ReportExport","scope":{{"Bundle":"{bundle_id}"}},"extends":null,"optimizer":null,"evaluator":null,"replay_cache":null,"report":{{"export_surfaces":[],"include_policy_trace":true,"include_route_explanation":true,"include_obligation_logs":true}},"scheduler":{{"parallelization":"ParallelIndependent","max_workers":2,"allow_parallel_replay":true,"allow_parallel_certification":true,"allow_parallel_exports":true,"deterministic_ordering":true,"allow_parallel_obligations":{allow_parallel},"max_obligation_workers":{workers},"allow_parallel_obligation_replay":{allow_parallel},"serialize_canonicalization_sensitive":true}},"canonicalizer_mode":null,"merge_policy":null,"notes":["obligation scheduler policy"]}} -proof {{"id":"PS_OBL","kind":"Square","nodes":["a","b","c","d"],"edges":[{{"from":"a","to":"b","label":"f"}},{{"from":"b","to":"d","label":"g"}},{{"from":"a","to":"c","label":"h"}},{{"from":"c","to":"d","label":"i"}}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"}} -bridge {{"id":"B_OBL","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"}} -atlas {{"id":"A_OBL","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"General","proof_target":"obligation","candidate_paths":[["B_OBL"]],"normalized_winner":["B_OBL"],"winner_state":"Candidate","loss_profile":{{"items":[]}},"proof_shapes_checked":["PS_OBL"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}}}} -theorem {{"id":"THS_OBL","statement":"obligation parallel theorem","hosts":["R_TOP","R_CALC"],"bridges":["B_OBL"],"operators":["OPR.Obl"],"target_equivalence":"eq","obligations":["OblAdm","OblTol","OblRed"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_OBL"]}} -obligation {{"id":"OBL_PAR_ADM","kind":"OblAdm","description":"adm","status":"Benchmarked"}} -obligation {{"id":"OBL_PAR_TOL","kind":"OblTol","description":"tol","status":"Benchmarked"}} -obligation {{"id":"OBL_PAR_RED","kind":"OblRed","description":"red","status":"Benchmarked"}} -target {{"id":"TGT_OBL","burden_class":"General","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]}} -ledger {{"id":"TRL_OBL","theorem":"THS_OBL","paths":[["B_OBL"]],"budget":{{"max_loss":1,"allow_lossy_supported":false,"require_proof":true}},"losses":[],"receipts":[],"normalized_path":["B_OBL"]}} -campaign {{"id":"CPG_OBL","theorem":"THS_OBL","target_profile":"TGT_OBL","route_ledger":"TRL_OBL","obligations":["OBL_PAR_ADM","OBL_PAR_TOL","OBL_PAR_RED"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["obligation"]}} -"#, - allow_parallel = if allow_parallel { "true" } else { "false" }, - workers = workers, - ) -} - -fn chain_rule_bundle( - stem: &str, - allow_parallel: bool, - strict_evaluator: bool, - include_promoted_operator: bool, -) -> String { - let bundle_id = format!("BND_{}", stem.to_ascii_uppercase().replace('-', "_")); - let scheduler_policy = format!( - r#"policy-object {{"id":"MOP_{bundle_id}_SCHED","kind":"ReportExport","scope":{{"Bundle":"{bundle_id}"}},"extends":null,"optimizer":null,"evaluator":null,"replay_cache":null,"report":{{"export_surfaces":[],"include_policy_trace":true,"include_route_explanation":true,"include_obligation_logs":true}},"scheduler":{{"parallelization":"ParallelIndependent","max_workers":2,"allow_parallel_replay":true,"allow_parallel_certification":true,"allow_parallel_exports":true,"deterministic_ordering":true,"allow_parallel_obligations":{allow_parallel},"max_obligation_workers":3,"allow_parallel_obligation_replay":{allow_parallel},"serialize_canonicalization_sensitive":true}},"canonicalizer_mode":null,"merge_policy":null,"notes":["flagship chain rule scheduler"]}}"# - ); - let evaluator_policy = if strict_evaluator { - format!( - r#" -policy-object {{"id":"MOP_{bundle_id}_EVAL","kind":"Evaluator","scope":{{"Bundle":"{bundle_id}"}},"extends":null,"optimizer":null,"evaluator":{{"evidence_preference":"RecomputeIfSupported","allow_approximation":false,"unsupported_mode":"StrictFail","require_symbolic_fidelity_route":false,"prefer_comp_replay":true}},"replay_cache":null,"report":null,"scheduler":null,"canonicalizer_mode":null,"merge_policy":null,"notes":["strict chain rule evaluator"]}}"# - ) - } else { - String::new() - }; - let promoted_operator = if include_promoted_operator { - r#" -object {"id":"OPR_PROMOTED_OPR_CHAIN1","identity":{"tag":"OPR","cid":"cid:OPR_PROMOTED_OPR_CHAIN1","codebook":"QC0_CORE","remap":"none","lineage":"derived-from:THS_CHAIN_RULE"},"structural":{"head":"operator","args":["THS_CHAIN_RULE","CPG_CHAIN_RULE"],"local_sections":["first-order derivative composition"],"morphism_hooks":["B_TOP_TO_CALC"]},"constraint":{"regime":"R_CALC","contracts":["chain-rule","first-order"],"invariants":["jet-compose","reduction-exact"],"equivalence":"first-order jet equivalence","admissibility":"promoted after exact certified discharge"},"evidence":{"evidence_class":"DerivedPromotion","traces":["THS_CHAIN_RULE"],"receipts":["CRT_CHAIN_RULE","REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE"],"maturity":"Certified","gate_verdict":"Pass"},"alias":{"aliases":["OPR.Chain1"],"profile_pack":["STD","chain-rule"],"qm_binding":"THS·ChainRule","qa_binding":"OPR.Chain1","projection_policy":"canonical-authored"}} -"# - } else { - "" - }; - format!( - r#"!l64-bundle v1 -{scheduler_policy}{evaluator_policy}{promoted_operator} -theorem {{"id":"THS_CHAIN_RULE","statement":"DER(g∘f,x) ≈1 DER(g,f(x))∘DER(f,x)","hosts":["R_TOP","R_CALC"],"bridges":["B_TOP_TO_CALC"],"operators":["OPR.Chain1"],"target_equivalence":"first-order jet equivalence","obligations":["OblEq","OblAdm","OblLoc","OblRed"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_SQUARE_TOPO"]}} -obligation {{"id":"OBL_CHAIN_EQ","kind":"OblEq","description":"first-order slack equivalence preserved under composition","status":"Benchmarked"}} -obligation {{"id":"OBL_CHAIN_ADM","kind":"OblAdm","description":"both derivatives admitted in R_CALC","status":"Benchmarked"}} -obligation {{"id":"OBL_CHAIN_LOC","kind":"OblLoc","description":"same brace-localization at x","status":"Benchmarked"}} -obligation {{"id":"OBL_CHAIN_RED","kind":"OblRed","description":"reduction of remainder terms preserves first-order equivalence","status":"RouteFound"}} -target {{"id":"TGT_CHAIN_RULE","burden_class":"DerivativeLocalWitnessExtraction","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"first-order jet equivalence","allowed_bridge_classes":["Enriching","Conservative"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC_ths","required_proof_shape_family":"MixedBattery","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]}} -ledger {{"id":"TRL_CHAIN_RULE","theorem":"THS_CHAIN_RULE","paths":[["B_TOP_TO_CALC"]],"budget":{{"max_loss":1,"allow_lossy_supported":false,"require_proof":true}},"losses":[],"receipts":["Ref_1","Can","Red"],"normalized_path":["B_TOP_TO_CALC"]}} -certificate {{"id":"CRT_CHAIN_RULE","theorem":"THS_CHAIN_RULE","route_ledger":"TRL_CHAIN_RULE","proof_shapes":["PS_SQUARE_TOPO"],"receipts":["RC_ths","TR_chain","BENCH"],"verdict":"Benchmarked"}} -campaign {{"id":"CPG_CHAIN_RULE","theorem":"THS_CHAIN_RULE","target_profile":"TGT_CHAIN_RULE","route_ledger":"TRL_CHAIN_RULE","obligations":["OBL_CHAIN_EQ","OBL_CHAIN_ADM","OBL_CHAIN_LOC","OBL_CHAIN_RED"],"certificates":["CRT_CHAIN_RULE"],"dependencies":[],"campaign_class":"COperator","verdict":"Benchmarked","payoff":["OPR.Chain1","ATL.RouteClass.Chain"]}} -diagnostic {{"id":"DGN_CHAIN_RULE_ADEQUACY","class":"DNoAdequacy","atlas_cell":"A_TOP_TO_CALC","theorem":"THS_CHAIN_RULE","message":"semantic adequacy remains scaffolded rather than discharged"}} -"#, - scheduler_policy = scheduler_policy, - evaluator_policy = evaluator_policy, - promoted_operator = promoted_operator, - ) -} - -#[test] -#[serial] -fn authored_optimizer_policy_changes_route_winner() { - clear_cache(); - let dir = temp_dir(); - let exec_bundle = dir.join("opt_exec.dna"); - let sym_bundle = dir.join("opt_symbolic.dna"); - write_bundle(&exec_bundle, &route_bundle("opt_exec", "ExecutionFirst")); - write_bundle( - &sym_bundle, - &route_bundle("opt_symbolic", "SymbolicFidelityFirst"), - ); - - let exec = run_json( - "l64-cli", - &["certify-bundle", "--file", exec_bundle.to_str().unwrap()], - ); - let sym = run_json( - "l64-cli", - &["certify-bundle", "--file", sym_bundle.to_str().unwrap()], - ); - assert_eq!(exec[0]["selected_atlas_cell"], "A_FAST"); - assert_eq!(sym[0]["selected_atlas_cell"], "A_FAITHFUL"); - assert!( - sym[0]["policy_resolution"]["applied_policy_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item.as_str().unwrap().contains("MOP_BND_OPT_SYMBOLIC_OPT")) - ); -} - -#[test] -#[serial] -fn authored_evaluator_policy_changes_verdict() { - clear_cache(); - let dir = temp_dir(); - let base_bundle = dir.join("eval_base.dna"); - let strict_bundle = dir.join("eval_strict.dna"); - write_bundle(&base_bundle, &evaluator_bundle("eval_base", false)); - write_bundle(&strict_bundle, &evaluator_bundle("eval_strict", true)); - - let base = run_json( - "l64-cli", - &["certify-bundle", "--file", base_bundle.to_str().unwrap()], - ); - let strict = run_json( - "l64-cli", - &["certify-bundle", "--file", strict_bundle.to_str().unwrap()], - ); - assert_ne!(base[0]["verdict"], strict[0]["verdict"]); - assert_eq!(strict[0]["verdict"], "BlockedOpen"); -} - -#[test] -#[serial] -fn authored_replay_policy_changes_cache_behavior() { - clear_cache(); - let dir = temp_dir(); - let cache_bundle = dir.join("replay_cache.dna"); - let nocache_bundle = dir.join("replay_nocache.dna"); - write_bundle(&cache_bundle, &replay_bundle("replay_cache", true)); - write_bundle(&nocache_bundle, &replay_bundle("replay_nocache", false)); - - let _ = run_json( - "l64-cli", - &["certify-bundle", "--file", cache_bundle.to_str().unwrap()], - ); - let second = run_json( - "l64-cli", - &["certify-bundle", "--file", cache_bundle.to_str().unwrap()], - ); - assert_eq!(second[0]["execution_envelope"]["replay_status"], "CacheHit"); - - let _ = run_json( - "l64-cli", - &["certify-bundle", "--file", nocache_bundle.to_str().unwrap()], - ); - let second_no = run_json( - "l64-cli", - &["certify-bundle", "--file", nocache_bundle.to_str().unwrap()], - ); - assert_eq!(second_no[0]["execution_envelope"]["replay_status"], "Fresh"); -} - -#[test] -#[serial] -fn lock_manifest_and_replay_flow_work() { - clear_cache(); - let dir = temp_dir(); - let bundle = dir.join("opt_exec.dna"); - let other = dir.join("opt_symbolic.dna"); - write_bundle(&bundle, &route_bundle("opt_exec", "ExecutionFirst")); - write_bundle( - &other, - &route_bundle("opt_symbolic", "SymbolicFidelityFirst"), - ); - - let locked = run_json( - "l64-admin", - &[ - "lock-bundle", - bundle.to_str().unwrap(), - "--optimizer-policy", - "execution-first", - ], - ); - let lock_id = locked["lock"]["id"].as_str().unwrap().to_string(); - let manifest_id = locked["manifest"]["id"].as_str().unwrap().to_string(); - - let manifest = run_json("l64-admin", &["dump-execution-manifest", &manifest_id]); - assert_eq!(manifest["bundle_id"], "BND_OPT_EXEC"); - - let replay = run_json("l64-admin", &["replay-with-lock", &lock_id]); - assert_eq!(replay[0]["selected_atlas_cell"], "A_FAST"); - - let removed_projection_export = Command::new(cargo_bin("l64-admin")) - .current_dir(workspace_root()) - .args([ - "export-artifact-projection", - "--id", - &manifest_id, - "--to", - "qc0", - ]) - .output() - .unwrap(); - assert!(!removed_projection_export.status.success()); - - let removed_primary_export = Command::new(cargo_bin("l64-admin")) - .current_dir(workspace_root()) - .args(["export-artifact", "--id", &manifest_id, "--to", "qc0"]) - .output() - .unwrap(); - assert!(!removed_primary_export.status.success()); - - let locked_other = run_json( - "l64-admin", - &[ - "lock-bundle", - other.to_str().unwrap(), - "--optimizer-policy", - "symbolic-fidelity-first", - ], - ); - let other_lock_id = locked_other["lock"]["id"].as_str().unwrap().to_string(); - let diff = run_json("l64-admin", &["compare-locks", &lock_id, &other_lock_id]); - assert!( - diff["semantic_changes"] - .as_array() - .unwrap() - .iter() - .any(|item| item.as_str().unwrap().contains("policy graph") - || item.as_str().unwrap().contains("route winners")) - ); -} - -#[test] -#[serial] -fn observe_predict_plan_and_assess_route_drift_workflow() { - clear_cache(); - let dir = temp_dir(); - let exec_bundle = dir.join("predict_exec.dna"); - let sym_bundle = dir.join("predict_sym.dna"); - write_bundle( - &exec_bundle, - &route_bundle_named( - "predict_exec", - "ExecutionFirst", - "THS_LOCAL_ROUTE", - "CPG_ROUTE_EXEC", - ), - ); - write_bundle( - &sym_bundle, - &route_bundle_named( - "predict_sym", - "SymbolicFidelityFirst", - "THS_LOCAL_ROUTE", - "CPG_ROUTE_SYMBOLIC", - ), - ); - - let baseline = run_json( - "l64-cli", - &["certify-bundle", "--file", exec_bundle.to_str().unwrap()], - ); - assert_eq!(baseline[0]["selected_atlas_cell"], "A_FAST"); - let baseline_report_id = "REPORT_THS_LOCAL_ROUTE_CPG_ROUTE_EXEC"; - - let observed = run_json( - "l64-admin", - &["observe-run", "--report", baseline_report_id], - ); - assert_eq!( - observed[0]["artifact"]["record"]["report_id"], - baseline_report_id - ); - - let prediction = run_json( - "l64-admin", - &[ - "predict-impact", - "--report", - baseline_report_id, - "--bundle-file", - sym_bundle.to_str().unwrap(), - ], - ); - assert_eq!(prediction["prediction"]["class"], "RouteWinnerChangeLikely"); - let prediction_id = prediction["prediction"]["id"].as_str().unwrap(); - - let plan = run_json( - "l64-admin", - &["plan-recompute", "--prediction", prediction_id], - ); - assert!( - plan["steps"] - .as_array() - .unwrap() - .iter() - .any(|item| item["kind"] == "ReRoute") - ); - - let actual = run_json( - "l64-cli", - &["certify-bundle", "--file", sym_bundle.to_str().unwrap()], - ); - assert_eq!(actual[0]["selected_atlas_cell"], "A_FAITHFUL"); - let actual_report_id = "REPORT_THS_LOCAL_ROUTE_CPG_ROUTE_SYMBOLIC"; - - let diff = run_json( - "l64-admin", - &["compare-reports", baseline_report_id, actual_report_id], - ); - assert!( - diff["summary"] - .as_array() - .unwrap() - .iter() - .any(|item| item.as_str().unwrap().contains("route winner changed")) - ); - - let assessment = run_json( - "l64-admin", - &["assess-prediction", prediction_id, actual_report_id], - ); - assert_eq!(assessment["outcome"], "PredictionUnderestimated"); -} - -#[test] -#[serial] -fn surface_only_bundle_change_predicts_no_semantic_impact() { - clear_cache(); - let dir = temp_dir(); - let base_bundle = dir.join("surface_base.dna"); - let same_bundle = dir.join("surface_same.dna"); - let content = evaluator_bundle("surface_base", false) - .replace("THS_LOCAL_EVAL", "THS_SURFACE") - .replace("CPG_LOCAL_EVAL", "CPG_SURFACE") - .replace("TGT_LOCAL_EVAL", "TGT_SURFACE") - .replace("TRL_LOCAL_EVAL", "TRL_SURFACE") - .replace("OBL_LOCAL_EQ", "OBL_SURFACE"); - write_bundle(&base_bundle, &content); - write_bundle(&same_bundle, &content); - - let _ = run_json( - "l64-cli", - &["certify-bundle", "--file", base_bundle.to_str().unwrap()], - ); - let prediction = run_json( - "l64-admin", - &[ - "predict-impact", - "--report", - "REPORT_THS_SURFACE_CPG_SURFACE", - "--bundle-file", - same_bundle.to_str().unwrap(), - ], - ); - assert_eq!(prediction["prediction"]["class"], "NoImpactPredicted"); -} - -#[test] -#[serial] -fn execute_plan_reconciles_predicted_route_drift() { - clear_cache(); - let dir = temp_dir(); - let exec_bundle = dir.join("sched_exec.dna"); - let sym_bundle = dir.join("sched_sym.dna"); - write_bundle( - &exec_bundle, - &route_bundle_named( - "sched_exec", - "ExecutionFirst", - "THS_SCHED_ROUTE", - "CPG_SCHED_EXEC", - ), - ); - write_bundle( - &sym_bundle, - &route_bundle_named( - "sched_sym", - "SymbolicFidelityFirst", - "THS_SCHED_ROUTE", - "CPG_SCHED_SYMBOLIC", - ), - ); - - let _ = run_json( - "l64-cli", - &["certify-bundle", "--file", exec_bundle.to_str().unwrap()], - ); - let prediction = run_json( - "l64-admin", - &[ - "predict-impact", - "--report", - "REPORT_THS_SCHED_ROUTE_CPG_SCHED_EXEC", - "--bundle-file", - sym_bundle.to_str().unwrap(), - ], - ); - let prediction_id = prediction["prediction"]["id"].as_str().unwrap(); - let execution = run_json( - "l64-admin", - &["execute-plan", "--prediction", prediction_id], - ); - assert!( - execution["outcomes"] - .as_array() - .unwrap() - .iter() - .any(|item| item["status"] == "Executed") - ); - assert_eq!( - execution["resulting_reports"][0]["selected_atlas_cell"], - "A_FAITHFUL" - ); - assert!( - execution["resulting_reports"][0]["reconciliation_summary"] - .as_array() - .unwrap() - .len() - > 0 - ); -} - -#[test] -#[serial] -fn runtime_roots_and_artifact_resolution_use_workspace_root() { - clear_cache(); - let dir = temp_dir(); - let bundle = dir.join("root_exec.dna"); - write_bundle(&bundle, &route_bundle("root_exec", "ExecutionFirst")); - - let locked = run_json( - "l64-admin", - &[ - "lock-bundle", - bundle.to_str().unwrap(), - "--optimizer-policy", - "execution-first", - ], - ); - let manifest_id = locked["manifest"]["id"].as_str().unwrap().to_string(); - - let roots = run_json("l64-admin", &["dump-runtime-roots"]); - assert!( - roots["project_root"]["absolute_path"] - .as_str() - .unwrap() - .contains("Locus64") - ); - - let locator = run_json("l64-admin", &["resolve-artifact-path", &manifest_id]); - assert!( - locator["normalized_path"] - .as_str() - .unwrap() - .contains(".l64-cache/namespaces/") - ); - assert!( - locator["normalized_path"] - .as_str() - .unwrap() - .contains("/manifests/") - ); -} - -#[test] -#[serial] -fn compare_executions_and_reconcile_run_are_live() { - clear_cache(); - let dir = temp_dir(); - let exec_bundle = dir.join("cmp_exec.dna"); - let sym_bundle = dir.join("cmp_sym.dna"); - write_bundle( - &exec_bundle, - &route_bundle_named( - "cmp_exec", - "ExecutionFirst", - "THS_CMP_ROUTE", - "CPG_CMP_EXEC", - ), - ); - write_bundle( - &sym_bundle, - &route_bundle_named( - "cmp_sym", - "SymbolicFidelityFirst", - "THS_CMP_ROUTE", - "CPG_CMP_SYM", - ), - ); - let _ = run_json( - "l64-cli", - &["certify-bundle", "--file", exec_bundle.to_str().unwrap()], - ); - let pred_a = run_json( - "l64-admin", - &[ - "predict-impact", - "--report", - "REPORT_THS_CMP_ROUTE_CPG_CMP_EXEC", - "--bundle-file", - sym_bundle.to_str().unwrap(), - ], - ); - let run_a = run_json( - "l64-admin", - &[ - "execute-plan", - "--prediction", - pred_a["prediction"]["id"].as_str().unwrap(), - ], - ); - - let pred_b = run_json( - "l64-admin", - &[ - "predict-impact", - "--report", - "REPORT_THS_CMP_ROUTE_CPG_CMP_EXEC", - "--bundle-file", - exec_bundle.to_str().unwrap(), - ], - ); - let run_b = run_json( - "l64-admin", - &[ - "execute-plan", - "--prediction", - pred_b["prediction"]["id"].as_str().unwrap(), - "--dry-run", - ], - ); - - let diff = run_json( - "l64-admin", - &[ - "compare-executions", - run_a["id"].as_str().unwrap(), - run_b["id"].as_str().unwrap(), - ], - ); - assert!(diff["summary"].as_array().unwrap().len() > 0); - - let reconciliation = run_json( - "l64-admin", - &[ - "reconcile-run", - "--prediction", - pred_a["prediction"]["id"].as_str().unwrap(), - "--actual-report", - "REPORT_THS_CMP_ROUTE_CPG_CMP_SYM", - ], - ); - assert!( - reconciliation["assessment"]["outcome"] - .as_str() - .unwrap() - .starts_with("Prediction") - ); -} - -#[test] -fn parallel_execute_plan_uses_multiple_lanes_under_namespace_isolation() { - let namespace = format!( - "ns_parallel_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let dir = temp_dir(); - let baseline_bundle = dir.join("parallel_base.dna"); - let proposed_bundle = dir.join("parallel_proposed.dna"); - write_bundle(&baseline_bundle, ¶llel_campaign_bundle("parallel_base")); - write_bundle( - &proposed_bundle, - ¶llel_campaign_bundle_with_optimizer("parallel_proposed", "SymbolicFidelityFirst"), - ); - - let _baseline = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - baseline_bundle.to_str().unwrap(), - ], - ); - let report_ref = "REPORT_THS_PAR_A_CPG_PAR_A".to_string(); - let prediction = run_json_ns( - &namespace, - "l64-admin", - &[ - "predict-impact", - "--report", - &report_ref, - "--bundle-file", - proposed_bundle.to_str().unwrap(), - ], - ); - let execution = run_json_ns( - &namespace, - "l64-admin", - &[ - "execute-plan", - "--prediction", - prediction["prediction"]["id"].as_str().unwrap(), - "--parallel", - "--max-workers", - "2", - "--strict-determinism", - ], - ); - assert!(execution["lane_records"].as_array().unwrap().len() >= 2); - assert_eq!( - execution["scheduler_policy"]["parallelization"], - "ParallelIndependent" - ); - assert_eq!( - execution["execution_scope"]["cache_namespace"]["id"], - namespace - ); -} - -#[test] -fn schedule_and_namespace_tools_work_without_global_serialization() { - let namespace = format!( - "ns_sched_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let dir = temp_dir(); - let baseline_bundle = dir.join("parallel_tools_base.dna"); - let proposed_bundle = dir.join("parallel_tools_proposed.dna"); - write_bundle( - &baseline_bundle, - ¶llel_campaign_bundle("parallel_tools_base"), - ); - write_bundle( - &proposed_bundle, - ¶llel_campaign_bundle_with_optimizer("parallel_tools_proposed", "ExecutionFirst"), - ); - - let _baseline = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - baseline_bundle.to_str().unwrap(), - ], - ); - let report_ref = "REPORT_THS_PAR_A_CPG_PAR_A".to_string(); - let prediction = run_json_ns( - &namespace, - "l64-admin", - &[ - "predict-impact", - "--report", - &report_ref, - "--bundle-file", - proposed_bundle.to_str().unwrap(), - ], - ); - let execution = run_json_ns( - &namespace, - "l64-admin", - &[ - "execute-plan", - "--prediction", - prediction["prediction"]["id"].as_str().unwrap(), - "--parallel", - "--max-workers", - "2", - ], - ); - assert!(execution["schedule_hash"]["hash"].as_str().unwrap().len() > 0); - let namespaces = run_json_ns(&namespace, "l64-admin", &["dump-cache-namespaces"]); - assert!( - namespaces - .as_array() - .unwrap() - .iter() - .any(|item| item.as_str() == Some(namespace.as_str())) - ); -} - -#[test] -fn obligation_parallel_groups_are_visible_in_reports_and_execution() { - let namespace = format!( - "ns_obl_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let dir = temp_dir(); - let baseline_bundle = dir.join("obl_serial.dna"); - let parallel_bundle = dir.join("obl_parallel.dna"); - write_bundle( - &baseline_bundle, - &obligation_parallel_bundle("obl_serial", false), - ); - write_bundle( - ¶llel_bundle, - &obligation_parallel_bundle("obl_parallel", true), - ); - - let baseline = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - baseline_bundle.to_str().unwrap(), - ], - ); - let parallel = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - parallel_bundle.to_str().unwrap(), - ], - ); - assert_eq!(baseline[0]["obligation_lanes"].as_array().unwrap().len(), 1); - assert!(parallel[0]["obligation_lanes"].as_array().unwrap().len() >= 2); - assert!( - parallel[0]["replay_legality_checks"] - .as_array() - .unwrap() - .len() - >= 3 - ); -} - -#[test] -fn replay_with_lock_exposes_obligation_parallel_replay_structure() { - let namespace = format!( - "ns_obl_replay_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let dir = temp_dir(); - let bundle = dir.join("obl_replay.dna"); - write_bundle(&bundle, &obligation_parallel_bundle("obl_replay", true)); - - let lock_output = run_json_ns( - &namespace, - "l64-admin", - &[ - "lock-bundle", - bundle.to_str().unwrap(), - "--optimizer-policy", - "conservative", - ], - ); - let lock_id = lock_output["lock"]["id"].as_str().unwrap(); - let replay = run_json_ns( - &namespace, - "l64-admin", - &[ - "replay-with-lock", - lock_id, - "--parallel-obligations", - "--max-obligation-workers", - "3", - ], - ); - assert!( - replay.as_array().unwrap()[0]["replay_legality_checks"] - .as_array() - .unwrap() - .len() - >= 3 - ); - assert!( - replay.as_array().unwrap()[0]["obligation_lanes"] - .as_array() - .unwrap() - .len() - >= 2 - ); -} - -#[test] -fn flagship_chain_rule_bundle_uses_scheduler_and_surfaces_deficiencies() { - let namespace = format!( - "ns_chain_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let dir = temp_dir(); - let bundle = dir.join("chain_rule_parallel.dna"); - write_bundle( - &bundle, - &chain_rule_bundle("chain_rule_parallel", true, false, false), - ); - - let report = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - bundle.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ], - ); - assert_eq!(report[0]["campaign_id"], "CPG_CHAIN_RULE"); - assert_eq!(report[0]["selected_atlas_cell"], "A_TOP_TO_CALC"); - assert_eq!(report[0]["verdict"], "Integrated"); - assert!( - report[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["obligation_id"] == "OBL_CHAIN_EQ" - && item["evaluation_mode"] == "RecomputedExact" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - }) - ); - assert!( - report[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["obligation_id"] == "OBL_CHAIN_RED" - && item["evaluation_mode"] == "RecomputedExact" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "RED_CHAIN_OPERATOR_DEFAULT_SELECTION") - }) - ); - assert!(report[0]["reasons"].as_array().unwrap().iter().any(|item| { - item.as_str() - .unwrap() - .contains("flagship adequacy-first campaign selected") - })); - assert!( - report[0]["reasons"] - .as_array() - .unwrap() - .iter() - .any(|item| item.as_str().unwrap().contains("reduction witness exactly")) - ); - assert!(report[0]["obligation_lanes"].as_array().unwrap().len() >= 2); - assert!( - !report[0]["deficiencies"] - .as_array() - .unwrap() - .iter() - .any(|item| item["id"] == "DGN_CHAIN_RULE_ADEQUACY") - ); - assert!( - report[0]["promotion_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - report[0]["default_selected_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!(report[0]["reasons"].as_array().unwrap().iter().any(|item| { - item.as_str() - .unwrap() - .contains("default-selected the canonical Chain₁ operator") - })); -} - -#[test] -fn flagship_chain_rule_lock_replay_and_obligation_comparison_are_deterministic() { - let namespace = format!( - "ns_chain_lock_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let dir = temp_dir(); - let baseline_bundle = dir.join("chain_rule_serial.dna"); - let proposed_bundle = dir.join("chain_rule_parallel.dna"); - write_bundle( - &baseline_bundle, - &chain_rule_bundle("chain_rule_serial", false, false, false), - ); - write_bundle( - &proposed_bundle, - &chain_rule_bundle("chain_rule_parallel", true, false, false), - ); - - let _baseline = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - baseline_bundle.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ], - ); - let prediction = run_json_ns( - &namespace, - "l64-admin", - &[ - "predict-impact", - "--report", - "REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE", - "--bundle-file", - proposed_bundle.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ], - ); - let prediction_id = prediction["prediction"]["id"].as_str().unwrap(); - let execution_a = run_json_ns( - &namespace, - "l64-admin", - &[ - "execute-plan", - "--prediction", - prediction_id, - "--parallel-obligations", - "--max-obligation-workers", - "3", - ], - ); - let execution_b = run_json_ns( - &namespace, - "l64-admin", - &[ - "execute-plan", - "--prediction", - prediction_id, - "--parallel-obligations", - "--max-obligation-workers", - "3", - ], - ); - let explain = run_json_ns( - &namespace, - "l64-admin", - &[ - "explain-obligation-plan", - execution_a["id"].as_str().unwrap(), - ], - ); - assert!(explain["plans"].as_array().unwrap().len() > 0); - assert!( - explain["obligation_statuses"][0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["obligation_id"] == "OBL_CHAIN_EQ" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - }) - ); - assert!( - explain["obligation_statuses"][0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["obligation_id"] == "OBL_CHAIN_RED" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "RED_CHAIN_OPERATOR_DEFAULT_SELECTION") - }) - ); - let compare = run_json_ns( - &namespace, - "l64-admin", - &[ - "compare-obligation-executions", - execution_a["id"].as_str().unwrap(), - execution_b["id"].as_str().unwrap(), - ], - ); - assert_eq!(compare["same"], true); - - let lock_output = run_json_ns( - &namespace, - "l64-admin", - &[ - "lock-bundle", - proposed_bundle.to_str().unwrap(), - "--optimizer-policy", - "conservative", - "--conflict-policy", - "exact-match", - ], - ); - let lock_id = lock_output["lock"]["id"].as_str().unwrap(); - let replay = run_json_ns( - &namespace, - "l64-admin", - &[ - "replay-with-lock", - lock_id, - "--parallel-obligations", - "--max-obligation-workers", - "3", - ], - ); - assert!( - replay.as_array().unwrap()[0]["obligation_lanes"] - .as_array() - .unwrap() - .len() - >= 2 - ); - assert!( - replay.as_array().unwrap()[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["obligation_id"] == "OBL_CHAIN_EQ" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - }) - ); -} - -#[test] -fn flagship_chain_rule_strict_evaluator_emits_structured_blockers() { - let namespace = format!( - "ns_chain_fail_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let dir = temp_dir(); - let bundle = dir.join("chain_rule_strict.dna"); - write_bundle( - &bundle, - &chain_rule_bundle("chain_rule_strict", true, true, false), - ); - - let report = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - bundle.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ], - ); - assert_eq!(report[0]["verdict"], "Integrated"); - assert!( - !report[0]["deficiencies"] - .as_array() - .unwrap() - .iter() - .any(|item| item["id"] == "DGN_CHAIN_RULE_ADEQUACY") - ); - assert!( - !report[0]["deficiencies"] - .as_array() - .unwrap() - .iter() - .any(|item| item["message"].as_str().unwrap().contains("OBL_CHAIN_RED")) - ); - assert!( - report[0]["promotion_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - report[0]["default_selected_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); -} - -#[test] -fn flagship_chain_rule_promoted_operator_is_reused_and_integrated() { - let namespace = format!( - "ns_chain_integrated_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let dir = temp_dir(); - let baseline_bundle = dir.join("chain_rule_integrated_base.dna"); - let integrated_bundle = dir.join("chain_rule_integrated.dna"); - write_bundle( - &baseline_bundle, - &chain_rule_bundle("chain_rule_integrated_base", true, false, false), - ); - write_bundle( - &integrated_bundle, - &chain_rule_bundle("chain_rule_integrated", true, false, true), - ); - - let baseline = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - baseline_bundle.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ], - ); - let integrated = run_json_ns( - &namespace, - "l64-cli", - &[ - "certify-bundle", - "--file", - integrated_bundle.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ], - ); - - assert_eq!(baseline[0]["verdict"], "Integrated"); - assert!( - baseline[0]["default_selected_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - baseline[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CHAIN_EQ" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION")) - ); - assert_eq!(integrated[0]["verdict"], "Integrated"); - assert!( - integrated[0]["reused_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - integrated[0]["default_selected_artifact_ids"] - .as_array() - .unwrap() - .is_empty() - ); - assert!( - integrated[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CHAIN_EQ" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "EQR_CHAIN_OPERATOR_REUSE")) - ); - assert!( - integrated[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CHAIN_RED" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "RED_CHAIN_OPERATOR_REUSE")) - ); - - let baseline_eq_receipts = baseline[0]["obligations"] - .as_array() - .unwrap() - .iter() - .find(|item| item["obligation_id"] == "OBL_CHAIN_EQ") - .unwrap()["receipts"] - .as_array() - .unwrap() - .iter() - .map(|item| item["id"].as_str().unwrap().to_string()) - .collect::>(); - let integrated_eq_receipts = integrated[0]["obligations"] - .as_array() - .unwrap() - .iter() - .find(|item| item["obligation_id"] == "OBL_CHAIN_EQ") - .unwrap()["receipts"] - .as_array() - .unwrap() - .iter() - .map(|item| item["id"].as_str().unwrap().to_string()) - .collect::>(); - assert!( - baseline_eq_receipts - .iter() - .any(|item| item == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - ); - assert!( - integrated_eq_receipts - .iter() - .any(|item| item == "EQR_CHAIN_OPERATOR_REUSE") - ); - assert!( - integrated[0]["reasons"] - .as_array() - .unwrap() - .iter() - .any(|item| item - .as_str() - .unwrap() - .contains("reused promoted Chain₁ operator")) - ); - assert!( - baseline[0]["reasons"] - .as_array() - .unwrap() - .iter() - .any(|item| item - .as_str() - .unwrap() - .contains("default-selected the canonical Chain₁ operator")) - ); - - let lock_output = run_json_ns( - &namespace, - "l64-admin", - &[ - "lock-bundle", - integrated_bundle.to_str().unwrap(), - "--optimizer-policy", - "conservative", - "--conflict-policy", - "exact-match", - ], - ); - let lock_id = lock_output["lock"]["id"].as_str().unwrap(); - let replay = run_json_ns( - &namespace, - "l64-admin", - &[ - "replay-with-lock", - lock_id, - "--parallel-obligations", - "--max-obligation-workers", - "3", - ], - ); - assert_eq!(replay[0]["verdict"], "Integrated"); - assert!( - replay[0]["reused_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); -} - -#[test] -fn second_burden_recipe_path_auto_reuses_chain1_with_payoff() { - let namespace = format!( - "ns_chain_recipe_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let report = run_json_ns( - &namespace, - "l64-cli", - &["certify-derived", "--campaign", "CPG_CHAIN_RULE_RECIPE"], - ); - assert_eq!(report["campaign_id"], "CPG_CHAIN_RULE_RECIPE"); - assert_eq!(report["verdict"], "Integrated"); - assert!( - report["default_selected_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - report["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_SECOND_BURDEN_DEFAULT_REUSE") - ); - assert!( - report["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_OBLIGATION_COUNT_REDUCTION_4_TO_2") - ); - assert_eq!(report["obligations"].as_array().unwrap().len(), 2); - assert!( - report["reasons"] - .as_array() - .unwrap() - .iter() - .any(|item| item.as_str().unwrap().contains("adjacent recipe burden")) - ); -} - -#[test] -fn adjacent_transport_path_auto_reuses_chain1_with_payoff() { - let namespace = format!( - "ns_chain_transport_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let report = run_json_ns( - &namespace, - "l64-cli", - &["certify-derived", "--campaign", "CPG_CHAIN_RULE_TRANSPORT"], - ); - assert_eq!(report["campaign_id"], "CPG_CHAIN_RULE_TRANSPORT"); - assert_eq!(report["verdict"], "Integrated"); - assert!( - report["default_selected_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - report["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_ADJACENT_TRANSPORT_DEFAULT_REUSE") - ); - assert!( - report["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_LOCALITY_WITNESS_RETAINED") - ); - assert!( - report["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_OBLIGATION_COUNT_REDUCTION_4_TO_3") - ); - assert_eq!(report["obligations"].as_array().unwrap().len(), 3); - assert!( - report["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CHAIN_LOC") - ); - assert!( - report["reasons"] - .as_array() - .unwrap() - .iter() - .any(|item| item.as_str().unwrap().contains("adjacent transport burden")) - ); -} - -#[test] -fn bayes_brace_observation_surfaces_active_adequacy_without_deficiencies() { - let namespace = format!( - "ns_bayes_brace_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let report = run_json_ns( - &namespace, - "l64-cli", - &["certify-derived", "--campaign", "CPG_BAYES_BRACE"], - ); - assert_eq!(report["campaign_id"], "CPG_BAYES_BRACE"); - assert_eq!(report["verdict"], "Certified"); - let observed = run_json_ns( - &namespace, - "l64-admin", - &[ - "observe-run", - "--report", - "REPORT_THS_BAYES_BRACE_CPG_BAYES_BRACE", - ], - ); - assert!( - observed[0]["artifact"]["graph"]["obligation_traces"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_BAYES_ADE" - && item["evaluation_mode"] == "RecomputedExact") - ); - assert!( - report["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_BAYES_TOP_PROB_BRIDGE") - ); - assert!(report["deficiencies"].as_array().unwrap().is_empty()); -} - -#[test] -fn ch_norm_observation_surfaces_exact_type_normalization_closure() { - let namespace = format!( - "ns_ch_norm_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let report = run_json_ns( - &namespace, - "l64-cli", - &["certify-derived", "--campaign", "CPG_CH_NORM"], - ); - assert_eq!(report["campaign_id"], "CPG_CH_NORM"); - assert_eq!(report["verdict"], "Certified"); - assert!(report["deficiencies"].as_array().unwrap().is_empty()); - let observed = run_json_ns( - &namespace, - "l64-admin", - &["observe-run", "--report", "REPORT_THS_CH_NORM_CPG_CH_NORM"], - ); - assert!( - observed[0]["artifact"]["graph"]["obligation_traces"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CH_ADE" - && item["evaluation_mode"] == "RecomputedExact") - ); -} - -#[test] -fn exec_infer_observation_surfaces_active_adequacy_without_deficiencies() { - let namespace = format!( - "ns_exec_infer_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let report = run_json_ns( - &namespace, - "l64-cli", - &["certify-derived", "--campaign", "CPG_EXEC_INFER"], - ); - assert_eq!(report["campaign_id"], "CPG_EXEC_INFER"); - assert_eq!(report["verdict"], "Certified"); - let observed = run_json_ns( - &namespace, - "l64-admin", - &[ - "observe-run", - "--report", - "REPORT_THS_EXEC_INFER_CPG_EXEC_INFER", - ], - ); - assert!( - observed[0]["artifact"]["graph"]["obligation_traces"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_EXEC_RED" - && item["evaluation_mode"] == "RecomputedExact") - ); - assert!( - report["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_EXEC_PROB_COMP_BRIDGE") - ); - assert!(report["deficiencies"].as_array().unwrap().is_empty()); -} - -#[test] -fn cert_prop_observation_surfaces_active_adequacy_without_deficiencies() { - let namespace = format!( - "ns_cert_prop_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let report = run_json_ns( - &namespace, - "l64-cli", - &["certify-derived", "--campaign", "CPG_CERT_PROP"], - ); - assert_eq!(report["campaign_id"], "CPG_CERT_PROP"); - assert_eq!(report["verdict"], "Certified"); - let observed = run_json_ns( - &namespace, - "l64-admin", - &[ - "observe-run", - "--report", - "REPORT_THS_CERT_PROP_CPG_CERT_PROP", - ], - ); - assert!( - observed[0]["artifact"]["graph"]["obligation_traces"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CERT_OBS" - && item["evaluation_mode"] == "RecomputedExact") - ); - assert!( - report["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_CERT_COMP_LOG_BRIDGE") - ); - assert!(report["deficiencies"].as_array().unwrap().is_empty()); -} - -#[test] -fn ch_inh_observation_surfaces_exact_type_algebra_closure() { - let namespace = format!( - "ns_ch_inh_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let report = run_json_ns( - &namespace, - "l64-cli", - &["certify-derived", "--campaign", "CPG_CH_INH"], - ); - assert_eq!(report["campaign_id"], "CPG_CH_INH"); - assert_eq!(report["verdict"], "Certified"); - assert!(report["deficiencies"].as_array().unwrap().is_empty()); - let observed = run_json_ns( - &namespace, - "l64-admin", - &["observe-run", "--report", "REPORT_THS_CH_INH_CPG_CH_INH"], - ); - assert!( - observed[0]["artifact"]["graph"]["obligation_traces"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CHI_EQ" - && item["evaluation_mode"] == "RecomputedExact") - ); - assert!( - observed[0]["artifact"]["graph"]["obligation_traces"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CHI_ADE" - && item["evaluation_mode"] == "RecomputedExact") - ); -} - -#[test] -fn replay_with_lock_preserves_active_adequacy_records() { - let namespace = format!( - "ns_chain_adequacy_replay_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ); - let lock_output = run_json_ns( - &namespace, - "l64-admin", - &[ - "lock-bundle", - "samples/chain_rule_integrated_bundle.dna", - "--optimizer-policy", - "conservative", - "--conflict-policy", - "exact-match", - ], - ); - let lock_id = lock_output["lock"]["id"].as_str().unwrap(); - let replay = run_json_ns( - &namespace, - "l64-admin", - &[ - "replay-with-lock", - lock_id, - "--parallel-obligations", - "--max-obligation-workers", - "3", - ], - ); - assert!( - replay[0]["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_CHAIN_TOP_CALC_BRIDGE") - ); - assert!( - replay[0]["adequacy_records"] - .as_array() - .unwrap() - .iter() - .all(|item| item["verdict"] == "Certified") - ); -} diff --git a/l64-atlas/.gitignore b/l64-atlas/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/l64-atlas/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/l64-atlas/Cargo.toml b/l64-atlas/Cargo.toml deleted file mode 100644 index 0dd82d1..0000000 --- a/l64-atlas/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "l64-atlas" -edition.workspace = true -version.workspace = true -license.workspace = true - -[dependencies] -l64-core = { path = "../l64-core" } -l64-kernel = { path = "../l64-kernel" } -l64-registry = { path = "../l64-registry" } -l64-policy = { path = "../l64-policy" } -serde = { workspace = true } -thiserror = { workspace = true } diff --git a/l64-atlas/src/lib.rs b/l64-atlas/src/lib.rs deleted file mode 100644 index 11f298f..0000000 --- a/l64-atlas/src/lib.rs +++ /dev/null @@ -1,539 +0,0 @@ -use l64_core::{ - AtlasCell, Budget, BurdenClass, CertificationVerdict, ComposeBridge, OptimizationAxis, - OptimizerBackend, OptimizerPolicy, PolicyResolution, RegistryLookup, ReversibilityClass, - RouteExplanation, RouteScoreVector, RouteSelection, SurfaceCompatibilityClass, - SurfaceTransitionCost, WinnerState, -}; -use l64_kernel::ConstitutionKernel; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use thiserror::Error; - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CompiledEdge { - pub atlas_cell_id: String, - pub src: String, - pub tgt: String, - pub burden_class: BurdenClass, - pub path: Vec, - pub loss_count: usize, - pub surface_penalty: usize, - pub reversibility: Vec, - pub proof_shapes: Vec, - pub winner_state: WinnerState, - pub surface_transition: Option, -} - -#[derive(Debug, Clone)] -pub struct CompiledAtlas { - pub edges: Vec, - by_src_tgt: HashMap<(String, String), Vec>, - by_src_tgt_burden: HashMap<(String, String, BurdenClass), Vec>, -} - -#[derive(Debug, Error)] -pub enum AtlasError { - #[error("unknown bridge `{0}`")] - UnknownBridge(String), - #[error("no route found")] - NoRoute, -} - -impl CompiledAtlas { - pub fn compile(registry: &R) -> Result { - let mut edges = Vec::new(); - let mut by_src_tgt = HashMap::new(); - let mut by_src_tgt_burden = HashMap::new(); - - for cell in registry.atlas_cells() { - let reversibility = cell - .normalized_winner - .iter() - .map(|id| { - registry - .get_bridge(id) - .map(|bridge| bridge.reversibility) - .ok_or_else(|| AtlasError::UnknownBridge(id.clone())) - }) - .collect::, _>>()?; - - let edge = CompiledEdge { - atlas_cell_id: cell.id.clone(), - src: cell.source_regime.clone(), - tgt: cell.target_regime.clone(), - burden_class: cell.burden_class.clone(), - path: cell.normalized_winner.clone(), - loss_count: cell.loss_profile.items.len(), - surface_penalty: cell - .surface_transition - .as_ref() - .map(|item| item.total_penalty) - .unwrap_or_else(|| infer_surface_penalty(&cell)), - reversibility, - proof_shapes: cell.proof_shapes_checked.clone(), - winner_state: cell.winner_state.clone(), - surface_transition: cell.surface_transition.clone(), - }; - let index = edges.len(); - edges.push(edge); - by_src_tgt - .entry((cell.source_regime.clone(), cell.target_regime.clone())) - .or_insert_with(Vec::new) - .push(index); - by_src_tgt_burden - .entry(( - cell.source_regime.clone(), - cell.target_regime.clone(), - cell.burden_class.clone(), - )) - .or_insert_with(Vec::new) - .push(index); - } - - Ok(Self { - edges, - by_src_tgt, - by_src_tgt_burden, - }) - } - - pub fn compile_summary(&self) -> AtlasCompileSummary { - AtlasCompileSummary { - edge_count: self.edges.len(), - indexed_src_tgt_pairs: self.by_src_tgt.len(), - indexed_burden_pairs: self.by_src_tgt_burden.len(), - } - } - - pub fn select_policy_driven( - &self, - src: &str, - tgt: &str, - burden_class: Option<&BurdenClass>, - budget: Option<&Budget>, - resolution: Option<&PolicyResolution>, - bundle_resolution_ok: bool, - ) -> Result { - let indices = if let Some(burden_class) = burden_class { - self.by_src_tgt_burden - .get(&(src.to_string(), tgt.to_string(), burden_class.clone())) - .cloned() - .unwrap_or_default() - } else { - self.by_src_tgt - .get(&(src.to_string(), tgt.to_string())) - .cloned() - .unwrap_or_default() - }; - - let mut candidate_edges = indices - .into_iter() - .filter_map(|index| self.edges.get(index).cloned()) - .filter(|edge| { - budget - .map(|budget| edge.loss_count <= budget.max_loss) - .unwrap_or(true) - }) - .collect::>(); - - let policy = resolution - .map(|item| item.optimizer.optimizer_policy.clone()) - .unwrap_or(OptimizerPolicy::Conservative); - let backend = resolution - .map(|item| item.optimizer.backend.clone()) - .unwrap_or(OptimizerBackend::Lexicographic); - let axes = resolution - .map(|item| item.optimizer.active_axes.clone()) - .unwrap_or_else(optimizer_axes); - - candidate_edges.sort_by(|left, right| { - let left_score = route_score(left, &policy, &axes, bundle_resolution_ok); - let right_score = route_score(right, &policy, &axes, bundle_resolution_ok); - left_score.cmp(&right_score) - }); - - let dominated_candidates = if backend == OptimizerBackend::ParetoBounded { - pareto_dominated(&candidate_edges, &axes, bundle_resolution_ok) - } else { - candidate_edges - .iter() - .skip(1) - .map(|edge| edge.atlas_cell_id.clone()) - .collect::>() - }; - - let candidates = candidate_edges - .iter() - .map(to_atlas_cell_stub) - .collect::>(); - let winner = candidate_edges.first().map(to_atlas_cell_stub); - if winner.is_none() { - return Err(AtlasError::NoRoute); - } - - Ok(RouteSelection { - candidates, - winner, - reasons: vec![format!("compiled atlas {:?} selection", backend)], - route_explanation: Some(RouteExplanation { - optimizer_policy: policy, - optimizer_backend: backend.clone(), - policy_resolution_id: resolution.map(|item| item.id.clone()), - winner_atlas_cell_id: candidate_edges - .first() - .map(|edge| edge.atlas_cell_id.clone()), - winner_score: candidate_edges - .first() - .map(|edge| route_score_vector(edge, bundle_resolution_ok)), - dominated_candidates, - rejected_candidates: Vec::new(), - axes_used: axes.clone(), - explanation: vec![format!( - "winner chosen by constitutional {:?} optimizer", - backend - )], - }), - }) - } - - pub fn select_lexicographic( - &self, - src: &str, - tgt: &str, - burden_class: Option<&BurdenClass>, - budget: Option<&Budget>, - optimizer_policy: OptimizerPolicy, - bundle_resolution_ok: bool, - ) -> Result { - let resolution = PolicyResolution { - id: "MPR_INLINE".into(), - scope: l64_core::PolicyScope::Global, - applied_policy_ids: vec!["INLINE".into()], - conflicts: Vec::new(), - trace: l64_core::PolicyTrace { - id: "MPT_INLINE".into(), - steps: vec!["inline optimizer policy".into()], - }, - optimizer: l64_core::OptimizerPolicyConfig { - optimizer_policy, - backend: OptimizerBackend::Lexicographic, - active_axes: optimizer_axes(), - route_explanation_verbosity: "standard".into(), - symbolic_fidelity_preferred: false, - tie_break_rules: vec!["shorter-path".into()], - }, - evaluator: l64_core::EvaluatorPolicyConfig { - evidence_preference: l64_core::EvidencePreference::RecomputeIfSupported, - allow_approximation: true, - unsupported_mode: l64_core::UnsupportedHandlingMode::Permit, - require_symbolic_fidelity_route: false, - prefer_comp_replay: true, - }, - replay_cache: l64_core::ReplayCachePolicyConfig { - replay_allowed: true, - exact_policy_match_required: true, - survive_surface_only_changes: false, - reuse_approximate_results: false, - optimizer_change_invalidates: true, - surface_pack_change_invalidates: true, - trust_class: l64_core::ReplayTrustClass::ExactPolicyOnly, - }, - report: l64_core::ReportPolicyConfig { - export_surfaces: Vec::new(), - include_policy_trace: true, - include_route_explanation: true, - include_obligation_logs: true, - }, - scheduler: l64_core::SchedulerPolicyConfig { - parallelization: l64_core::ParallelizationPolicy::Serialize, - max_workers: 1, - allow_parallel_replay: false, - allow_parallel_certification: true, - allow_parallel_exports: true, - deterministic_ordering: true, - allow_parallel_obligations: false, - max_obligation_workers: 1, - allow_parallel_obligation_replay: false, - serialize_canonicalization_sensitive: true, - }, - verdict: l64_core::PolicyVerdict::Applied, - }; - self.select_policy_driven( - src, - tgt, - burden_class, - budget, - Some(&resolution), - bundle_resolution_ok, - ) - } - - pub fn edge_by_atlas_cell(&self, atlas_cell_id: &str) -> Option<&CompiledEdge> { - self.edges - .iter() - .find(|edge| edge.atlas_cell_id == atlas_cell_id) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct AtlasCompileSummary { - pub edge_count: usize, - pub indexed_src_tgt_pairs: usize, - pub indexed_burden_pairs: usize, -} - -fn route_score( - edge: &CompiledEdge, - policy: &OptimizerPolicy, - axes: &[OptimizationAxis], - bundle_resolution_ok: bool, -) -> Vec { - let vector = route_score_vector(edge, bundle_resolution_ok); - let preferred_axes = if axes.is_empty() { - match policy { - OptimizerPolicy::Conservative => optimizer_axes(), - OptimizerPolicy::SymbolicFidelityFirst => vec![ - OptimizationAxis::SymbolicFidelity, - OptimizationAxis::SurfaceTransitionPenalty, - OptimizationAxis::IdentityPreservation, - OptimizationAxis::LossCompliance, - OptimizationAxis::ProofShapeSatisfiability, - OptimizationAxis::ExecutionCost, - ], - OptimizerPolicy::ExecutionFirst => vec![ - OptimizationAxis::ExecutionCost, - OptimizationAxis::LossCompliance, - OptimizationAxis::Lawfulness, - OptimizationAxis::BundleResolution, - OptimizationAxis::SymbolicFidelity, - ], - OptimizerPolicy::LowLoss => vec![ - OptimizationAxis::LossCompliance, - OptimizationAxis::SurfaceTransitionPenalty, - OptimizationAxis::RollbackViability, - OptimizationAxis::IdentityPreservation, - OptimizationAxis::ExecutionCost, - ], - OptimizerPolicy::BenchmarkFriendly => vec![ - OptimizationAxis::MaturityConfidence, - OptimizationAxis::ExecutionCost, - OptimizationAxis::ProofShapeSatisfiability, - OptimizationAxis::ReceiptCompleteness, - OptimizationAxis::LossCompliance, - ], - } - } else { - axes.to_vec() - }; - preferred_axes - .into_iter() - .map(|axis| axis_value(&vector, &axis)) - .collect() -} - -fn route_score_vector(edge: &CompiledEdge, bundle_resolution_ok: bool) -> RouteScoreVector { - RouteScoreVector { - lawfulness: usize::from(edge.winner_state != WinnerState::SeedWinner), - identity_preservation: usize::from( - edge.reversibility - .contains(&ReversibilityClass::LossySupported), - ), - loss_compliance: edge.loss_count, - rollback_viability: usize::from( - edge.reversibility - .contains(&ReversibilityClass::LossySupported), - ), - proof_shape_satisfiability: usize::from(edge.proof_shapes.is_empty()), - bundle_resolution: usize::from(!bundle_resolution_ok), - surface_transition_penalty: edge.surface_penalty, - execution_cost: edge.path.len(), - derived_obligation_depth: usize::from(edge.proof_shapes.is_empty()), - maturity_confidence: usize::from(edge.winner_state != WinnerState::SeedWinner), - symbolic_fidelity: match edge - .surface_transition - .as_ref() - .map(|item| &item.compatibility) - { - Some( - SurfaceCompatibilityClass::AuthorityPreserving - | SurfaceCompatibilityClass::SymbolicFidelityPreserving, - ) => 0, - Some(SurfaceCompatibilityClass::DebugMirrorOnly) => 2, - Some(SurfaceCompatibilityClass::IngressProjectionOnly) => 3, - None => 1, - }, - receipt_completeness: usize::from(edge.surface_transition.is_none()), - } -} - -fn optimizer_axes() -> Vec { - vec![ - OptimizationAxis::Lawfulness, - OptimizationAxis::IdentityPreservation, - OptimizationAxis::LossCompliance, - OptimizationAxis::RollbackViability, - OptimizationAxis::ProofShapeSatisfiability, - OptimizationAxis::BundleResolution, - OptimizationAxis::SurfaceTransitionPenalty, - OptimizationAxis::ExecutionCost, - OptimizationAxis::DerivedObligationDepth, - OptimizationAxis::MaturityConfidence, - OptimizationAxis::SymbolicFidelity, - OptimizationAxis::ReceiptCompleteness, - ] -} - -fn axis_value(vector: &RouteScoreVector, axis: &OptimizationAxis) -> usize { - match axis { - OptimizationAxis::Lawfulness => vector.lawfulness, - OptimizationAxis::IdentityPreservation => vector.identity_preservation, - OptimizationAxis::LossCompliance => vector.loss_compliance, - OptimizationAxis::RollbackViability => vector.rollback_viability, - OptimizationAxis::ProofShapeSatisfiability => vector.proof_shape_satisfiability, - OptimizationAxis::BundleResolution => vector.bundle_resolution, - OptimizationAxis::SurfaceTransitionPenalty => vector.surface_transition_penalty, - OptimizationAxis::ExecutionCost => vector.execution_cost, - OptimizationAxis::DerivedObligationDepth => vector.derived_obligation_depth, - OptimizationAxis::MaturityConfidence => vector.maturity_confidence, - OptimizationAxis::SymbolicFidelity => vector.symbolic_fidelity, - OptimizationAxis::ReceiptCompleteness => vector.receipt_completeness, - } -} - -fn pareto_dominated( - edges: &[CompiledEdge], - axes: &[OptimizationAxis], - bundle_resolution_ok: bool, -) -> Vec { - let mut dominated = Vec::new(); - for (i, edge) in edges.iter().enumerate() { - let score = route_score_vector(edge, bundle_resolution_ok); - let is_dominated = edges.iter().enumerate().any(|(j, other)| { - if i == j { - return false; - } - let other_score = route_score_vector(other, bundle_resolution_ok); - dominates(&other_score, &score, axes) - }); - if is_dominated { - dominated.push(edge.atlas_cell_id.clone()); - } - } - dominated -} - -fn dominates(left: &RouteScoreVector, right: &RouteScoreVector, axes: &[OptimizationAxis]) -> bool { - let mut strictly_better = false; - for axis in axes { - let left_value = axis_value(left, axis); - let right_value = axis_value(right, axis); - if left_value > right_value { - return false; - } - if left_value < right_value { - strictly_better = true; - } - } - strictly_better -} - -fn to_atlas_cell_stub(edge: &CompiledEdge) -> AtlasCell { - AtlasCell { - id: edge.atlas_cell_id.clone(), - source_regime: edge.src.clone(), - target_regime: edge.tgt.clone(), - burden_class: edge.burden_class.clone(), - proof_target: "compiled".into(), - candidate_paths: vec![edge.path.clone()], - normalized_winner: edge.path.clone(), - winner_state: edge.winner_state.clone(), - loss_profile: l64_core::LossProfile { - items: vec!["compiled".into(); edge.loss_count], - }, - proof_shapes_checked: edge.proof_shapes.clone(), - recipe_maturity: l64_core::RecipeMaturity::Stable, - failure_signatures: Vec::new(), - side_conditions: vec!["compiled-atlas".into()], - surface_transition: edge.surface_transition.clone(), - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TheoremExecution { - pub theorem_id: String, - pub selected_route: Vec, - pub verdict: CertificationVerdict, -} - -pub fn run_seed_theorem( - registry: &R, - theorem_id: &str, - atlas: &CompiledAtlas, -) -> Result { - let theorem = registry - .get_theorem_spec(theorem_id) - .ok_or(AtlasError::NoRoute)?; - let src = theorem.hosts.first().ok_or(AtlasError::NoRoute)?; - let tgt = theorem.hosts.last().ok_or(AtlasError::NoRoute)?; - let route = - atlas.select_lexicographic(src, tgt, None, None, OptimizerPolicy::Conservative, true)?; - let selected = route.winner.ok_or(AtlasError::NoRoute)?; - let kernel = ConstitutionKernel; - let path = selected.normalized_winner.clone(); - let bridges = path - .iter() - .filter_map(|id| registry.get_bridge(id)) - .collect::>(); - kernel - .compose_bridge_path(&bridges, None) - .map_err(|_| AtlasError::NoRoute)?; - - Ok(TheoremExecution { - theorem_id: theorem.id, - selected_route: path, - verdict: theorem.verdict, - }) -} - -fn infer_surface_penalty(cell: &AtlasCell) -> usize { - let mut penalty = 0usize; - if cell - .loss_profile - .items - .iter() - .any(|item| item.contains("ascii") || item.contains("debug")) - { - penalty += 3; - } - if cell - .side_conditions - .iter() - .any(|item| item.contains("qk-ingress-only") || item.contains("projection")) - { - penalty += 2; - } - penalty -} - -#[cfg(test)] -mod tests { - use super::*; - use l64_registry::SeedRegistry; - - #[test] - fn compiled_atlas_selects_seed_route() { - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let result = atlas - .select_lexicographic( - "R_TYP", - "R_SET", - None, - None, - OptimizerPolicy::Conservative, - true, - ) - .unwrap(); - assert_eq!(result.winner.unwrap().id, "A_TYPE_TO_SET"); - } -} diff --git a/l64-bundle/Cargo.toml b/l64-bundle/Cargo.toml deleted file mode 100644 index b4159c2..0000000 --- a/l64-bundle/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "l64-bundle" -version = "0.1.0" -edition = "2024" - -[dependencies] -anyhow = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -thiserror = { workspace = true } -l64-core = { path = "../l64-core" } -l64-locus = { path = "../l64-locus" } -l64-registry = { path = "../l64-registry" } diff --git a/l64-bundle/src/lib.rs b/l64-bundle/src/lib.rs deleted file mode 100644 index d26fd4e..0000000 --- a/l64-bundle/src/lib.rs +++ /dev/null @@ -1,2001 +0,0 @@ -use anyhow::{Result, anyhow}; -use l64_core::{ - AdequacyClause, AliasExpansionPolicy, ArtifactOrigin, AtlasCell, AtlasDeficiency, - AuthorityComplement, BenchmarkReceipt, BridgeBurden, BridgeContract, BundleConflict, - BundleConflictPolicy, BundleDependency, BundleEntry, BundleExecutionReceipt, BundleManifest, - BundleMergeReport, BurdenPack, Campaign, CampaignPortfolio, CanonicalWorkUnit, Certificate, - ChallengeReceipt, ClaimPacket, CodebookPack, CodonHeader, CodonPhase, ComboPack, - CyclePolicyResult, DeterministicAuthorityMerge, DigestRole, DomainClosureReport, - DuplexPairStatus, EquivalenceClass, EvidenceContract, ExecutionManifest, GlyphPack, - MechanizationPackage, MechanizationPolicyObject, MolecularCodecEnvelope, MolecularCodecRecord, - Obligation, OpenObligation, OverlayRegistryDescriptor, PairLaw, PolicyBinding, - PolicyResolution, ProjectionPolicy, ProofShape, QaDocument, QaEntry, QcObject, RegimePack, - RegistryBundle, RegistryLookup, ReplayLockManifest, ReproducibilityPacket, RouteClass, - RouteLedger, SemanticStrand, SubstrateAtom, SubstrateBond, SubstratePrimitive, - SubstratePrimitiveKind, SurfaceDeficiency, SurfaceKind, TargetProfile, TheoremSpec, - ensure_cache_subdir, role_digest_value, -}; -use l64_registry::SeedRegistry; -use serde::{Deserialize, Serialize}; -use std::{ - collections::{HashMap, HashSet}, - fs, - path::{Path, PathBuf}, -}; - -#[derive(Debug, Clone)] -pub struct OverlayRegistry { - pub parent: SeedRegistry, - pub bundle_id: String, - pub local: RegistryBundle, - pub merge_report: BundleMergeReport, -} - -#[derive(Debug, Clone)] -pub struct BundleWorld { - pub manifest: BundleManifest, - pub overlay: OverlayRegistry, - pub substrate_parity: BundleSubstrateParityReport, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum BundleMigrationIngressKind { - BundleEntryText, - DnaBundlePayload, - InMemoryDocument, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct BundleMigrationIngress { - pub kind: BundleMigrationIngressKind, - pub document: QaDocument, -} - -impl BundleMigrationIngress { - pub fn from_entry_text(document: QaDocument) -> Self { - Self { - kind: BundleMigrationIngressKind::BundleEntryText, - document, - } - } - - pub fn from_dna_payload(document: QaDocument) -> Self { - Self { - kind: BundleMigrationIngressKind::DnaBundlePayload, - document, - } - } - - pub fn from_in_memory_document(document: QaDocument) -> Self { - Self { - kind: BundleMigrationIngressKind::InMemoryDocument, - document, - } - } - - pub fn is_native_authority(&self) -> bool { - false - } - - pub fn into_document(self) -> QaDocument { - self.document - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct CachedBundleWorld { - manifest: BundleManifest, - bundle_id: String, - local: RegistryBundle, - merge_report: BundleMergeReport, - #[serde(default)] - substrate_parity: BundleSubstrateParityReport, -} - -fn bundle_cache_root() -> Result { - Ok(ensure_cache_subdir("bundles").map_err(anyhow::Error::msg)?) -} - -pub fn load_bundle_world(bundle_id: &str) -> Result { - let path = bundle_cache_root()?.join(format!("{bundle_id}.json")); - let cached: CachedBundleWorld = serde_json::from_str(&fs::read_to_string(path)?)?; - Ok(BundleWorld { - manifest: cached.manifest, - overlay: OverlayRegistry { - parent: SeedRegistry::load()?, - bundle_id: cached.bundle_id, - local: cached.local, - merge_report: cached.merge_report, - }, - substrate_parity: cached.substrate_parity, - }) -} - -pub fn persist_bundle_world(world: &BundleWorld) -> Result<()> { - let path = bundle_cache_root()?.join(format!("{}.json", world.manifest.id)); - let cached = CachedBundleWorld { - manifest: world.manifest.clone(), - bundle_id: world.overlay.bundle_id.clone(), - local: world.overlay.local.clone(), - merge_report: world.overlay.merge_report.clone(), - substrate_parity: world.substrate_parity.clone(), - }; - fs::write(path, serde_json::to_string_pretty(&cached)?)?; - Ok(()) -} - -pub fn local_registry_from_document(document: &QaDocument) -> LocalRegistry { - LocalRegistry { - bundle_id: "DOC_LOCAL".into(), - local: bundle_from_document(document), - } -} - -pub fn bundle_document_to_molecular_codec_records( - document: &QaDocument, - origin_authority: &str, -) -> Vec { - let mut records = document - .entries - .iter() - .map(|entry| { - let entry_id = entry.id(); - MolecularCodecRecord { - codon_symbol: "A#".into(), - phase: CodonPhase::DnaAuthority, - origin_authority: origin_authority.into(), - subject: entry_id.clone(), - primitive_kind: SubstratePrimitiveKind::Atom, - primitive: SubstratePrimitive::Atom(SubstrateAtom { - id: entry_id, - codon_symbol: "A#".into(), - lexon_symbol: None, - }), - } - }) - .collect::>(); - - let local = bundle_from_document(document); - for dep in bundle_dependencies(&local) { - for depends_on in dep.depends_on { - records.push(MolecularCodecRecord { - codon_symbol: "B#".into(), - phase: CodonPhase::DnaAuthority, - origin_authority: origin_authority.into(), - subject: dep.id.clone(), - primitive_kind: SubstratePrimitiveKind::Bond, - primitive: SubstratePrimitive::Bond(SubstrateBond { - id: format!( - "BOND_{}", - role_digest_value(DigestRole::AuthorityId, &("<-", &dep.id, &depends_on)) - ), - relation_codon: "<-".into(), - left: dep.id.clone(), - right: depends_on, - }), - }); - } - } - - records -} - -pub fn bundle_document_to_molecular_codec_envelopes( - document: &QaDocument, - origin_authority: &str, -) -> Vec { - bundle_document_to_molecular_codec_records(document, origin_authority) - .into_iter() - .map(|record| MolecularCodecEnvelope { - header: CodonHeader { - protocol: "l64".into(), - version: 2, - phase: record.phase, - class_symbol: record.codon_symbol.clone(), - role_symbol: "|-".into(), - subject: record.subject.clone(), - }, - record, - }) - .collect() -} - -fn bundle_envelope_to_duplex_pair(envelope: &MolecularCodecEnvelope) -> l64_core::DuplexPair { - let semantic = SemanticStrand { - id: format!("SEM_{}", envelope.record.subject), - canonical_structure_id: envelope.record.subject.clone(), - authority_scope: "bundle-substrate".into(), - }; - let complement = AuthorityComplement { - id: format!("CMP_{}", envelope.record.subject), - authority_scope: "bundle-substrate".into(), - admission_law_id: "ADM_BUNDLE_SUBSTRATE_V1".into(), - exclusions: vec![ - "strand-only-promotion".into(), - "receipt-only-complement".into(), - ], - invariants: vec![ - "molecular-envelope-valid".into(), - "bundle-entry-or-dependency-preserved".into(), - ], - dependency_burdens: vec![], - required_witness_forms: vec!["molecular-codec-envelope-validation".into()], - closure_requirements: vec!["bundle-substrate-domain-closure".into()], - rollback_law_id: "RBK_REJECT_BUNDLE_PAIR_V1".into(), - }; - let pair_law = PairLaw { - id: "PAIR_BUNDLE_SUBSTRATE_V1".into(), - required_semantic_scope: "bundle-substrate".into(), - required_complement_scope: "bundle-substrate".into(), - required_admission_law_id: "ADM_BUNDLE_SUBSTRATE_V1".into(), - strand_only_promotion_allowed: false, - }; - l64_core::assemble_duplex_pair(semantic, complement, pair_law) -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] -pub struct BundleSubstrateParityReport { - pub entry_count: usize, - pub dependency_edge_count: usize, - pub substrate_record_count: usize, - #[serde(default)] - pub duplex_pair_count: usize, - #[serde(default)] - pub locally_valid_pair_count: usize, - #[serde(default)] - pub domain_closure: Option, - #[serde(default)] - pub deterministic_merge: Option, - pub valid: bool, - pub failures: Vec, -} - -pub fn bundle_substrate_parity_report( - document: &QaDocument, - origin_authority: &str, -) -> BundleSubstrateParityReport { - let local = bundle_from_document(document); - let dependencies = bundle_dependencies(&local); - let dependency_edge_count = dependencies - .iter() - .map(|dependency| dependency.depends_on.len()) - .sum::(); - let envelopes = bundle_document_to_molecular_codec_envelopes(document, origin_authority); - let duplex_pairs = envelopes - .iter() - .map(bundle_envelope_to_duplex_pair) - .collect::>(); - let pair_validations = duplex_pairs - .iter() - .map(|pair| l64_core::validate_duplex_pair(Some(pair))) - .collect::>(); - let mut failures = Vec::new(); - - if envelopes.len() != document.entries.len() + dependency_edge_count { - failures.push("substrate record count does not match entries plus dependency edges".into()); - } - for envelope in &envelopes { - let report = l64_core::validate_molecular_codec_envelope(envelope); - if !report.valid { - failures.extend(report.failures); - } - } - for entry in &document.entries { - let id = entry.id(); - if !envelopes.iter().any(|envelope| { - matches!(envelope.record.primitive, SubstratePrimitive::Atom(_)) - && envelope.record.subject == id - }) { - failures.push(format!("missing substrate atom for entry {id}")); - } - } - for dependency in &dependencies { - for depends_on in &dependency.depends_on { - if !envelopes - .iter() - .any(|envelope| match &envelope.record.primitive { - SubstratePrimitive::Bond(bond) => { - bond.left == dependency.id && bond.right == *depends_on - } - _ => false, - }) - { - failures.push(format!( - "missing substrate bond for dependency {} <- {}", - dependency.id, depends_on - )); - } - } - } - - for validation in &pair_validations { - if validation.status != DuplexPairStatus::LocallyValid { - failures.extend(validation.failures.clone()); - } - } - let open_frontier = if failures.is_empty() { - Vec::new() - } else { - vec![OpenObligation { - id: "OBL_BUNDLE_SUBSTRATE_PARITY".into(), - description: "bundle substrate parity failures block domain closure".into(), - }] - }; - let domain_closure = l64_core::evaluate_domain_closure( - &pair_validations, - open_frontier, - Vec::::new(), - CyclePolicyResult::Acyclic, - ); - let work_units = pair_validations - .iter() - .filter_map(|validation| { - validation - .pair_commitment - .as_ref() - .map(|commitment| CanonicalWorkUnit { - coordinate: commitment.clone(), - payload_commitment: commitment.clone(), - }) - }) - .collect::>(); - let deterministic_merge = l64_core::deterministic_authority_merge(&work_units, 1); - let locally_valid_pair_count = pair_validations - .iter() - .filter(|validation| validation.status == DuplexPairStatus::LocallyValid) - .count(); - - BundleSubstrateParityReport { - entry_count: document.entries.len(), - dependency_edge_count, - substrate_record_count: envelopes.len(), - duplex_pair_count: duplex_pairs.len(), - locally_valid_pair_count, - domain_closure: Some(domain_closure), - deterministic_merge: Some(deterministic_merge), - valid: failures.is_empty(), - failures, - } -} - -pub fn overlay_registry_from_document( - parent: SeedRegistry, - document: &QaDocument, -) -> OverlayRegistry { - OverlayRegistry { - parent, - bundle_id: "DOC_OVERLAY".into(), - local: bundle_from_document(document), - merge_report: BundleMergeReport { - id: "BMERGE_DOC_OVERLAY".into(), - policy: BundleConflictPolicy::Reject, - imported_entries: document.entries.len(), - conflicts: Vec::new(), - namespaced_entries: 0, - }, - } -} - -fn parse_bundle_document_from_entry_text(text: &str) -> Result { - let mut saw_header = false; - let mut entries = Vec::new(); - for line in text.lines().map(str::trim).filter(|line| !line.is_empty()) { - if line == "!l64-bundle v1" { - saw_header = true; - continue; - } - if line.starts_with('!') { - if line.starts_with("!qc0") || line.starts_with("!qa0") { - return Err(anyhow!( - "obsolete projection bundle header `{}`; use `!l64-bundle v1`", - line.split_whitespace().next().unwrap_or(line) - )); - } - return Err(anyhow!("unknown bundle header `{line}`")); - } - let (kind, payload) = line - .split_once(' ') - .ok_or_else(|| anyhow!("bundle entry is missing JSON payload: `{line}`"))?; - if matches!( - kind, - "surface-policy" - | "transform-receipt" - | "roundtrip-report" - | "capability" - | "surface-budget" - ) { - return Err(anyhow!( - "deprecated surface-schema bundle entry `{kind}` is not admitted by bundle-entry text" - )); - } - entries.push( - QaEntry::from_surface_json(kind, payload) - .map_err(|err| anyhow!("invalid `{kind}` bundle entry: {err}"))?, - ); - } - if !saw_header { - return Err(anyhow!( - "bundle-entry text must start with `!l64-bundle v1`" - )); - } - if entries.is_empty() { - return Err(anyhow!("bundle-entry text must contain at least one entry")); - } - Ok(QaDocument { entries }) -} - -pub fn bundle_migration_ingress_from_entry_text(text: &str) -> Result { - parse_bundle_document_from_entry_text(text).map(BundleMigrationIngress::from_entry_text) -} - -pub fn bundle_document_from_entry_text(text: &str) -> Result { - Ok(bundle_migration_ingress_from_entry_text(text)?.into_document()) -} - -pub fn import_bundle_file( - path: &Path, - forced_kind: Option, - policy: BundleConflictPolicy, - namespace: Option<&str>, -) -> Result { - let parent = SeedRegistry::load()?; - if forced_kind.is_some() { - return Err(anyhow!( - "explicit projection bundle import has been removed; compile bundle-entry text with `compile-bundle` without `--as`, then import the resulting .dna" - )); - } - if !matches!( - path.extension().and_then(|value| value.to_str()), - Some("dna") - ) { - return Err(anyhow!( - "bundle execution inputs must be .dna; compile bundle-entry text with `compile-bundle` first" - )); - } - let document: QaDocument = l64_locus::decode_section_payload( - &fs::read(path)?, - l64_core::LocusOpcode::CanonicalPayload, - ) - .map_err(anyhow::Error::msg)?; - let ingress = BundleMigrationIngress::from_dna_payload(document); - let bundle_id = path - .file_stem() - .and_then(|value| value.to_str()) - .map(|value| format!("BND_{}", value.to_ascii_uppercase().replace('-', "_"))) - .unwrap_or_else(|| "BND_IMPORTED".into()); - import_bundle_ingress(parent, bundle_id, ingress, policy, namespace) -} - -pub fn import_bundle_document( - parent: SeedRegistry, - bundle_id: String, - document: QaDocument, - policy: BundleConflictPolicy, - namespace: Option<&str>, -) -> Result { - import_bundle_ingress( - parent, - bundle_id, - BundleMigrationIngress::from_in_memory_document(document), - policy, - namespace, - ) -} - -pub fn import_bundle_ingress( - parent: SeedRegistry, - bundle_id: String, - ingress: BundleMigrationIngress, - policy: BundleConflictPolicy, - namespace: Option<&str>, -) -> Result { - let document = ingress.into_document(); - let document = if policy == BundleConflictPolicy::NamespacedImport { - namespace_document( - document, - namespace.unwrap_or(&bundle_id.to_ascii_lowercase().replace("bnd_", "bnd.")), - ) - } else { - document - }; - let local = bundle_from_document(&document); - let merge_report = detect_conflicts(&parent, &local, &policy)?; - if policy == BundleConflictPolicy::Reject && !merge_report.conflicts.is_empty() { - return Err(anyhow!("bundle import rejected due to conflicts")); - } - let substrate_parity = bundle_substrate_parity_report(&document, &format!("{bundle_id}.dna")); - let domain_closed = substrate_parity - .domain_closure - .as_ref() - .map(|closure| closure.promotable) - .unwrap_or(false); - if !substrate_parity.valid || !domain_closed { - return Err(anyhow!( - "bundle import rejected because native substrate parity is not closed: {:?}", - substrate_parity.failures - )); - } - let manifest = BundleManifest { - id: bundle_id.clone(), - entries: bundle_entries(&local), - dependencies: bundle_dependencies(&local), - merge_report: merge_report.clone(), - overlay: OverlayRegistryDescriptor { - id: format!("BOVR_{bundle_id}"), - parent: "seed".into(), - bundle_id: bundle_id.clone(), - local_entries: bundle_entries(&local).len(), - shadowed_entries: merge_report - .conflicts - .iter() - .map(|item| item.id.clone()) - .collect(), - }, - execution_receipt: BundleExecutionReceipt { - id: format!("BREC_{bundle_id}"), - bundle_id: bundle_id.clone(), - theorem_ids: local - .theorem_specs - .iter() - .map(|item| item.id.clone()) - .collect(), - campaign_ids: local.campaigns.iter().map(|item| item.id.clone()).collect(), - overlay_id: format!("BOVR_{bundle_id}"), - import_receipt_ids: Vec::new(), - merge_report_id: format!("BMER_{bundle_id}"), - }, - }; - let world = BundleWorld { - manifest, - overlay: OverlayRegistry { - parent, - bundle_id, - local, - merge_report, - }, - substrate_parity, - }; - persist_bundle_world(&world)?; - Ok(world) -} - -fn detect_conflicts( - parent: &SeedRegistry, - local: &RegistryBundle, - policy: &BundleConflictPolicy, -) -> Result { - let mut conflicts = Vec::new(); - collect_conflicts(&mut conflicts, policy, &local.objects, |id| { - parent - .get_object(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.regimes, |id| { - parent - .get_regime(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.bridges, |id| { - parent - .get_bridge(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.proof_shapes, |id| { - parent - .get_proof_shape(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.atlas_cells, |id| { - parent - .get_atlas_cell(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.theorem_specs, |id| { - parent - .get_theorem_spec(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.target_profiles, |id| { - parent - .get_target_profile(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.route_ledgers, |id| { - parent - .get_route_ledger(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.certificates, |id| { - parent - .get_certificate(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.campaigns, |id| { - parent - .get_campaign(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.burden_packs, |id| { - parent - .get_burden_pack(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.claim_packets, |id| { - parent - .get_claim_packet(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.evidence_contracts, |id| { - parent - .get_evidence_contract(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.benchmark_receipts, |id| { - parent - .get_benchmark_receipt(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts(&mut conflicts, policy, &local.challenge_receipts, |id| { - parent - .get_challenge_receipt(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - collect_conflicts( - &mut conflicts, - policy, - &local.reproducibility_packets, - |id| { - parent - .get_reproducibility_packet(id) - .map(|item| serde_json::to_value(item).unwrap()) - }, - ); - collect_conflicts(&mut conflicts, policy, &local.policy_objects, |id| { - parent - .get_policy_object(id) - .map(|item| serde_json::to_value(item).unwrap()) - }); - - Ok(BundleMergeReport { - id: "BMER_IMPORTED".into(), - policy: policy.clone(), - imported_entries: bundle_entries(local).len(), - namespaced_entries: usize::from(*policy == BundleConflictPolicy::NamespacedImport) - * bundle_entries(local).len(), - conflicts, - }) -} - -fn collect_conflicts( - conflicts: &mut Vec, - policy: &BundleConflictPolicy, - items: &[T], - existing: impl Fn(&str) -> Option, -) where - T: HasId, -{ - for item in items { - if let Some(existing_value) = existing(item.id()) { - let local_value = serde_json::to_value(item).unwrap(); - let exact = existing_value == local_value; - let message = if exact { - "exact-match".to_string() - } else { - "shadowed-or-conflicting".to_string() - }; - if !exact || *policy != BundleConflictPolicy::ExactMatch { - conflicts.push(BundleConflict { - id: item.id().to_string(), - kind: std::any::type_name::() - .rsplit("::") - .next() - .unwrap_or("entry") - .into(), - policy: policy.clone(), - message, - }); - } - } - } -} - -fn bundle_entries(local: &RegistryBundle) -> Vec { - registry_bundle_entries(local) -} - -fn bundle_dependencies(local: &RegistryBundle) -> Vec { - let mut deps = Vec::new(); - deps.extend(local.theorem_specs.iter().map(|item| BundleDependency { - id: item.id.clone(), - depends_on: item.bridges.clone(), - })); - deps.extend(local.adequacy_clauses.iter().map(|item| { - BundleDependency { - id: item.id.clone(), - depends_on: item - .bridge_ids - .iter() - .cloned() - .chain(item.theorem_ids.iter().cloned()) - .chain(item.burden_pack_ids.iter().cloned()) - .chain(item.claim_packet_ids.iter().cloned()) - .chain(item.evidence_contract_ids.iter().cloned()) - .chain(item.benchmark_receipt_ids.iter().cloned()) - .chain(item.challenge_receipt_ids.iter().cloned()) - .chain(item.reproducibility_packet_ids.iter().cloned()) - .collect(), - } - })); - deps.extend(local.campaigns.iter().map(|item| { - BundleDependency { - id: item.id.clone(), - depends_on: std::iter::once(item.theorem.clone()) - .chain(std::iter::once(item.target_profile.clone())) - .chain(std::iter::once(item.route_ledger.clone())) - .chain(item.obligations.clone()) - .chain(item.certificates.clone()) - .collect(), - } - })); - deps -} - -fn bundle_from_document(document: &QaDocument) -> RegistryBundle { - let mut bundle = RegistryBundle::default(); - for entry in &document.entries { - match entry { - QaEntry::Object(item) => bundle.objects.push(item.clone()), - QaEntry::Regime(item) => bundle.regimes.push(item.clone()), - QaEntry::Bridge(item) => bundle.bridges.push(item.clone()), - QaEntry::ProofShape(item) => bundle.proof_shapes.push(item.clone()), - QaEntry::AtlasCell(item) => bundle.atlas_cells.push(item.clone()), - QaEntry::MechanizationPackage(item) => bundle.mechanization_packages.push(item.clone()), - QaEntry::TheoremSpec(item) => bundle.theorem_specs.push(item.clone()), - QaEntry::Obligation(item) => bundle.obligations.push(item.clone()), - QaEntry::TargetProfile(item) => bundle.target_profiles.push(item.clone()), - QaEntry::RouteLedger(item) => bundle.route_ledgers.push(item.clone()), - QaEntry::Certificate(item) => bundle.certificates.push(item.clone()), - QaEntry::Campaign(item) => bundle.campaigns.push(item.clone()), - QaEntry::CampaignPortfolio(item) => bundle.campaign_portfolios.push(item.clone()), - QaEntry::RouteClass(item) => bundle.route_classes.push(item.clone()), - QaEntry::AtlasDeficiency(item) => bundle.atlas_deficiencies.push(item.clone()), - QaEntry::AdequacyClause(item) => bundle.adequacy_clauses.push(item.clone()), - QaEntry::BurdenPack(item) => bundle.burden_packs.push(item.clone()), - QaEntry::ClaimPacket(item) => bundle.claim_packets.push(item.clone()), - QaEntry::EvidenceContract(item) => bundle.evidence_contracts.push(item.clone()), - QaEntry::BenchmarkReceipt(item) => bundle.benchmark_receipts.push(item.clone()), - QaEntry::ChallengeReceipt(item) => bundle.challenge_receipts.push(item.clone()), - QaEntry::ReproducibilityPacket(item) => { - bundle.reproducibility_packets.push(item.clone()) - } - QaEntry::SurfacePolicy(_) - | QaEntry::TransformReceipt(_) - | QaEntry::RoundTripReport(_) - | QaEntry::CapabilityMatrix(_) - | QaEntry::SurfaceBudget(_) => {} - QaEntry::PolicyObject(item) => bundle.policy_objects.push(item.clone()), - QaEntry::PolicyBinding(item) => bundle.policy_bindings.push(item.clone()), - QaEntry::PolicyResolution(item) => bundle.policy_resolutions.push(item.clone()), - QaEntry::BundleLock(item) => bundle.bundle_locks.push(item.clone()), - QaEntry::ExecutionManifest(item) => bundle.execution_manifests.push(item.clone()), - QaEntry::ReplayLockManifest(item) => bundle.replay_lock_manifests.push(item.clone()), - QaEntry::LockReceipt(_) => {} - QaEntry::LockDiff(_) => {} - QaEntry::RecomputationPlan(_) => {} - QaEntry::PlanExecution(_) => {} - QaEntry::PredictionAssessment(_) => {} - QaEntry::Reconciliation(_) => {} - QaEntry::RootResolution(_) => {} - } - } - bundle -} - -fn namespace_document(mut document: QaDocument, namespace: &str) -> QaDocument { - let prefix = format!("{namespace}::"); - let id_map = collect_ids(&document) - .into_iter() - .map(|id| (id.clone(), format!("{prefix}{id}"))) - .collect::>(); - for entry in &mut document.entries { - match entry { - QaEntry::Object(item) => { - item.id = remap(&item.id, &id_map); - item.identity.cid = remap(&item.identity.cid, &id_map); - item.constraint.regime = remap(&item.constraint.regime, &id_map); - item.constraint.contracts = remap_vec(&item.constraint.contracts, &id_map); - item.constraint.invariants = remap_vec(&item.constraint.invariants, &id_map); - } - QaEntry::Regime(item) => item.id = remap(&item.id, &id_map), - QaEntry::Bridge(item) => { - item.id = remap(&item.id, &id_map); - item.src = remap(&item.src, &id_map); - item.tgt = remap(&item.tgt, &id_map); - item.receipts = remap_vec(&item.receipts, &id_map); - } - QaEntry::ProofShape(item) => { - item.id = remap(&item.id, &id_map); - item.receipts = remap_vec(&item.receipts, &id_map); - } - QaEntry::AtlasCell(item) => { - item.id = remap(&item.id, &id_map); - item.source_regime = remap(&item.source_regime, &id_map); - item.target_regime = remap(&item.target_regime, &id_map); - item.candidate_paths = item - .candidate_paths - .iter() - .map(|path| remap_vec(path, &id_map)) - .collect(); - item.normalized_winner = remap_vec(&item.normalized_winner, &id_map); - item.proof_shapes_checked = remap_vec(&item.proof_shapes_checked, &id_map); - } - QaEntry::MechanizationPackage(item) => item.id = remap(&item.id, &id_map), - QaEntry::TheoremSpec(item) => { - item.id = remap(&item.id, &id_map); - item.hosts = remap_vec(&item.hosts, &id_map); - item.bridges = remap_vec(&item.bridges, &id_map); - item.proof_shapes = remap_vec(&item.proof_shapes, &id_map); - } - QaEntry::Obligation(item) => item.id = remap(&item.id, &id_map), - QaEntry::TargetProfile(item) => item.id = remap(&item.id, &id_map), - QaEntry::RouteLedger(item) => { - item.id = remap(&item.id, &id_map); - item.theorem = remap(&item.theorem, &id_map); - item.paths = item - .paths - .iter() - .map(|path| remap_vec(path, &id_map)) - .collect(); - item.receipts = remap_vec(&item.receipts, &id_map); - item.normalized_path = remap_vec(&item.normalized_path, &id_map); - } - QaEntry::Certificate(item) => { - item.id = remap(&item.id, &id_map); - item.theorem = remap(&item.theorem, &id_map); - item.route_ledger = remap(&item.route_ledger, &id_map); - item.proof_shapes = remap_vec(&item.proof_shapes, &id_map); - item.receipts = remap_vec(&item.receipts, &id_map); - } - QaEntry::Campaign(item) => { - item.id = remap(&item.id, &id_map); - item.theorem = remap(&item.theorem, &id_map); - item.target_profile = remap(&item.target_profile, &id_map); - item.route_ledger = remap(&item.route_ledger, &id_map); - item.obligations = remap_vec(&item.obligations, &id_map); - item.certificates = remap_vec(&item.certificates, &id_map); - item.dependencies = remap_vec(&item.dependencies, &id_map); - } - QaEntry::CampaignPortfolio(item) => { - item.id = remap(&item.id, &id_map); - item.campaigns = remap_vec(&item.campaigns, &id_map); - } - QaEntry::RouteClass(item) => { - item.id = remap(&item.id, &id_map); - item.theorem = remap(&item.theorem, &id_map); - item.target_profile = remap(&item.target_profile, &id_map); - item.equivalent_paths = item - .equivalent_paths - .iter() - .map(|path| remap_vec(path, &id_map)) - .collect(); - item.canonical_path = remap_vec(&item.canonical_path, &id_map); - } - QaEntry::AtlasDeficiency(item) => { - item.id = remap(&item.id, &id_map); - item.atlas_cell = item.atlas_cell.as_ref().map(|id| remap(id, &id_map)); - item.theorem = item.theorem.as_ref().map(|id| remap(id, &id_map)); - } - QaEntry::AdequacyClause(item) => { - item.id = remap(&item.id, &id_map); - item.regime_ids = remap_vec(&item.regime_ids, &id_map); - item.bridge_ids = remap_vec(&item.bridge_ids, &id_map); - item.theorem_ids = remap_vec(&item.theorem_ids, &id_map); - item.burden_pack_ids = remap_vec(&item.burden_pack_ids, &id_map); - item.claim_packet_ids = remap_vec(&item.claim_packet_ids, &id_map); - item.evidence_contract_ids = remap_vec(&item.evidence_contract_ids, &id_map); - item.benchmark_receipt_ids = remap_vec(&item.benchmark_receipt_ids, &id_map); - item.challenge_receipt_ids = remap_vec(&item.challenge_receipt_ids, &id_map); - item.reproducibility_packet_ids = - remap_vec(&item.reproducibility_packet_ids, &id_map); - } - QaEntry::BurdenPack(item) => { - item.id = remap(&item.id, &id_map); - item.allowed_host_cluster = remap_vec(&item.allowed_host_cluster, &id_map); - item.obligation_ids = remap_vec(&item.obligation_ids, &id_map); - item.adequacy_clause_ids = remap_vec(&item.adequacy_clause_ids, &id_map); - item.route_class_constraints = remap_vec(&item.route_class_constraints, &id_map); - item.evidence_contract_ids = remap_vec(&item.evidence_contract_ids, &id_map); - } - QaEntry::ClaimPacket(item) => { - item.id = remap(&item.id, &id_map); - } - QaEntry::EvidenceContract(item) => { - item.id = remap(&item.id, &id_map); - } - QaEntry::BenchmarkReceipt(item) => { - item.id = remap(&item.id, &id_map); - item.claim_packet_id = remap(&item.claim_packet_id, &id_map); - item.reproducibility_ref = remap(&item.reproducibility_ref, &id_map); - } - QaEntry::ChallengeReceipt(item) => { - item.id = remap(&item.id, &id_map); - item.claim_packet_id = remap(&item.claim_packet_id, &id_map); - } - QaEntry::ReproducibilityPacket(item) => { - item.id = remap(&item.id, &id_map); - item.claim_packet_id = remap(&item.claim_packet_id, &id_map); - item.benchmark_refs = remap_vec(&item.benchmark_refs, &id_map); - item.artifact_refs = remap_vec(&item.artifact_refs, &id_map); - } - QaEntry::SurfacePolicy(_) - | QaEntry::TransformReceipt(_) - | QaEntry::RoundTripReport(_) - | QaEntry::CapabilityMatrix(_) - | QaEntry::SurfaceBudget(_) => {} - QaEntry::PolicyObject(item) => { - item.id = remap(&item.id, &id_map); - item.extends = item.extends.as_ref().map(|id| remap(id, &id_map)); - } - QaEntry::PolicyBinding(item) => { - item.id = remap(&item.id, &id_map); - item.policy_id = remap(&item.policy_id, &id_map); - item.target_id = item.target_id.as_ref().map(|id| remap(id, &id_map)); - } - QaEntry::PolicyResolution(item) => { - item.id = remap(&item.id, &id_map); - item.applied_policy_ids = remap_vec(&item.applied_policy_ids, &id_map); - item.trace.id = remap(&item.trace.id, &id_map); - } - QaEntry::BundleLock(item) => { - item.id = remap(&item.id, &id_map); - item.bundle_id = remap(&item.bundle_id, &id_map); - item.policy_resolution_id = remap(&item.policy_resolution_id, &id_map); - item.report_ids = remap_vec(&item.report_ids, &id_map); - item.manifest_id = remap(&item.manifest_id, &id_map); - } - QaEntry::ExecutionManifest(item) => { - item.id = remap(&item.id, &id_map); - item.bundle_id = remap(&item.bundle_id, &id_map); - item.policy_manifest.id = remap(&item.policy_manifest.id, &id_map); - item.policy_manifest.resolution_id = - remap(&item.policy_manifest.resolution_id, &id_map); - item.policy_manifest.policy_ids = - remap_vec(&item.policy_manifest.policy_ids, &id_map); - item.route_winner_ids = remap_vec(&item.route_winner_ids, &id_map); - item.report_ids = remap_vec(&item.report_ids, &id_map); - } - QaEntry::ReplayLockManifest(item) => { - item.id = remap(&item.id, &id_map); - item.report_id = remap(&item.report_id, &id_map); - } - QaEntry::LockReceipt(item) => { - item.id = remap(&item.id, &id_map); - item.lock_id = remap(&item.lock_id, &id_map); - item.manifest_id = remap(&item.manifest_id, &id_map); - item.bundle_id = remap(&item.bundle_id, &id_map); - item.receipt_ids = remap_vec(&item.receipt_ids, &id_map); - } - QaEntry::LockDiff(item) => { - item.id = remap(&item.id, &id_map); - item.left_lock_id = remap(&item.left_lock_id, &id_map); - item.right_lock_id = remap(&item.right_lock_id, &id_map); - } - QaEntry::RecomputationPlan(_) => {} - QaEntry::PlanExecution(_) => {} - QaEntry::PredictionAssessment(_) => {} - QaEntry::Reconciliation(_) => {} - QaEntry::RootResolution(_) => {} - } - } - document -} - -fn collect_ids(document: &QaDocument) -> HashSet { - document.entries.iter().map(QaEntry::id).collect() -} - -fn registry_bundle_entries(local: &RegistryBundle) -> Vec { - let mut entries = Vec::new(); - entries.extend(local.objects.iter().cloned().map(QaEntry::Object)); - entries.extend(local.regimes.iter().cloned().map(QaEntry::Regime)); - entries.extend(local.bridges.iter().cloned().map(QaEntry::Bridge)); - entries.extend(local.proof_shapes.iter().cloned().map(QaEntry::ProofShape)); - entries.extend(local.atlas_cells.iter().cloned().map(QaEntry::AtlasCell)); - entries.extend( - local - .mechanization_packages - .iter() - .cloned() - .map(QaEntry::MechanizationPackage), - ); - entries.extend( - local - .theorem_specs - .iter() - .cloned() - .map(QaEntry::TheoremSpec), - ); - entries.extend(local.obligations.iter().cloned().map(QaEntry::Obligation)); - entries.extend( - local - .target_profiles - .iter() - .cloned() - .map(QaEntry::TargetProfile), - ); - entries.extend( - local - .route_ledgers - .iter() - .cloned() - .map(QaEntry::RouteLedger), - ); - entries.extend(local.certificates.iter().cloned().map(QaEntry::Certificate)); - entries.extend(local.campaigns.iter().cloned().map(QaEntry::Campaign)); - entries.extend( - local - .campaign_portfolios - .iter() - .cloned() - .map(QaEntry::CampaignPortfolio), - ); - entries.extend(local.route_classes.iter().cloned().map(QaEntry::RouteClass)); - entries.extend( - local - .atlas_deficiencies - .iter() - .cloned() - .map(QaEntry::AtlasDeficiency), - ); - entries.extend( - local - .adequacy_clauses - .iter() - .cloned() - .map(QaEntry::AdequacyClause), - ); - entries.extend(local.burden_packs.iter().cloned().map(QaEntry::BurdenPack)); - entries.extend( - local - .claim_packets - .iter() - .cloned() - .map(QaEntry::ClaimPacket), - ); - entries.extend( - local - .evidence_contracts - .iter() - .cloned() - .map(QaEntry::EvidenceContract), - ); - entries.extend( - local - .benchmark_receipts - .iter() - .cloned() - .map(QaEntry::BenchmarkReceipt), - ); - entries.extend( - local - .challenge_receipts - .iter() - .cloned() - .map(QaEntry::ChallengeReceipt), - ); - entries.extend( - local - .reproducibility_packets - .iter() - .cloned() - .map(QaEntry::ReproducibilityPacket), - ); - entries.extend( - local - .policy_objects - .iter() - .cloned() - .map(QaEntry::PolicyObject), - ); - entries.extend( - local - .policy_bindings - .iter() - .cloned() - .map(QaEntry::PolicyBinding), - ); - entries.extend( - local - .policy_resolutions - .iter() - .cloned() - .map(QaEntry::PolicyResolution), - ); - entries.extend(local.bundle_locks.iter().cloned().map(QaEntry::BundleLock)); - entries.extend( - local - .execution_manifests - .iter() - .cloned() - .map(QaEntry::ExecutionManifest), - ); - entries.extend( - local - .replay_lock_manifests - .iter() - .cloned() - .map(QaEntry::ReplayLockManifest), - ); - entries - .into_iter() - .map(|entry| BundleEntry { - id: entry.id(), - kind: entry.kind_tag().into(), - }) - .collect() -} - -fn remap(value: &str, map: &HashMap) -> String { - map.get(value).cloned().unwrap_or_else(|| value.to_string()) -} - -fn remap_vec(values: &[String], map: &HashMap) -> Vec { - values.iter().map(|value| remap(value, map)).collect() -} - -impl OverlayRegistry { - pub fn local_only(&self) -> LocalRegistry { - LocalRegistry { - bundle_id: self.bundle_id.clone(), - local: self.local.clone(), - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct LocalRegistry { - pub bundle_id: String, - pub local: RegistryBundle, -} - -macro_rules! lookup_local_then_parent { - ($self:expr, $field:ident, $id:expr, $parent_method:ident) => { - $self - .local - .$field - .iter() - .find(|item| item.id == $id) - .cloned() - .or_else(|| $self.parent.$parent_method($id)) - }; -} - -macro_rules! lookup_local_only { - ($self:expr, $field:ident, $id:expr) => { - $self - .local - .$field - .iter() - .find(|item| item.id == $id) - .cloned() - }; -} - -impl RegistryLookup for OverlayRegistry { - fn get_object(&self, id: &str) -> Option { - lookup_local_then_parent!(self, objects, id, get_object) - } - fn get_object_origin(&self, id: &str) -> ArtifactOrigin { - if self.local.objects.iter().any(|item| item.id == id) { - ArtifactOrigin::Overlay - } else { - self.parent.get_object_origin(id) - } - } - fn get_regime(&self, id: &str) -> Option { - lookup_local_then_parent!(self, regimes, id, get_regime) - } - fn get_bridge(&self, id: &str) -> Option { - lookup_local_then_parent!(self, bridges, id, get_bridge) - } - fn get_proof_shape(&self, id: &str) -> Option { - lookup_local_then_parent!(self, proof_shapes, id, get_proof_shape) - } - fn get_atlas_cell(&self, id: &str) -> Option { - lookup_local_then_parent!(self, atlas_cells, id, get_atlas_cell) - } - fn get_mechanization_package(&self, id: &str) -> Option { - lookup_local_then_parent!(self, mechanization_packages, id, get_mechanization_package) - } - fn get_theorem_spec(&self, id: &str) -> Option { - lookup_local_then_parent!(self, theorem_specs, id, get_theorem_spec) - } - fn get_obligation(&self, id: &str) -> Option { - lookup_local_then_parent!(self, obligations, id, get_obligation) - } - fn get_target_profile(&self, id: &str) -> Option { - lookup_local_then_parent!(self, target_profiles, id, get_target_profile) - } - fn get_route_ledger(&self, id: &str) -> Option { - lookup_local_then_parent!(self, route_ledgers, id, get_route_ledger) - } - fn get_certificate(&self, id: &str) -> Option { - lookup_local_then_parent!(self, certificates, id, get_certificate) - } - fn get_campaign(&self, id: &str) -> Option { - lookup_local_then_parent!(self, campaigns, id, get_campaign) - } - fn get_campaign_portfolio(&self, id: &str) -> Option { - lookup_local_then_parent!(self, campaign_portfolios, id, get_campaign_portfolio) - } - fn get_route_class(&self, id: &str) -> Option { - lookup_local_then_parent!(self, route_classes, id, get_route_class) - } - fn get_atlas_deficiency(&self, id: &str) -> Option { - lookup_local_then_parent!(self, atlas_deficiencies, id, get_atlas_deficiency) - } - fn atlas_deficiencies(&self) -> Vec { - let mut items = self.local.atlas_deficiencies.clone(); - items.extend(self.parent.atlas_deficiencies()); - dedupe_by_id(items, |item| item.id.clone()) - } - fn get_adequacy_clause(&self, id: &str) -> Option { - lookup_local_then_parent!(self, adequacy_clauses, id, get_adequacy_clause) - } - fn adequacy_clauses(&self) -> Vec { - let mut items = self.local.adequacy_clauses.clone(); - items.extend(self.parent.adequacy_clauses()); - dedupe_by_id(items, |item| item.id.clone()) - } - fn get_burden_pack(&self, id: &str) -> Option { - lookup_local_then_parent!(self, burden_packs, id, get_burden_pack) - } - fn burden_packs(&self) -> Vec { - let mut items = self.local.burden_packs.clone(); - items.extend(self.parent.burden_packs()); - dedupe_by_id(items, |item| item.id.clone()) - } - fn get_claim_packet(&self, id: &str) -> Option { - lookup_local_then_parent!(self, claim_packets, id, get_claim_packet) - } - fn claim_packets(&self) -> Vec { - let mut items = self.local.claim_packets.clone(); - items.extend(self.parent.claim_packets()); - dedupe_by_id(items, |item| item.id.clone()) - } - fn get_evidence_contract(&self, id: &str) -> Option { - lookup_local_then_parent!(self, evidence_contracts, id, get_evidence_contract) - } - fn evidence_contracts(&self) -> Vec { - let mut items = self.local.evidence_contracts.clone(); - items.extend(self.parent.evidence_contracts()); - dedupe_by_id(items, |item| item.id.clone()) - } - fn get_benchmark_receipt(&self, id: &str) -> Option { - lookup_local_then_parent!(self, benchmark_receipts, id, get_benchmark_receipt) - } - fn benchmark_receipts(&self) -> Vec { - let mut items = self.local.benchmark_receipts.clone(); - items.extend(self.parent.benchmark_receipts()); - dedupe_by_id(items, |item| item.id.clone()) - } - fn get_challenge_receipt(&self, id: &str) -> Option { - lookup_local_then_parent!(self, challenge_receipts, id, get_challenge_receipt) - } - fn challenge_receipts(&self) -> Vec { - let mut items = self.local.challenge_receipts.clone(); - items.extend(self.parent.challenge_receipts()); - dedupe_by_id(items, |item| item.id.clone()) - } - fn get_reproducibility_packet(&self, id: &str) -> Option { - lookup_local_then_parent!( - self, - reproducibility_packets, - id, - get_reproducibility_packet - ) - } - fn reproducibility_packets(&self) -> Vec { - let mut items = self.local.reproducibility_packets.clone(); - items.extend(self.parent.reproducibility_packets()); - dedupe_by_id(items, |item| item.id.clone()) - } - fn get_codebook_pack(&self, id: &str) -> Option { - lookup_local_then_parent!(self, codebook_packs, id, get_codebook_pack) - } - fn get_glyph_pack(&self, id: &str) -> Option { - lookup_local_then_parent!(self, glyph_packs, id, get_glyph_pack) - } - fn get_combo_pack(&self, id: &str) -> Option { - lookup_local_then_parent!(self, combo_packs, id, get_combo_pack) - } - fn get_projection_policy(&self, id: &str) -> Option { - lookup_local_then_parent!(self, projection_policies, id, get_projection_policy) - } - fn get_alias_expansion_policy(&self, id: &str) -> Option { - lookup_local_then_parent!( - self, - alias_expansion_policies, - id, - get_alias_expansion_policy - ) - } - fn get_surface_deficiency(&self, id: &str) -> Option { - lookup_local_then_parent!(self, surface_deficiencies, id, get_surface_deficiency) - } - fn get_policy_object(&self, id: &str) -> Option { - lookup_local_then_parent!(self, policy_objects, id, get_policy_object) - } - fn policy_objects(&self) -> Vec { - let mut items = self.local.policy_objects.clone(); - items.extend(self.parent.policy_objects()); - items - } - fn policy_bindings(&self) -> Vec { - let mut items = self.local.policy_bindings.clone(); - items.extend(self.parent.policy_bindings()); - items - } - fn find_equivalence_class(&self, object_id: &str, regime: &str) -> Option { - self.local - .equivalence_classes - .iter() - .find(|item| { - item.regime == regime && item.members.iter().any(|member| member == object_id) - }) - .cloned() - .or_else(|| self.parent.find_equivalence_class(object_id, regime)) - } - fn atlas_cells(&self) -> Vec { - let mut items = self.local.atlas_cells.clone(); - items.extend(self.parent.atlas_cells()); - items - } -} - -impl RegistryLookup for LocalRegistry { - fn get_object(&self, id: &str) -> Option { - lookup_local_only!(self, objects, id) - } - fn get_object_origin(&self, id: &str) -> ArtifactOrigin { - if self.local.objects.iter().any(|item| item.id == id) { - ArtifactOrigin::Overlay - } else { - ArtifactOrigin::Unknown - } - } - fn get_regime(&self, id: &str) -> Option { - lookup_local_only!(self, regimes, id) - } - fn get_bridge(&self, id: &str) -> Option { - lookup_local_only!(self, bridges, id) - } - fn get_proof_shape(&self, id: &str) -> Option { - lookup_local_only!(self, proof_shapes, id) - } - fn get_atlas_cell(&self, id: &str) -> Option { - lookup_local_only!(self, atlas_cells, id) - } - fn get_mechanization_package(&self, id: &str) -> Option { - lookup_local_only!(self, mechanization_packages, id) - } - fn get_theorem_spec(&self, id: &str) -> Option { - lookup_local_only!(self, theorem_specs, id) - } - fn get_obligation(&self, id: &str) -> Option { - lookup_local_only!(self, obligations, id) - } - fn get_target_profile(&self, id: &str) -> Option { - lookup_local_only!(self, target_profiles, id) - } - fn get_route_ledger(&self, id: &str) -> Option { - lookup_local_only!(self, route_ledgers, id) - } - fn get_certificate(&self, id: &str) -> Option { - lookup_local_only!(self, certificates, id) - } - fn get_campaign(&self, id: &str) -> Option { - lookup_local_only!(self, campaigns, id) - } - fn get_campaign_portfolio(&self, id: &str) -> Option { - lookup_local_only!(self, campaign_portfolios, id) - } - fn get_route_class(&self, id: &str) -> Option { - lookup_local_only!(self, route_classes, id) - } - fn get_atlas_deficiency(&self, id: &str) -> Option { - lookup_local_only!(self, atlas_deficiencies, id) - } - fn atlas_deficiencies(&self) -> Vec { - self.local.atlas_deficiencies.clone() - } - fn get_adequacy_clause(&self, id: &str) -> Option { - lookup_local_only!(self, adequacy_clauses, id) - } - fn adequacy_clauses(&self) -> Vec { - self.local.adequacy_clauses.clone() - } - fn get_burden_pack(&self, id: &str) -> Option { - lookup_local_only!(self, burden_packs, id) - } - fn burden_packs(&self) -> Vec { - self.local.burden_packs.clone() - } - fn get_claim_packet(&self, id: &str) -> Option { - lookup_local_only!(self, claim_packets, id) - } - fn claim_packets(&self) -> Vec { - self.local.claim_packets.clone() - } - fn get_evidence_contract(&self, id: &str) -> Option { - lookup_local_only!(self, evidence_contracts, id) - } - fn evidence_contracts(&self) -> Vec { - self.local.evidence_contracts.clone() - } - fn get_benchmark_receipt(&self, id: &str) -> Option { - lookup_local_only!(self, benchmark_receipts, id) - } - fn benchmark_receipts(&self) -> Vec { - self.local.benchmark_receipts.clone() - } - fn get_challenge_receipt(&self, id: &str) -> Option { - lookup_local_only!(self, challenge_receipts, id) - } - fn challenge_receipts(&self) -> Vec { - self.local.challenge_receipts.clone() - } - fn get_reproducibility_packet(&self, id: &str) -> Option { - lookup_local_only!(self, reproducibility_packets, id) - } - fn reproducibility_packets(&self) -> Vec { - self.local.reproducibility_packets.clone() - } - fn get_codebook_pack(&self, id: &str) -> Option { - lookup_local_only!(self, codebook_packs, id) - } - fn get_glyph_pack(&self, id: &str) -> Option { - lookup_local_only!(self, glyph_packs, id) - } - fn get_combo_pack(&self, id: &str) -> Option { - lookup_local_only!(self, combo_packs, id) - } - fn get_projection_policy(&self, id: &str) -> Option { - lookup_local_only!(self, projection_policies, id) - } - fn get_alias_expansion_policy(&self, id: &str) -> Option { - lookup_local_only!(self, alias_expansion_policies, id) - } - fn get_surface_deficiency(&self, id: &str) -> Option { - lookup_local_only!(self, surface_deficiencies, id) - } - fn get_policy_object(&self, id: &str) -> Option { - lookup_local_only!(self, policy_objects, id) - } - fn policy_objects(&self) -> Vec { - self.local.policy_objects.clone() - } - fn policy_bindings(&self) -> Vec { - self.local.policy_bindings.clone() - } - fn find_equivalence_class(&self, object_id: &str, regime: &str) -> Option { - self.local - .equivalence_classes - .iter() - .find(|item| { - item.regime == regime && item.members.iter().any(|member| member == object_id) - }) - .cloned() - } - fn atlas_cells(&self) -> Vec { - self.local.atlas_cells.clone() - } -} - -trait HasId { - fn id(&self) -> &str; -} - -fn dedupe_by_id(items: Vec, id: impl Fn(&T) -> String) -> Vec { - let mut seen = HashSet::new(); - let mut deduped = Vec::new(); - for item in items { - let item_id = id(&item); - if seen.insert(item_id) { - deduped.push(item); - } - } - deduped -} - -macro_rules! impl_has_id { - ($($t:ty),+ $(,)?) => { - $(impl HasId for $t { - fn id(&self) -> &str { &self.id } - })+ - }; -} - -impl_has_id!( - QcObject, - RegimePack, - BridgeContract, - ProofShape, - AtlasCell, - TheoremSpec, - TargetProfile, - RouteLedger, - Certificate, - Campaign, - AdequacyClause, - BurdenPack, - ClaimPacket, - EvidenceContract, - BenchmarkReceipt, - ChallengeReceipt, - ReproducibilityPacket, - MechanizationPolicyObject, - PolicyBinding, - PolicyResolution, - l64_core::BundleLock, - ExecutionManifest, - ReplayLockManifest -); - -#[cfg(test)] -mod tests { - use super::*; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn test_theorem(id: &str, statement: &str, bridges: &[&str]) -> TheoremSpec { - TheoremSpec { - id: id.into(), - statement: statement.into(), - hosts: vec!["R_SET".into()], - bridges: bridges.iter().map(|bridge| (*bridge).into()).collect(), - operators: vec![], - target_equivalence: "eq".into(), - obligations: vec![], - primary_zone: l64_core::ProofMechanismZone::PmzSemantic, - verdict: l64_core::CertificationVerdict::RouteFound, - proof_shapes: vec![], - } - } - - #[test] - fn overlay_prefers_local_theorem() { - let mut local = RegistryBundle::default(); - local - .theorem_specs - .push(test_theorem("THS_LOCAL", "local", &[])); - let overlay = OverlayRegistry { - parent: SeedRegistry::load().unwrap(), - bundle_id: "BND_TEST".into(), - local, - merge_report: BundleMergeReport { - id: "BMER".into(), - policy: BundleConflictPolicy::Reject, - imported_entries: 1, - namespaced_entries: 0, - conflicts: Vec::new(), - }, - }; - assert!(overlay.get_theorem_spec("THS_LOCAL").is_some()); - assert!(overlay.get_theorem_spec("THS_CHAIN_RULE").is_some()); - } - - #[test] - fn bundle_document_import_does_not_require_surface_parser() { - let theorem = test_theorem("THS_DOC_NATIVE", "native document import", &[]); - let document = QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }; - let world = import_bundle_document( - SeedRegistry::load().unwrap(), - "BND_DOC_NATIVE".into(), - document, - BundleConflictPolicy::Reject, - None, - ) - .expect("native document import"); - assert_eq!(world.manifest.id, "BND_DOC_NATIVE"); - assert_eq!(world.manifest.entries.len(), 1); - assert!(world.overlay.get_theorem_spec("THS_DOC_NATIVE").is_some()); - assert!( - world.substrate_parity.valid, - "{:?}", - world.substrate_parity.failures - ); - assert_eq!(world.substrate_parity.entry_count, 1); - } - - #[test] - fn bundle_document_import_can_cross_explicit_migration_ingress() { - let theorem = test_theorem("THS_DOC_INGRESS", "migration ingress import", &[]); - let document = QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }; - let ingress = BundleMigrationIngress::from_in_memory_document(document); - - assert_eq!(ingress.kind, BundleMigrationIngressKind::InMemoryDocument); - assert!(!ingress.is_native_authority()); - - let world = import_bundle_ingress( - SeedRegistry::load().unwrap(), - "BND_DOC_INGRESS".into(), - ingress, - BundleConflictPolicy::Reject, - None, - ) - .expect("migration ingress import"); - assert_eq!(world.manifest.id, "BND_DOC_INGRESS"); - assert!(world.overlay.get_theorem_spec("THS_DOC_INGRESS").is_some()); - assert!(world.substrate_parity.valid); - } - - #[test] - fn bundle_document_lowers_entries_into_substrate_atoms() { - let theorem = test_theorem("THS_SUBSTRATE", "substrate lowering", &[]); - let document = QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }; - - let records = bundle_document_to_molecular_codec_records(&document, "BND_SUBSTRATE_DNA"); - assert_eq!(records.len(), 1); - let record = &records[0]; - assert_eq!(record.codon_symbol, "A#"); - assert_eq!(record.primitive_kind, SubstratePrimitiveKind::Atom); - assert_eq!(record.subject, "THS_SUBSTRATE"); - match &record.primitive { - SubstratePrimitive::Atom(atom) => { - assert_eq!(atom.id, "THS_SUBSTRATE"); - assert_eq!(atom.codon_symbol, "A#"); - assert!(atom.lexon_symbol.is_none()); - } - other => panic!("expected substrate atom, got {other:?}"), - } - let validation = l64_core::validate_molecular_codec_record(record); - assert!(validation.valid, "{:?}", validation.failures); - } - - #[test] - fn bundle_document_lowers_entries_into_codec_envelopes() { - let theorem = test_theorem("THS_SUBSTRATE_ENVELOPE", "substrate envelope lowering", &[]); - let document = QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }; - - let envelopes = - bundle_document_to_molecular_codec_envelopes(&document, "BND_SUBSTRATE_DNA"); - assert_eq!(envelopes.len(), 1); - let envelope = &envelopes[0]; - assert_eq!(envelope.header.phase, envelope.record.phase); - assert_eq!(envelope.header.subject, envelope.record.subject); - assert_eq!(envelope.header.class_symbol, "A#"); - assert_eq!(envelope.header.role_symbol, "|-"); - - let validation = l64_core::validate_molecular_codec_envelope(envelope); - assert!(validation.valid, "{:?}", validation.failures); - let encoded = - l64_core::encode_molecular_codec_envelope(envelope).expect("bundle envelope encoding"); - let decoded = - l64_core::decode_molecular_codec_envelope(&encoded).expect("bundle envelope decoding"); - assert_eq!(decoded, *envelope); - } - - #[test] - fn bundle_substrate_parity_preserves_dependency_edges_as_bonds() { - let theorem = test_theorem( - "THS_DEP_SUBSTRATE", - "substrate lowering with dependencies", - &["BR_DEP"], - ); - let document = QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }; - - let report = bundle_substrate_parity_report(&document, "BND_SUBSTRATE_DNA"); - assert!(report.valid, "{:?}", report.failures); - assert_eq!(report.entry_count, 1); - assert_eq!(report.dependency_edge_count, 1); - assert_eq!(report.substrate_record_count, 2); - assert_eq!(report.duplex_pair_count, 2); - assert_eq!(report.locally_valid_pair_count, 2); - let closure = report.domain_closure.as_ref().expect("domain closure"); - assert!(closure.promotable, "{closure:?}"); - let merge = report - .deterministic_merge - .as_ref() - .expect("deterministic merge"); - assert_eq!(merge.ordered_coordinates.len(), 2); - assert_eq!(merge.ordered_payload_commitments.len(), 2); - - let records = bundle_document_to_molecular_codec_records(&document, "BND_SUBSTRATE_DNA"); - assert!(records.iter().any(|record| match &record.primitive { - SubstratePrimitive::Bond(bond) => { - bond.left == "THS_DEP_SUBSTRATE" - && bond.right == "BR_DEP" - && bond.relation_codon == "<-" - } - _ => false, - })); - } - - #[test] - fn bundle_substrate_domain_closure_blocks_invalid_parity() { - let document = QaDocument { entries: vec![] }; - let report = bundle_substrate_parity_report(&document, "BND_EMPTY_SUBSTRATE_DNA"); - assert!(report.valid); - assert_eq!(report.duplex_pair_count, 0); - let closure = report.domain_closure.as_ref().expect("domain closure"); - assert!(!closure.promotable); - assert!(closure.locally_valid_pairs.is_empty()); - } - - #[test] - fn bundle_substrate_parity_follows_namespace_rewrites() { - let theorem = test_theorem( - "THS_NAMESPACE_SUBSTRATE", - "substrate lowering with namespace", - &["BR_NAMESPACE"], - ); - let document = namespace_document( - QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }, - "ns.test", - ); - - let report = bundle_substrate_parity_report(&document, "BND_NAMESPACED_DNA"); - assert!(report.valid, "{:?}", report.failures); - assert_eq!(report.entry_count, 1); - assert_eq!(report.dependency_edge_count, 1); - - let records = bundle_document_to_molecular_codec_records(&document, "BND_NAMESPACED_DNA"); - assert!(records.iter().any(|record| match &record.primitive { - SubstratePrimitive::Atom(atom) => atom.id == "ns.test::THS_NAMESPACE_SUBSTRATE", - _ => false, - })); - assert!(records.iter().any(|record| match &record.primitive { - SubstratePrimitive::Bond(bond) => { - bond.left == "ns.test::THS_NAMESPACE_SUBSTRATE" && bond.right == "BR_NAMESPACE" - } - _ => false, - })); - } - - #[test] - fn bundle_substrate_parity_coexists_with_exact_match_conflict_policy() { - let parent = SeedRegistry::load().unwrap(); - let theorem = parent - .get_theorem_spec("THS_CHAIN_RULE") - .expect("seed theorem"); - let document = QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }; - - let parity = bundle_substrate_parity_report(&document, "BND_EXACT_MATCH_DNA"); - assert!(parity.valid, "{:?}", parity.failures); - assert_eq!(parity.entry_count, 1); - - let world = import_bundle_document( - parent, - "BND_EXACT_MATCH".into(), - document, - BundleConflictPolicy::ExactMatch, - None, - ) - .expect("exact match overlap should import"); - assert!(world.overlay.merge_report.conflicts.is_empty()); - assert!(world.overlay.get_theorem_spec("THS_CHAIN_RULE").is_some()); - assert!( - world.substrate_parity.valid, - "{:?}", - world.substrate_parity.failures - ); - } - - #[test] - fn bundle_substrate_parity_keeps_reject_conflict_policy_negative_behavior() { - let parent = SeedRegistry::load().unwrap(); - let theorem = parent - .get_theorem_spec("THS_CHAIN_RULE") - .expect("seed theorem"); - let document = QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }; - - let parity = bundle_substrate_parity_report(&document, "BND_REJECT_CONFLICT_DNA"); - assert!(parity.valid, "{:?}", parity.failures); - - let err = import_bundle_document( - parent, - "BND_REJECT_CONFLICT".into(), - document, - BundleConflictPolicy::Reject, - None, - ) - .expect_err("reject policy should reject seed overlap"); - assert!(err.to_string().contains("conflicts")); - } - - #[test] - fn bundle_dna_file_import_bypasses_surface_parser() { - let theorem = test_theorem("THS_DNA_NATIVE", "dna-native document import", &[]); - let document = QaDocument { - entries: vec![QaEntry::TheoremSpec(theorem)], - }; - let bytes = l64_locus::encode_section_packet( - l64_core::LocusPacketKind::CanonicalTransfer, - l64_core::LocusOpcode::CanonicalPayload, - "BND_DNA_NATIVE", - "bundle_document.v1", - &document, - l64_core::LocusCapabilityMask::default(), - 1, - ) - .expect("bundle dna packet"); - let path = std::env::temp_dir().join(format!( - "l64_bundle_native_{}.dna", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::write(&path, bytes).expect("write bundle packet"); - let world = import_bundle_file(&path, None, BundleConflictPolicy::Reject, None) - .expect("dna bundle import"); - let loaded = - load_bundle_world(&world.manifest.id).expect("load persisted dna bundle world"); - let _ = fs::remove_file(&path); - assert!(world.overlay.get_theorem_spec("THS_DNA_NATIVE").is_some()); - assert!( - world.substrate_parity.valid, - "{:?}", - world.substrate_parity.failures - ); - assert_eq!(loaded.substrate_parity, world.substrate_parity); - } - - #[test] - fn bundle_import_drops_deprecated_surface_schema_records() { - let theorem = test_theorem("THS_SURFACE_SCHEMA_DROP", "drop deprecated records", &[]); - let document = QaDocument { - entries: vec![ - QaEntry::TheoremSpec(theorem), - QaEntry::SurfacePolicy(l64_core::SurfacePolicy { - id: "SP_DROP".into(), - codebook_pack: "CB_DROP".into(), - profile: "drop".into(), - projection_policy: "PP_DROP".into(), - combo_pack: None, - glyph_pack: None, - alias_expansion_policy: "AL_DROP".into(), - allowed_loss_classes: Vec::new(), - }), - QaEntry::CapabilityMatrix(l64_core::CapabilityMatrix { - id: "CAP_DROP".into(), - surface_kind: SurfaceKind::Qc0, - supported_packs: Vec::new(), - import_support: true, - export_support: true, - transcode_support: Vec::new(), - roundtrip_support: false, - known_limits: Vec::new(), - }), - ], - }; - - let world = import_bundle_document( - SeedRegistry::load().unwrap(), - "BND_SURFACE_SCHEMA_DROP".into(), - document, - BundleConflictPolicy::Reject, - None, - ) - .expect("surface-schema entries should be quarantined, not materialized"); - - assert!( - world - .overlay - .get_theorem_spec("THS_SURFACE_SCHEMA_DROP") - .is_some() - ); - assert!(world.overlay.local.surface_policies.is_empty()); - assert!(world.overlay.local.capability_matrices.is_empty()); - assert_eq!(world.manifest.entries.len(), 1); - } - - #[test] - fn bundle_entry_text_requires_l64_header_and_rejects_q_headers() { - let valid = r#"!l64-bundle v1 -theorem {"id":"THS_L64_HEADER","statement":"native bundle header","hosts":["R_SET"],"bridges":[],"operators":[],"target_equivalence":"eq","obligations":[],"primary_zone":"PmzSemantic","verdict":"RouteFound","proof_shapes":[]}"#; - let ingress = - bundle_migration_ingress_from_entry_text(valid).expect("bundle migration ingress"); - assert_eq!(ingress.kind, BundleMigrationIngressKind::BundleEntryText); - assert!(!ingress.is_native_authority()); - let document = bundle_document_from_entry_text(valid).expect("native bundle header"); - assert_eq!(document.entries.len(), 1); - - let missing = r#"theorem {"id":"THS_NO_HEADER","statement":"missing header","hosts":["R_SET"],"bridges":[],"operators":[],"target_equivalence":"eq","obligations":[],"primary_zone":"PmzSemantic","verdict":"RouteFound","proof_shapes":[]}"#; - let err = bundle_document_from_entry_text(missing).unwrap_err(); - assert!(err.to_string().contains("!l64-bundle v1")); - - let empty = "!l64-bundle v1"; - let err = bundle_document_from_entry_text(empty).unwrap_err(); - assert!(err.to_string().contains("at least one entry")); - - let obsolete = r#"!qc0 {"surface_kind":"Qc0","version":"1"} -theorem {"id":"THS_OLD_HEADER","statement":"old header","hosts":["R_SET"],"bridges":[],"operators":[],"target_equivalence":"eq","obligations":[],"primary_zone":"PmzSemantic","verdict":"RouteFound","proof_shapes":[]}"#; - let err = bundle_document_from_entry_text(obsolete).unwrap_err(); - assert!( - err.to_string() - .contains("obsolete projection bundle header") - ); - } - - #[test] - fn bundle_entry_text_rejects_deprecated_surface_schema_entries() { - for (kind, payload) in [ - ( - "surface-policy", - r#"{"id":"SP_OLD","accepted":["Qc0"],"canonical_target":"Dna","default_projection":null}"#, - ), - ( - "transform-receipt", - r#"{"id":"FTR_OLD","src_surface":"Qc0","dst_surface":"Dna","object_ids":[],"transform_kind":"Transcode","policy_id":"SP_OLD","defaults_used":[],"alias_expansions":[],"loss_classes":[],"hash_before":"a","hash_after":"b","verdict":"Lossless","rollback_ref":null,"replay_ref":null}"#, - ), - ( - "roundtrip-report", - r#"{"id":"RTR_OLD","surface_kind":"Qc0","policy_id":"SP_OLD","object_ids":[],"receipt_ids":[],"verdict":"Invalid","fragility_vector":[]}"#, - ), - ( - "capability", - r#"{"id":"CAP_OLD","surface_kind":"Qc0","supported_packs":[],"import_support":true,"export_support":true,"transcode_support":[],"roundtrip_support":false,"known_limits":[]}"#, - ), - ( - "surface-budget", - r#"{"id":"SB_OLD","max_loss_classes":1,"forbid_silent_defaulting":true}"#, - ), - ] { - let text = format!("!l64-bundle v1\n{kind} {payload}"); - let err = bundle_document_from_entry_text(&text).unwrap_err(); - assert!( - err.to_string() - .contains("deprecated surface-schema bundle entry"), - "{kind}: {err}" - ); - } - } - - #[test] - fn bundle_projection_import_is_rejected() { - let dir = std::env::temp_dir().join(format!( - "l64_bundle_projection_reject_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join("bundle.locus.rna"); - fs::write( - &path, - r#"!l64-bundle v1 -theorem {"id":"THS_PROJECTION_ONLY","statement":"projection-only","hosts":["R_SET"],"bridges":[],"operators":[],"target_equivalence":"eq","obligations":[],"primary_zone":"PmzSemantic","verdict":"RouteFound","proof_shapes":[]}"#, - ) - .unwrap(); - - let err = import_bundle_file(&path, None, BundleConflictPolicy::Reject, None).unwrap_err(); - assert!(err.to_string().contains("compile-bundle")); - - let err = import_bundle_file( - &path, - Some(SurfaceKind::Qc0), - BundleConflictPolicy::Reject, - None, - ) - .unwrap_err(); - assert!(err.to_string().contains("projection bundle import")); - } -} diff --git a/l64-canon/.gitignore b/l64-canon/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/l64-canon/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/l64-canon/Cargo.toml b/l64-canon/Cargo.toml deleted file mode 100644 index 7c8951b..0000000 --- a/l64-canon/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "l64-canon" -edition.workspace = true -version.workspace = true -license.workspace = true - -[dependencies] -l64-core = { path = "../l64-core" } -l64-runtime = { path = "../l64-runtime" } -l64-registry = { path = "../l64-registry" } -thiserror = { workspace = true } diff --git a/l64-canon/src/lib.rs b/l64-canon/src/lib.rs deleted file mode 100644 index e22f79c..0000000 --- a/l64-canon/src/lib.rs +++ /dev/null @@ -1,143 +0,0 @@ -use l64_core::{CanonId, EqClassId}; -use l64_registry::SeedRegistry; -use l64_runtime::{RuntimeObjectId, RuntimeWorld}; -use std::collections::HashMap; -use thiserror::Error; - -#[derive(Debug, Error)] -pub enum CanonError { - #[error("unknown runtime object")] - UnknownObject, -} - -#[derive(Debug, Clone)] -pub struct UnionFind { - parent: Vec, - rank: Vec, -} - -impl UnionFind { - pub fn new(size: usize) -> Self { - Self { - parent: (0..size).collect(), - rank: vec![0; size], - } - } - - pub fn find(&mut self, value: usize) -> usize { - if self.parent[value] != value { - let root = self.find(self.parent[value]); - self.parent[value] = root; - } - self.parent[value] - } - - pub fn union(&mut self, left: usize, right: usize) { - let left_root = self.find(left); - let right_root = self.find(right); - if left_root == right_root { - return; - } - if self.rank[left_root] < self.rank[right_root] { - self.parent[left_root] = right_root; - } else if self.rank[left_root] > self.rank[right_root] { - self.parent[right_root] = left_root; - } else { - self.parent[right_root] = left_root; - self.rank[left_root] += 1; - } - } -} - -#[derive(Debug, Clone)] -pub struct CanonEngine { - world: RuntimeWorld, - union_find: UnionFind, - canonical_map: HashMap, - eq_class_map: HashMap, -} - -impl CanonEngine { - pub fn compile(registry: &SeedRegistry) -> Self { - let world = RuntimeWorld::compile_seed(registry); - let mut union_find = UnionFind::new(world.objects.len()); - - for class in ®istry.bundle().equivalence_classes { - if let Some((first, rest)) = class.members.split_first() { - if let Some(first_id) = world.lookup_object(first) { - for member in rest { - if let Some(member_id) = world.lookup_object(member) { - union_find.union(first_id.0 as usize, member_id.0 as usize); - } - } - } - } - } - - let mut canonical_map = HashMap::new(); - let mut eq_class_map = HashMap::new(); - let mut next_canon: u32 = 0; - let mut next_eq: u32 = 0; - for index in 0..world.objects.len() { - let root = union_find.find(index); - canonical_map.entry(root).or_insert_with(|| { - let id: CanonId = next_canon; - next_canon += 1; - id - }); - eq_class_map.entry(root).or_insert_with(|| { - let id = next_eq; - next_eq += 1; - id - }); - } - - Self { - world, - union_find, - canonical_map, - eq_class_map, - } - } - - pub fn equivalent(&mut self, left: RuntimeObjectId, right: RuntimeObjectId) -> bool { - self.union_find.find(left.0 as usize) == self.union_find.find(right.0 as usize) - } - - pub fn canonicalize(&mut self, object: RuntimeObjectId) -> Result { - let root = self.union_find.find(object.0 as usize); - self.canonical_map - .get(&root) - .copied() - .ok_or(CanonError::UnknownObject) - } - - pub fn eq_class(&mut self, object: RuntimeObjectId) -> Result { - let root = self.union_find.find(object.0 as usize); - self.eq_class_map - .get(&root) - .copied() - .ok_or(CanonError::UnknownObject) - } - - pub fn world(&self) -> &RuntimeWorld { - &self.world - } -} -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn seed_equivalence_classes_canonicalize() { - let registry = SeedRegistry::load().unwrap(); - let mut engine = CanonEngine::compile(®istry); - let left = engine.world().lookup_object("OBJ_CTX_SET").unwrap(); - let right = engine.world().lookup_object("OBJ_CTX_SET_CANON").unwrap(); - assert!(engine.equivalent(left, right)); - assert_eq!( - engine.canonicalize(left).unwrap(), - engine.canonicalize(right).unwrap() - ); - } -} diff --git a/l64-cert/.gitignore b/l64-cert/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/l64-cert/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/l64-cert/Cargo.toml b/l64-cert/Cargo.toml deleted file mode 100644 index 96fd888..0000000 --- a/l64-cert/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "l64-cert" -edition.workspace = true -version.workspace = true -license.workspace = true - -[dependencies] -l64-core = { path = "../l64-core" } -l64-locus = { path = "../l64-locus" } -l64-kernel = { path = "../l64-kernel" } -l64-registry = { path = "../l64-registry" } -l64-atlas = { path = "../l64-atlas" } -l64-runtime = { path = "../l64-runtime" } -l64-policy = { path = "../l64-policy" } -serde = { workspace = true } -serde_json = { workspace = true } -bincode = { workspace = true } -thiserror = { workspace = true } - -[dev-dependencies] -l64-bundle = { path = "../l64-bundle" } -serial_test = "3.2" diff --git a/l64-cert/src/lib.rs b/l64-cert/src/lib.rs deleted file mode 100644 index de0282b..0000000 --- a/l64-cert/src/lib.rs +++ /dev/null @@ -1,6657 +0,0 @@ -use l64_atlas::CompiledAtlas; -use l64_core::{ - ArtifactOrigin, AtlasDeficiency, AtlasDeficiencyClass, Budget, CalibrationPressureMap, - CandidateAdequacyClause, CandidateAtlasCell, CandidateCampaign, CandidateCheckerExtension, - CandidatePayoffTask, CandidateSemanticLeaf, Certificate, CertificationCandidate, - CertificationReport, CertificationVerdict, CheckProofShape, CheckerReceipt, CheckerReceiptKind, - CoverageDecision, DeterministicExecutionEnvelope, DistressVector, EvidenceExactness, - EvidencePreference, ExecutionClosureReceipt, Frontier, FrontierLedger, GeneratedStatus, - GenerationReceipt, GeneratorContract, GenomeArtifactClass, GenomeSurface, HelpRequest, - LocusCapabilityMask, LocusDecodeMode, LocusOpcode, LocusPacket, LocusPacketHeader, - LocusPacketKind, LocusSection, Obligation, ObligationCacheShard, ObligationCollisionReport, - ObligationConcurrencyClass, ObligationDagEdge, ObligationDagNode, ObligationEvaluationMode, - ObligationEvidenceReceipt, ObligationGroup, ObligationKind, ObligationLaneRecord, - ObligationMergeReceipt, ObligationNamespaceReceipt, ObligationOrderingReceipt, ObligationPlan, - ObligationStatus, ObligationWriteSet, OptimizerPolicy, OverridePressureReceipt, PolicyVerdict, - PromotionCandidate, ProofCoverageDispatch, ProofCoverageEnvelope, ProposalKind, QaDocument, - QaEntry, RecipeDelta, RecipeRecord, RegistryLookup, ReplayBarrierReceipt, - ReplayDivergenceRecord, ReplayLegalityCheck, ReplayLockManifest, ReplayMergeReceipt, - ReplayStatus, RequiredProofShapeFamily, ResidualVerificationReceipt, ReuseDecisionReceipt, - ReuseLegalityReceipt, RouteLedger, RouteScoreVector, SearchCompartment, - UnsupportedHandlingMode, VerticalCompoundingBundle, cache_hash_v1_str, - decode_locus_packet_with_mode, ensure_cache_subdir, -}; -use l64_kernel::ConstitutionKernel; -use l64_locus::{ - decode_section_payload, decode_summary as decode_locus_summary, load_bundle_lock, - load_execution_manifest, -}; -use l64_policy::resolve_policy_graph; -use l64_runtime::{ - HostExecutionResult, exec_ch_inh_type_witness, exec_ch_norm_type_witness, - exec_chain_rule_jet_compose, exec_chain_rule_reduction, exec_host, -}; -use serde::{Deserialize, Serialize}; -use std::{fs, path::PathBuf, sync::mpsc, thread}; -use thiserror::Error; - -const EVALUATOR_VERSION: &str = "l64-cert-obl-v8"; - -#[derive(Debug, Error)] -pub enum CertError { - #[error("unknown theorem `{0}`")] - UnknownTheorem(String), - #[error("unknown campaign `{0}`")] - UnknownCampaign(String), - #[error("unknown target profile `{0}`")] - UnknownTargetProfile(String), - #[error("replay-only requested but no cached report exists")] - ReplayMiss, - #[error("{0}")] - Message(String), -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CertificationOptions { - pub optimizer_policy: OptimizerPolicy, - pub bundle_hash: String, - pub policy_hash: String, - pub bundle_id: Option, - pub evaluator_policy: Option, - pub cache_policy: Option, - pub no_cache: bool, - pub replay_only: bool, - pub strict_derived: bool, - pub strict_policy: bool, - pub force_parallel_obligations: bool, - pub max_obligation_workers: Option, -} - -impl Default for CertificationOptions { - fn default() -> Self { - Self { - optimizer_policy: OptimizerPolicy::Conservative, - bundle_hash: "seed".into(), - policy_hash: "default".into(), - bundle_id: None, - evaluator_policy: None, - cache_policy: None, - no_cache: false, - replay_only: false, - strict_derived: false, - strict_policy: false, - force_parallel_obligations: false, - max_obligation_workers: None, - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CachedCertificationReport { - pub cache_key: String, - pub theorem_id: String, - pub campaign_id: Option, - pub target_profile_id: String, - pub bundle_hash: String, - pub policy_hash: String, - pub route_winner_hash: String, - pub evaluator_version: String, - pub report: CertificationReport, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct ExecutionCache { - pub reports: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -struct CachedExecutionPacketHeader { - pub cache_key: String, - pub theorem_id: String, - pub campaign_id: Option, - pub target_profile_id: String, - pub bundle_hash: String, - pub policy_hash: String, - pub route_winner_hash: String, - pub evaluator_version: String, - pub report_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct CacheStats { - pub report_count: usize, - pub theorem_ids: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct InvalidationExplanation { - pub report_id: String, - pub valid: bool, - pub reasons: Vec, -} - -pub trait ObligationEvaluator { - fn supports(&self, regime: &str, kind: &ObligationKind) -> bool; - fn evaluate(&self, regime: &str, obligation: &Obligation) -> Option; - fn version(&self) -> &'static str; -} - -#[derive(Debug, Default)] -pub struct SeedObligationEvaluator; - -impl ObligationEvaluator for SeedObligationEvaluator { - fn supports(&self, regime: &str, kind: &ObligationKind) -> bool { - matches!( - (regime, kind), - ( - "R_SET", - ObligationKind::OblEq - | ObligationKind::OblFin - | ObligationKind::OblAdm - | ObligationKind::OblKnt - ) | ( - "R_ALG", - ObligationKind::OblAdm | ObligationKind::OblKnt | ObligationKind::OblEq - ) | ("R_TOP", ObligationKind::OblLoc | ObligationKind::OblGlu) - | ( - "R_CALC", - ObligationKind::OblAdm | ObligationKind::OblTol | ObligationKind::OblRed - ) - | ( - "R_PROB", - ObligationKind::OblTol | ObligationKind::OblObs | ObligationKind::OblAde - ) - | ( - "R_COMP", - ObligationKind::OblRed | ObligationKind::OblObs | ObligationKind::OblTol - ) - | ("R_LOG", ObligationKind::OblAde) - | ("R_TYP", ObligationKind::OblRed | ObligationKind::OblAde) - ) - } - - fn evaluate(&self, regime: &str, obligation: &Obligation) -> Option { - let result = exec_host(regime, None).ok()?; - obligation_from_result(regime, obligation.clone(), result) - } - - fn version(&self) -> &'static str { - EVALUATOR_VERSION - } -} - -#[derive(Debug, Clone)] -struct ObligationExecutionArtifacts { - statuses: Vec, - plan: ObligationPlan, - lanes: Vec, - ordering_receipt: ObligationOrderingReceipt, - merge_receipt: ObligationMergeReceipt, - replay_legality_checks: Vec, - replay_barrier_receipts: Vec, - replay_merge_receipt: ReplayMergeReceipt, - replay_divergence_records: Vec, - cache_shards: Vec, - write_sets: Vec, - collision_reports: Vec, - namespace_receipt: ObligationNamespaceReceipt, - notes: Vec, -} - -pub fn certify_derived_campaign( - registry: &(impl RegistryLookup + Sync), - atlas: &CompiledAtlas, - campaign_id: &str, -) -> Result { - certify_derived_campaign_with_options( - registry, - atlas, - campaign_id, - &CertificationOptions::default(), - ) -} - -pub fn certify_derived_campaign_with_options( - registry: &(impl RegistryLookup + Sync), - atlas: &CompiledAtlas, - campaign_id: &str, - options: &CertificationOptions, -) -> Result { - let campaign = registry - .get_campaign(campaign_id) - .ok_or_else(|| CertError::UnknownCampaign(campaign_id.to_string()))?; - certify_derived_theorem_with_options( - registry, - atlas, - &campaign.theorem, - &campaign.target_profile, - Some(&campaign.id), - options, - ) -} - -pub fn certify_derived_theorem( - registry: &(impl RegistryLookup + Sync), - atlas: &CompiledAtlas, - theorem_id: &str, - target_profile_id: &str, - campaign_id: Option<&str>, -) -> Result { - certify_derived_theorem_with_options( - registry, - atlas, - theorem_id, - target_profile_id, - campaign_id, - &CertificationOptions::default(), - ) -} - -pub fn certify_derived_theorem_with_options( - registry: &(impl RegistryLookup + Sync), - atlas: &CompiledAtlas, - theorem_id: &str, - target_profile_id: &str, - campaign_id: Option<&str>, - options: &CertificationOptions, -) -> Result { - let theorem = registry - .get_theorem_spec(theorem_id) - .ok_or_else(|| CertError::UnknownTheorem(theorem_id.to_string()))?; - let target = registry - .get_target_profile(target_profile_id) - .ok_or_else(|| CertError::UnknownTargetProfile(target_profile_id.to_string()))?; - let mut resolved_policy = resolve_policy_graph( - registry, - options.bundle_id.as_deref(), - Some(&theorem.id), - campaign_id, - Some(target_profile_id), - options.strict_policy, - target - .optimizer_policy - .clone() - .unwrap_or_else(|| options.optimizer_policy.clone()), - ) - .map_err(|err| CertError::Message(err.to_string()))?; - if let Some(policy_id) = &options.evaluator_policy { - let policy = registry - .get_policy_object(policy_id) - .ok_or_else(|| CertError::Message(format!("unknown evaluator policy `{policy_id}`")))?; - let evaluator = policy.evaluator.ok_or_else(|| { - CertError::Message(format!( - "policy `{policy_id}` does not carry evaluator config" - )) - })?; - resolved_policy - .resolution - .applied_policy_ids - .push(policy_id.clone()); - resolved_policy.resolution.evaluator = evaluator; - resolved_policy - .resolution - .trace - .steps - .push(format!("cli-selected evaluator policy {policy_id}")); - } - if let Some(policy_id) = &options.cache_policy { - let policy = registry - .get_policy_object(policy_id) - .ok_or_else(|| CertError::Message(format!("unknown cache policy `{policy_id}`")))?; - let replay_cache = policy.replay_cache.ok_or_else(|| { - CertError::Message(format!( - "policy `{policy_id}` does not carry replay/cache config" - )) - })?; - resolved_policy - .resolution - .applied_policy_ids - .push(policy_id.clone()); - resolved_policy.resolution.replay_cache = replay_cache; - resolved_policy - .resolution - .trace - .steps - .push(format!("cli-selected cache policy {policy_id}")); - } - let optimizer_policy = resolved_policy - .resolution - .optimizer - .optimizer_policy - .clone(); - let effective_policy_hash = - stable_hash(&serde_json::to_string(&resolved_policy.resolution).unwrap_or_default()); - let cache_key = certification_cache_key( - &theorem.id, - target_profile_id, - campaign_id, - &options.bundle_hash, - &effective_policy_hash, - &optimizer_policy, - ); - if !options.no_cache && resolved_policy.resolution.replay_cache.replay_allowed { - if let Some(mut cached) = load_cached_report(&cache_key)? { - if options.replay_only - || cached.cache_key == cache_key - || cache_entry_valid( - &cached, - options, - &effective_policy_hash, - Some(&resolved_policy.resolution), - ) - { - cached.report.execution_envelope = - cached.report.execution_envelope.as_ref().map(|env| { - let mut env = env.clone(); - env.replay_status = if options.replay_only { - ReplayStatus::ReplayOnly - } else { - ReplayStatus::CacheHit - }; - env - }); - return Ok(cached.report); - } - } else if options.replay_only { - return Err(CertError::ReplayMiss); - } - } else if options.replay_only { - return Err(CertError::ReplayMiss); - } - - let kernel = ConstitutionKernel; - kernel - .validate_theorem_spec(&theorem, registry) - .map_err(|err| CertError::Message(err.to_string()))?; - kernel - .validate_target_profile(&target) - .map_err(|err| CertError::Message(err.to_string()))?; - - let route = atlas - .select_policy_driven( - theorem - .hosts - .first() - .ok_or_else(|| CertError::Message("missing theorem source host".into()))?, - theorem - .hosts - .last() - .ok_or_else(|| CertError::Message("missing theorem target host".into()))?, - Some(&target.burden_class), - Some(&l64_core::Budget { - max_loss: target.loss_ceiling, - allow_lossy_supported: target - .allowed_bridge_classes - .contains(&l64_core::ReversibilityClass::LossySupported), - require_proof: true, - }), - Some(&resolved_policy.resolution), - true, - ) - .map_err(|err| CertError::Message(err.to_string()))?; - - let winner = route - .winner - .clone() - .ok_or_else(|| CertError::Message("no winner selected".into()))?; - let edge = atlas - .edge_by_atlas_cell(&winner.id) - .ok_or_else(|| CertError::Message("compiled winner edge missing".into()))?; - let proof_family_ok = proof_family_ok( - &target.required_proof_shape_family, - &edge.proof_shapes, - registry, - ); - let evaluator = SeedObligationEvaluator; - let obligation_artifacts = campaign_id - .and_then(|id| registry.get_campaign(id)) - .map(|campaign| { - let obligations = campaign - .obligations - .into_iter() - .filter_map(|id| registry.get_obligation(&id)) - .collect::>(); - evaluate_obligations( - registry, - &theorem.id, - campaign_id, - &theorem.hosts, - obligations, - &evaluator, - &resolved_policy.resolution, - options, - ) - }) - .transpose()? - .unwrap_or_else(|| ObligationExecutionArtifacts { - statuses: Vec::new(), - plan: ObligationPlan { - id: format!("OPL_{}", stable_hash(&theorem.id)), - theorem_id: theorem.id.clone(), - campaign_id: campaign_id.map(ToString::to_string), - nodes: Vec::new(), - edges: Vec::new(), - groups: Vec::new(), - notes: vec!["no campaign obligations were declared".into()], - }, - lanes: Vec::new(), - ordering_receipt: ObligationOrderingReceipt { - id: format!("OORD_{}", stable_hash(&theorem.id)), - ordered_group_ids: Vec::new(), - notes: vec!["no obligation groups were scheduled".into()], - }, - merge_receipt: ObligationMergeReceipt { - id: format!("OMER_{}", stable_hash(&theorem.id)), - merged_obligation_ids: Vec::new(), - notes: vec!["no obligation merge required".into()], - }, - replay_legality_checks: Vec::new(), - replay_barrier_receipts: Vec::new(), - replay_merge_receipt: ReplayMergeReceipt { - id: format!("RMR_{}", stable_hash(&theorem.id)), - reused_obligation_ids: Vec::new(), - rerun_obligation_ids: Vec::new(), - notes: vec!["no obligation replay merge required".into()], - }, - replay_divergence_records: Vec::new(), - cache_shards: Vec::new(), - write_sets: Vec::new(), - collision_reports: Vec::new(), - namespace_receipt: ObligationNamespaceReceipt { - id: format!("ONR_{}", stable_hash(&theorem.id)), - namespace_id: "default".into(), - shard_ids: Vec::new(), - notes: vec!["no obligation namespace activity".into()], - }, - notes: Vec::new(), - }); - let obligations = obligation_artifacts.statuses.clone(); - - if options.strict_derived - && obligations.iter().any(|item| { - matches!( - item.evaluation_mode, - ObligationEvaluationMode::StoredReceiptUsed | ObligationEvaluationMode::Unsupported - ) - }) - { - return Err(CertError::Message( - "strict-derived rejected stored/unsupported obligations".into(), - )); - } - - let winner_vector = route - .route_explanation - .as_ref() - .and_then(|item| item.winner_score.clone()); - let candidates = vec![CertificationCandidate { - atlas_cell_id: winner.id.clone(), - path: edge.path.clone(), - loss_count: edge.loss_count, - proof_shapes: edge.proof_shapes.clone(), - route_class_id: registry - .get_route_class(&format!("RTC_{}", theorem.id.trim_start_matches("THS_"))) - .map(|item| item.id), - score: winner_vector - .as_ref() - .map(score_vector_to_legacy) - .unwrap_or_else(|| { - vec![ - edge.loss_count, - edge.path.len(), - usize::from(!proof_family_ok), - ] - }), - route_score: winner_vector.clone(), - }]; - - let certificate = - registry.get_certificate(&format!("CRT_{}", theorem.id.trim_start_matches("THS_"))); - let mut verdict = if let Some(certificate) = &certificate { - certificate.verdict.clone() - } else if proof_family_ok { - CertificationVerdict::RouteFound - } else { - CertificationVerdict::Underspecified - }; - if obligations - .iter() - .any(|item| item.verdict == CertificationVerdict::BlockedContradiction) - { - verdict = CertificationVerdict::BlockedContradiction; - } else if obligations - .iter() - .any(|item| item.verdict == CertificationVerdict::BlockedOpen) - { - verdict = CertificationVerdict::BlockedOpen; - } else if obligations - .iter() - .any(|item| item.verdict == CertificationVerdict::Underspecified) - { - verdict = CertificationVerdict::Underspecified; - } else if resolved_policy.resolution.evaluator.unsupported_mode - == UnsupportedHandlingMode::StrictFail - && obligations - .iter() - .any(|item| item.evaluation_mode == ObligationEvaluationMode::Unsupported) - { - verdict = CertificationVerdict::BlockedOpen; - } - let adequacy_records = evaluate_active_adequacy_clauses( - registry, - &theorem.id, - Some(&edge.atlas_cell_id), - &edge.path, - &obligations, - ); - let checker_receipts = collect_checker_receipts( - registry, - &theorem, - &target, - &edge.proof_shapes, - campaign_id, - &obligations, - ); - let deficiencies = collect_campaign_deficiencies( - registry, - &theorem.id, - campaign_id, - Some(&edge.atlas_cell_id), - &obligations, - &adequacy_records, - proof_family_ok, - ); - if deficiency_blocks_campaign(&deficiencies) - && !matches!( - verdict, - CertificationVerdict::BlockedOpen | CertificationVerdict::BlockedContradiction - ) - { - verdict = if deficiencies - .iter() - .any(|item| item.class == l64_core::AtlasDeficiencyClass::DOpenConjectural) - { - CertificationVerdict::Underspecified - } else { - CertificationVerdict::BlockedOpen - }; - } - if proof_family_ok - && deficiencies.is_empty() - && obligations - .iter() - .all(|item| item.verdict == CertificationVerdict::Certified) - && matches!( - verdict, - CertificationVerdict::Benchmarked | CertificationVerdict::RouteFound - ) - { - verdict = CertificationVerdict::Certified; - } - let promotion_artifact_ids = collect_promotion_artifact_ids( - &theorem, - &target, - &obligations, - &adequacy_records, - &deficiencies, - &verdict, - ); - let reused_artifact_ids = collect_reused_artifact_ids(registry, &theorem.id, &obligations); - let default_selected_artifact_ids = - collect_default_selected_artifact_ids(registry, &theorem.id, &obligations); - let payoff_receipt_ids = - collect_payoff_receipt_ids(&theorem.id, &obligations, &default_selected_artifact_ids); - if verdict == CertificationVerdict::Certified && !reused_artifact_ids.is_empty() { - verdict = CertificationVerdict::Integrated; - } - - let route_winner_hash = stable_hash(&format!("{}::{}", winner.id, edge.path.join("->"))); - let mut reasons = vec![format!( - "derived certification from compiled atlas using {:?}", - optimizer_policy - )]; - if let Some(reason) = flagship_selection_reason(&theorem.id, campaign_id) { - reasons.push(reason); - } - let mut report = CertificationReport { - theorem_id: theorem.id.clone(), - campaign_id: campaign_id.map(ToString::to_string), - target_profile_id: target.id.clone(), - verdict, - selected_atlas_cell: Some(winner.id), - selected_path: edge.path.clone(), - route_class_id: registry - .get_route_class(&format!("RTC_{}", theorem.id.trim_start_matches("THS_"))) - .map(|item| item.id), - certificate_id: certificate.map(|item| item.id), - candidates, - obligations, - reasons, - diagnostics: if proof_family_ok { - Vec::new() - } else { - vec!["required proof-shape family not satisfied".into()] - }, - deficiencies, - adequacy_records, - checker_receipts, - burden_pack_ids: collect_related_burden_pack_ids(registry, campaign_id), - claim_packet_ids: collect_related_claim_packet_ids(registry, campaign_id), - evidence_contract_ids: collect_related_evidence_contract_ids(registry, campaign_id), - benchmark_receipt_ids: collect_related_benchmark_receipt_ids(registry, campaign_id), - challenge_receipt_ids: collect_related_challenge_receipt_ids(registry, campaign_id), - reproducibility_packet_ids: collect_related_reproducibility_packet_ids( - registry, - campaign_id, - ), - promotion_artifact_ids, - reused_artifact_ids, - default_selected_artifact_ids, - payoff_receipt_ids, - policy_resolution: Some(resolved_policy.resolution.clone()), - route_explanation: route.route_explanation.clone(), - execution_envelope: None, - reconciliation_summary: Vec::new(), - obligation_plan: Some(obligation_artifacts.plan.clone()), - obligation_lanes: obligation_artifacts.lanes.clone(), - obligation_ordering_receipt: Some(obligation_artifacts.ordering_receipt.clone()), - obligation_merge_receipt: Some(obligation_artifacts.merge_receipt.clone()), - replay_legality_checks: obligation_artifacts.replay_legality_checks.clone(), - replay_barrier_receipts: obligation_artifacts.replay_barrier_receipts.clone(), - replay_merge_receipt: Some(obligation_artifacts.replay_merge_receipt.clone()), - replay_divergence_records: obligation_artifacts.replay_divergence_records.clone(), - obligation_cache_shards: obligation_artifacts.cache_shards.clone(), - reuse_legality_receipts: Vec::new(), - reuse_decision_receipts: Vec::new(), - residual_verification_receipts: Vec::new(), - obligation_write_sets: obligation_artifacts.write_sets.clone(), - obligation_collision_reports: obligation_artifacts.collision_reports.clone(), - obligation_namespace_receipt: Some(obligation_artifacts.namespace_receipt.clone()), - }; - let coverage = derive_proof_coverage_envelope(&report); - report.reuse_legality_receipts = derive_reuse_legality_receipts(&report); - report.reuse_decision_receipts = derive_reuse_decision_receipts(&report, &coverage); - report.residual_verification_receipts = - derive_residual_verification_receipts(&report, &coverage); - let obligation_replay_keys = report - .obligations - .iter() - .map(|item| { - stable_hash(&format!( - "{}::{:?}::{:?}", - item.obligation_id, item.kind, item.evaluation_mode - )) - }) - .collect::>(); - let report_hash = stable_hash(&format!( - "{}|{}|{:?}|{}|{}|{}|{}|{}|{}", - report.theorem_id, - report - .campaign_id - .clone() - .unwrap_or_else(|| "THEOREM".into()), - report.verdict, - report.selected_atlas_cell.clone().unwrap_or_default(), - route_winner_hash, - report - .obligations - .iter() - .map(|item| format!( - "{}:{:?}:{:?}", - item.obligation_id, item.verdict, item.evaluation_mode - )) - .collect::>() - .join("|"), - report - .deficiencies - .iter() - .map(|item| item.id.as_str()) - .collect::>() - .join("|"), - report - .adequacy_records - .iter() - .map(|item| format!("{}:{:?}", item.clause_id, item.verdict)) - .collect::>() - .join("|"), - report - .checker_receipts - .iter() - .map(|item| format!("{}:{:?}", item.subject_id, item.verdict)) - .collect::>() - .join("|") - )); - report.execution_envelope = Some(DeterministicExecutionEnvelope { - bundle_hash: options.bundle_hash.clone(), - bundle_id: options.bundle_id.clone(), - policy_hash: effective_policy_hash.clone(), - policy_resolution_id: Some(resolved_policy.resolution.id.clone()), - manifest_id: None, - lock_id: None, - route_winner_hash: route_winner_hash.clone(), - obligation_replay_keys, - report_hash: report_hash.clone(), - replay_status: ReplayStatus::Fresh, - executed_plan_id: None, - reconciliation_id: None, - }); - report.diagnostics.extend(obligation_artifacts.notes); - if let Some(eq_status) = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CHAIN_EQ") - { - if !eq_status.receipts.is_empty() { - report.diagnostics.push(format!( - "chain-rule equivalence receipts: {}", - eq_status - .receipts - .iter() - .map(|item| receipt_leaf_counts(item).0 + receipt_leaf_counts(item).1) - .sum::() - )); - } - if eq_status.evaluation_mode == ObligationEvaluationMode::RecomputedExact - && eq_status.verdict == CertificationVerdict::Certified - { - report.diagnostics.push( - "chain-rule equivalence fully discharged through executable jet transport".into(), - ); - report - .reasons - .push("runtime discharged the Chain Rule equivalence witness strongly enough to lift the seeded benchmark certificate".into()); - } - } - if let Some(red_status) = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CHAIN_RED") - { - if !red_status.receipts.is_empty() { - report.diagnostics.push(format!( - "chain-rule reduction receipts: {}", - red_status - .receipts - .iter() - .map(|item| receipt_leaf_counts(item).0 + receipt_leaf_counts(item).1) - .sum::() - )); - } - if red_status.evaluation_mode == ObligationEvaluationMode::RecomputedExact - && red_status.verdict == CertificationVerdict::Certified - { - report - .reasons - .push("runtime discharged the Chain Rule reduction witness exactly on the active finite route-local model".into()); - } - } - if !report.promotion_artifact_ids.is_empty() { - report.diagnostics.push(format!( - "promotion artifacts realized: {}", - report.promotion_artifact_ids.join(",") - )); - } - if !report.reused_artifact_ids.is_empty() { - report.diagnostics.push(format!( - "reused integrated artifacts: {}", - report.reused_artifact_ids.join(",") - )); - report - .reasons - .push("reused promoted Chain₁ operator to reduce future certification work on the active derivative-composition burden".into()); - } - if !report.default_selected_artifact_ids.is_empty() { - report.diagnostics.push(format!( - "default-selected integrated artifacts: {}", - report.default_selected_artifact_ids.join(",") - )); - report - .reasons - .push("selector/certifier default-selected the canonical Chain₁ operator for the active derivative-composition burden".into()); - } - if !report.payoff_receipt_ids.is_empty() { - report.diagnostics.push(format!( - "operator payoff receipts: {}", - report.payoff_receipt_ids.join(",") - )); - report - .reasons - .push(payoff_reason(&theorem.id, &report.payoff_receipt_ids)); - } - if !report.checker_receipts.is_empty() { - report.diagnostics.push(format!( - "checker receipts: {}", - report.checker_receipts.len() - )); - } - if !report.adequacy_records.is_empty() { - report.diagnostics.push(format!( - "active adequacy clauses: {}", - report.adequacy_records.len() - )); - if report - .adequacy_records - .iter() - .all(|item| item.verdict == CertificationVerdict::Certified) - { - report.reasons.push(adequacy_cluster_reason(&theorem.id)); - } - } - - if !options.no_cache && resolved_policy.resolution.replay_cache.replay_allowed { - persist_cached_report(CachedCertificationReport { - cache_key, - theorem_id: theorem.id.clone(), - campaign_id: campaign_id.map(ToString::to_string), - target_profile_id: target.id, - bundle_hash: options.bundle_hash.clone(), - policy_hash: effective_policy_hash, - route_winner_hash, - evaluator_version: evaluator.version().into(), - report: report.clone(), - })?; - } - - Ok(report) -} - -pub fn replay_report(report_id: &str) -> Result { - let cache = load_execution_cache().map_err(|err| CertError::Message(err.to_string()))?; - cache - .reports - .into_iter() - .find(|item| report_storage_id(&item.report) == report_id) - .map(|item| item.report) - .ok_or(CertError::ReplayMiss) -} - -pub fn cache_stats() -> Result { - let cache = load_execution_cache().map_err(|err| CertError::Message(err.to_string()))?; - Ok(CacheStats { - report_count: cache.reports.len(), - theorem_ids: cache - .reports - .into_iter() - .map(|item| item.theorem_id) - .collect(), - }) -} - -pub fn clear_cache(scope: Option<&str>) -> Result<(), CertError> { - let path = execution_cache_path().map_err(|err| CertError::Message(err.to_string()))?; - match scope { - Some("all") | None | Some("reports") | Some("obligations") => { - if path.exists() { - fs::remove_dir_all(&path).map_err(|err| CertError::Message(err.to_string()))?; - } - } - Some(_) => {} - } - Ok(()) -} - -pub fn explain_invalidation( - report_id: &str, - bundle_hash: &str, - policy_hash: &str, -) -> Result { - let cache = load_execution_cache().map_err(|err| CertError::Message(err.to_string()))?; - let Some(cached) = cache - .reports - .into_iter() - .find(|item| report_storage_id(&item.report) == report_id) - else { - return Ok(InvalidationExplanation { - report_id: report_id.into(), - valid: false, - reasons: vec!["report not found in execution cache".into()], - }); - }; - let mut reasons = Vec::new(); - if cached.bundle_hash != bundle_hash { - reasons.push("bundle hash changed".into()); - } - if cached.policy_hash != policy_hash { - let exact_required = cached - .report - .policy_resolution - .as_ref() - .map(|item| item.replay_cache.exact_policy_match_required) - .unwrap_or(true); - if exact_required { - reasons.push("policy hash changed and replay policy requires exact match".into()); - } else { - reasons.push("policy hash changed but replay policy may permit reuse".into()); - } - } - if cached.evaluator_version != EVALUATOR_VERSION { - reasons.push("evaluator version changed".into()); - } - Ok(InvalidationExplanation { - report_id: report_id.into(), - valid: reasons.is_empty(), - reasons, - }) -} - -fn proof_family_ok( - family: &RequiredProofShapeFamily, - proof_shapes: &[String], - registry: &(impl RegistryLookup + Sync), -) -> bool { - match family { - RequiredProofShapeFamily::Minimal | RequiredProofShapeFamily::MixedBattery => { - !proof_shapes.is_empty() - } - RequiredProofShapeFamily::Triangle => proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Triangle) - .unwrap_or(false) - }), - RequiredProofShapeFamily::Square => proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Square) - .unwrap_or(false) - }), - RequiredProofShapeFamily::Diamond => proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Diamond) - .unwrap_or(false) - }), - RequiredProofShapeFamily::Pentagon => proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Pentagon) - .unwrap_or(false) - }), - RequiredProofShapeFamily::Hexagon => proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Hexagon) - .unwrap_or(false) - }), - } -} - -fn flagship_selection_reason(theorem_id: &str, campaign_id: Option<&str>) -> Option { - match (theorem_id, campaign_id) { - ("THS_CHAIN_RULE", Some("CPG_CHAIN_RULE")) => Some( - "flagship adequacy-first campaign selected: Chain Rule maximizes bridge reuse on the seeded R_TOP→R_CALC atlas while keeping proof-shape novelty low".into(), - ), - ("THS_BAYES_BRACE", Some("CPG_BAYES_BRACE")) => Some( - "next flagship selected: BayesBrace reuses the active adequacy/control machinery on the seeded R_TOP→R_PROB atlas with the lowest host-law novelty beyond the Chain Rule cluster".into(), - ), - ("THS_CH_NORM", Some("CPG_CH_NORM")) => Some( - "next flagship selected: CH_Norm is the lowest-friction logic/type campaign because the seeded R_TYP→R_SET atlas and current runtime already support its first normalization witnesses".into(), - ), - ("THS_EXEC_INFER", Some("CPG_EXEC_INFER")) => Some( - "cheap seeded closure selected: ExecInfer is the lowest-friction A_PROB→COMP campaign because the existing probability and computation kernels already discharge its executable realization obligations".into(), - ), - ("THS_PROB_JUDG", Some("CPG_PROB_JUDG")) => Some( - "cheap seeded closure selected: ProbJudg reuses the active probability adequacy layer on the seeded A_PROB→LOG atlas without introducing new host-law machinery".into(), - ), - ("THS_CERT_PROP", Some("CPG_CERT_PROP")) => Some( - "cheap seeded closure selected: CertProp is the lowest-friction A_COMP→LOG campaign because the computation kernel already exposes the certified property witnesses its route requires".into(), - ), - ("THS_CH_INH", Some("CPG_CH_INH")) => Some( - "cheap seeded closure selected: CH-Inh is the next bounded type/algebra campaign because the seeded A_TYPE→ALG atlas already exists even though its exact inhabitance semantics are still colder".into(), - ), - _ => None, - } -} - -fn collect_campaign_deficiencies( - registry: &(impl RegistryLookup + Sync), - theorem_id: &str, - campaign_id: Option<&str>, - atlas_cell_id: Option<&str>, - obligations: &[ObligationStatus], - adequacy_records: &[l64_core::AdequacyRecord], - proof_family_ok: bool, -) -> Vec { - let chain_rule_eq_closed = theorem_id == "THS_CHAIN_RULE" - && obligations.iter().any(|item| { - item.obligation_id == "OBL_CHAIN_EQ" - && item.evaluation_mode == ObligationEvaluationMode::RecomputedExact - && item.verdict == CertificationVerdict::Certified - }); - let mut deficiencies = registry - .atlas_deficiencies() - .into_iter() - .filter(|item| item.theorem.as_deref() == Some(theorem_id)) - .filter(|item| atlas_cell_id.is_none() || item.atlas_cell.as_deref() == atlas_cell_id) - .filter(|item| !(chain_rule_eq_closed && item.id == "DGN_CHAIN_RULE_ADEQUACY")) - .collect::>(); - - if !proof_family_ok { - deficiencies.push(l64_core::AtlasDeficiency { - id: format!("DGN_{}_PROOF_FAMILY", theorem_id), - class: l64_core::AtlasDeficiencyClass::DNoCommutingProof, - atlas_cell: atlas_cell_id.map(ToString::to_string), - theorem: Some(theorem_id.to_string()), - message: "required proof-shape family not satisfied".into(), - blocking_scope: l64_core::blocking_scope(true), - control_effects: l64_core::blocking_control_effects(true), - suggested_seam: Some( - "proof-shape family closure is still required for this campaign".into(), - ), - }); - } - - for obligation in obligations { - let receipt_residual = obligation.receipts.iter().any(receipt_has_residual); - if !receipt_residual - && (matches!( - obligation.evaluation_mode, - ObligationEvaluationMode::Unsupported - | ObligationEvaluationMode::StoredReceiptUsed - | ObligationEvaluationMode::RecomputedPartial - ) || matches!( - obligation.verdict, - CertificationVerdict::BlockedOpen - | CertificationVerdict::BlockedContradiction - | CertificationVerdict::Underspecified - )) - { - deficiencies.push(l64_core::obligation_status_deficiency( - theorem_id, - atlas_cell_id, - format!( - "DGN_OBL_{}_{}_{}", - theorem_id, - campaign_id.unwrap_or("THEOREM"), - obligation.obligation_id - ), - obligation, - true, - Some(format!( - "obligation {} remains constitutionally open on the active campaign", - obligation.obligation_id - )), - )); - } - for receipt in &obligation.receipts { - collect_receipt_deficiencies( - &mut deficiencies, - theorem_id, - atlas_cell_id, - &obligation.obligation_id, - receipt, - ); - } - } - - for record in adequacy_records { - if record.verdict != CertificationVerdict::Certified { - deficiencies.push(adequacy_record_deficiency( - theorem_id, - atlas_cell_id, - record, - )); - } - } - - deficiencies.sort_by(|left, right| left.id.cmp(&right.id)); - deficiencies.dedup_by(|left, right| left.id == right.id); - deficiencies -} - -fn evaluate_active_adequacy_clauses( - registry: &(impl RegistryLookup + Sync), - theorem_id: &str, - atlas_cell_id: Option<&str>, - selected_path: &[String], - obligations: &[ObligationStatus], -) -> Vec { - let theorem_scoped_clauses = registry - .adequacy_clauses() - .into_iter() - .filter(|item| { - item.theorem_ids.is_empty() || item.theorem_ids.iter().any(|id| id == theorem_id) - }) - .collect::>(); - if theorem_scoped_clauses.is_empty() - || (!supports_active_adequacy(theorem_id) - && theorem_scoped_clauses.iter().all(|clause| { - !matches!( - clause.kind, - l64_core::AdequacyClauseKind::ProjectionInterpretation - | l64_core::AdequacyClauseKind::ContainmentInterpretation - | l64_core::AdequacyClauseKind::ClosureInterpretation - | l64_core::AdequacyClauseKind::RunningLawInterpretation - | l64_core::AdequacyClauseKind::EvidenceContractInterpretation - | l64_core::AdequacyClauseKind::BenchmarkInterpretation - | l64_core::AdequacyClauseKind::StressInterpretation - | l64_core::AdequacyClauseKind::ChallengeInterpretation - ) - })) - { - return Vec::new(); - } - let top = exec_host("R_TOP", None).ok(); - let calc = exec_host("R_CALC", None).ok(); - let prob = exec_host("R_PROB", None).ok(); - let _set = exec_host("R_SET", None).ok(); - let typ = exec_host("R_TYP", None).ok(); - let comp = exec_host("R_COMP", None).ok(); - let log = exec_host("R_LOG", None).ok(); - let alg = exec_host("R_ALG", None).ok(); - let ledger_id = format!("TRL_{}", theorem_id.trim_start_matches("THS_")); - let ledger = registry.get_route_ledger(&ledger_id); - - let mut records = theorem_scoped_clauses - .into_iter() - .map(|clause| { - let (verdict, computed, detail, receipt_ids) = match clause.id.as_str() { - "ADQ_CHAIN_CALC_OBJECT" => { - let (ok, detail) = match &calc { - Some(HostExecutionResult::Calculus { - local_linear_witness, - finite_difference_derivative, - .. - }) => ( - *local_linear_witness && *finite_difference_derivative, - format!( - "local_linear={} finite_difference={}", - local_linear_witness, finite_difference_derivative - ), - ), - _ => (false, "missing R_CALC executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CHAIN_CALC_OBJECT_WIT".into()], - ) - } - "ADQ_CHAIN_TOP_THREAD" => { - let (ok, detail) = match &top { - Some(HostExecutionResult::Topology { - continuity_holds, - overlap_compatible, - .. - }) => ( - *continuity_holds && *overlap_compatible, - format!( - "continuity={} overlap={}", - continuity_holds, overlap_compatible - ), - ), - _ => (false, "missing R_TOP executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CHAIN_TOP_THREAD_WIT".into()], - ) - } - "ADQ_CHAIN_CALC_EQ" => { - adequacy_from_obligation(obligations, "OBL_CHAIN_EQ", "ADQ_CHAIN_EQ_RECEIPT") - } - "ADQ_CHAIN_CALC_TOLL" => { - adequacy_from_obligation(obligations, "OBL_CHAIN_RED", "ADQ_CHAIN_RED_RECEIPT") - } - "ADQ_CHAIN_TOP_KNOT" => { - let (ok, detail) = match &top { - Some(HostExecutionResult::Topology { - cover_legal, - overlap_compatible, - .. - }) => ( - *cover_legal && *overlap_compatible, - format!("cover={} overlap={}", cover_legal, overlap_compatible), - ), - _ => (false, "missing R_TOP knot witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CHAIN_TOP_KNOT_WIT".into()], - ) - } - "ADQ_CHAIN_TOP_CALC_BRIDGE" => { - let has_ref = ledger - .as_ref() - .map(|item| item.receipts.iter().any(|receipt| receipt == "Ref_1")) - .unwrap_or(false); - let selected_direct = selected_path == ["B_TOP_TO_CALC".to_string()]; - let on_cell = atlas_cell_id == Some("A_TOP_TO_CALC"); - ( - if has_ref && selected_direct && on_cell { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!( - "atlas_cell={:?} selected_path={} receipt_ref1={}", - atlas_cell_id, - selected_path.join("->"), - has_ref - ), - vec!["ADQ_CHAIN_BRIDGE_SOUND_WIT".into()], - ) - } - "ADQ_BAYES_PROB_OBJECT" => { - let (ok, detail) = match &prob { - Some(HostExecutionResult::Probability { - normalized, - pushforward_ok, - conditioning_legal, - .. - }) => ( - *normalized && *pushforward_ok && *conditioning_legal, - format!( - "normalized={} pushforward={} conditioning={}", - normalized, pushforward_ok, conditioning_legal - ), - ), - _ => (false, "missing R_PROB executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_BAYES_PROB_OBJECT_WIT".into()], - ) - } - "ADQ_BAYES_TOP_THREAD" => { - let (ok, detail) = match &top { - Some(HostExecutionResult::Topology { - continuity_holds, - overlap_compatible, - .. - }) => ( - *continuity_holds && *overlap_compatible, - format!( - "continuity={} overlap={}", - continuity_holds, overlap_compatible - ), - ), - _ => (false, "missing R_TOP executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_BAYES_TOP_THREAD_WIT".into()], - ) - } - "ADQ_BAYES_PROB_EQ" => { - adequacy_from_obligation(obligations, "OBL_BAYES_ADE", "ADQ_BAYES_ADE_RECEIPT") - } - "ADQ_BAYES_PROB_TOLL" => { - adequacy_from_obligation(obligations, "OBL_BAYES_TOL", "ADQ_BAYES_TOL_RECEIPT") - } - "ADQ_BAYES_TOP_KNOT" => { - let (ok, detail) = match &top { - Some(HostExecutionResult::Topology { - cover_legal, - overlap_compatible, - .. - }) => ( - *cover_legal && *overlap_compatible, - format!("cover={} overlap={}", cover_legal, overlap_compatible), - ), - _ => (false, "missing R_TOP knot witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_BAYES_TOP_KNOT_WIT".into()], - ) - } - "ADQ_BAYES_TOP_PROB_BRIDGE" => { - let has_measprob = ledger - .as_ref() - .map(|item| item.receipts.iter().any(|receipt| receipt == "MeasProb_mu")) - .unwrap_or(false); - let selected_direct = selected_path == ["B_TOP_TO_PROB".to_string()]; - let on_cell = atlas_cell_id == Some("A_TOP_TO_PROB"); - ( - if has_measprob && selected_direct && on_cell { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!( - "atlas_cell={:?} selected_path={} receipt_measprob={}", - atlas_cell_id, - selected_path.join("->"), - has_measprob - ), - vec!["ADQ_BAYES_BRIDGE_SOUND_WIT".into()], - ) - } - "ADQ_CH_TYP_OBJECT" => { - let (ok, detail) = match &typ { - Some(HostExecutionResult::TypeTheory { - witness_inhabited, .. - }) => ( - *witness_inhabited, - format!("witness_inhabited={witness_inhabited}"), - ), - _ => (false, "missing R_TYP executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CH_TYP_OBJECT_WIT".into()], - ) - } - "ADQ_CH_TYP_THREAD" => { - let (ok, detail) = match &typ { - Some(HostExecutionResult::TypeTheory { - witness_inhabited, - normalization_correspondence, - }) => ( - *witness_inhabited && *normalization_correspondence, - format!( - "witness_inhabited={} normalization_correspondence={}", - witness_inhabited, normalization_correspondence - ), - ), - _ => (false, "missing R_TYP executable thread witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CH_TYP_THREAD_WIT".into()], - ) - } - "ADQ_CH_SET_EQ" => { - adequacy_from_obligation(obligations, "OBL_CH_EQ", "ADQ_CH_EQ_RECEIPT") - } - "ADQ_CH_TYP_TOLL" => { - adequacy_from_obligation(obligations, "OBL_CH_RED", "ADQ_CH_RED_RECEIPT") - } - "ADQ_CH_TYP_KNOT" => { - let (ok, detail) = match &typ { - Some(HostExecutionResult::TypeTheory { - witness_inhabited, - normalization_correspondence, - }) => ( - *witness_inhabited && *normalization_correspondence, - format!( - "witness_inhabited={} normalization_correspondence={}", - witness_inhabited, normalization_correspondence - ), - ), - _ => (false, "missing R_TYP executable knot witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CH_TYP_KNOT_WIT".into()], - ) - } - "ADQ_CH_TYP_SET_BRIDGE" => { - let has_rig = ledger - .as_ref() - .map(|item| item.receipts.iter().any(|receipt| receipt == "Rig")) - .unwrap_or(false); - let selected_direct = selected_path == ["B_TYPE_TO_SET".to_string()]; - let on_cell = atlas_cell_id == Some("A_TYPE_TO_SET"); - ( - if has_rig && selected_direct && on_cell { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!( - "atlas_cell={:?} selected_path={} receipt_rig={}", - atlas_cell_id, - selected_path.join("->"), - has_rig - ), - vec!["ADQ_CH_TYP_SET_BRIDGE_WIT".into()], - ) - } - "ADQ_EXEC_PROB_OBJECT" => { - let (ok, detail) = match &prob { - Some(HostExecutionResult::Probability { - normalized, - pushforward_ok, - conditioning_legal, - .. - }) => ( - *normalized && *pushforward_ok && *conditioning_legal, - format!( - "normalized={} pushforward={} conditioning={}", - normalized, pushforward_ok, conditioning_legal - ), - ), - _ => (false, "missing R_PROB executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_EXEC_PROB_OBJECT_WIT".into()], - ) - } - "ADQ_EXEC_PROB_THREAD" => adequacy_from_obligation( - obligations, - "OBL_EXEC_TOL", - "ADQ_EXEC_PROB_THREAD_WIT", - ), - "ADQ_EXEC_COMP_EQ" => adequacy_from_obligation( - obligations, - "OBL_EXEC_ADE", - "ADQ_EXEC_COMP_EQ_RECEIPT", - ), - "ADQ_EXEC_COMP_TOLL" => adequacy_from_obligation( - obligations, - "OBL_EXEC_TOL", - "ADQ_EXEC_COMP_TOLL_RECEIPT", - ), - "ADQ_EXEC_COMP_KNOT" => { - let (ok, detail) = match &comp { - Some(HostExecutionResult::Computation { - reached_normal_form, - replayable_trace, - .. - }) => ( - *reached_normal_form && *replayable_trace, - format!( - "normal_form={} replayable_trace={}", - reached_normal_form, replayable_trace - ), - ), - _ => (false, "missing R_COMP executable knot witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_EXEC_COMP_KNOT_WIT".into()], - ) - } - "ADQ_EXEC_PROB_COMP_BRIDGE" => { - let has_exec = ledger - .as_ref() - .map(|item| item.receipts.iter().any(|receipt| receipt == "Exec")) - .unwrap_or(false); - let selected_direct = selected_path == ["B_PROB_TO_COMP".to_string()]; - let on_cell = atlas_cell_id == Some("A_PROB_TO_COMP"); - ( - if has_exec && selected_direct && on_cell { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!( - "atlas_cell={:?} selected_path={} receipt_exec={}", - atlas_cell_id, - selected_path.join("->"), - has_exec - ), - vec!["ADQ_EXEC_PROB_COMP_BRIDGE_WIT".into()], - ) - } - "ADQ_JDG_PROB_OBJECT" => { - let (ok, detail) = match &prob { - Some(HostExecutionResult::Probability { normalized, .. }) => { - (*normalized, format!("normalized={normalized}")) - } - _ => (false, "missing R_PROB executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_JDG_PROB_OBJECT_WIT".into()], - ) - } - "ADQ_JDG_PROB_THREAD" => { - adequacy_from_obligation(obligations, "OBL_JDG_TOL", "ADQ_JDG_PROB_THREAD_WIT") - } - "ADQ_JDG_LOG_EQ" => { - let (ok, detail) = match &log { - Some(HostExecutionResult::Logic { - proposition_well_formed, - witness_available, - }) => ( - *proposition_well_formed && *witness_available, - format!( - "logic proposition={} witness={}", - proposition_well_formed, witness_available - ), - ), - _ => (false, "missing R_LOG executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_JDG_LOG_EQ_RECEIPT".into()], - ) - } - "ADQ_JDG_PROB_TOLL" => adequacy_from_obligation( - obligations, - "OBL_JDG_TOL", - "ADQ_JDG_PROB_TOLL_RECEIPT", - ), - "ADQ_JDG_PROB_KNOT" => { - let (ok, detail) = match &prob { - Some(HostExecutionResult::Probability { - normalized, - conditioning_legal, - pushforward_ok, - .. - }) => ( - *normalized && *conditioning_legal && *pushforward_ok, - format!( - "normalized={} conditioning={} pushforward={}", - normalized, conditioning_legal, pushforward_ok - ), - ), - _ => (false, "missing R_PROB executable knot witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_JDG_PROB_KNOT_WIT".into()], - ) - } - "ADQ_JDG_PROB_LOG_BRIDGE" => { - let has_probjudg = ledger - .as_ref() - .map(|item| { - item.receipts - .iter() - .any(|receipt| receipt == "ProbJudg_phi") - }) - .unwrap_or(false); - let selected_direct = selected_path == ["B_PROB_TO_LOG".to_string()]; - let on_cell = atlas_cell_id == Some("A_PROB_TO_LOG"); - ( - if has_probjudg && selected_direct && on_cell { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!( - "atlas_cell={:?} selected_path={} receipt_probjudg={}", - atlas_cell_id, - selected_path.join("->"), - has_probjudg - ), - vec!["ADQ_JDG_PROB_LOG_BRIDGE_WIT".into()], - ) - } - "ADQ_CERT_COMP_OBJECT" => { - let (ok, detail) = match &comp { - Some(HostExecutionResult::Computation { - reached_normal_form, - observationally_equivalent, - .. - }) => ( - *reached_normal_form && *observationally_equivalent, - format!( - "normal_form={} observationally_equivalent={}", - reached_normal_form, observationally_equivalent - ), - ), - _ => (false, "missing R_COMP executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CERT_COMP_OBJECT_WIT".into()], - ) - } - "ADQ_CERT_COMP_THREAD" => { - let (ok, detail) = match &comp { - Some(HostExecutionResult::Computation { - replayable_trace, .. - }) => ( - *replayable_trace, - format!("replayable_trace={replayable_trace}"), - ), - _ => (false, "missing R_COMP replay witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CERT_COMP_THREAD_WIT".into()], - ) - } - "ADQ_CERT_LOG_EQ" => { - let (ok, detail) = match &log { - Some(HostExecutionResult::Logic { - proposition_well_formed, - witness_available, - }) => ( - *proposition_well_formed && *witness_available, - format!( - "logic proposition={} witness={}", - proposition_well_formed, witness_available - ), - ), - _ => (false, "missing R_LOG executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CERT_LOG_EQ_RECEIPT".into()], - ) - } - "ADQ_CERT_COMP_TOLL" => adequacy_from_obligation( - obligations, - "OBL_CERT_TOL", - "ADQ_CERT_COMP_TOLL_RECEIPT", - ), - "ADQ_CERT_COMP_KNOT" => { - adequacy_from_obligation(obligations, "OBL_CERT_RED", "ADQ_CERT_COMP_KNOT_WIT") - } - "ADQ_CERT_COMP_LOG_BRIDGE" => { - let has_cert = ledger - .as_ref() - .map(|item| item.receipts.iter().any(|receipt| receipt == "Cert_phi")) - .unwrap_or(false); - let selected_direct = selected_path == ["B_COMP_TO_LOG".to_string()]; - let on_cell = atlas_cell_id == Some("A_COMP_TO_LOG"); - ( - if has_cert && selected_direct && on_cell { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!( - "atlas_cell={:?} selected_path={} receipt_cert={}", - atlas_cell_id, - selected_path.join("->"), - has_cert - ), - vec!["ADQ_CERT_COMP_LOG_BRIDGE_WIT".into()], - ) - } - "ADQ_CHI_TYP_OBJECT" => { - let (ok, detail) = match &typ { - Some(HostExecutionResult::TypeTheory { - witness_inhabited, .. - }) => ( - *witness_inhabited, - format!("witness_inhabited={witness_inhabited}"), - ), - _ => (false, "missing R_TYP executable witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CHI_TYP_OBJECT_WIT".into()], - ) - } - "ADQ_CHI_TYP_THREAD" => { - let (ok, detail) = match &typ { - Some(HostExecutionResult::TypeTheory { - witness_inhabited, - normalization_correspondence, - }) => ( - *witness_inhabited && *normalization_correspondence, - format!( - "witness_inhabited={} normalization_correspondence={}", - witness_inhabited, normalization_correspondence - ), - ), - _ => (false, "missing R_TYP executable thread witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CHI_TYP_THREAD_WIT".into()], - ) - } - "ADQ_CHI_ALG_EQ" => { - adequacy_from_obligation(obligations, "OBL_CHI_EQ", "ADQ_CHI_ALG_EQ_RECEIPT") - } - "ADQ_CHI_TYP_TOLL" => { - adequacy_from_obligation(obligations, "OBL_CHI_ADE", "ADQ_CHI_TYP_TOLL_RECEIPT") - } - "ADQ_CHI_TYP_KNOT" => { - let (ok, detail) = match &typ { - Some(HostExecutionResult::TypeTheory { - witness_inhabited, - normalization_correspondence, - }) => ( - *witness_inhabited && *normalization_correspondence, - format!( - "witness_inhabited={} normalization_correspondence={}", - witness_inhabited, normalization_correspondence - ), - ), - _ => (false, "missing R_TYP executable knot witness".into()), - }; - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - detail, - vec!["ADQ_CHI_TYP_KNOT_WIT".into()], - ) - } - "ADQ_CHI_TYP_ALG_BRIDGE" => { - let has_lift = ledger - .as_ref() - .map(|item| { - item.receipts - .iter() - .any(|receipt| receipt == "Lift^Typ->Alg") - }) - .unwrap_or(false); - let selected_direct = selected_path == ["B_TYPE_TO_ALG".to_string()]; - let on_cell = atlas_cell_id == Some("A_TYPE_TO_ALG"); - let alg_ok = matches!( - &alg, - Some(HostExecutionResult::Algebra { - closure_holds: true, - associative: true, - .. - }) - ); - ( - if has_lift && selected_direct && on_cell && alg_ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!( - "atlas_cell={:?} selected_path={} receipt_lift={} algebra_ready={}", - atlas_cell_id, - selected_path.join("->"), - has_lift, - alg_ok - ), - vec!["ADQ_CHI_TYP_ALG_BRIDGE_WIT".into()], - ) - } - _ => generic_adequacy_evaluation(registry, &clause), - }; - l64_core::AdequacyRecord { - id: format!("ADR_{}_{}", theorem_id, clause.id), - clause_id: clause.id, - kind: clause.kind, - verdict, - computed, - blocking: clause.blocking, - detail, - receipt_ids, - } - }) - .collect::>(); - records.sort_by(|left, right| left.id.cmp(&right.id)); - records -} - -fn adequacy_from_obligation( - obligations: &[ObligationStatus], - obligation_id: &str, - receipt_id: &str, -) -> (CertificationVerdict, bool, String, Vec) { - if let Some(item) = obligations - .iter() - .find(|item| item.obligation_id == obligation_id) - { - ( - item.verdict.clone(), - item.evaluation_mode != ObligationEvaluationMode::Unsupported, - item.detail.clone(), - vec![receipt_id.into()], - ) - } else { - ( - CertificationVerdict::Underspecified, - false, - format!("missing obligation {obligation_id}"), - vec![receipt_id.into()], - ) - } -} - -fn generic_adequacy_evaluation( - registry: &(impl RegistryLookup + Sync), - clause: &l64_core::AdequacyClause, -) -> (CertificationVerdict, bool, String, Vec) { - generic_adequacy_evaluator(&clause.kind)(registry, clause) -} - -type GenericAdequacyEvaluator = fn( - &(dyn RegistryLookup + Sync), - &l64_core::AdequacyClause, -) -> (CertificationVerdict, bool, String, Vec); - -fn generic_adequacy_evaluator(kind: &l64_core::AdequacyClauseKind) -> GenericAdequacyEvaluator { - match kind { - l64_core::AdequacyClauseKind::EvidenceContractInterpretation => { - eval_evidence_contract_adequacy - } - l64_core::AdequacyClauseKind::BenchmarkInterpretation => eval_benchmark_adequacy, - l64_core::AdequacyClauseKind::StressInterpretation => eval_stress_adequacy, - l64_core::AdequacyClauseKind::ChallengeInterpretation => eval_challenge_adequacy, - l64_core::AdequacyClauseKind::ProjectionInterpretation - | l64_core::AdequacyClauseKind::ContainmentInterpretation - | l64_core::AdequacyClauseKind::ClosureInterpretation - | l64_core::AdequacyClauseKind::RunningLawInterpretation => eval_missing_host_pack_adequacy, - _ => eval_underspecified_adequacy, - } -} - -fn eval_evidence_contract_adequacy( - registry: &(dyn RegistryLookup + Sync), - clause: &l64_core::AdequacyClause, -) -> (CertificationVerdict, bool, String, Vec) { - let contracts = clause - .evidence_contract_ids - .iter() - .filter_map(|id| registry.get_evidence_contract(id)) - .collect::>(); - if contracts.len() != clause.evidence_contract_ids.len() || contracts.is_empty() { - return ( - CertificationVerdict::BlockedOpen, - true, - "required evidence contracts missing".into(), - clause.evidence_contract_ids.clone(), - ); - } - ( - CertificationVerdict::Certified, - true, - format!("evidence_contracts={}", contracts.len()), - clause.evidence_contract_ids.clone(), - ) -} - -fn eval_benchmark_adequacy( - registry: &(dyn RegistryLookup + Sync), - clause: &l64_core::AdequacyClause, -) -> (CertificationVerdict, bool, String, Vec) { - let receipts = clause - .benchmark_receipt_ids - .iter() - .filter_map(|id| registry.get_benchmark_receipt(id)) - .collect::>(); - let ok = receipts.len() == clause.benchmark_receipt_ids.len() - && !receipts.is_empty() - && receipts - .iter() - .all(|item| item.verdict == CertificationVerdict::Certified); - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!("benchmark_receipts={} all_certified={}", receipts.len(), ok), - clause.benchmark_receipt_ids.clone(), - ) -} - -fn eval_stress_adequacy( - registry: &(dyn RegistryLookup + Sync), - clause: &l64_core::AdequacyClause, -) -> (CertificationVerdict, bool, String, Vec) { - let receipts = clause - .benchmark_receipt_ids - .iter() - .filter_map(|id| registry.get_benchmark_receipt(id)) - .filter(|item| item.role == l64_core::BenchmarkRole::Stress) - .collect::>(); - let ok = !receipts.is_empty() - && receipts - .iter() - .all(|item| item.verdict == CertificationVerdict::Certified); - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!("stress_receipts={} all_certified={}", receipts.len(), ok), - receipts.into_iter().map(|item| item.id).collect(), - ) -} - -fn eval_challenge_adequacy( - registry: &(dyn RegistryLookup + Sync), - clause: &l64_core::AdequacyClause, -) -> (CertificationVerdict, bool, String, Vec) { - let receipts = clause - .challenge_receipt_ids - .iter() - .filter_map(|id| registry.get_challenge_receipt(id)) - .collect::>(); - let ok = !receipts.is_empty() - && receipts - .iter() - .all(|item| item.status != l64_core::ChallengeStatus::Open); - ( - if ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - true, - format!("challenge_receipts={} all_closed={}", receipts.len(), ok), - clause.challenge_receipt_ids.clone(), - ) -} - -fn eval_missing_host_pack_adequacy( - _registry: &(dyn RegistryLookup + Sync), - clause: &l64_core::AdequacyClause, -) -> (CertificationVerdict, bool, String, Vec) { - ( - CertificationVerdict::BlockedOpen, - true, - "host semantic pack not yet implemented for this burden".into(), - clause.burden_pack_ids.clone(), - ) -} - -fn eval_underspecified_adequacy( - _registry: &(dyn RegistryLookup + Sync), - _clause: &l64_core::AdequacyClause, -) -> (CertificationVerdict, bool, String, Vec) { - ( - CertificationVerdict::Underspecified, - false, - "no executable adequacy evaluator registered for this clause".into(), - Vec::new(), - ) -} - -fn adequacy_record_deficiency( - theorem_id: &str, - atlas_cell_id: Option<&str>, - record: &l64_core::AdequacyRecord, -) -> l64_core::AtlasDeficiency { - l64_core::adequacy_record_deficiency( - theorem_id, - atlas_cell_id, - format!("DGN_ADQ_{}_{}", theorem_id, record.clause_id), - record, - ) -} - -fn campaign_related_burden_packs( - registry: &(impl RegistryLookup + Sync), - campaign_id: Option<&str>, -) -> Vec { - let Some(campaign_id) = campaign_id else { - return Vec::new(); - }; - let Some(campaign) = registry.get_campaign(campaign_id) else { - return Vec::new(); - }; - registry - .burden_packs() - .into_iter() - .filter(|pack| { - pack.obligation_ids - .iter() - .any(|id| campaign.obligations.iter().any(|candidate| candidate == id)) - }) - .collect() -} - -fn collect_related_burden_pack_ids( - registry: &(impl RegistryLookup + Sync), - campaign_id: Option<&str>, -) -> Vec { - campaign_related_burden_packs(registry, campaign_id) - .into_iter() - .map(|item| item.id) - .collect() -} - -fn collect_related_evidence_contract_ids( - registry: &(impl RegistryLookup + Sync), - campaign_id: Option<&str>, -) -> Vec { - campaign_related_burden_packs(registry, campaign_id) - .into_iter() - .flat_map(|item| item.evidence_contract_ids) - .collect::>() - .into_iter() - .collect() -} - -fn collect_related_claim_packet_ids( - registry: &(impl RegistryLookup + Sync), - campaign_id: Option<&str>, -) -> Vec { - let contract_ids = collect_related_evidence_contract_ids(registry, campaign_id); - let expected_kinds = registry - .evidence_contracts() - .into_iter() - .filter(|contract| contract_ids.iter().any(|id| id == &contract.id)) - .flat_map(|contract| contract.required_evidence_kinds) - .collect::>(); - registry - .claim_packets() - .into_iter() - .filter(|packet| { - expected_kinds.is_empty() || expected_kinds.contains(&packet.target_sector) - }) - .map(|packet| packet.id) - .collect() -} - -fn collect_related_benchmark_receipt_ids( - registry: &(impl RegistryLookup + Sync), - campaign_id: Option<&str>, -) -> Vec { - let claim_ids = collect_related_claim_packet_ids(registry, campaign_id); - registry - .benchmark_receipts() - .into_iter() - .filter(|item| claim_ids.iter().any(|id| id == &item.claim_packet_id)) - .map(|item| item.id) - .collect() -} - -fn collect_related_challenge_receipt_ids( - registry: &(impl RegistryLookup + Sync), - campaign_id: Option<&str>, -) -> Vec { - let claim_ids = collect_related_claim_packet_ids(registry, campaign_id); - registry - .challenge_receipts() - .into_iter() - .filter(|item| claim_ids.iter().any(|id| id == &item.claim_packet_id)) - .map(|item| item.id) - .collect() -} - -fn collect_related_reproducibility_packet_ids( - registry: &(impl RegistryLookup + Sync), - campaign_id: Option<&str>, -) -> Vec { - let claim_ids = collect_related_claim_packet_ids(registry, campaign_id); - registry - .reproducibility_packets() - .into_iter() - .filter(|item| claim_ids.iter().any(|id| id == &item.claim_packet_id)) - .map(|item| item.id) - .collect() -} - -fn deficiency_blocks_campaign(deficiencies: &[l64_core::AtlasDeficiency]) -> bool { - deficiencies.iter().any(|item| { - item.control_effects - .iter() - .any(|effect| effect == &l64_core::DeficiencyControlEffect::BlockCampaign) - }) -} - -fn deficiency_blocks_promotion(deficiencies: &[l64_core::AtlasDeficiency]) -> bool { - deficiencies.iter().any(|item| { - item.control_effects - .iter() - .any(|effect| effect == &l64_core::DeficiencyControlEffect::BlockPromotion) - }) -} - -fn collect_receipt_deficiencies( - deficiencies: &mut Vec, - theorem_id: &str, - atlas_cell_id: Option<&str>, - obligation_id: &str, - receipt: &ObligationEvidenceReceipt, -) { - if receipt.subreceipts.is_empty() { - if receipt.verdict != CertificationVerdict::Certified { - deficiencies.push(l64_core::receipt_deficiency( - theorem_id, - atlas_cell_id, - format!("DGN_EQR_{}_{}", obligation_id, receipt.id), - receipt, - l64_core::AtlasDeficiencyClass::DNoAdequacy, - l64_core::AtlasDeficiencyClass::DOpenConjectural, - format!( - "receipt {} remains open and still blocks semantic discharge", - receipt.id - ), - )); - } - return; - } - - for subreceipt in &receipt.subreceipts { - collect_receipt_deficiencies( - deficiencies, - theorem_id, - atlas_cell_id, - obligation_id, - subreceipt, - ); - } -} - -fn receipt_has_computed_failure(receipt: &ObligationEvidenceReceipt) -> bool { - if receipt.subreceipts.is_empty() { - return receipt.computed - && matches!( - receipt.verdict, - CertificationVerdict::BlockedContradiction | CertificationVerdict::BlockedOpen - ); - } - receipt.subreceipts.iter().any(receipt_has_computed_failure) -} - -fn receipt_has_residual(receipt: &ObligationEvidenceReceipt) -> bool { - if receipt.subreceipts.is_empty() { - return !receipt.computed || receipt.verdict != CertificationVerdict::Certified; - } - receipt.subreceipts.iter().any(receipt_has_residual) -} - -fn receipt_leaf_counts(receipt: &ObligationEvidenceReceipt) -> (usize, usize) { - if receipt.subreceipts.is_empty() { - let success = - usize::from(receipt.computed && receipt.verdict == CertificationVerdict::Certified); - let residual = usize::from(receipt.verdict != CertificationVerdict::Certified); - return (success, residual); - } - receipt - .subreceipts - .iter() - .map(receipt_leaf_counts) - .fold((0usize, 0usize), |(sa, ra), (sb, rb)| (sa + sb, ra + rb)) -} - -fn evaluate_flagship_equivalence_obligation( - registry: &(impl RegistryLookup + Sync), - theorem_id: &str, - obligation: &Obligation, -) -> Option { - if theorem_id == "THS_CH_INH" && obligation.id == "OBL_CHI_EQ" { - let witness = exec_ch_inh_type_witness().ok()?; - let mut subreceipts = vec![ - ObligationEvidenceReceipt { - id: "CHI_EQ_QUOTIENT_TRANSPORT".into(), - label: "quotient transport agreement".into(), - verdict: if witness.quotient_transport_exact { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "direct_carrier={:?} lifted_carrier={:?}", - witness.direct_carrier, witness.lifted_carrier - ), - subreceipts: Vec::new(), - }, - ObligationEvidenceReceipt { - id: "CHI_EQ_HOMOMORPHISM_PRESERVE".into(), - label: "homomorphism preservation".into(), - verdict: if witness.homomorphism_preserved_exact { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: "lifted algebra operations preserve the inherited carrier witness".into(), - subreceipts: Vec::new(), - }, - ]; - if witness.proof_relevance_preserved { - subreceipts.push(ObligationEvidenceReceipt { - id: "CHI_EQ_PROOF_TERM_TRANSPORT".into(), - label: "proof-term transport".into(), - verdict: CertificationVerdict::Certified, - computed: true, - detail: format!( - "direct_proofs={:?} lifted_proofs={:?}", - witness.direct_proof_terms, witness.lifted_proof_terms - ), - subreceipts: Vec::new(), - }); - subreceipts.push(ObligationEvidenceReceipt { - id: "CHI_EQ_PROOF_TERM_NORMAL_FORM".into(), - label: "proof-term normal-form agreement".into(), - verdict: CertificationVerdict::Certified, - computed: true, - detail: "proof-relevant carrier witnesses normalize to the same inherited representative".into(), - subreceipts: Vec::new(), - }); - } else { - subreceipts.push(ObligationEvidenceReceipt { - id: "CHI_EQ_PROOF_RELEVANCE_BOUNDARY".into(), - label: "proof-relevant equality boundary".into(), - verdict: CertificationVerdict::Underspecified, - computed: false, - detail: witness.residual_boundary.clone().unwrap_or_else(|| { - "proof-relevant algebra equality boundary remains open".into() - }), - subreceipts: Vec::new(), - }); - } - let computed_failure = subreceipts.iter().any(receipt_has_computed_failure); - let residual_scaffold = subreceipts.iter().any(receipt_has_residual); - let (computed_successes, residuals) = subreceipts - .iter() - .map(receipt_leaf_counts) - .fold((0usize, 0usize), |(sa, ra), (sb, rb)| (sa + sb, ra + rb)); - return Some(ObligationStatus { - obligation_id: obligation.id.clone(), - kind: obligation.kind.clone(), - verdict: if computed_failure || residual_scaffold { - CertificationVerdict::BlockedOpen - } else { - CertificationVerdict::Certified - }, - evaluation_mode: if residual_scaffold { - ObligationEvaluationMode::RecomputedPartial - } else { - ObligationEvaluationMode::RecomputedExact - }, - detail: format!( - "CH-Inh algebra equality factored into {} computed receipts with {} residual blocker(s)", - computed_successes, residuals - ), - receipts: vec![ObligationEvidenceReceipt { - id: "CHI_EQ_INHERITANCE".into(), - label: "proof-relevant inherited algebra equality".into(), - verdict: if residual_scaffold { - CertificationVerdict::BlockedOpen - } else { - CertificationVerdict::Certified - }, - computed: !residual_scaffold, - detail: "algebra equality decomposed into quotient transport, homomorphism preservation, and proof-relevance witness structure".into(), - subreceipts, - }], - }); - } - if !is_chain_rule_family(theorem_id) || obligation.id != "OBL_CHAIN_EQ" { - return None; - } - if let Some(operator) = chain_rule_promoted_operator(registry) { - let (apply_id, apply_label, reuse_id, reuse_label, detail) = match operator.origin { - ArtifactOrigin::Seed => ( - "EQR_CHAIN_OPERATOR_DEFAULT_APPLICABILITY", - "default promoted operator applicability", - "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION", - "default promoted operator selection", - format!( - "default-selected canonical Chain₁ operator `{}` for first-order equivalence discharge", - operator.id - ), - ), - ArtifactOrigin::Overlay | ArtifactOrigin::Unknown => ( - "EQR_CHAIN_OPERATOR_APPLICABILITY", - "promoted operator applicability", - "EQR_CHAIN_OPERATOR_REUSE", - "promoted operator reuse", - format!( - "reused promoted Chain₁ operator witness `{}` for first-order equivalence discharge", - operator.id - ), - ), - }; - return Some(ObligationStatus { - obligation_id: obligation.id.clone(), - kind: obligation.kind.clone(), - verdict: CertificationVerdict::Certified, - evaluation_mode: ObligationEvaluationMode::RecomputedExact, - detail, - receipts: vec![ - ObligationEvidenceReceipt { - id: apply_id.into(), - label: apply_label.into(), - verdict: CertificationVerdict::Certified, - computed: true, - detail: format!( - "promoted operator `{}` matches first-order derivative composition burden", - operator.id - ), - subreceipts: Vec::new(), - }, - ObligationEvidenceReceipt { - id: reuse_id.into(), - label: reuse_label.into(), - verdict: CertificationVerdict::Certified, - computed: true, - detail: match operator.origin { - ArtifactOrigin::Seed => { - "default-selected integrated Chain₁ witness instead of expanding the full composed-jet stack" - .into() - } - ArtifactOrigin::Overlay | ArtifactOrigin::Unknown => { - "reused integrated Chain₁ witness instead of expanding the full composed-jet stack".into() - } - }, - subreceipts: Vec::new(), - }, - ], - }); - } - let top = exec_host("R_TOP", None).ok()?; - let calc = exec_host("R_CALC", None).ok()?; - let ledger = registry.get_route_ledger("TRL_CHAIN_RULE"); - - let mut receipts = Vec::new(); - if let HostExecutionResult::Topology { - cover_legal, - continuity_holds, - overlap_compatible, - .. - } = top - { - receipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_LOC_TRANSPORT".into(), - label: "brace-local transport".into(), - verdict: if cover_legal && continuity_holds && overlap_compatible { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - computed: true, - detail: format!( - "cover={} continuity={} overlap={}", - cover_legal, continuity_holds, overlap_compatible - ), - subreceipts: Vec::new(), - }); - } - if let HostExecutionResult::Calculus { - local_linear_witness, - finite_difference_derivative, - symbolic_only, - .. - } = calc - { - receipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_DERIV_REP".into(), - label: "first-order derivative representative".into(), - verdict: if local_linear_witness && finite_difference_derivative { - CertificationVerdict::Certified - } else if symbolic_only { - CertificationVerdict::Underspecified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "local_linear={} finite_difference={} symbolic_only={}", - local_linear_witness, finite_difference_derivative, symbolic_only - ), - subreceipts: Vec::new(), - }); - } - if let Some(ledger) = ledger { - let has_can = ledger.receipts.iter().any(|item| item == "Can"); - let has_red = ledger.receipts.iter().any(|item| item == "Red"); - let route_is_direct = ledger.normalized_path == vec!["B_TOP_TO_CALC".to_string()]; - receipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_ROUTE_BINDING".into(), - label: "bridge-route equivalence transport".into(), - verdict: if has_can && has_red && route_is_direct { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "route={} canonical_receipt={} reduction_receipt={}", - ledger.normalized_path.join("->"), - has_can, - has_red - ), - subreceipts: Vec::new(), - }); - } - if let Ok(jet) = exec_chain_rule_jet_compose() { - let mut subreceipts = Vec::new(); - subreceipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_JET_LINEAR_AGREE".into(), - label: "composed local linear form agreement".into(), - verdict: if jet.local_linear_form_agrees { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "direct={:?} composed={:?}", - jet.direct.entries, jet.composed.entries - ), - subreceipts: Vec::new(), - }); - subreceipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_JET_NORMAL_FORM".into(), - label: "route-normalized representative agreement".into(), - verdict: if jet.normalized_representative_agrees { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "normalized_direct={:?} normalized_composed={:?}", - jet.direct.entries, jet.composed.entries - ), - subreceipts: Vec::new(), - }); - subreceipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_JET_REDUCTION_PRESERVE".into(), - label: "reduction-preservation agreement".into(), - verdict: if jet.reduction_preserves_form { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: "finite-difference representative agrees with composed local linear form" - .into(), - subreceipts: Vec::new(), - }); - subreceipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_JET_CHART_OVERLAP".into(), - label: "chart-overlap compatibility".into(), - verdict: if jet.chart_overlap_compatible { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "transition_direct={:?} transition_composed={:?}", - jet.direct_in_transition.entries, jet.composed_in_transition.entries - ), - subreceipts: Vec::new(), - }); - subreceipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_JET_TRANSITION_TRANSPORT".into(), - label: "transition transport agreement".into(), - verdict: if jet.transition_transport_agrees { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "transition_direct={:?} transition_composed={:?}", - jet.direct_in_transition.entries, jet.composed_in_transition.entries - ), - subreceipts: Vec::new(), - }); - subreceipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_JET_GAUGE_NORMALIZE".into(), - label: "gauge-normalized representative agreement".into(), - verdict: if jet.gauge_normalized_representative_agrees { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "normalized_transition_direct={:?} normalized_transition_composed={:?}", - jet.direct_in_transition.entries, jet.composed_in_transition.entries - ), - subreceipts: Vec::new(), - }); - if let Some(boundary) = jet.residual_boundary { - subreceipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_JET_GAUGE_BOUNDARY".into(), - label: "chart-global gauge boundary".into(), - verdict: CertificationVerdict::Underspecified, - computed: false, - detail: boundary, - subreceipts: Vec::new(), - }); - } - let jet_computed_failure = subreceipts.iter().any(receipt_has_computed_failure); - let jet_residual = subreceipts.iter().any(receipt_has_residual); - let jet_successes = subreceipts - .iter() - .filter(|item| item.computed && item.verdict == CertificationVerdict::Certified) - .count(); - receipts.push(ObligationEvidenceReceipt { - id: "EQR_CHAIN_JET_COMPOSE".into(), - label: "composite first-order jet equality".into(), - verdict: if jet_computed_failure { - CertificationVerdict::BlockedOpen - } else if jet_residual { - CertificationVerdict::Benchmarked - } else { - CertificationVerdict::Certified - }, - computed: true, - detail: format!( - "computed {} composed-jet subreceipts; residual_boundary={}", - jet_successes, jet_residual - ), - subreceipts, - }); - } - - let computed_failure = receipts.iter().any(receipt_has_computed_failure); - let residual_scaffold = receipts.iter().any(receipt_has_residual); - let verdict = if computed_failure { - CertificationVerdict::BlockedOpen - } else if residual_scaffold { - CertificationVerdict::Benchmarked - } else { - CertificationVerdict::Certified - }; - let (computed_successes, residuals) = receipts - .iter() - .map(receipt_leaf_counts) - .fold((0usize, 0usize), |(sa, ra), (sb, rb)| (sa + sb, ra + rb)); - - Some(ObligationStatus { - obligation_id: obligation.id.clone(), - kind: obligation.kind.clone(), - verdict, - evaluation_mode: if residual_scaffold { - ObligationEvaluationMode::RecomputedPartial - } else { - ObligationEvaluationMode::RecomputedExact - }, - detail: format!( - "chain-rule equivalence factored into {} computed receipts with {} residual blocker(s)", - computed_successes, residuals - ), - receipts, - }) -} - -fn evaluate_flagship_reduction_obligation( - registry: &(impl RegistryLookup + Sync), - theorem_id: &str, - obligation: &Obligation, -) -> Option { - if theorem_id == "THS_CH_NORM" && obligation.id == "OBL_CH_RED" { - let witness = exec_ch_norm_type_witness().ok()?; - let receipts = vec![ - ObligationEvidenceReceipt { - id: "CHN_RED_BETA_ETA_NORMALIZE".into(), - label: "beta-eta normalization".into(), - verdict: if witness.beta_eta_normalization_exact { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "direct_normal_form={:?} collapsed_normal_form={:?}", - witness.direct_normal_form, witness.collapsed_normal_form - ), - subreceipts: Vec::new(), - }, - ObligationEvidenceReceipt { - id: "CHN_RED_EXTENSIONAL_NORMAL_FORM".into(), - label: "extensional carrier normal-form agreement".into(), - verdict: if witness.extensional_normal_form_agrees { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: "collapsed carrier and direct witness normalize to the same representative" - .into(), - subreceipts: Vec::new(), - }, - ]; - let residual_scaffold = receipts.iter().any(receipt_has_residual); - return Some(ObligationStatus { - obligation_id: obligation.id.clone(), - kind: obligation.kind.clone(), - verdict: if residual_scaffold { - CertificationVerdict::BlockedOpen - } else { - CertificationVerdict::Certified - }, - evaluation_mode: if residual_scaffold { - ObligationEvaluationMode::RecomputedPartial - } else { - ObligationEvaluationMode::RecomputedExact - }, - detail: "CH-Norm reduction witness discharged through exact route-local normalization checks".into(), - receipts, - }); - } - if !is_chain_rule_family(theorem_id) || obligation.id != "OBL_CHAIN_RED" { - return None; - } - if let Some(operator) = chain_rule_promoted_operator(registry) { - let (apply_id, apply_label, reuse_id, reuse_label, detail) = match operator.origin { - ArtifactOrigin::Seed => ( - "RED_CHAIN_OPERATOR_DEFAULT_APPLICABILITY", - "default promoted operator applicability", - "RED_CHAIN_OPERATOR_DEFAULT_SELECTION", - "default promoted operator selection", - format!( - "default-selected canonical Chain₁ operator `{}` for reduction exactness", - operator.id - ), - ), - ArtifactOrigin::Overlay | ArtifactOrigin::Unknown => ( - "RED_CHAIN_OPERATOR_APPLICABILITY", - "promoted operator applicability", - "RED_CHAIN_OPERATOR_REUSE", - "promoted operator reuse", - format!( - "reused promoted Chain₁ operator witness `{}` for reduction exactness", - operator.id - ), - ), - }; - return Some(ObligationStatus { - obligation_id: obligation.id.clone(), - kind: obligation.kind.clone(), - verdict: CertificationVerdict::Certified, - evaluation_mode: ObligationEvaluationMode::RecomputedExact, - detail, - receipts: vec![ - ObligationEvidenceReceipt { - id: apply_id.into(), - label: apply_label.into(), - verdict: CertificationVerdict::Certified, - computed: true, - detail: format!( - "promoted operator `{}` is valid on the active R_TOP→R_CALC route", - operator.id - ), - subreceipts: Vec::new(), - }, - ObligationEvidenceReceipt { - id: reuse_id.into(), - label: reuse_label.into(), - verdict: CertificationVerdict::Certified, - computed: true, - detail: match operator.origin { - ArtifactOrigin::Seed => { - "default-selected integrated Chain₁ witness instead of recomputing the full remainder-reduction micro-kernel" - .into() - } - ArtifactOrigin::Overlay | ArtifactOrigin::Unknown => { - "reused integrated Chain₁ witness instead of recomputing the full remainder-reduction micro-kernel" - .into() - } - }, - subreceipts: Vec::new(), - }, - ], - }); - } - let reduction = exec_chain_rule_reduction().ok()?; - let mut receipts = Vec::new(); - receipts.push(ObligationEvidenceReceipt { - id: "RED_CHAIN_FINITE_DIFF_AGREE".into(), - label: "finite-difference agreement".into(), - verdict: if reduction.finite_difference_agrees { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "direct_difference={:?} composed_difference={:?}", - reduction.direct_difference, reduction.composed_difference - ), - subreceipts: Vec::new(), - }); - receipts.push(ObligationEvidenceReceipt { - id: "RED_CHAIN_NORMAL_FORM".into(), - label: "reduction normal-form preservation".into(), - verdict: if reduction.reduction_normal_form_preserved { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!( - "remainder_normal_form={:?}", - reduction.remainder_normal_form - ), - subreceipts: Vec::new(), - }); - receipts.push(ObligationEvidenceReceipt { - id: "RED_CHAIN_REMAINDER_TRANSPORT".into(), - label: "remainder transport compatibility".into(), - verdict: if reduction.remainder_transport_compatible { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: - "route-local remainder witness remains stable under the active brace/chart transport" - .into(), - subreceipts: Vec::new(), - }); - receipts.push(ObligationEvidenceReceipt { - id: "RED_CHAIN_EXACT_ZERO".into(), - label: "exact first-order remainder vanishing".into(), - verdict: if reduction.remainder_exact_zero { - CertificationVerdict::Certified - } else { - CertificationVerdict::Underspecified - }, - computed: true, - detail: format!( - "remainder_normal_form={:?}", - reduction.remainder_normal_form - ), - subreceipts: Vec::new(), - }); - if let Some(boundary) = reduction.residual_boundary { - receipts.push(ObligationEvidenceReceipt { - id: "RED_CHAIN_EXACTNESS_BOUNDARY".into(), - label: "route-local reduction exactness boundary".into(), - verdict: CertificationVerdict::Underspecified, - computed: false, - detail: boundary, - subreceipts: Vec::new(), - }); - } - - let computed_failure = receipts.iter().any(receipt_has_computed_failure); - let residual_scaffold = receipts.iter().any(receipt_has_residual); - let verdict = if computed_failure { - CertificationVerdict::BlockedOpen - } else if residual_scaffold { - CertificationVerdict::Benchmarked - } else { - CertificationVerdict::Certified - }; - let (computed_successes, residuals) = receipts - .iter() - .map(receipt_leaf_counts) - .fold((0usize, 0usize), |(sa, ra), (sb, rb)| (sa + sb, ra + rb)); - - Some(ObligationStatus { - obligation_id: obligation.id.clone(), - kind: obligation.kind.clone(), - verdict, - evaluation_mode: if residual_scaffold { - ObligationEvaluationMode::RecomputedPartial - } else { - ObligationEvaluationMode::RecomputedExact - }, - detail: format!( - "chain-rule reduction factored into {} computed receipts with {} residual blocker(s)", - computed_successes, residuals - ), - receipts, - }) -} - -fn evaluate_flagship_type_obligation( - theorem_id: &str, - obligation: &Obligation, -) -> Option { - match (theorem_id, obligation.id.as_str()) { - ("THS_CH_NORM", "OBL_CH_ADE") => { - let witness = exec_ch_norm_type_witness().ok()?; - let receipts = vec![ - ObligationEvidenceReceipt { - id: "CHN_ADE_INHABITANCE_PRESERVE".into(), - label: "inhabitance preservation".into(), - verdict: if witness.inhabitance_preserved { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!("direct_normal_form={:?}", witness.direct_normal_form), - subreceipts: Vec::new(), - }, - ObligationEvidenceReceipt { - id: "CHN_ADE_CARRIER_COLLAPSE".into(), - label: "carrier-collapse exactness".into(), - verdict: if witness.carrier_collapse_exact { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: - "extensional carrier collapse preserves the canonical normalization witness" - .into(), - subreceipts: Vec::new(), - }, - ]; - let residual = receipts.iter().any(receipt_has_residual); - Some(ObligationStatus { - obligation_id: obligation.id.clone(), - kind: obligation.kind.clone(), - verdict: if residual { - CertificationVerdict::BlockedOpen - } else { - CertificationVerdict::Certified - }, - evaluation_mode: if residual { - ObligationEvaluationMode::RecomputedPartial - } else { - ObligationEvaluationMode::RecomputedExact - }, - detail: "CH-Norm adequacy witness discharged through exact inhabitance and carrier-collapse checks".into(), - receipts, - }) - } - ("THS_CH_INH", "OBL_CHI_ADE") => { - let witness = exec_ch_inh_type_witness().ok()?; - let receipts = vec![ - ObligationEvidenceReceipt { - id: "CHI_ADE_INHABITANCE_TRANSPORT".into(), - label: "inhabitance transport".into(), - verdict: if witness.inhabitance_transport_exact { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!("direct_carrier={:?}", witness.direct_carrier), - subreceipts: Vec::new(), - }, - ObligationEvidenceReceipt { - id: "CHI_ADE_CARRIER_LIFT".into(), - label: "carrier lift exactness".into(), - verdict: if witness.carrier_lift_exact { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - computed: true, - detail: format!("lifted_carrier={:?}", witness.lifted_carrier), - subreceipts: Vec::new(), - }, - ]; - let residual = receipts.iter().any(receipt_has_residual); - Some(ObligationStatus { - obligation_id: obligation.id.clone(), - kind: obligation.kind.clone(), - verdict: if residual { - CertificationVerdict::BlockedOpen - } else { - CertificationVerdict::Certified - }, - evaluation_mode: if residual { - ObligationEvaluationMode::RecomputedPartial - } else { - ObligationEvaluationMode::RecomputedExact - }, - detail: "CH-Inh adequacy witness discharged through exact inhabitance transport and carrier lift checks".into(), - receipts, - }) - } - _ => None, - } -} - -fn collect_promotion_artifact_ids( - theorem: &l64_core::TheoremSpec, - target: &l64_core::TargetProfile, - obligations: &[ObligationStatus], - adequacy_records: &[l64_core::AdequacyRecord], - deficiencies: &[l64_core::AtlasDeficiency], - verdict: &CertificationVerdict, -) -> Vec { - if !is_chain_rule_family(&theorem.id) - || target.promotion_goal != l64_core::PromotionGoal::PromoteOperator - || *verdict != CertificationVerdict::Certified - || adequacy_records - .iter() - .any(|item| item.blocking && item.verdict != CertificationVerdict::Certified) - || deficiency_blocks_promotion(deficiencies) - || obligations - .iter() - .any(|item| item.evaluation_mode != ObligationEvaluationMode::RecomputedExact) - { - return Vec::new(); - } - theorem - .operators - .iter() - .map(|operator| { - format!( - "OPR_PROMOTED_{}", - operator.replace('.', "_").to_ascii_uppercase() - ) - }) - .collect() -} - -fn collect_reused_artifact_ids( - registry: &dyn RegistryLookup, - theorem_id: &str, - obligations: &[ObligationStatus], -) -> Vec { - if !is_chain_rule_family(theorem_id) { - return Vec::new(); - } - let Some(operator) = chain_rule_promoted_operator(registry) else { - return Vec::new(); - }; - if obligations.iter().any(|item| { - matches!( - item.obligation_id.as_str(), - "OBL_CHAIN_EQ" | "OBL_CHAIN_RED" - ) && item.receipts.iter().any(|receipt| { - matches!( - receipt.id.as_str(), - "EQR_CHAIN_OPERATOR_REUSE" - | "RED_CHAIN_OPERATOR_REUSE" - | "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION" - | "RED_CHAIN_OPERATOR_DEFAULT_SELECTION" - ) - }) - }) { - vec![operator.id] - } else { - Vec::new() - } -} - -fn collect_checker_receipts( - registry: &(impl RegistryLookup + Sync), - theorem: &l64_core::TheoremSpec, - target: &l64_core::TargetProfile, - proof_shape_ids: &[String], - campaign_id: Option<&str>, - obligations: &[ObligationStatus], -) -> Vec { - let kernel = ConstitutionKernel::default(); - let mut receipts = Vec::new(); - - receipts.push(checker_receipt( - CheckerReceiptKind::TheoremSpec, - &theorem.id, - kernel - .validate_theorem_spec(theorem, registry) - .map(|_| "theorem specification validated".to_string()), - )); - receipts.push(checker_receipt( - CheckerReceiptKind::TargetProfile, - &target.id, - kernel - .validate_target_profile(target) - .map(|_| "target profile validated".to_string()), - )); - let ledger_id = format!("TRL_{}", theorem.id.trim_start_matches("THS_")); - if let Some(ledger) = registry.get_route_ledger(&ledger_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::RouteLedger, - &ledger.id, - kernel - .validate_route_ledger(&ledger, registry) - .map(|_| "route ledger validated".to_string()), - )); - } - if let Some(campaign_id) = campaign_id { - if let Some(campaign) = registry.get_campaign(campaign_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::Campaign, - &campaign.id, - kernel - .validate_campaign(&campaign, registry) - .map(|_| "campaign validated".to_string()), - )); - } - } - let certificate_id = format!("CRT_{}", theorem.id.trim_start_matches("THS_")); - if let Some(certificate) = registry.get_certificate(&certificate_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::Certificate, - &certificate.id, - kernel - .validate_certificate(&certificate, registry) - .map(|_| "certificate validated".to_string()), - )); - } - for proof_shape_id in proof_shape_ids { - if let Some(shape) = registry.get_proof_shape(proof_shape_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::ProofShape, - &shape.id, - kernel - .check_proof_shape(&shape, registry) - .map_err(l64_kernel::KernelError::Message) - .map(|_| "proof shape validated".to_string()), - )); - } - } - for clause in registry.adequacy_clauses().into_iter().filter(|item| { - item.theorem_ids.is_empty() || item.theorem_ids.iter().any(|id| id == &theorem.id) - }) { - let clause_id = clause.id.clone(); - receipts.push(checker_receipt( - CheckerReceiptKind::AdequacyClause, - &clause_id, - kernel - .validate_adequacy_clause(&clause, registry) - .map(|_| "adequacy clause validated".to_string()), - )); - } - for obligation in obligations { - receipts.push(checker_receipt( - CheckerReceiptKind::ObligationVerdict, - &obligation.obligation_id, - kernel - .validate_obligation_status(obligation) - .map(|_| "obligation verdict validated".to_string()), - )); - } - for pack_id in collect_related_burden_pack_ids(registry, campaign_id) { - if let Some(pack) = registry.get_burden_pack(&pack_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::BurdenPack, - &pack.id, - Ok("burden pack validated structurally".to_string()), - )); - } - } - for packet_id in collect_related_claim_packet_ids(registry, campaign_id) { - if let Some(packet) = registry.get_claim_packet(&packet_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::ClaimPacket, - &packet.id, - Ok("claim packet validated structurally".to_string()), - )); - } - } - for contract_id in collect_related_evidence_contract_ids(registry, campaign_id) { - if let Some(contract) = registry.get_evidence_contract(&contract_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::EvidenceContract, - &contract.id, - Ok("evidence contract validated structurally".to_string()), - )); - } - } - for receipt_id in collect_related_benchmark_receipt_ids(registry, campaign_id) { - if let Some(receipt) = registry.get_benchmark_receipt(&receipt_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::BenchmarkReceipt, - &receipt.id, - Ok("benchmark receipt validated structurally".to_string()), - )); - } - } - for receipt_id in collect_related_challenge_receipt_ids(registry, campaign_id) { - if let Some(receipt) = registry.get_challenge_receipt(&receipt_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::ChallengeReceipt, - &receipt.id, - Ok("challenge receipt validated structurally".to_string()), - )); - } - } - for packet_id in collect_related_reproducibility_packet_ids(registry, campaign_id) { - if let Some(packet) = registry.get_reproducibility_packet(&packet_id) { - receipts.push(checker_receipt( - CheckerReceiptKind::ReproducibilityPacket, - &packet.id, - Ok("reproducibility packet validated structurally".to_string()), - )); - } - } - - receipts.sort_by(|left, right| left.id.cmp(&right.id)); - receipts -} - -fn checker_receipt( - kind: CheckerReceiptKind, - subject_id: &str, - result: Result, -) -> CheckerReceipt { - let id = format!( - "CHK_{}", - stable_hash(&(subject_id.to_string() + &format!("{kind:?}"))) - ); - match result { - Ok(detail) => CheckerReceipt { - id, - kind, - subject_id: subject_id.to_string(), - verdict: CertificationVerdict::Certified, - detail, - }, - Err(error) => CheckerReceipt { - id, - kind, - subject_id: subject_id.to_string(), - verdict: CertificationVerdict::BlockedOpen, - detail: error.to_string(), - }, - } -} - -fn collect_default_selected_artifact_ids( - registry: &dyn RegistryLookup, - theorem_id: &str, - obligations: &[ObligationStatus], -) -> Vec { - if !is_chain_rule_family(theorem_id) { - return Vec::new(); - } - let Some(operator) = chain_rule_promoted_operator(registry) else { - return Vec::new(); - }; - if operator.origin != ArtifactOrigin::Seed { - return Vec::new(); - } - if obligations.iter().any(|item| { - matches!( - item.obligation_id.as_str(), - "OBL_CHAIN_EQ" | "OBL_CHAIN_RED" - ) && item.receipts.iter().any(|receipt| { - matches!( - receipt.id.as_str(), - "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION" | "RED_CHAIN_OPERATOR_DEFAULT_SELECTION" - ) - }) - }) { - vec![operator.id] - } else { - Vec::new() - } -} - -fn chain_rule_promoted_operator( - registry: &dyn RegistryLookup, -) -> Option { - let object = registry.get_object("OPR_PROMOTED_OPR_CHAIN1")?; - if object.constraint.regime == "R_CALC" - && matches!( - object.evidence.maturity, - l64_core::EvidenceMaturity::Validated | l64_core::EvidenceMaturity::Certified - ) - && object.evidence.gate_verdict == l64_core::GateVerdict::Pass - { - Some(ChainRulePromotedOperatorContext { - id: object.id, - origin: registry.get_object_origin("OPR_PROMOTED_OPR_CHAIN1"), - }) - } else { - None - } -} - -fn collect_payoff_receipt_ids( - theorem_id: &str, - obligations: &[ObligationStatus], - default_selected_artifact_ids: &[String], -) -> Vec { - if default_selected_artifact_ids.is_empty() { - return Vec::new(); - } - let mut receipts = Vec::new(); - match theorem_id { - "THS_CHAIN_RULE_RECIPE" => { - if obligations.iter().any(|item| { - item.obligation_id == "OBL_CHAIN_EQ" - && item - .receipts - .iter() - .any(|receipt| receipt.id == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - }) { - receipts.push("PAY_CHAIN1_SECOND_BURDEN_DEFAULT_REUSE".into()); - } - if obligations.len() < 4 { - receipts.push(format!( - "PAY_CHAIN1_OBLIGATION_COUNT_REDUCTION_{}_TO_{}", - 4, - obligations.len() - )); - } - } - "THS_CHAIN_RULE_TRANSPORT" => { - if obligations.iter().any(|item| { - item.obligation_id == "OBL_CHAIN_EQ" - && item - .receipts - .iter() - .any(|receipt| receipt.id == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - }) { - receipts.push("PAY_CHAIN1_ADJACENT_TRANSPORT_DEFAULT_REUSE".into()); - } - if obligations - .iter() - .any(|item| item.obligation_id == "OBL_CHAIN_LOC") - { - receipts.push("PAY_CHAIN1_LOCALITY_WITNESS_RETAINED".into()); - } - if obligations.len() < 4 { - receipts.push(format!( - "PAY_CHAIN1_OBLIGATION_COUNT_REDUCTION_{}_TO_{}", - 4, - obligations.len() - )); - } - } - _ => {} - } - receipts -} - -fn is_chain_rule_family(theorem_id: &str) -> bool { - matches!( - theorem_id, - "THS_CHAIN_RULE" | "THS_CHAIN_RULE_RECIPE" | "THS_CHAIN_RULE_TRANSPORT" - ) -} - -fn supports_active_adequacy(theorem_id: &str) -> bool { - is_chain_rule_family(theorem_id) - || matches!( - theorem_id, - "THS_BAYES_BRACE" - | "THS_CH_NORM" - | "THS_EXEC_INFER" - | "THS_PROB_JUDG" - | "THS_CERT_PROP" - | "THS_CH_INH" - ) -} - -fn payoff_reason(theorem_id: &str, payoff_receipt_ids: &[String]) -> String { - match theorem_id { - "THS_CHAIN_RULE_RECIPE" => { - "default-selected Chain₁ reduced the adjacent recipe burden relative to the full flagship obligation stack" - .into() - } - "THS_CHAIN_RULE_TRANSPORT" => { - if payoff_receipt_ids - .iter() - .any(|item| item == "PAY_CHAIN1_LOCALITY_WITNESS_RETAINED") - { - "default-selected Chain₁ reduced the adjacent transport burden while retaining a live locality obligation on the same route cluster" - .into() - } else { - "default-selected Chain₁ reduced the adjacent transport burden on the same route cluster".into() - } - } - _ => format!("operator payoff receipts: {}", payoff_receipt_ids.join(",")), - } -} - -fn adequacy_cluster_reason(theorem_id: &str) -> String { - match theorem_id { - "THS_BAYES_BRACE" => { - "active adequacy clauses for the touched R_TOP/R_PROB/bridge cluster all discharged on the selected route" - .into() - } - "THS_CH_NORM" => { - "active adequacy clauses for the touched R_TYP/R_SET/bridge cluster all discharged on the selected route" - .into() - } - "THS_EXEC_INFER" => { - "active adequacy clauses for the touched R_PROB/R_COMP/bridge cluster all discharged on the selected route" - .into() - } - "THS_PROB_JUDG" => { - "active adequacy clauses for the touched R_PROB/R_LOG/bridge cluster all discharged on the selected route" - .into() - } - "THS_CERT_PROP" => { - "active adequacy clauses for the touched R_COMP/R_LOG/bridge cluster all discharged on the selected route" - .into() - } - "THS_CH_INH" => { - "active adequacy clauses for the touched R_TYP/R_ALG/bridge cluster all discharged on the selected route" - .into() - } - _ => { - "active adequacy clauses for the touched R_TOP/R_CALC/bridge cluster all discharged on the selected route" - .into() - } - } -} - -fn evaluate_obligation( - registry: &(impl RegistryLookup + Sync), - theorem_id: &str, - theorem_hosts: &[String], - obligation: Obligation, - evaluator: &(impl ObligationEvaluator + Sync), - evaluator_policy: &l64_core::EvaluatorPolicyConfig, -) -> ObligationStatus { - if let Some(status) = evaluate_flagship_type_obligation(theorem_id, &obligation) { - return apply_evaluator_policy(status, evaluator_policy); - } - if let Some(status) = - evaluate_flagship_equivalence_obligation(registry, theorem_id, &obligation) - { - return apply_evaluator_policy(status, evaluator_policy); - } - if let Some(status) = evaluate_flagship_reduction_obligation(registry, theorem_id, &obligation) - { - return apply_evaluator_policy(status, evaluator_policy); - } - for regime in theorem_hosts { - if evaluator.supports(regime, &obligation.kind) { - if let Some(status) = evaluator.evaluate(regime, &obligation) { - return apply_evaluator_policy(status, evaluator_policy); - } - } - } - let can_use_stored = matches!( - evaluator_policy.evidence_preference, - EvidencePreference::PreferStored | EvidencePreference::StoredOnlyWhenUnavailable - ); - if can_use_stored { - if let Some(certificate) = registry.get_certificate(&obligation.id) { - let verdict = certificate.verdict.clone(); - return ObligationStatus { - obligation_id: obligation.id, - kind: obligation.kind, - verdict: verdict.clone(), - evaluation_mode: ObligationEvaluationMode::StoredReceiptUsed, - detail: "stored native certificate evidence reused".into(), - receipts: vec![ObligationEvidenceReceipt { - id: certificate.id, - label: "stored-certificate".into(), - verdict, - computed: false, - detail: "native certificate record supplied stored obligation evidence".into(), - subreceipts: Vec::new(), - }], - }; - } - if let Some(proof_shape) = registry.get_proof_shape(&obligation.id) { - let verdict = obligation.status.clone(); - return ObligationStatus { - obligation_id: obligation.id, - kind: obligation.kind, - verdict: verdict.clone(), - evaluation_mode: ObligationEvaluationMode::StoredReceiptUsed, - detail: "stored native proof-shape evidence reused".into(), - receipts: vec![ObligationEvidenceReceipt { - id: proof_shape.id, - label: "stored-proof-shape".into(), - verdict, - computed: false, - detail: "native proof-shape record supplied stored obligation evidence".into(), - subreceipts: Vec::new(), - }], - }; - } - } - let mut unsupported = ObligationStatus { - obligation_id: obligation.id, - kind: obligation.kind, - verdict: if evaluator_policy.unsupported_mode == UnsupportedHandlingMode::StrictFail { - CertificationVerdict::BlockedOpen - } else { - obligation.status - }, - evaluation_mode: ObligationEvaluationMode::Unsupported, - detail: "current executable kernel does not support recomputation for this obligation" - .into(), - receipts: Vec::new(), - }; - if evaluator_policy.unsupported_mode == UnsupportedHandlingMode::StrictFail { - unsupported - .detail - .push_str("; strict evaluator policy forbids unsupported fallback"); - } - unsupported -} - -fn evaluate_obligations( - registry: &(impl RegistryLookup + Sync), - theorem_id: &str, - campaign_id: Option<&str>, - theorem_hosts: &[String], - obligations: Vec, - evaluator: &(impl ObligationEvaluator + Sync), - policy_resolution: &l64_core::PolicyResolution, - options: &CertificationOptions, -) -> Result { - let namespace = ensure_cache_subdir("obligation-shards").map_err(CertError::Message)?; - let namespace_id = namespace - .parent() - .and_then(|path| path.file_name()) - .map(|item| item.to_string_lossy().to_string()) - .unwrap_or_else(|| "default".into()); - let mut sorted = obligations; - sorted.sort_by(|left, right| left.id.cmp(&right.id)); - let mut nodes = Vec::new(); - let mut legality = Vec::new(); - let mut shards = Vec::new(); - let mut write_sets = Vec::new(); - let mut collisions = Vec::new(); - let mut reused_ids = Vec::new(); - let mut rerun_ids = Vec::new(); - let mut notes = Vec::new(); - - for obligation in &sorted { - let class = obligation_concurrency_class(&obligation.kind, policy_resolution); - let replay_allowed = obligation_replay_allowed(obligation, policy_resolution, options); - legality.push(ReplayLegalityCheck { - id: format!( - "RLC_{}", - stable_hash(&(theorem_id.to_string() + &obligation.id)) - ), - obligation_id: obligation.id.clone(), - allowed: replay_allowed, - reasons: replay_legality_reasons(obligation, &class, policy_resolution, options), - }); - if replay_allowed { - reused_ids.push(obligation.id.clone()); - } else { - rerun_ids.push(obligation.id.clone()); - } - let barrier_after = matches!( - class, - ObligationConcurrencyClass::CanonicalizationSensitive - | ObligationConcurrencyClass::StrictlySerialized - ); - nodes.push(ObligationDagNode { - id: format!("ODN_{}", obligation.id), - obligation_id: obligation.id.clone(), - concurrency_class: class.clone(), - barrier_after, - notes: vec![format!("obligation class {:?}", class)], - }); - } - let (edges, barriers, group_waves, wave_notes) = - build_obligation_waves(theorem_id, &sorted, policy_resolution); - let groups = group_waves.iter().flatten().cloned().collect::>(); - notes.extend(wave_notes); - - let allow_parallel = (policy_resolution.scheduler.allow_parallel_obligations - || options.force_parallel_obligations) - && options - .max_obligation_workers - .unwrap_or(policy_resolution.scheduler.max_obligation_workers) - > 1 - && groups.len() > 1; - let worker_count = if allow_parallel { - options - .max_obligation_workers - .unwrap_or(policy_resolution.scheduler.max_obligation_workers) - .min(groups.len()) - .max(1) - } else { - 1 - }; - let lanes = assign_obligation_lanes(&group_waves, worker_count, allow_parallel); - - let mut results = Vec::new(); - if allow_parallel { - let mut any_parallel_wave = false; - let mut next_index = 0usize; - for wave in &group_waves { - if wave.len() > 1 { - any_parallel_wave = true; - let (tx, rx) = mpsc::channel(); - thread::scope(|scope| { - for (offset, group) in wave.iter().cloned().enumerate() { - let tx = tx.clone(); - let obligations = sorted.clone(); - let hosts = theorem_hosts.to_vec(); - let policy = policy_resolution.evaluator.clone(); - scope.spawn(move || { - let mut statuses = Vec::new(); - for obligation_id in &group.obligation_ids { - if let Some(obligation) = - obligations.iter().find(|item| &item.id == obligation_id) - { - statuses.push(evaluate_obligation( - registry, - theorem_id, - &hosts, - obligation.clone(), - evaluator, - &policy, - )); - } - } - let _ = tx.send((offset, group, statuses)); - }); - } - }); - drop(tx); - let mut wave_results = Vec::new(); - for item in rx { - wave_results.push(item); - } - wave_results.sort_by_key(|(offset, _, _)| *offset); - for (_, group, statuses) in wave_results { - results.push((next_index, group, statuses)); - next_index += 1; - } - } else { - for group in wave { - let mut statuses = Vec::new(); - for obligation_id in &group.obligation_ids { - if let Some(obligation) = - sorted.iter().find(|item| &item.id == obligation_id) - { - statuses.push(evaluate_obligation( - registry, - theorem_id, - theorem_hosts, - obligation.clone(), - evaluator, - &policy_resolution.evaluator, - )); - } - } - results.push((next_index, group.clone(), statuses)); - next_index += 1; - } - } - } - if any_parallel_wave { - notes.push("independent obligation groups executed in parallel".into()); - } else { - notes.push("obligation barriers limited the campaign to serialized waves despite parallel policy".into()); - } - } else { - for (index, group) in groups.iter().cloned().enumerate() { - let mut statuses = Vec::new(); - for obligation_id in &group.obligation_ids { - if let Some(obligation) = sorted.iter().find(|item| &item.id == obligation_id) { - statuses.push(evaluate_obligation( - registry, - theorem_id, - theorem_hosts, - obligation.clone(), - evaluator, - &policy_resolution.evaluator, - )); - } - } - results.push((index, group, statuses)); - } - notes.push( - "obligation execution remained serialized under current policy or barrier conditions" - .into(), - ); - } - - let mut statuses = Vec::new(); - for (_, group, group_statuses) in &results { - shards.push(ObligationCacheShard { - id: format!("OCS_{}", stable_hash(&(theorem_id.to_string() + &group.id))), - obligation_ids: group.obligation_ids.clone(), - namespace_id: namespace_id.clone(), - }); - write_sets.push(ObligationWriteSet { - id: format!( - "OWS_{}", - stable_hash(&(theorem_id.to_string() + &group.id + "|writes")) - ), - artifact_ids: group - .obligation_ids - .iter() - .map(|id| format!("OBL_RESULT_{id}")) - .collect(), - notes: vec!["obligation results staged and merged deterministically".into()], - }); - if group.obligation_ids.len() > 1 - && matches!( - group.concurrency_class, - ObligationConcurrencyClass::ReplaySafeWriteSensitive - | ObligationConcurrencyClass::CacheSensitive - ) - { - collisions.push(ObligationCollisionReport { - id: format!("OCR_{}", stable_hash(&(group.id.clone() + "|collision"))), - obligation_ids: group.obligation_ids.clone(), - reasons: vec!["group remained within a single deterministic lane due to cache/write sensitivity".into()], - }); - } - statuses.extend(group_statuses.clone()); - } - statuses.sort_by(|left, right| left.obligation_id.cmp(&right.obligation_id)); - - let ordering_receipt = ObligationOrderingReceipt { - id: format!( - "OORD_{}", - stable_hash(&(theorem_id.to_string() + "|obligations")) - ), - ordered_group_ids: groups.iter().map(|item| item.id.clone()).collect(), - notes: vec!["obligation groups merged in stable group order".into()], - }; - let merge_receipt = ObligationMergeReceipt { - id: format!("OMER_{}", stable_hash(&(theorem_id.to_string() + "|merge"))), - merged_obligation_ids: statuses - .iter() - .map(|item| item.obligation_id.clone()) - .collect(), - notes: vec![ - "obligation statuses merged deterministically into certification report".into(), - ], - }; - let replay_merge_receipt = ReplayMergeReceipt { - id: format!( - "RMR_{}", - stable_hash(&(theorem_id.to_string() + "|replay-merge")) - ), - reused_obligation_ids: reused_ids, - rerun_obligation_ids: rerun_ids, - notes: vec!["replay legality checked at obligation granularity before merge".into()], - }; - let namespace_receipt = ObligationNamespaceReceipt { - id: format!( - "ONR_{}", - stable_hash(&(theorem_id.to_string() + "|namespace")) - ), - namespace_id: namespace_id.clone(), - shard_ids: shards.iter().map(|item| item.id.clone()).collect(), - notes: vec!["obligation shards resolved beneath the active cache namespace".into()], - }; - let plan = ObligationPlan { - id: format!( - "OPL_{}", - stable_hash(&(theorem_id.to_string() + campaign_id.unwrap_or("THEOREM"))) - ), - theorem_id: theorem_id.into(), - campaign_id: campaign_id.map(ToString::to_string), - nodes, - edges, - groups: groups.clone(), - notes: notes.clone(), - }; - Ok(ObligationExecutionArtifacts { - statuses, - plan, - lanes, - ordering_receipt, - merge_receipt, - replay_legality_checks: legality, - replay_barrier_receipts: barriers, - replay_merge_receipt, - replay_divergence_records: Vec::new(), - cache_shards: shards, - write_sets, - collision_reports: collisions, - namespace_receipt, - notes, - }) -} - -fn obligation_concurrency_class( - kind: &ObligationKind, - policy_resolution: &l64_core::PolicyResolution, -) -> ObligationConcurrencyClass { - if policy_resolution - .scheduler - .serialize_canonicalization_sensitive - { - match kind { - ObligationKind::OblEq | ObligationKind::OblRed => { - return ObligationConcurrencyClass::CanonicalizationSensitive; - } - _ => {} - } - } - match kind { - ObligationKind::OblLoc | ObligationKind::OblGlu => { - ObligationConcurrencyClass::ReplaySafeWriteSensitive - } - ObligationKind::OblTol | ObligationKind::OblObs => { - ObligationConcurrencyClass::CacheSensitive - } - ObligationKind::OblAde => ObligationConcurrencyClass::StrictlySerialized, - _ => ObligationConcurrencyClass::ParallelSafe, - } -} - -fn obligation_replay_allowed( - obligation: &Obligation, - policy_resolution: &l64_core::PolicyResolution, - options: &CertificationOptions, -) -> bool { - if !policy_resolution.replay_cache.replay_allowed || options.no_cache { - return false; - } - if !(policy_resolution.scheduler.allow_parallel_obligation_replay - || options.force_parallel_obligations) - && options.replay_only - { - return false; - } - !matches!( - obligation_concurrency_class(&obligation.kind, policy_resolution), - ObligationConcurrencyClass::StrictlySerialized - ) -} - -fn replay_legality_reasons( - obligation: &Obligation, - class: &ObligationConcurrencyClass, - policy_resolution: &l64_core::PolicyResolution, - options: &CertificationOptions, -) -> Vec { - let mut reasons = Vec::new(); - if !policy_resolution.replay_cache.replay_allowed { - reasons.push("replay policy disabled obligation reuse".into()); - } - if options.no_cache { - reasons.push("no-cache execution requested".into()); - } - if matches!(class, ObligationConcurrencyClass::StrictlySerialized) { - reasons.push("strictly serialized obligation cannot participate in parallel replay".into()); - } - if options.replay_only && !policy_resolution.scheduler.allow_parallel_obligation_replay { - reasons.push("scheduler policy forbids parallel obligation replay".into()); - } - if reasons.is_empty() { - reasons.push(format!( - "obligation {} is eligible for replay-aware grouped execution", - obligation.id - )); - } - reasons -} - -fn build_obligation_waves( - theorem_id: &str, - obligations: &[Obligation], - policy_resolution: &l64_core::PolicyResolution, -) -> ( - Vec, - Vec, - Vec>, - Vec, -) { - use std::collections::{BTreeMap, BTreeSet, HashMap}; - - let classes = obligations - .iter() - .map(|item| { - ( - item.id.clone(), - obligation_concurrency_class(&item.kind, policy_resolution), - ) - }) - .collect::>(); - let dependencies = obligation_dependency_pairs(theorem_id, obligations, policy_resolution); - let mut incoming = obligations - .iter() - .map(|item| (item.id.clone(), 0usize)) - .collect::>(); - let mut outgoing = obligations - .iter() - .map(|item| (item.id.clone(), Vec::::new())) - .collect::>(); - let mut edges = Vec::new(); - let mut barriers = Vec::new(); - - for (from, to, reason) in dependencies { - if let Some(count) = incoming.get_mut(&to) { - *count += 1; - } - outgoing.entry(from.clone()).or_default().push(to.clone()); - edges.push(ObligationDagEdge { - id: format!("ODE_{}", stable_hash(&(from.clone() + &to))), - from: format!("ODN_{from}"), - to: format!("ODN_{to}"), - reason: reason.clone(), - }); - barriers.push(ReplayBarrierReceipt { - id: format!("RBR_{}", stable_hash(&(from.clone() + &to))), - obligation_ids: vec![from, to], - reason, - }); - } - - let obligation_ids = obligations - .iter() - .map(|item| item.id.clone()) - .collect::>(); - let mut remaining = obligation_ids.clone(); - let mut waves = Vec::new(); - let mut notes = Vec::new(); - - while !remaining.is_empty() { - let mut ready = obligations - .iter() - .filter(|item| remaining.contains(&item.id)) - .filter(|item| incoming.get(&item.id).copied().unwrap_or_default() == 0) - .map(|item| item.id.clone()) - .collect::>(); - ready.sort(); - if ready.is_empty() { - if let Some(fallback) = remaining.iter().next().cloned() { - ready.push(fallback.clone()); - notes.push(format!( - "obligation cycle fallback engaged at {fallback}; forced deterministic serialization" - )); - } - } - - let mut buckets = BTreeMap::>::new(); - for id in &ready { - let class = classes - .get(id) - .cloned() - .unwrap_or(ObligationConcurrencyClass::StrictlySerialized); - let bucket_key = match class { - ObligationConcurrencyClass::ParallelSafe => "parallel".to_string(), - _ => id.clone(), - }; - buckets.entry(bucket_key).or_default().push(id.clone()); - } - - let mut wave_groups = buckets - .into_values() - .map(|ids| { - let class = classes - .get(&ids[0]) - .cloned() - .unwrap_or(ObligationConcurrencyClass::StrictlySerialized); - let serialized_reason = if ids.len() == 1 { - match class { - ObligationConcurrencyClass::ParallelSafe => Some( - "dependency wave contained a single parallel-safe obligation".into(), - ), - ObligationConcurrencyClass::ReplaySafeWriteSensitive => Some( - "write-sensitive obligation isolated into its own deterministic group" - .into(), - ), - ObligationConcurrencyClass::CacheSensitive => Some( - "cache-sensitive obligation isolated into its own deterministic group" - .into(), - ), - ObligationConcurrencyClass::CanonicalizationSensitive => Some( - "canonicalization-sensitive obligation forms an explicit barrier group" - .into(), - ), - ObligationConcurrencyClass::StrictlySerialized => Some( - "strictly serialized obligation forms an explicit barrier group".into(), - ), - } - } else { - None - }; - ObligationGroup { - id: format!("OGR_{}", stable_hash(&ids.join("|"))), - concurrency_class: class, - obligation_ids: ids, - serialized_reason, - } - }) - .collect::>(); - wave_groups.sort_by(|left, right| left.id.cmp(&right.id)); - if wave_groups.len() > 1 { - notes.push(format!( - "dependency wave {} exposes {} independent obligation groups", - waves.len(), - wave_groups.len() - )); - } - waves.push(wave_groups); - - for id in ready { - remaining.remove(&id); - if let Some(nexts) = outgoing.get(&id) { - for next in nexts { - if let Some(count) = incoming.get_mut(next) { - *count = count.saturating_sub(1); - } - } - } - } - } - - (edges, barriers, waves, notes) -} - -fn obligation_dependency_pairs( - theorem_id: &str, - obligations: &[Obligation], - policy_resolution: &l64_core::PolicyResolution, -) -> Vec<(String, String, String)> { - let ids = obligations - .iter() - .map(|item| item.id.as_str()) - .collect::>(); - if theorem_id == "THS_CHAIN_RULE" { - let mut pairs = Vec::new(); - if ids.contains("OBL_CHAIN_ADM") && ids.contains("OBL_CHAIN_RED") { - pairs.push(( - "OBL_CHAIN_ADM".into(), - "OBL_CHAIN_RED".into(), - "chain rule reduction depends on derivative admissibility".into(), - )); - } - if ids.contains("OBL_CHAIN_LOC") && ids.contains("OBL_CHAIN_RED") { - pairs.push(( - "OBL_CHAIN_LOC".into(), - "OBL_CHAIN_RED".into(), - "chain rule remainder reduction depends on brace-local compatibility".into(), - )); - } - if ids.contains("OBL_CHAIN_RED") && ids.contains("OBL_CHAIN_EQ") { - pairs.push(( - "OBL_CHAIN_RED".into(), - "OBL_CHAIN_EQ".into(), - "first-order equivalence discharge waits on remainder reduction".into(), - )); - } - return pairs; - } - - let mut pairs = Vec::new(); - for window in obligations.windows(2) { - if let [left, right] = window { - let left_class = obligation_concurrency_class(&left.kind, policy_resolution); - let right_class = obligation_concurrency_class(&right.kind, policy_resolution); - if matches!( - left_class, - ObligationConcurrencyClass::CanonicalizationSensitive - | ObligationConcurrencyClass::StrictlySerialized - ) || matches!( - right_class, - ObligationConcurrencyClass::CanonicalizationSensitive - | ObligationConcurrencyClass::StrictlySerialized - ) { - pairs.push(( - left.id.clone(), - right.id.clone(), - "canonicalization-sensitive or strict obligation barrier".into(), - )); - } - } - } - pairs -} - -fn assign_obligation_lanes( - waves: &[Vec], - worker_count: usize, - allow_parallel: bool, -) -> Vec { - let lane_count = if allow_parallel { - worker_count.max(1) - } else { - 1 - }; - let mut lanes = (0..lane_count) - .map(|index| ObligationLaneRecord { - lane_id: format!("OLAN_{index}"), - group_ids: Vec::new(), - obligation_ids: Vec::new(), - serialized_reason: if allow_parallel { - None - } else { - Some("obligation policy or barriers required serialized execution".into()) - }, - }) - .collect::>(); - for wave in waves { - for (index, group) in wave.iter().enumerate() { - let lane_index = if allow_parallel { - index % lane_count - } else { - 0 - }; - lanes[lane_index].group_ids.push(group.id.clone()); - lanes[lane_index] - .obligation_ids - .extend(group.obligation_ids.clone()); - } - } - lanes -} - -fn apply_evaluator_policy( - mut status: ObligationStatus, - evaluator_policy: &l64_core::EvaluatorPolicyConfig, -) -> ObligationStatus { - if !evaluator_policy.allow_approximation - && matches!( - status.evaluation_mode, - ObligationEvaluationMode::RecomputedApproximate - | ObligationEvaluationMode::RecomputedPartial - ) - { - status.verdict = CertificationVerdict::Underspecified; - status - .detail - .push_str("; approximation disallowed by evaluator policy"); - } - status -} - -fn obligation_from_result( - regime: &str, - obligation: Obligation, - result: HostExecutionResult, -) -> Option { - let (verdict, mode, detail) = match (regime, obligation.kind.clone(), result) { - ( - "R_SET", - ObligationKind::OblEq, - HostExecutionResult::Set { - extensional_equal, .. - }, - ) => ( - if extensional_equal { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedExact, - "finite extensional equality checked".into(), - ), - ("R_SET", ObligationKind::OblFin, HostExecutionResult::Set { powerset_bound, .. }) => ( - CertificationVerdict::Certified, - ObligationEvaluationMode::RecomputedExact, - format!("finite powerset bound {powerset_bound}"), - ), - ( - "R_SET", - ObligationKind::OblAdm, - HostExecutionResult::Set { - total_function_graph, - injective, - surjective, - .. - }, - ) => ( - if total_function_graph { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedPartial, - format!( - "finite function graph total={total_function_graph} injective={injective} surjective={surjective}" - ), - ), - ( - "R_SET", - ObligationKind::OblKnt, - HostExecutionResult::Set { - injective, - surjective, - .. - }, - ) => ( - if injective && surjective { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - ObligationEvaluationMode::RecomputedPartial, - format!("finite map injective={injective} surjective={surjective}"), - ), - ( - "R_ALG", - ObligationKind::OblAdm, - HostExecutionResult::Algebra { - closure_holds, - associative, - distributive, - .. - }, - ) => ( - if closure_holds && associative { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedExact, - format!( - "closure={closure_holds} associative={associative} distributive={distributive}" - ), - ), - ( - "R_ALG", - ObligationKind::OblKnt, - HostExecutionResult::Algebra { - identity_holds, - inverse_holds, - .. - }, - ) => ( - if identity_holds && inverse_holds { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedExact, - format!("identity={identity_holds} inverse={inverse_holds}"), - ), - ( - "R_ALG", - ObligationKind::OblEq, - HostExecutionResult::Algebra { - quotient_compatible, - homomorphism_preserving, - .. - }, - ) => ( - if quotient_compatible && homomorphism_preserving { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - ObligationEvaluationMode::RecomputedPartial, - format!( - "quotient-compatible={quotient_compatible} homomorphism={homomorphism_preserving}" - ), - ), - ( - "R_TOP", - ObligationKind::OblLoc, - HostExecutionResult::Topology { - cover_legal, - continuity_holds, - overlap_compatible, - .. - }, - ) => ( - if cover_legal && continuity_holds && overlap_compatible { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedExact, - format!( - "cover={cover_legal} continuity={continuity_holds} overlap={overlap_compatible}" - ), - ), - ( - "R_TOP", - ObligationKind::OblGlu, - HostExecutionResult::Topology { - gluing_compatible, - obstruction, - .. - }, - ) => ( - if gluing_compatible { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - ObligationEvaluationMode::RecomputedPartial, - obstruction.unwrap_or_else(|| "finite gluing witness constructed".into()), - ), - ( - "R_CALC", - ObligationKind::OblAdm, - HostExecutionResult::Calculus { - local_linear_witness, - .. - }, - ) => ( - if local_linear_witness { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - ObligationEvaluationMode::RecomputedExact, - "local linear witness checked".into(), - ), - ( - "R_CALC", - ObligationKind::OblTol, - HostExecutionResult::Calculus { - accumulation_ok, .. - }, - ) => ( - if accumulation_ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedApproximate, - "finite accumulation/toll check".into(), - ), - ( - "R_CALC", - ObligationKind::OblRed, - HostExecutionResult::Calculus { - finite_difference_derivative, - symbolic_only, - .. - }, - ) => ( - if finite_difference_derivative { - CertificationVerdict::Certified - } else if symbolic_only { - CertificationVerdict::Underspecified - } else { - CertificationVerdict::BlockedOpen - }, - if symbolic_only { - ObligationEvaluationMode::RecomputedPartial - } else { - ObligationEvaluationMode::RecomputedApproximate - }, - format!("finite-difference derivative witness; symbolic_only={symbolic_only}"), - ), - ( - "R_PROB", - ObligationKind::OblTol, - HostExecutionResult::Probability { - normalized, - expectation, - conditioning_legal, - pushforward_ok, - .. - }, - ) => ( - if normalized && conditioning_legal && pushforward_ok { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedExact, - format!( - "normalized={normalized} conditioning={conditioning_legal} pushforward={pushforward_ok} expectation={}/{}", - expectation.num, expectation.den - ), - ), - ( - "R_PROB", - ObligationKind::OblObs, - HostExecutionResult::Probability { independent, .. }, - ) => ( - if independent { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - ObligationEvaluationMode::RecomputedApproximate, - format!("finite independence check independent={independent}"), - ), - ( - "R_PROB", - ObligationKind::OblAde, - HostExecutionResult::Probability { - normalized, - conditioning_legal, - pushforward_ok, - .. - }, - ) => ( - if pushforward_ok && normalized && conditioning_legal { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - if pushforward_ok && normalized && conditioning_legal { - ObligationEvaluationMode::RecomputedExact - } else { - ObligationEvaluationMode::RecomputedPartial - }, - format!( - "finite pushforward check pushforward_ok={} normalized={} conditioning={}", - pushforward_ok, normalized, conditioning_legal - ), - ), - ( - "R_COMP", - ObligationKind::OblRed, - HostExecutionResult::Computation { - reached_normal_form, - replayable_trace, - .. - }, - ) => ( - if reached_normal_form { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedExact, - format!( - "normal form reached={reached_normal_form} replayable_trace={replayable_trace}" - ), - ), - ( - "R_COMP", - ObligationKind::OblObs, - HostExecutionResult::Computation { - observationally_equivalent, - .. - }, - ) => ( - if observationally_equivalent { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedContradiction - }, - ObligationEvaluationMode::RecomputedExact, - format!("observational equivalence={observationally_equivalent}"), - ), - ("R_COMP", ObligationKind::OblTol, HostExecutionResult::Computation { cost, .. }) => ( - CertificationVerdict::Certified, - ObligationEvaluationMode::RecomputedExact, - format!("cost accumulation={}", cost.0), - ), - ( - "R_LOG", - ObligationKind::OblAde, - HostExecutionResult::Logic { - proposition_well_formed, - witness_available, - }, - ) => ( - if proposition_well_formed && witness_available { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - ObligationEvaluationMode::RecomputedPartial, - format!("logic proposition={proposition_well_formed} witness={witness_available}"), - ), - ( - "R_TYP", - ObligationKind::OblAde, - HostExecutionResult::TypeTheory { - witness_inhabited, .. - }, - ) => ( - if witness_inhabited { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - ObligationEvaluationMode::RecomputedPartial, - format!("type witness inhabited={witness_inhabited}"), - ), - ( - "R_TYP", - ObligationKind::OblRed, - HostExecutionResult::TypeTheory { - normalization_correspondence, - .. - }, - ) => ( - if normalization_correspondence { - CertificationVerdict::Certified - } else { - CertificationVerdict::BlockedOpen - }, - ObligationEvaluationMode::RecomputedApproximate, - format!("normalization correspondence={normalization_correspondence}"), - ), - _ => return None, - }; - Some(ObligationStatus { - obligation_id: obligation.id, - kind: obligation.kind, - verdict, - evaluation_mode: mode, - detail, - receipts: Vec::new(), - }) -} - -fn execution_cache_root() -> Result { - ensure_cache_subdir("execution").map_err(CertError::Message) -} - -fn execution_cache_entries_root() -> Result { - let root = execution_cache_root()?.join("reports"); - fs::create_dir_all(&root).map_err(|err| CertError::Message(err.to_string()))?; - Ok(root) -} - -fn execution_cache_path() -> Result { - execution_cache_entries_root() -} - -fn execution_cache_entry_path(cache_key: &str) -> Result { - Ok(execution_cache_entries_root()?.join(format!("{}.dna", cache_key_filename(cache_key)))) -} - -fn cache_key_filename(cache_key: &str) -> String { - cache_key - .chars() - .map(|ch| match ch { - 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' => ch, - _ => '_', - }) - .collect() -} - -fn load_execution_cache() -> Result { - let root = execution_cache_entries_root()?; - let mut cache = ExecutionCache::default(); - let mut saw_binary = false; - for entry in fs::read_dir(&root).map_err(|err| CertError::Message(err.to_string()))? { - let entry = entry.map_err(|err| CertError::Message(err.to_string()))?; - let path = entry.path(); - if path.extension().and_then(|item| item.to_str()) != Some("dna") { - continue; - } - saw_binary = true; - match fs::read(&path) - .map_err(|err| CertError::Message(err.to_string())) - .and_then(|bytes| decode_cached_report_packet(&bytes)) - { - Ok(report) => cache.reports.push(report), - Err(_) => { - let _ = fs::remove_file(&path); - } - } - } - let _ = saw_binary; - Ok(cache) -} - -fn load_cached_report(cache_key: &str) -> Result, CertError> { - let path = execution_cache_entry_path(cache_key)?; - if path.exists() { - let bytes = fs::read(&path).map_err(|err| CertError::Message(err.to_string()))?; - match decode_cached_report_packet(&bytes) { - Ok(report) => return Ok(Some(report)), - Err(_) => { - let _ = fs::remove_file(&path); - return Ok(None); - } - } - } - let cache = load_execution_cache()?; - Ok(cache - .reports - .into_iter() - .find(|item| item.cache_key == cache_key)) -} - -fn persist_cached_report(entry: CachedCertificationReport) -> Result<(), CertError> { - let path = execution_cache_entry_path(&entry.cache_key)?; - let bytes = encode_cached_report_packet(&entry)?; - fs::write(path, bytes).map_err(|err| CertError::Message(err.to_string())) -} - -fn cache_entry_valid( - entry: &CachedCertificationReport, - options: &CertificationOptions, - current_policy_hash: &str, - resolution: Option<&l64_core::PolicyResolution>, -) -> bool { - let exact_policy_required = resolution - .map(|item| item.replay_cache.exact_policy_match_required) - .unwrap_or(true); - let approx_ok = resolution - .map(|item| item.replay_cache.reuse_approximate_results) - .unwrap_or(false); - let policy_ok = if exact_policy_required { - entry.policy_hash == current_policy_hash - || entry - .report - .execution_envelope - .as_ref() - .map(|env| env.policy_hash.as_str()) - == Some(current_policy_hash) - } else { - true - }; - let approx_ok_for_report = approx_ok - || !entry.report.obligations.iter().any(|item| { - matches!( - item.evaluation_mode, - ObligationEvaluationMode::RecomputedApproximate - | ObligationEvaluationMode::RecomputedPartial - ) - }); - entry.bundle_hash == options.bundle_hash - && policy_ok - && (entry.policy_hash == current_policy_hash || !exact_policy_required) - && approx_ok_for_report - && entry.evaluator_version == EVALUATOR_VERSION -} - -fn certification_cache_key( - theorem_id: &str, - target_profile_id: &str, - campaign_id: Option<&str>, - bundle_hash: &str, - policy_hash: &str, - optimizer_policy: &OptimizerPolicy, -) -> String { - stable_hash(&format!( - "{theorem_id}|{target_profile_id}|{}|{bundle_hash}|{policy_hash}|{:?}", - campaign_id.unwrap_or("THEOREM"), - optimizer_policy - )) -} - -fn report_storage_id(report: &CertificationReport) -> String { - format!( - "REPORT_{}_{}", - report.theorem_id, - report - .campaign_id - .clone() - .unwrap_or_else(|| "THEOREM".into()) - ) -} - -fn stable_hash(input: &str) -> String { - cache_hash_v1_str(input) -} - -fn derive_reuse_legality_receipts(report: &CertificationReport) -> Vec { - let subject_id = report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()); - let lawful = !report.reused_artifact_ids.is_empty() - && report - .replay_legality_checks - .iter() - .all(|item| item.allowed); - let mut basis = Vec::new(); - if !report.reused_artifact_ids.is_empty() { - basis.push("reused-artifact-lineage-present".into()); - } - if report - .replay_legality_checks - .iter() - .all(|item| item.allowed) - { - basis.push("replay-legality-passed".into()); - } else { - basis.push("replay-legality-blocked".into()); - } - if !report.selected_path.is_empty() { - basis.push("route-selection-resolved".into()); - } - vec![ReuseLegalityReceipt { - id: format!( - "RLR_{}", - stable_hash(&(subject_id.clone() + "|reuse-legality")) - ), - subject_id: subject_id.clone(), - lawful, - basis, - lineage_refs: vec![format!("LIN_{subject_id}")], - policy_scope: report - .policy_resolution - .as_ref() - .map(|item| item.id.clone()), - }] -} - -fn derive_reuse_decision_receipts( - _report: &CertificationReport, - coverage: &ProofCoverageEnvelope, -) -> Vec { - let subject_id = coverage.subject_id.clone(); - let fallback_required = !matches!( - coverage.decision, - CoverageDecision::Exact - | CoverageDecision::Subsumed - | CoverageDecision::TransportEquivalent - ) || !coverage.residual_obligation_ids.is_empty(); - let reason = if fallback_required { - "reuse path left residual work; fallback verification remains required" - } else { - "reuse path fully discharged the active coverage seam" - }; - vec![ReuseDecisionReceipt { - id: format!( - "RDR_{}", - stable_hash(&(subject_id.clone() + "|reuse-decision")) - ), - subject_id, - reused_artifact_ids: coverage.covered_by.clone(), - skipped_obligation_ids: coverage.skipped_obligation_ids.clone(), - fallback_required, - reason: reason.into(), - }] -} - -fn derive_residual_verification_receipts( - report: &CertificationReport, - coverage: &ProofCoverageEnvelope, -) -> Vec { - let subject_id = coverage.subject_id.clone(); - let fully_discharged = coverage.residual_obligation_ids.is_empty(); - let mut notes = Vec::new(); - if fully_discharged { - notes.push("no residual obligations remain after lawful reuse evaluation".into()); - } else { - notes.push("residual obligations remain explicit and must not be silently skipped".into()); - } - if report.reused_artifact_ids.is_empty() { - notes.push("no promoted artifact reuse was available on this run".into()); - } - vec![ResidualVerificationReceipt { - id: format!( - "RVR_{}", - stable_hash(&(subject_id.clone() + "|residual-verification")) - ), - subject_id, - residual_obligation_ids: coverage.residual_obligation_ids.clone(), - fully_discharged, - notes, - }] -} - -pub fn derive_execution_closure_receipt(report: &CertificationReport) -> ExecutionClosureReceipt { - let subject_id = report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()); - let exactness = if report.verdict == CertificationVerdict::Certified - && report - .obligations - .iter() - .all(|item| item.verdict == CertificationVerdict::Certified) - { - EvidenceExactness::WitnessBacked - } else if report.obligations.iter().any(|item| { - matches!( - item.verdict, - CertificationVerdict::BlockedOpen | CertificationVerdict::BlockedContradiction - ) - }) { - EvidenceExactness::CounterexampleCandidate - } else { - EvidenceExactness::Undischarged - }; - let reuse_reported = !report.reused_artifact_ids.is_empty() - || !report.reuse_legality_receipts.is_empty() - || !report.reuse_decision_receipts.is_empty(); - let residuals_reported = !report.residual_verification_receipts.is_empty() - || report - .obligations - .iter() - .any(|item| item.verdict != CertificationVerdict::Certified); - ExecutionClosureReceipt { - id: format!("ECR_{}", stable_hash(&(subject_id.clone() + "|execution-closure"))), - subject_id, - exactness, - lower_lineage_required: true, - reuse_reported, - residuals_reported, - promotion_gate_visible: report.verdict == CertificationVerdict::Certified - || !report.deficiencies.is_empty(), - notes: vec![ - "execution/certification closure is explicit; exact proof, numeric evidence, and residual work must not be merged".into(), - ], - } -} - -fn score_vector_to_legacy(score: &RouteScoreVector) -> Vec { - vec![ - score.lawfulness, - score.loss_compliance, - score.surface_transition_penalty, - score.execution_cost, - score.symbolic_fidelity, - ] -} - -pub fn derive_proof_coverage_envelope(report: &CertificationReport) -> ProofCoverageEnvelope { - let subject_id = report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()); - let decision = if !report.default_selected_artifact_ids.is_empty() { - CoverageDecision::Subsumed - } else if !report.reused_artifact_ids.is_empty() { - CoverageDecision::TransportEquivalent - } else { - CoverageDecision::Fallback - }; - let skipped_obligation_ids = if report.reused_artifact_ids.is_empty() { - Vec::new() - } else { - report - .obligations - .iter() - .filter(|item| item.verdict == CertificationVerdict::Certified) - .map(|item| item.obligation_id.clone()) - .collect() - }; - let residual_obligation_ids = report - .obligations - .iter() - .filter(|item| item.verdict != CertificationVerdict::Certified) - .map(|item| item.obligation_id.clone()) - .collect(); - let reuse_envelope_hash = stable_hash(&format!( - "{}|{}|{}|{}", - report.theorem_id, - report.target_profile_id, - report.selected_atlas_cell.clone().unwrap_or_default(), - report.selected_path.join(",") - )); - ProofCoverageEnvelope { - subject_id, - decision, - covered_by: report.reused_artifact_ids.clone(), - skipped_obligation_ids, - residual_obligation_ids, - reuse_envelope_hash, - payoff_receipt_ids: report.payoff_receipt_ids.clone(), - } -} - -pub fn dispatch_proof_coverage(report: &CertificationReport) -> ProofCoverageDispatch { - let coverage = derive_proof_coverage_envelope(report); - let lineage_id = format!("LIN_{}", coverage.subject_id); - let route_fast_path = matches!( - coverage.decision, - CoverageDecision::Exact - | CoverageDecision::Subsumed - | CoverageDecision::TransportEquivalent - ) && coverage.residual_obligation_ids.is_empty(); - let reuse_legality_receipts = derive_reuse_legality_receipts(report); - let reuse_decision_receipts = derive_reuse_decision_receipts(report, &coverage); - let residual_verification_receipts = derive_residual_verification_receipts(report, &coverage); - let reason = match coverage.decision { - CoverageDecision::Exact => "exact promoted coverage available", - CoverageDecision::Subsumed => "subsuming promoted coverage available", - CoverageDecision::TransportEquivalent => "transport-equivalent promoted coverage available", - CoverageDecision::Fallback => "fallback to proof path required", - CoverageDecision::Unsupported => "no lawful proof coverage exists yet", - } - .to_string(); - ProofCoverageDispatch { - subject_id: coverage.subject_id, - decision: coverage.decision, - route_fast_path, - reason, - covered_by: coverage.covered_by, - residual_obligation_ids: coverage.residual_obligation_ids.clone(), - lineage_refs: vec![lineage_id], - reuse_legality_receipts, - reuse_decision_receipts, - residual_verification_receipts, - } -} - -pub fn derive_distress_vector( - report: &CertificationReport, - bundle: &VerticalCompoundingBundle, -) -> DistressVector { - let repeated_blocker_ids = report - .deficiencies - .iter() - .map(|item| item.id.clone()) - .collect(); - let checker_gaps = bundle - .checker_extensions - .iter() - .map(|item| item.object_family.clone()) - .collect(); - let route_scarcity = if bundle.atlas_cells.is_empty() && !report.deficiencies.is_empty() { - vec![report.selected_path.join("->")] - } else { - Vec::new() - }; - let payoff_drought = - report.payoff_receipt_ids.is_empty() && !report.promotion_artifact_ids.is_empty(); - let stalled_frontier_motion = - !report.deficiencies.is_empty() && report.reused_artifact_ids.is_empty(); - DistressVector { - repeated_blocker_ids, - checker_gaps, - route_scarcity, - payoff_drought, - stalled_frontier_motion, - } -} - -pub fn derive_help_request( - report: &CertificationReport, - distress: &DistressVector, -) -> Option { - let severe = distress.stalled_frontier_motion - || !distress.route_scarcity.is_empty() - || !distress.repeated_blocker_ids.is_empty(); - if !severe { - return None; - } - Some(HelpRequest { - id: format!( - "HELP_{}", - report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()) - ), - task_ref: report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()), - distress_vector: distress.clone(), - minimal_reproduction: report_storage_id(report), - requested_capacity: if !distress.route_scarcity.is_empty() { - "atlas-or-shell-expansion".into() - } else if !distress.checker_gaps.is_empty() { - "checker-extension".into() - } else { - "semantic-leaf".into() - }, - expected_relief: "convert repeated blocker into bounded verified next seam".into(), - }) -} - -pub fn derive_recipe_records( - report: &CertificationReport, - bundle: &VerticalCompoundingBundle, -) -> ( - Vec, - Vec, - Vec, - CalibrationPressureMap, - Vec, -) { - let seam = report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()); - let recipes = vec![RecipeRecord { - id: format!("RCP_{seam}"), - seam: seam.clone(), - tactic_family: if report.deficiencies.is_empty() { - "coverage-reuse".into() - } else { - "semantic-closure".into() - }, - generated_status: GeneratedStatus::VerifiedCandidate, - expected_relief: "lower future frontier cost on sibling burdens".into(), - }]; - let recipe_deltas = vec![RecipeDelta { - id: format!("RDEL_{seam}"), - recipe_record_id: format!("RCP_{seam}"), - changed_fields: vec!["coverage".into(), "checker".into(), "frontier".into()], - strengthening_value: report.checker_receipts.len() - + report.adequacy_records.len() - + bundle.payoff_tasks.len(), - }]; - let promotion_candidates = report - .promotion_artifact_ids - .iter() - .map(|artifact_id| PromotionCandidate { - id: format!("PRCND_{artifact_id}"), - artifact_id: artifact_id.clone(), - candidate_kind: "operator-or-certificate".into(), - generated_status: GeneratedStatus::VerifiedCandidate, - proof_grade: if report.verdict == CertificationVerdict::Certified { - "certified".into() - } else { - "bounded".into() - }, - }) - .collect(); - let calibration_pressure = CalibrationPressureMap { - override_pressure: report.reasons.len(), - emitted_duplication: bundle.campaigns.len() + bundle.atlas_cells.len(), - conformance_friction: report.deficiencies.len(), - extension_cost: bundle.compartments.len() + bundle.help_requests.len(), - }; - let override_pressure_receipts = report - .reasons - .iter() - .enumerate() - .map(|(idx, note)| OverridePressureReceipt { - id: format!("OPR_{seam}_{idx}"), - source_id: seam.clone(), - pressure_class: "reason".into(), - notes: vec![note.clone()], - }) - .collect(); - ( - recipes, - recipe_deltas, - promotion_candidates, - calibration_pressure, - override_pressure_receipts, - ) -} - -pub fn build_vertical_compounding_bundle( - registry: &impl RegistryLookup, - report: &CertificationReport, -) -> VerticalCompoundingBundle { - let subject_id = report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()); - let frontier = Frontier { - id: format!("FRT_{subject_id}"), - title: format!("frontier for {subject_id}"), - burden_class: if report.deficiencies.is_empty() { - "reuse-expansion".into() - } else { - "semantic-closure".into() - }, - blocker_ids: report - .deficiencies - .iter() - .map(|item| item.id.clone()) - .collect(), - closure_witness: if report.verdict == CertificationVerdict::Certified { - Some(format!("CLS_{subject_id}")) - } else { - None - }, - residual_budget: if report.verdict == CertificationVerdict::Certified { - None - } else { - Some("bounded-seam".into()) - }, - strengthening_value: report.checker_receipts.len() + report.adequacy_records.len(), - coldness: if report.deficiencies.is_empty() { - "mid-to-cold".into() - } else { - "mid-friction".into() - }, - }; - - let semantic_leaves = report - .deficiencies - .iter() - .map(|item| CandidateSemanticLeaf { - id: format!("CND_LEAF_{}", item.id), - frontier_id: frontier.id.clone(), - description: item.message.clone(), - generated_status: GeneratedStatus::VerifiedCandidate, - expected_relief: "narrow semantic closure or sharper blocker".into(), - }) - .collect(); - - let adequacy_clauses = report - .adequacy_records - .iter() - .filter(|item| item.verdict != CertificationVerdict::Certified) - .map(|item| CandidateAdequacyClause { - id: format!("CND_ADQ_{}", item.clause_id), - frontier_id: frontier.id.clone(), - clause_stub: item.clause_id.clone(), - generated_status: GeneratedStatus::Suggestion, - expected_relief: "exact adequacy discharge".into(), - }) - .collect(); - - let checker_extensions = report - .checker_receipts - .iter() - .filter(|item| item.verdict != CertificationVerdict::Certified) - .map(|item| CandidateCheckerExtension { - id: format!("CND_CHK_{}", item.subject_id), - frontier_id: frontier.id.clone(), - object_family: format!("{:?}", item.kind), - generated_status: GeneratedStatus::Suggestion, - expected_relief: "increase reusable machine validation".into(), - }) - .collect(); - - let campaigns = if report.verdict == CertificationVerdict::Certified { - Vec::new() - } else { - registry - .atlas_cells() - .into_iter() - .take(3) - .map(|cell| CandidateCampaign { - id: format!("CND_CPG_{}", cell.id), - theorem_id: report.theorem_id.clone(), - target_profile_id: report.target_profile_id.clone(), - generated_status: GeneratedStatus::Scaffold, - expected_relief: format!("probe atlas cell {}", cell.id), - }) - .collect() - }; - - let atlas_cells = report - .deficiencies - .iter() - .filter(|item| matches!(item.class, AtlasDeficiencyClass::DNoRoute)) - .map(|item| CandidateAtlasCell { - id: format!("CND_ATL_{}", item.id), - src: report.selected_path.first().cloned().unwrap_or_default(), - tgt: report.selected_path.last().cloned().unwrap_or_default(), - generated_status: GeneratedStatus::Suggestion, - expected_relief: item.message.clone(), - }) - .collect(); - - let payoff_tasks = report - .promotion_artifact_ids - .iter() - .map(|artifact_id| CandidatePayoffTask { - id: format!("CND_PAY_{artifact_id}"), - artifact_id: artifact_id.clone(), - burden_hint: report.theorem_id.clone(), - generated_status: GeneratedStatus::Suggestion, - expected_relief: "prove broader lawful fast-path coverage".into(), - }) - .collect(); - - let compartments = if report.deficiencies.is_empty() { - Vec::new() - } else { - vec![SearchCompartment { - id: format!("SCMP_{subject_id}"), - task_fingerprint: format!("{}:{}", report.theorem_id, report.target_profile_id), - allowed_grammars: vec!["semantic-leaf".into(), "checker-extension".into()], - budget: "bounded-micro-generator".into(), - evaluator_profile: EVALUATOR_VERSION.into(), - admissibility_surface: vec!["campaign-truth".into(), "adequacy".into()], - kill_criteria: vec!["cold-blocker".into(), "no-frontier-motion".into()], - expected_relief: "resolve active blocker without widening host law".into(), - }] - }; - - let generator_contracts = vec![GeneratorContract { - id: format!("GCTR_{subject_id}"), - proposal_kind: if report.deficiencies.is_empty() { - ProposalKind::CheckerExtension - } else { - ProposalKind::SemanticLeaf - }, - seam: subject_id.clone(), - verifier: EVALUATOR_VERSION.into(), - compatibility_path: report.selected_path.join("->"), - }]; - - let generation_receipts = vec![GenerationReceipt { - id: format!("GRCPT_{subject_id}"), - generator_contract_id: format!("GCTR_{subject_id}"), - output_ids: vec![frontier.id.clone()], - generated_status: GeneratedStatus::VerifiedCandidate, - notes: vec!["derived from live campaign truth".into()], - }]; - - let mut bundle = VerticalCompoundingBundle { - frontier_ledger: FrontierLedger { - frontiers: vec![frontier], - notes: vec!["generated from certification truth".into()], - }, - semantic_leaves, - adequacy_clauses, - checker_extensions, - campaigns, - atlas_cells, - payoff_tasks, - compartments, - generator_contracts, - generation_receipts, - distress: None, - help_requests: Vec::new(), - recipes: Vec::new(), - recipe_deltas: Vec::new(), - promotion_candidates: Vec::new(), - calibration_pressure: None, - override_pressure_receipts: Vec::new(), - lineage_refs: vec![format!("LIN_{subject_id}")], - lineage_required: true, - }; - let distress = derive_distress_vector(report, &bundle); - let help_request = derive_help_request(report, &distress); - let ( - recipes, - recipe_deltas, - promotion_candidates, - calibration_pressure, - override_pressure_receipts, - ) = derive_recipe_records(report, &bundle); - bundle.distress = Some(distress); - if let Some(item) = help_request { - bundle.help_requests.push(item); - } - bundle.recipes = recipes; - bundle.recipe_deltas = recipe_deltas; - bundle.promotion_candidates = promotion_candidates; - bundle.calibration_pressure = Some(calibration_pressure); - bundle.override_pressure_receipts = override_pressure_receipts; - bundle -} - -pub fn encode_locus_packet_for_report(report: &CertificationReport) -> Result, CertError> { - let capabilities = LocusCapabilityMask { - has_checker: !report.checker_receipts.is_empty(), - has_adequacy: !report.adequacy_records.is_empty(), - has_route: !report.selected_path.is_empty(), - has_certificate: report.certificate_id.is_some(), - has_frontier: !report.deficiencies.is_empty(), - has_forensic: !report.diagnostics.is_empty() || !report.reasons.is_empty(), - }; - let coverage = derive_proof_coverage_envelope(report); - let mut sections = Vec::new(); - sections.push(LocusSection { - opcode: LocusOpcode::CanonicalPayload, - flags: 0, - subject_id: report.theorem_id.clone(), - payload: bincode::serialize(report).map_err(|err| CertError::Message(err.to_string()))?, - }); - sections.push(LocusSection { - opcode: LocusOpcode::Coverage, - flags: 0, - subject_id: coverage.subject_id.clone(), - payload: bincode::serialize(&coverage) - .map_err(|err| CertError::Message(err.to_string()))?, - }); - if !report.adequacy_records.is_empty() { - sections.push(LocusSection { - opcode: LocusOpcode::AdequacyTable, - flags: report.adequacy_records.len() as u16, - subject_id: report.theorem_id.clone(), - payload: bincode::serialize(&report.adequacy_records) - .map_err(|err| CertError::Message(err.to_string()))?, - }); - } - if !report.checker_receipts.is_empty() { - sections.push(LocusSection { - opcode: LocusOpcode::Checker, - flags: report.checker_receipts.len() as u16, - subject_id: report.theorem_id.clone(), - payload: bincode::serialize(&report.checker_receipts) - .map_err(|err| CertError::Message(err.to_string()))?, - }); - } - let packet = LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Gene, - surface: GenomeSurface::Dna, - kind: LocusPacketKind::CertificationEnvelope, - version_major: 1, - version_minor: 0, - authority_tier: if report.verdict == CertificationVerdict::Certified { - 3 - } else { - 2 - }, - capabilities, - grammar_id: "report-envelope.v1".into(), - schema_hash: stable_hash(&format!( - "{}|{}|{}", - report.theorem_id, report.target_profile_id, EVALUATOR_VERSION - )), - integrity_hash: stable_hash(&serde_json::to_string(report).unwrap_or_default()), - strand_manifest: vec!["core".into(), "cert".into(), "trace".into()], - feature_flags: 0, - root_subject_id: report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()), - }, - sections, - }; - l64_core::encode_locus_packet(&packet).map_err(CertError::Message) -} - -pub fn decode_locus_packet_report(bytes: &[u8]) -> Result { - decode_section_payload(bytes, LocusOpcode::CanonicalPayload) - .map_err(|err| CertError::Message(err.to_string())) -} - -pub fn decode_locus_packet_summary( - bytes: &[u8], -) -> Result, CertError> { - decode_locus_summary(bytes).map_err(|err| CertError::Message(err.to_string())) -} - -pub fn report_cache_root() -> Result { - ensure_cache_subdir("reports").map_err(CertError::Message) -} - -pub fn report_cache_path(id: &str) -> Result { - Ok(report_cache_root()?.join(format!("{id}.dna"))) -} - -pub fn report_id(report: &CertificationReport) -> String { - format!( - "REPORT_{}_{}", - report.theorem_id, - report - .campaign_id - .clone() - .unwrap_or_else(|| "THEOREM".into()) - ) -} - -pub fn persist_report_document(report: &CertificationReport) -> Result<(), CertError> { - let path = report_cache_path(&report_id(report))?; - let bytes = encode_locus_packet_for_report(report)?; - fs::write(path, bytes).map_err(|err| CertError::Message(err.to_string()))?; - Ok(()) -} - -pub fn report_related_entries( - registry: &dyn RegistryLookup, - report: &CertificationReport, -) -> Vec { - let mut entries = Vec::new(); - for id in &report.burden_pack_ids { - if let Some(item) = registry.get_burden_pack(id) { - entries.push(QaEntry::BurdenPack(item)); - } - } - for id in &report.claim_packet_ids { - if let Some(item) = registry.get_claim_packet(id) { - entries.push(QaEntry::ClaimPacket(item)); - } - } - for id in &report.evidence_contract_ids { - if let Some(item) = registry.get_evidence_contract(id) { - entries.push(QaEntry::EvidenceContract(item)); - } - } - for id in &report.benchmark_receipt_ids { - if let Some(item) = registry.get_benchmark_receipt(id) { - entries.push(QaEntry::BenchmarkReceipt(item)); - } - } - for id in &report.challenge_receipt_ids { - if let Some(item) = registry.get_challenge_receipt(id) { - entries.push(QaEntry::ChallengeReceipt(item)); - } - } - for id in &report.reproducibility_packet_ids { - if let Some(item) = registry.get_reproducibility_packet(id) { - entries.push(QaEntry::ReproducibilityPacket(item)); - } - } - for record in &report.adequacy_records { - if let Some(item) = registry.get_adequacy_clause(&record.clause_id) { - entries.push(QaEntry::AdequacyClause(item)); - } - } - entries -} - -pub fn report_to_validation_bundle_with_registry( - report: &CertificationReport, - registry: &dyn RegistryLookup, -) -> Result { - let mut document = report_to_document_with_registry(report, registry)?; - let mut extra = Vec::new(); - if let Some(theorem) = registry.get_theorem_spec(&report.theorem_id) { - for host in &theorem.hosts { - if let Some(regime) = registry.get_regime(host) { - extra.push(QaEntry::Regime(regime)); - } - } - for shape_id in &theorem.proof_shapes { - if let Some(shape) = registry.get_proof_shape(shape_id) { - extra.push(QaEntry::ProofShape(shape)); - } - } - extra.push(QaEntry::TheoremSpec(theorem)); - } - if let Some(target) = registry.get_target_profile(&report.target_profile_id) { - extra.push(QaEntry::TargetProfile(target)); - } - if let Some(campaign_id) = &report.campaign_id { - if let Some(campaign) = registry.get_campaign(campaign_id) { - for obligation_id in &campaign.obligations { - if let Some(obligation) = registry.get_obligation(obligation_id) { - extra.push(QaEntry::Obligation(obligation)); - } - } - extra.push(QaEntry::Campaign(campaign)); - } - } - if let Some(route_class_id) = &report.route_class_id { - if let Some(route_class) = registry.get_route_class(route_class_id) { - extra.push(QaEntry::RouteClass(route_class)); - } - } - for bridge_id in &report.selected_path { - if let Some(bridge) = registry.get_bridge(bridge_id) { - if let Some(source) = registry.get_regime(&bridge.src) { - extra.push(QaEntry::Regime(source)); - } - if let Some(target) = registry.get_regime(&bridge.tgt) { - extra.push(QaEntry::Regime(target)); - } - extra.push(QaEntry::Bridge(bridge)); - } - } - if let Some(cell_id) = &report.selected_atlas_cell { - if let Some(cell) = registry.get_atlas_cell(cell_id) { - extra.push(QaEntry::AtlasCell(cell)); - } - } - document.entries.extend(extra); - Ok(QaDocument { - entries: document - .entries - .into_iter() - .fold(Vec::new(), |mut acc, entry| { - let id = entry.id(); - if !acc.iter().any(|existing: &QaEntry| existing.id() == id) { - acc.push(entry); - } - acc - }), - }) -} - -pub fn report_to_document_with_registry( - report: &CertificationReport, - registry: &dyn RegistryLookup, -) -> Result { - let report_id = report_id(report); - let ledger = RouteLedger { - id: format!("TRL_{report_id}"), - theorem: report.theorem_id.clone(), - paths: vec![report.selected_path.clone()], - budget: Budget { - max_loss: report - .candidates - .first() - .map(|item| item.loss_count) - .unwrap_or_default(), - allow_lossy_supported: true, - require_proof: true, - }, - losses: report - .candidates - .first() - .map(|item| vec![format!("loss-count={}", item.loss_count)]) - .unwrap_or_default(), - receipts: Vec::new(), - normalized_path: report.selected_path.clone(), - }; - let certificate = Certificate { - id: format!("CRT_{report_id}"), - theorem: report.theorem_id.clone(), - route_ledger: ledger.id.clone(), - proof_shapes: report - .candidates - .first() - .map(|item| item.proof_shapes.clone()) - .unwrap_or_default(), - receipts: report - .reused_artifact_ids - .iter() - .cloned() - .chain( - report - .adequacy_records - .iter() - .filter(|item| item.verdict == CertificationVerdict::Certified) - .map(|item| item.id.clone()), - ) - .chain(report.payoff_receipt_ids.iter().cloned()) - .collect(), - verdict: report.verdict.clone(), - }; - let mut entries = vec![ - QaEntry::RouteLedger(ledger.clone()), - QaEntry::Certificate(certificate.clone()), - ]; - entries.extend(report_related_entries(registry, report)); - entries.extend( - report - .promotion_artifact_ids - .iter() - .map(|id| QaEntry::Object(promoted_operator_object(report, id))), - ); - if let Some(policy_resolution) = &report.policy_resolution { - entries.push(QaEntry::PolicyResolution(policy_resolution.clone())); - } - if let Some(envelope) = &report.execution_envelope { - if let Some(manifest_id) = &envelope.manifest_id { - if let Ok(manifest) = load_execution_manifest(manifest_id) { - entries.push(QaEntry::ExecutionManifest(manifest)); - } - } - if let Some(lock_id) = &envelope.lock_id { - if let Ok(lock) = load_bundle_lock(lock_id) { - entries.push(QaEntry::BundleLock(lock)); - } - } - if let (Some(lock_id), Some(manifest_id)) = (&envelope.lock_id, &envelope.manifest_id) { - entries.push(QaEntry::ReplayLockManifest(ReplayLockManifest { - id: format!("RLM_{report_id}"), - report_id: report_id.clone(), - report_hash: envelope.report_hash.clone(), - route_winner_hash: envelope.route_winner_hash.clone(), - policy_hash: envelope.policy_hash.clone(), - bundle_hash: envelope.bundle_hash.clone(), - })); - entries.push(QaEntry::LockReceipt(l64_core::LockReceipt { - id: format!("LRC_{report_id}"), - lock_id: lock_id.clone(), - manifest_id: manifest_id.clone(), - bundle_id: envelope.bundle_hash.clone(), - receipt_ids: vec![format!("RLM_{report_id}")], - verdict: report - .policy_resolution - .as_ref() - .map(|item| item.verdict.clone()) - .unwrap_or(PolicyVerdict::Applied), - })); - } - } - entries.extend( - report - .deficiencies - .iter() - .cloned() - .map(QaEntry::AtlasDeficiency), - ); - entries.extend( - report - .adequacy_records - .iter() - .enumerate() - .map(|(index, item)| { - QaEntry::AtlasDeficiency(l64_core::adequacy_record_deficiency( - &report.theorem_id, - report.selected_atlas_cell.as_deref(), - format!("DGN_ADQ_{report_id}_{index}"), - item, - )) - }), - ); - entries.extend( - report - .diagnostics - .iter() - .enumerate() - .map(|(index, message)| { - QaEntry::AtlasDeficiency(AtlasDeficiency { - id: format!("DGN_{report_id}_{index}"), - class: AtlasDeficiencyClass::DNoCommutingProof, - atlas_cell: report.selected_atlas_cell.clone(), - theorem: Some(report.theorem_id.clone()), - message: message.clone(), - blocking_scope: None, - control_effects: Vec::new(), - suggested_seam: None, - }) - }), - ); - entries.extend(report.obligations.iter().enumerate().map(|(index, item)| { - QaEntry::AtlasDeficiency(l64_core::obligation_status_deficiency( - &report.theorem_id, - report.selected_atlas_cell.as_deref(), - format!("DGN_OBL_{report_id}_{index}"), - item, - false, - None, - )) - })); - if let Some(explanation) = &report.route_explanation { - entries.push(QaEntry::AtlasDeficiency( - l64_core::route_explanation_deficiency( - &report.theorem_id, - report.selected_atlas_cell.as_deref(), - format!("DGN_ROUTE_{report_id}"), - explanation, - false, - ), - )); - } - Ok(QaDocument { entries }) -} - -pub fn load_report_document_with_registry( - id: &str, - registry: &dyn RegistryLookup, -) -> Result { - let path = report_cache_path(id)?; - if path.exists() { - let bytes = fs::read(path).map_err(|err| CertError::Message(err.to_string()))?; - let report = decode_locus_packet_report(&bytes)?; - return report_to_document_with_registry(&report, registry); - } - Err(CertError::Message(format!("report packet not found: {id}"))) -} - -fn promoted_operator_object(report: &CertificationReport, id: &str) -> l64_core::QcObject { - let alias = if let Some(suffix) = id.strip_prefix("OPR_PROMOTED_") { - suffix.replace('_', ".") - } else { - id.replace('_', ".") - }; - l64_core::QcObject { - id: id.to_string(), - identity: l64_core::IdentityFace { - tag: l64_core::ObjectTag::Opr, - cid: format!("cid:{id}"), - codebook: "QC0_CORE".into(), - remap: "none".into(), - lineage: format!("derived-from:{}", report.theorem_id), - }, - structural: l64_core::StructuralFace { - head: "operator".into(), - args: vec![ - report.theorem_id.clone(), - report - .campaign_id - .clone() - .unwrap_or_else(|| "THEOREM".into()), - ], - local_sections: vec!["first-order derivative composition".into()], - morphism_hooks: report.selected_path.clone(), - }, - constraint: l64_core::ConstraintFace { - regime: "R_CALC".into(), - contracts: vec!["chain-rule".into(), "first-order".into()], - invariants: vec!["jet-compose".into(), "reduction-exact".into()], - equivalence: "first-order jet equivalence".into(), - admissibility: "promoted after exact certified discharge".into(), - }, - evidence: l64_core::EvidenceFace { - evidence_class: "DerivedPromotion".into(), - traces: vec![report.theorem_id.clone()], - receipts: vec![ - report - .certificate_id - .clone() - .unwrap_or_else(|| format!("CRT_{}", report_id(report))), - format!( - "REPORT_{}_{}", - report.theorem_id, - report - .campaign_id - .clone() - .unwrap_or_else(|| "THEOREM".into()) - ), - ], - maturity: l64_core::EvidenceMaturity::Certified, - gate_verdict: l64_core::GateVerdict::Pass, - }, - alias: l64_core::AliasFace { - aliases: vec![alias], - profile_pack: vec!["STD".into(), "chain-rule".into()], - qm_binding: "THS·ChainRule".into(), - qa_binding: "OPR.Chain1".into(), - projection_policy: "canonical-authored".into(), - }, - } -} - -fn encode_cached_report_packet(entry: &CachedCertificationReport) -> Result, CertError> { - let coverage = derive_proof_coverage_envelope(&entry.report); - let header_payload = CachedExecutionPacketHeader { - cache_key: entry.cache_key.clone(), - theorem_id: entry.theorem_id.clone(), - campaign_id: entry.campaign_id.clone(), - target_profile_id: entry.target_profile_id.clone(), - bundle_hash: entry.bundle_hash.clone(), - policy_hash: entry.policy_hash.clone(), - route_winner_hash: entry.route_winner_hash.clone(), - evaluator_version: entry.evaluator_version.clone(), - report_id: report_storage_id(&entry.report), - }; - let packet = LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Genome, - surface: GenomeSurface::Dna, - kind: LocusPacketKind::CertificationEnvelope, - version_major: 1, - version_minor: 1, - authority_tier: if entry.report.verdict == CertificationVerdict::Certified { - 3 - } else { - 2 - }, - capabilities: LocusCapabilityMask { - has_checker: !entry.report.checker_receipts.is_empty(), - has_adequacy: !entry.report.adequacy_records.is_empty(), - has_route: !entry.report.selected_path.is_empty(), - has_certificate: entry.report.certificate_id.is_some(), - has_frontier: !entry.report.deficiencies.is_empty(), - has_forensic: !entry.report.diagnostics.is_empty() - || !entry.report.reasons.is_empty(), - }, - grammar_id: "cached-report-envelope.v1".into(), - schema_hash: stable_hash(&format!( - "cache|{}|{}|{}", - entry.theorem_id, entry.target_profile_id, entry.evaluator_version - )), - integrity_hash: stable_hash(&serde_json::to_string(&entry.report).unwrap_or_default()), - strand_manifest: vec!["core".into(), "cert".into(), "trace".into()], - feature_flags: 0, - root_subject_id: header_payload.report_id.clone(), - }, - sections: vec![ - LocusSection { - opcode: LocusOpcode::Header, - flags: 0, - subject_id: header_payload.report_id.clone(), - payload: bincode::serialize(&header_payload) - .map_err(|err| CertError::Message(err.to_string()))?, - }, - LocusSection { - opcode: LocusOpcode::CanonicalPayload, - flags: 0, - subject_id: entry.theorem_id.clone(), - payload: bincode::serialize(&entry.report) - .map_err(|err| CertError::Message(err.to_string()))?, - }, - LocusSection { - opcode: LocusOpcode::Coverage, - flags: 0, - subject_id: coverage.subject_id.clone(), - payload: bincode::serialize(&coverage) - .map_err(|err| CertError::Message(err.to_string()))?, - }, - ], - }; - l64_core::encode_locus_packet(&packet).map_err(CertError::Message) -} - -fn decode_cached_report_packet(bytes: &[u8]) -> Result { - let packet = decode_locus_packet_with_mode(bytes, LocusDecodeMode::CurrentAuthority) - .map_err(CertError::Message)?; - let header = packet - .sections - .iter() - .find(|item| item.opcode == LocusOpcode::Header) - .ok_or_else(|| CertError::Message("cached locus packet missing header".into())) - .and_then(|item| { - bincode::deserialize::(&item.payload) - .map_err(|err| CertError::Message(err.to_string())) - })?; - let report = packet - .sections - .iter() - .find(|item| item.opcode == LocusOpcode::CanonicalPayload) - .ok_or_else(|| CertError::Message("cached locus packet missing canonical payload".into())) - .and_then(|item| { - bincode::deserialize::(&item.payload) - .map_err(|err| CertError::Message(err.to_string())) - })?; - Ok(CachedCertificationReport { - cache_key: header.cache_key, - theorem_id: header.theorem_id, - campaign_id: header.campaign_id, - target_profile_id: header.target_profile_id, - bundle_hash: header.bundle_hash, - policy_hash: header.policy_hash, - route_winner_hash: header.route_winner_hash, - evaluator_version: header.evaluator_version, - report, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use l64_bundle::import_bundle_file; - use l64_core::{QaDocument, QaEntry}; - use l64_registry::SeedRegistry; - use serial_test::serial; - use std::{ - fs, - time::{SystemTime, UNIX_EPOCH}, - }; - - fn test_namespace(label: &str) -> String { - format!( - "l64_cert_{}_{}", - label, - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ) - } - - #[derive(Debug)] - struct NoopObligationEvaluator; - - impl ObligationEvaluator for NoopObligationEvaluator { - fn supports(&self, _regime: &str, _kind: &ObligationKind) -> bool { - false - } - - fn evaluate(&self, _regime: &str, _obligation: &Obligation) -> Option { - None - } - - fn version(&self) -> &'static str { - "test-noop" - } - } - - fn write_bundle(path: &PathBuf, content: &str) { - if path.extension().and_then(|ext| ext.to_str()) == Some("dna") { - let document = bundle_document_from_text(content); - let bytes = l64_locus::encode_section_packet( - LocusPacketKind::CanonicalTransfer, - LocusOpcode::CanonicalPayload, - "BND_CERT_TEST", - "bundle_document.v1", - &document, - LocusCapabilityMask::default(), - 1, - ) - .unwrap(); - fs::write(path, bytes).unwrap(); - } else { - fs::write(path, content).unwrap(); - } - } - - fn bundle_document_from_text(bundle: &str) -> QaDocument { - let entries = bundle - .lines() - .filter_map(|line| { - let line = line.trim(); - if line.is_empty() || line.starts_with("!l64-bundle") { - return None; - } - let (kind, payload) = line.split_once(' ').unwrap(); - Some(QaEntry::from_surface_json(kind, payload).unwrap()) - }) - .collect(); - QaDocument { entries } - } - - #[test] - #[serial] - fn authored_obligation_status_does_not_satisfy_evidence() { - let registry = SeedRegistry::load().unwrap(); - let obligation = Obligation { - id: "OBL_AUTHORED_ONLY".into(), - kind: ObligationKind::OblAdm, - description: "authored status without executable or stored evidence".into(), - status: CertificationVerdict::Certified, - }; - let policy = l64_core::EvaluatorPolicyConfig { - evidence_preference: EvidencePreference::PreferStored, - allow_approximation: false, - unsupported_mode: UnsupportedHandlingMode::StrictFail, - require_symbolic_fidelity_route: false, - prefer_comp_replay: false, - }; - - let status = evaluate_obligation( - ®istry, - "THS_AUTHORED_ONLY", - &[], - obligation, - &NoopObligationEvaluator, - &policy, - ); - - assert_eq!(status.verdict, CertificationVerdict::BlockedOpen); - assert_eq!( - status.evaluation_mode, - ObligationEvaluationMode::Unsupported - ); - assert!(status.receipts.is_empty()); - assert!(status.detail.contains("strict evaluator policy")); - } - - #[test] - #[serial] - fn derived_certification_replays_seed_chain_rule() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("seed_chain")); - } - clear_cache(Some("all")).unwrap(); - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign(®istry, &atlas, "CPG_CHAIN_RULE").unwrap(); - assert_eq!(report.selected_atlas_cell.as_deref(), Some("A_TOP_TO_CALC")); - let eq = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CHAIN_EQ") - .unwrap(); - assert_eq!(report.verdict, CertificationVerdict::Integrated); - assert_eq!( - eq.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - assert!( - eq.receipts - .iter() - .any(|item| item.id == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - ); - assert!( - !report - .deficiencies - .iter() - .any(|item| item.id == "DGN_CHAIN_RULE_ADEQUACY") - ); - let red = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CHAIN_RED") - .unwrap(); - assert_eq!( - red.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - assert!( - red.receipts - .iter() - .any(|item| item.id == "RED_CHAIN_OPERATOR_DEFAULT_SELECTION") - ); - assert!( - report - .promotion_artifact_ids - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - report - .reused_artifact_ids - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - report - .default_selected_artifact_ids - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - } - - #[test] - #[serial] - fn derived_certification_reuses_chain1_on_adjacent_transport_shell() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("seed_chain_transport")); - } - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign_with_options( - ®istry, - &atlas, - "CPG_CHAIN_RULE_TRANSPORT", - &CertificationOptions { - no_cache: true, - bundle_hash: "seed".into(), - policy_hash: "test-chain-transport".into(), - ..CertificationOptions::default() - }, - ) - .unwrap(); - assert_eq!( - report.campaign_id.as_deref(), - Some("CPG_CHAIN_RULE_TRANSPORT") - ); - assert_eq!(report.verdict, CertificationVerdict::Integrated); - assert!( - report - .default_selected_artifact_ids - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - report - .payoff_receipt_ids - .iter() - .any(|item| item == "PAY_CHAIN1_ADJACENT_TRANSPORT_DEFAULT_REUSE") - ); - assert!( - report - .payoff_receipt_ids - .iter() - .any(|item| item == "PAY_CHAIN1_LOCALITY_WITNESS_RETAINED") - ); - assert!( - report - .payoff_receipt_ids - .iter() - .any(|item| item == "PAY_CHAIN1_OBLIGATION_COUNT_REDUCTION_4_TO_3") - ); - assert_eq!(report.obligations.len(), 3); - assert!( - report - .obligations - .iter() - .any(|item| item.obligation_id == "OBL_CHAIN_LOC") - ); - } - - #[test] - #[serial] - fn derived_certification_realizes_bayes_brace_on_top_prob_cluster() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("seed_bayes_brace")); - } - clear_cache(Some("all")).unwrap(); - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign(®istry, &atlas, "CPG_BAYES_BRACE").unwrap(); - assert_eq!(report.campaign_id.as_deref(), Some("CPG_BAYES_BRACE")); - assert_eq!(report.selected_atlas_cell.as_deref(), Some("A_TOP_TO_PROB")); - assert_eq!(report.verdict, CertificationVerdict::Certified); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_BAYES_TOP_PROB_BRIDGE") - ); - assert!(report.deficiencies.is_empty()); - let adequacy = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_BAYES_ADE") - .unwrap(); - assert_eq!( - adequacy.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - } - - #[test] - #[serial] - fn derived_certification_realizes_ch_norm_on_exact_type_normalization_witness() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("seed_ch_norm")); - } - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign_with_options( - ®istry, - &atlas, - "CPG_CH_NORM", - &CertificationOptions { - no_cache: true, - bundle_hash: "seed".into(), - policy_hash: "test-ch-norm".into(), - ..CertificationOptions::default() - }, - ) - .unwrap(); - assert_eq!(report.campaign_id.as_deref(), Some("CPG_CH_NORM")); - assert_eq!(report.selected_atlas_cell.as_deref(), Some("A_TYPE_TO_SET")); - assert_eq!(report.verdict, CertificationVerdict::Certified); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_CH_TYP_SET_BRIDGE") - ); - assert!(report.deficiencies.is_empty()); - let adequacy = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CH_ADE") - .unwrap(); - assert_eq!( - adequacy.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - assert!( - adequacy - .receipts - .iter() - .any(|item| item.id == "CHN_ADE_CARRIER_COLLAPSE") - ); - let reduction = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CH_RED") - .unwrap(); - assert_eq!( - reduction.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - assert!( - reduction - .receipts - .iter() - .any(|item| item.id == "CHN_RED_BETA_ETA_NORMALIZE") - ); - } - - #[test] - #[serial] - fn derived_certification_realizes_exec_infer_on_prob_comp_cluster() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("seed_exec_infer")); - } - clear_cache(Some("all")).unwrap(); - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign(®istry, &atlas, "CPG_EXEC_INFER").unwrap(); - assert_eq!(report.campaign_id.as_deref(), Some("CPG_EXEC_INFER")); - assert_eq!( - report.selected_atlas_cell.as_deref(), - Some("A_PROB_TO_COMP") - ); - assert_eq!(report.verdict, CertificationVerdict::Certified); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_EXEC_PROB_COMP_BRIDGE") - ); - assert!(report.deficiencies.is_empty()); - let red = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_EXEC_RED") - .unwrap(); - assert_eq!( - red.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - } - - #[test] - #[serial] - fn derived_certification_realizes_prob_judg_on_prob_log_cluster() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("seed_prob_judg")); - } - clear_cache(Some("all")).unwrap(); - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign(®istry, &atlas, "CPG_PROB_JUDG").unwrap(); - assert_eq!(report.campaign_id.as_deref(), Some("CPG_PROB_JUDG")); - assert_eq!(report.selected_atlas_cell.as_deref(), Some("A_PROB_TO_LOG")); - assert_eq!(report.verdict, CertificationVerdict::Certified); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_JDG_PROB_LOG_BRIDGE") - ); - assert!(report.deficiencies.is_empty()); - let ade = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_JDG_ADE") - .unwrap(); - assert_eq!( - ade.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - } - - #[test] - #[serial] - fn derived_certification_realizes_cert_prop_on_comp_log_cluster() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("seed_cert_prop")); - } - clear_cache(Some("all")).unwrap(); - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign(®istry, &atlas, "CPG_CERT_PROP").unwrap(); - assert_eq!(report.campaign_id.as_deref(), Some("CPG_CERT_PROP")); - assert_eq!(report.selected_atlas_cell.as_deref(), Some("A_COMP_TO_LOG")); - assert_eq!(report.verdict, CertificationVerdict::Certified); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_CERT_COMP_LOG_BRIDGE") - ); - assert!(report.deficiencies.is_empty()); - let obs = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CERT_OBS") - .unwrap(); - assert_eq!( - obs.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - } - - #[test] - #[serial] - fn derived_certification_realizes_ch_inh_on_exact_type_algebra_witness() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("seed_ch_inh")); - } - clear_cache(Some("all")).unwrap(); - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign(®istry, &atlas, "CPG_CH_INH").unwrap(); - assert_eq!(report.campaign_id.as_deref(), Some("CPG_CH_INH")); - assert_eq!(report.selected_atlas_cell.as_deref(), Some("A_TYPE_TO_ALG")); - assert_eq!(report.verdict, CertificationVerdict::Certified); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_CHI_TYP_ALG_BRIDGE") - ); - assert!(report.deficiencies.is_empty()); - let adequacy = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CHI_ADE") - .unwrap(); - assert_eq!( - adequacy.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - assert!( - adequacy - .receipts - .iter() - .any(|item| item.id == "CHI_ADE_CARRIER_LIFT") - ); - let eq = report - .obligations - .iter() - .find(|item| item.obligation_id == "OBL_CHI_EQ") - .unwrap(); - assert_eq!( - eq.evaluation_mode, - ObligationEvaluationMode::RecomputedExact - ); - assert!(eq.receipts.iter().any(|item| { - item.id == "CHI_EQ_INHERITANCE" - && item - .subreceipts - .iter() - .any(|sub| sub.id == "CHI_EQ_PROOF_TERM_TRANSPORT") - && item - .subreceipts - .iter() - .any(|sub| sub.id == "CHI_EQ_PROOF_TERM_NORMAL_FORM") - })); - } - - #[test] - #[serial] - fn seed_registry_exposes_chain_rule_adequacy_clauses() { - let registry = SeedRegistry::load().unwrap(); - let clauses = registry.adequacy_clauses(); - assert!( - clauses - .iter() - .any(|item| item.id == "ADQ_CHAIN_TOP_CALC_BRIDGE") - ); - assert!(clauses.iter().any(|item| item.id == "ADQ_CHAIN_CALC_EQ")); - assert!( - clauses - .iter() - .any(|item| item.id == "ADQ_BAYES_TOP_PROB_BRIDGE") - ); - assert!(clauses.iter().any(|item| item.id == "ADQ_BAYES_PROB_EQ")); - assert!( - clauses - .iter() - .any(|item| item.id == "ADQ_CH_TYP_SET_BRIDGE") - ); - assert!(clauses.iter().any(|item| item.id == "ADQ_CH_SET_EQ")); - assert!( - clauses - .iter() - .any(|item| item.id == "ADQ_EXEC_PROB_COMP_BRIDGE") - ); - assert!( - clauses - .iter() - .any(|item| item.id == "ADQ_JDG_PROB_LOG_BRIDGE") - ); - assert!( - clauses - .iter() - .any(|item| item.id == "ADQ_CERT_COMP_LOG_BRIDGE") - ); - assert!( - clauses - .iter() - .any(|item| item.id == "ADQ_CHI_TYP_ALG_BRIDGE") - ); - } - - #[test] - #[serial] - fn certification_reports_checker_receipts_for_active_campaign_objects() { - unsafe { - std::env::set_var( - "MF_CACHE_NAMESPACE", - test_namespace("seed_checker_receipts"), - ); - } - clear_cache(Some("all")).unwrap(); - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let report = certify_derived_campaign(®istry, &atlas, "CPG_EXEC_INFER").unwrap(); - assert!( - report - .checker_receipts - .iter() - .any(|item| item.kind == CheckerReceiptKind::TheoremSpec - && item.subject_id == "THS_EXEC_INFER") - ); - assert!( - report - .checker_receipts - .iter() - .any(|item| item.kind == CheckerReceiptKind::Campaign - && item.subject_id == "CPG_EXEC_INFER") - ); - assert!( - report - .checker_receipts - .iter() - .any(|item| item.kind == CheckerReceiptKind::AdequacyClause - && item.subject_id == "ADQ_EXEC_PROB_COMP_BRIDGE") - ); - assert!( - report - .checker_receipts - .iter() - .any(|item| item.kind == CheckerReceiptKind::ObligationVerdict - && item.subject_id == "OBL_EXEC_ADE") - ); - assert!( - report - .checker_receipts - .iter() - .all(|item| item.verdict == CertificationVerdict::Certified) - ); - } - - #[test] - #[serial] - fn cache_roundtrip_works() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("cache_roundtrip")); - } - clear_cache(Some("all")).unwrap(); - let registry = SeedRegistry::load().unwrap(); - let atlas = CompiledAtlas::compile(®istry).unwrap(); - let options = CertificationOptions { - bundle_hash: "test-bundle".into(), - policy_hash: "test-policy".into(), - ..CertificationOptions::default() - }; - let first = - certify_derived_campaign_with_options(®istry, &atlas, "CPG_CHAIN_RULE", &options) - .unwrap(); - let second = - certify_derived_campaign_with_options(®istry, &atlas, "CPG_CHAIN_RULE", &options) - .unwrap(); - assert_eq!(first.theorem_id, second.theorem_id); - assert!(matches!( - second - .execution_envelope - .as_ref() - .map(|item| &item.replay_status), - Some(ReplayStatus::CacheHit) | Some(ReplayStatus::Fresh) - )); - } - - #[test] - #[serial] - fn imported_overlay_bundle_certifies_directly() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("overlay_direct")); - } - let dir = std::env::temp_dir().join(format!( - "l64_cert_bundle_test_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let _ = fs::create_dir_all(&dir); - let file = dir.join("bundle.dna"); - write_bundle( - &file, - r#"!l64-bundle v1 -policy-object {"id":"MOP_BND_BUNDLE_TEST_SCHED","kind":"ReportExport","scope":{"Bundle":"BND_BUNDLE"},"extends":null,"optimizer":null,"evaluator":null,"replay_cache":null,"report":{"export_surfaces":[],"include_policy_trace":true,"include_route_explanation":true,"include_obligation_logs":true},"scheduler":{"parallelization":"ParallelIndependent","max_workers":2,"allow_parallel_replay":true,"allow_parallel_certification":true,"allow_parallel_exports":true,"deterministic_ordering":true,"allow_parallel_obligations":true,"max_obligation_workers":2,"allow_parallel_obligation_replay":true,"serialize_canonicalization_sensitive":true},"canonicalizer_mode":null,"merge_policy":null,"notes":["test scheduler"]} -proof {"id":"PS_T","kind":"Square","nodes":["a","b","c","d"],"edges":[{"from":"a","to":"b","label":"f"},{"from":"b","to":"d","label":"g"},{"from":"a","to":"c","label":"h"},{"from":"c","to":"d","label":"i"}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"} -bridge {"id":"B_T","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"} -atlas {"id":"A_T","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"General","proof_target":"test","candidate_paths":[["B_T"]],"normalized_winner":["B_T"],"winner_state":"Candidate","loss_profile":{"items":[]},"proof_shapes_checked":["PS_T"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}} -theorem {"id":"THS_T","statement":"test","hosts":["R_TOP","R_CALC"],"bridges":["B_T"],"operators":["OPR.T"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_T"]} -obligation {"id":"OBL_T","kind":"OblAdm","description":"adm","status":"Benchmarked"} -target {"id":"TGT_T","burden_class":"General","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]} -ledger {"id":"TRL_T","theorem":"THS_T","paths":[["B_T"]],"budget":{"max_loss":1,"allow_lossy_supported":false,"require_proof":true},"losses":[],"receipts":[],"normalized_path":["B_T"]} -campaign {"id":"CPG_T","theorem":"THS_T","target_profile":"TGT_T","route_ledger":"TRL_T","obligations":["OBL_T"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["test"]}"#, - ); - let world = - import_bundle_file(&file, None, l64_core::BundleConflictPolicy::Reject, None).unwrap(); - let atlas = CompiledAtlas::compile(&world.overlay).unwrap(); - let report = certify_derived_campaign_with_options( - &world.overlay, - &atlas, - "CPG_T", - &CertificationOptions { - bundle_hash: "bundle".into(), - policy_hash: "policy".into(), - bundle_id: Some(world.manifest.id.clone()), - no_cache: true, - ..CertificationOptions::default() - }, - ) - .unwrap(); - let _json = serde_json::to_string(&report).unwrap(); - assert_eq!(report.selected_atlas_cell.as_deref(), Some("A_T")); - } - - #[test] - #[serial] - fn imported_multi_campaign_bundle_serializes_reports() { - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", test_namespace("multi_bundle")); - } - let dir = std::env::temp_dir().join("l64_cert_bundle_test_multi"); - let _ = fs::create_dir_all(&dir); - let file = dir.join("bundle.dna"); - write_bundle( - &file, - r#"!l64-bundle v1 -policy-object {"id":"MOP_BND_PAR_SCHED","kind":"ReportExport","scope":{"Bundle":"BND_MULTI"},"extends":null,"optimizer":null,"evaluator":null,"replay_cache":null,"report":{"export_surfaces":[],"include_policy_trace":true,"include_route_explanation":true,"include_obligation_logs":true},"scheduler":{"parallelization":"ParallelIndependent","max_workers":2,"allow_parallel_replay":false,"allow_parallel_certification":true,"allow_parallel_exports":true,"deterministic_ordering":true,"allow_parallel_obligations":true,"max_obligation_workers":2,"allow_parallel_obligation_replay":false,"serialize_canonicalization_sensitive":true},"canonicalizer_mode":null,"merge_policy":null,"notes":["parallel scheduler policy"]} -proof {"id":"PS_PAR","kind":"Square","nodes":["a","b","c","d"],"edges":[{"from":"a","to":"b","label":"f"},{"from":"b","to":"d","label":"g"},{"from":"a","to":"c","label":"h"},{"from":"c","to":"d","label":"i"}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"} -bridge {"id":"B_PAR","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"} -atlas {"id":"A_PAR","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"General","proof_target":"parallel","candidate_paths":[["B_PAR"]],"normalized_winner":["B_PAR"],"winner_state":"Candidate","loss_profile":{"items":[]},"proof_shapes_checked":["PS_PAR"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}} -theorem {"id":"THS_PAR_A","statement":"parallel A","hosts":["R_TOP","R_CALC"],"bridges":["B_PAR"],"operators":["OPR.ParA"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_PAR"]} -theorem {"id":"THS_PAR_B","statement":"parallel B","hosts":["R_TOP","R_CALC"],"bridges":["B_PAR"],"operators":["OPR.ParB"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_PAR"]} -obligation {"id":"OBL_PAR","kind":"OblAdm","description":"adm","status":"Benchmarked"} -target {"id":"TGT_PAR","burden_class":"General","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]} -ledger {"id":"TRL_PAR_A","theorem":"THS_PAR_A","paths":[["B_PAR"]],"budget":{"max_loss":1,"allow_lossy_supported":false,"require_proof":true},"losses":[],"receipts":[],"normalized_path":["B_PAR"]} -ledger {"id":"TRL_PAR_B","theorem":"THS_PAR_B","paths":[["B_PAR"]],"budget":{"max_loss":1,"allow_lossy_supported":false,"require_proof":true},"losses":[],"receipts":[],"normalized_path":["B_PAR"]} -campaign {"id":"CPG_PAR_A","theorem":"THS_PAR_A","target_profile":"TGT_PAR","route_ledger":"TRL_PAR_A","obligations":["OBL_PAR"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["parallel"]} -campaign {"id":"CPG_PAR_B","theorem":"THS_PAR_B","target_profile":"TGT_PAR","route_ledger":"TRL_PAR_B","obligations":["OBL_PAR"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["parallel"]}"#, - ); - let world = - import_bundle_file(&file, None, l64_core::BundleConflictPolicy::Reject, None).unwrap(); - let atlas = CompiledAtlas::compile(&world.overlay).unwrap(); - let reports = ["CPG_PAR_A", "CPG_PAR_B"] - .iter() - .map(|id| { - certify_derived_campaign_with_options( - &world.overlay, - &atlas, - id, - &CertificationOptions { - bundle_hash: "bundle".into(), - policy_hash: "policy".into(), - bundle_id: Some(world.manifest.id.clone()), - no_cache: true, - ..CertificationOptions::default() - }, - ) - .unwrap() - }) - .collect::>(); - let _json = serde_json::to_string_pretty(&reports).unwrap(); - assert_eq!(reports.len(), 2); - } - - #[test] - #[serial] - fn imported_kernel_claim_bundle_computes_native_evidence_adequacy_and_checker_receipts() { - unsafe { - std::env::set_var( - "MF_CACHE_NAMESPACE", - test_namespace("imported_kernel_claim"), - ); - } - let dir = std::env::temp_dir().join(format!( - "l64_cert_kernel_claim_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let _ = fs::create_dir_all(&dir); - let file = dir.join("bundle.dna"); - write_bundle( - &file, - r#"!l64-bundle v1 -proof {"id":"PS_G1","kind":"Square","nodes":["a","b","c","d"],"edges":[{"from":"a","to":"b","label":"f"},{"from":"b","to":"d","label":"g"},{"from":"a","to":"c","label":"h"},{"from":"c","to":"d","label":"i"}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"} -bridge {"id":"B_G1","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"} -atlas {"id":"A_G1","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"ImportedKernelClaim","proof_target":"kernel-claim","candidate_paths":[["B_G1"]],"normalized_winner":["B_G1"],"winner_state":"Candidate","loss_profile":{"items":[]},"proof_shapes_checked":["PS_G1"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}} -theorem {"id":"THS_G1","statement":"imported kernel claim","hosts":["R_TOP","R_CALC"],"bridges":["B_G1"],"operators":["OPR.G1"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_G1"]} -obligation {"id":"OBL_G1","kind":"OblAdm","description":"imported admissibility","status":"Benchmarked"} -target {"id":"TGT_G1","burden_class":"ImportedKernelClaim","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"OpenBlocked","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]} -ledger {"id":"TRL_G1","theorem":"THS_G1","paths":[["B_G1"]],"budget":{"max_loss":1,"allow_lossy_supported":false,"require_proof":true},"losses":[],"receipts":["Trace_G1"],"normalized_path":["B_G1"]} -campaign {"id":"CPG_G1","theorem":"THS_G1","target_profile":"TGT_G1","route_ledger":"TRL_G1","obligations":["OBL_G1"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["kernel-claim"]} -burden-pack {"id":"BPK_G1","allowed_host_cluster":["R_TOP","R_CALC"],"obligation_ids":["OBL_G1"],"adequacy_clause_ids":["ADQ_G1_EVID","ADQ_G1_BENCH","ADQ_G1_STRESS","ADQ_G1_CHALLENGE"],"required_proof_shape_family":"Square","route_class_constraints":[],"evidence_contract_ids":["ECT_G1"],"promotion_ceiling":"Certified","blocker_taxonomy":["DEvidenceContract","DBenchmarkGap","DStressGap","DChallengeGap"]} -claim-packet {"id":"CLM_G1","claim_class":"Kernel","authority_state":"Evidence","target_sector":"kernel-claim","statement":"G1 imported claim","assumptions":["A1"],"open_caveats":[]} -evidence-contract {"id":"ECT_G1","required_evidence_kinds":["kernel-claim"],"required_benchmark_roles":["TargetCase","Stress"],"requires_stress":true,"requires_challenge":true,"admissibility_thresholds":["stable"],"promotion_ceiling":"Certified"} -benchmark-receipt {"id":"BMR_G1_TARGET","claim_packet_id":"CLM_G1","role":"TargetCase","verdict":"Certified","metrics":{"score":"1.0"},"reproducibility_ref":"RPK_G1"} -benchmark-receipt {"id":"BMR_G1_STRESS","claim_packet_id":"CLM_G1","role":"Stress","verdict":"Certified","metrics":{"stress":"pass"},"reproducibility_ref":"RPK_G1"} -challenge-receipt {"id":"CHR_G1","claim_packet_id":"CLM_G1","grounds":["baseline challenge"],"required_response":"addressed","status":"Addressed"} -reproducibility-packet {"id":"RPK_G1","claim_packet_id":"CLM_G1","derivation_path":["lab","bundle"],"code_refs":["src"],"benchmark_refs":["BMR_G1_TARGET","BMR_G1_STRESS"],"artifact_refs":["CLM_G1"]} -adequacy {"id":"ADQ_G1_EVID","kind":"EvidenceContractInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_G1"],"burden_pack_ids":["BPK_G1"],"claim_packet_ids":["CLM_G1"],"evidence_contract_ids":["ECT_G1"],"benchmark_receipt_ids":[],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_G1"],"description":"evidence contract present","blocking":true} -adequacy {"id":"ADQ_G1_BENCH","kind":"BenchmarkInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_G1"],"burden_pack_ids":["BPK_G1"],"claim_packet_ids":["CLM_G1"],"evidence_contract_ids":["ECT_G1"],"benchmark_receipt_ids":["BMR_G1_TARGET","BMR_G1_STRESS"],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_G1"],"description":"benchmark coverage present","blocking":true} -adequacy {"id":"ADQ_G1_STRESS","kind":"StressInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_G1"],"burden_pack_ids":["BPK_G1"],"claim_packet_ids":["CLM_G1"],"evidence_contract_ids":["ECT_G1"],"benchmark_receipt_ids":["BMR_G1_TARGET","BMR_G1_STRESS"],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_G1"],"description":"stress coverage present","blocking":true} -adequacy {"id":"ADQ_G1_CHALLENGE","kind":"ChallengeInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_G1"],"burden_pack_ids":["BPK_G1"],"claim_packet_ids":["CLM_G1"],"evidence_contract_ids":["ECT_G1"],"benchmark_receipt_ids":[],"challenge_receipt_ids":["CHR_G1"],"reproducibility_packet_ids":["RPK_G1"],"description":"challenge addressed","blocking":true}"#, - ); - let world = - import_bundle_file(&file, None, l64_core::BundleConflictPolicy::Reject, None).unwrap(); - let atlas = CompiledAtlas::compile(&world.overlay).unwrap(); - let report = certify_derived_campaign_with_options( - &world.overlay, - &atlas, - "CPG_G1", - &CertificationOptions { - bundle_hash: "bundle".into(), - policy_hash: "policy".into(), - bundle_id: Some(world.manifest.id.clone()), - no_cache: true, - ..CertificationOptions::default() - }, - ) - .unwrap(); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_G1_EVID" - && item.verdict == CertificationVerdict::Certified) - ); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_G1_STRESS" - && item.verdict == CertificationVerdict::Certified) - ); - assert!( - report - .checker_receipts - .iter() - .any(|item| item.kind == CheckerReceiptKind::BurdenPack - && item.subject_id == "BPK_G1") - ); - assert!(report.checker_receipts.iter().any(|item| item.kind - == CheckerReceiptKind::ClaimPacket - && item.subject_id == "CLM_G1")); - assert!(report.burden_pack_ids.iter().any(|item| item == "BPK_G1")); - assert!(report.claim_packet_ids.iter().any(|item| item == "CLM_G1")); - assert!( - report - .evidence_contract_ids - .iter() - .any(|item| item == "ECT_G1") - ); - assert!( - report - .benchmark_receipt_ids - .iter() - .any(|item| item == "BMR_G1_STRESS") - ); - assert!( - report - .challenge_receipt_ids - .iter() - .any(|item| item == "CHR_G1") - ); - assert!( - report - .reproducibility_packet_ids - .iter() - .any(|item| item == "RPK_G1") - ); - } - - #[test] - #[serial] - fn imported_kernel_claim_bundle_sharpens_missing_stress_gap() { - unsafe { - std::env::set_var( - "MF_CACHE_NAMESPACE", - test_namespace("imported_kernel_claim_gap"), - ); - } - let dir = std::env::temp_dir().join(format!( - "l64_cert_kernel_claim_gap_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let _ = fs::create_dir_all(&dir); - let file = dir.join("bundle.dna"); - write_bundle( - &file, - r#"!l64-bundle v1 -proof {"id":"PS_G2","kind":"Square","nodes":["a","b","c","d"],"edges":[{"from":"a","to":"b","label":"f"},{"from":"b","to":"d","label":"g"},{"from":"a","to":"c","label":"h"},{"from":"c","to":"d","label":"i"}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"} -bridge {"id":"B_G2","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"} -atlas {"id":"A_G2","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"ImportedKernelClaim","proof_target":"kernel-claim","candidate_paths":[["B_G2"]],"normalized_winner":["B_G2"],"winner_state":"Candidate","loss_profile":{"items":[]},"proof_shapes_checked":["PS_G2"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}} -theorem {"id":"THS_G2","statement":"imported kernel claim gap","hosts":["R_TOP","R_CALC"],"bridges":["B_G2"],"operators":["OPR.G2"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_G2"]} -obligation {"id":"OBL_G2","kind":"OblAdm","description":"imported admissibility","status":"Benchmarked"} -target {"id":"TGT_G2","burden_class":"ImportedKernelClaim","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"OpenBlocked","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]} -ledger {"id":"TRL_G2","theorem":"THS_G2","paths":[["B_G2"]],"budget":{"max_loss":1,"allow_lossy_supported":false,"require_proof":true},"losses":[],"receipts":["Trace_G2"],"normalized_path":["B_G2"]} -campaign {"id":"CPG_G2","theorem":"THS_G2","target_profile":"TGT_G2","route_ledger":"TRL_G2","obligations":["OBL_G2"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["kernel-claim"]} -burden-pack {"id":"BPK_G2","allowed_host_cluster":["R_TOP","R_CALC"],"obligation_ids":["OBL_G2"],"adequacy_clause_ids":["ADQ_G2_STRESS"],"required_proof_shape_family":"Square","route_class_constraints":[],"evidence_contract_ids":["ECT_G2"],"promotion_ceiling":"Certified","blocker_taxonomy":["DStressGap"]} -claim-packet {"id":"CLM_G2","claim_class":"Kernel","authority_state":"Evidence","target_sector":"kernel-claim","statement":"G2 imported claim","assumptions":["A1"],"open_caveats":[]} -evidence-contract {"id":"ECT_G2","required_evidence_kinds":["kernel-claim"],"required_benchmark_roles":["Stress"],"requires_stress":true,"requires_challenge":false,"admissibility_thresholds":["stable"],"promotion_ceiling":"Certified"} -benchmark-receipt {"id":"BMR_G2_TARGET","claim_packet_id":"CLM_G2","role":"TargetCase","verdict":"Certified","metrics":{"score":"1.0"},"reproducibility_ref":"RPK_G2"} -reproducibility-packet {"id":"RPK_G2","claim_packet_id":"CLM_G2","derivation_path":["lab","bundle"],"code_refs":["src"],"benchmark_refs":["BMR_G2_TARGET"],"artifact_refs":["CLM_G2"]} -adequacy {"id":"ADQ_G2_STRESS","kind":"StressInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_G2"],"burden_pack_ids":["BPK_G2"],"claim_packet_ids":["CLM_G2"],"evidence_contract_ids":["ECT_G2"],"benchmark_receipt_ids":["BMR_G2_TARGET"],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_G2"],"description":"stress coverage required","blocking":true}"#, - ); - let world = - import_bundle_file(&file, None, l64_core::BundleConflictPolicy::Reject, None).unwrap(); - let atlas = CompiledAtlas::compile(&world.overlay).unwrap(); - let report = certify_derived_campaign_with_options( - &world.overlay, - &atlas, - "CPG_G2", - &CertificationOptions { - bundle_hash: "bundle".into(), - policy_hash: "policy".into(), - bundle_id: Some(world.manifest.id.clone()), - no_cache: true, - ..CertificationOptions::default() - }, - ) - .unwrap(); - assert!( - report - .adequacy_records - .iter() - .any(|item| item.clause_id == "ADQ_G2_STRESS" - && item.verdict == CertificationVerdict::BlockedOpen) - ); - assert!( - report - .deficiencies - .iter() - .any(|item| item.class == l64_core::AtlasDeficiencyClass::DStressGap) - ); - } -} -#[derive(Debug, Clone, PartialEq, Eq)] -struct ChainRulePromotedOperatorContext { - id: String, - origin: ArtifactOrigin, -} diff --git a/l64-certification/Cargo.toml b/l64-certification/Cargo.toml new file mode 100644 index 0000000..05c5873 --- /dev/null +++ b/l64-certification/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "l64-certification" +edition.workspace = true +version.workspace = true +license.workspace = true + +[dependencies] +l64-native = { path = "../l64-native" } +l64-projection = { path = "../l64-projection" } diff --git a/l64-certification/README.md b/l64-certification/README.md new file mode 100644 index 0000000..3073b1a --- /dev/null +++ b/l64-certification/README.md @@ -0,0 +1,12 @@ +# l64-certification + +`l64-certification` is the current native structural-certification carrier. + +It certifies only facts already carried by canonical native authority: + +- an `L64D` frame decodes and re-encodes exactly; +- every native context yields a certification projection that verifies against that authority; +- each burden is directly classified as discharged, open, invalid, or missing evidence; +- an `L64B` frame is valid ordered transport whose members are certified independently. + +It does not create theorem registries, campaign records, cache keys, receipts, policy graphs, merged bundle worlds, or composite bundle authority. A compact state symbol is reported for diagnostics only; positive authority remains exact canonical DNA. diff --git a/l64-certification/src/lib.rs b/l64-certification/src/lib.rs new file mode 100644 index 0000000..844d0d2 --- /dev/null +++ b/l64-certification/src/lib.rs @@ -0,0 +1,243 @@ +#![forbid(unsafe_code)] + +use l64_native::{ContextId, DnaError, Graph, ROOT_CONTEXT, StateSymbol, decode_dna, dna_bytes}; +use l64_projection::{BurdenState, CertificationView, ProjectionError, ProjectionSet}; +use std::fmt::{self, Write as _}; + +pub const CERTIFICATION_VERSION: u16 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum CertificationVerdict { + Certified, + Open, + Incomplete, + Invalid, +} + +impl fmt::Display for CertificationVerdict { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Certified => "CERTIFIED", + Self::Open => "OPEN", + Self::Incomplete => "INCOMPLETE", + Self::Invalid => "INVALID", + }) + } +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BurdenCounts { + pub total: usize, + pub discharged: usize, + pub open: usize, + pub invalid: usize, + pub missing_evidence: usize, +} + +impl BurdenCounts { + fn from_view(view: &CertificationView) -> Self { + let mut counts = Self::default(); + for burden in &view.burdens { + counts.total += 1; + match burden.state { + BurdenState::Discharged => counts.discharged += 1, + BurdenState::Open => counts.open += 1, + BurdenState::Invalid => counts.invalid += 1, + BurdenState::MissingEvidence => counts.missing_evidence += 1, + } + } + counts + } + + pub fn verdict(self) -> CertificationVerdict { + if self.invalid != 0 { + CertificationVerdict::Invalid + } else if self.missing_evidence != 0 { + CertificationVerdict::Incomplete + } else if self.open != 0 { + CertificationVerdict::Open + } else { + CertificationVerdict::Certified + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ContextCertification { + pub context: ContextId, + pub projection_verified: bool, + pub burdens: BurdenCounts, + pub verdict: CertificationVerdict, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorityCertification { + pub symbol: StateSymbol, + pub node_count: usize, + pub context_count: usize, + pub journal_len: usize, + pub canonical_dna: bool, + pub contexts: Vec, + pub verdict: CertificationVerdict, +} + +impl AuthorityCertification { + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE CERTIFICATION v{CERTIFICATION_VERSION}"); + self.render_into(&mut out, ""); + out + } + + pub fn render_into(&self, out: &mut String, prefix: &str) { + let _ = writeln!(out, "{prefix}scope=native_structural_closure"); + let _ = writeln!(out, "{prefix}authority=exact_canonical_l64d"); + let _ = writeln!(out, "{prefix}canonical_dna={}", self.canonical_dna); + let _ = writeln!(out, "{prefix}symbol={}", self.symbol); + let _ = writeln!(out, "{prefix}symbol_authority=non_authoritative"); + let _ = writeln!(out, "{prefix}nodes={}", self.node_count); + let _ = writeln!(out, "{prefix}contexts={}", self.context_count); + let _ = writeln!(out, "{prefix}journal={}", self.journal_len); + let _ = writeln!(out, "{prefix}verdict={}", self.verdict); + for context in &self.contexts { + let context_prefix = format!("{prefix}context.{}.", context.context); + let _ = writeln!( + out, + "{context_prefix}projection_verified={}", + context.projection_verified + ); + let _ = writeln!(out, "{context_prefix}verdict={}", context.verdict); + let _ = writeln!(out, "{context_prefix}burdens={}", context.burdens.total); + let _ = writeln!( + out, + "{context_prefix}discharged={}", + context.burdens.discharged + ); + let _ = writeln!(out, "{context_prefix}open={}", context.burdens.open); + let _ = writeln!(out, "{context_prefix}invalid={}", context.burdens.invalid); + let _ = writeln!( + out, + "{context_prefix}missing_evidence={}", + context.burdens.missing_evidence + ); + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CertificationError { + Dna(DnaError), + NonCanonicalDna, + Projection { + context: ContextId, + error: ProjectionError, + }, +} + +impl fmt::Display for CertificationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Dna(error) => write!(f, "DNA certification failed: {error}"), + Self::NonCanonicalDna => f.write_str("certification requires canonical L64D authority"), + Self::Projection { context, error } => write!( + f, + "certification projection failed in context {context}: {error}" + ), + } + } +} + +impl std::error::Error for CertificationError {} + +pub fn certify_dna(bytes: &[u8]) -> Result { + let graph = decode_dna(bytes).map_err(CertificationError::Dna)?; + let canonical = dna_bytes(&graph).map_err(CertificationError::Dna)?; + if canonical != bytes { + return Err(CertificationError::NonCanonicalDna); + } + certify_graph(&graph) +} + +pub fn certify_graph(graph: &Graph) -> Result { + certify_graph_from_fresh_root(graph, None) +} + +pub fn certify_graph_with_root_projection( + graph: &Graph, + research_limit: usize, +) -> Result<(AuthorityCertification, ProjectionSet), CertificationError> { + // The root projection is derived inside the certification boundary. No retained or external + // projection can enter this path without a complete fresh derivation from exact authority. + let projection = + ProjectionSet::derive(graph, ROOT_CONTEXT, research_limit).map_err(|error| { + CertificationError::Projection { + context: ROOT_CONTEXT, + error, + } + })?; + let certification = certify_graph_from_fresh_root(graph, Some(&projection.certification))?; + Ok((certification, projection)) +} + +fn certify_graph_from_fresh_root( + graph: &Graph, + root: Option<&CertificationView>, +) -> Result { + let mut contexts = Vec::with_capacity(graph.context_count()); + for context in 0..graph.context_count() as ContextId { + // Fresh in-process derivation is graph-bound by construction. Retained or external + // certification projections must still cross `CertificationView::verify` before reuse. + let derived; + let view = if context == ROOT_CONTEXT { + if let Some(root) = root { + root + } else { + derived = CertificationView::derive(graph, context) + .map_err(|error| CertificationError::Projection { context, error })?; + &derived + } + } else { + derived = CertificationView::derive(graph, context) + .map_err(|error| CertificationError::Projection { context, error })?; + &derived + }; + let burdens = BurdenCounts::from_view(view); + contexts.push(ContextCertification { + context, + projection_verified: true, + verdict: burdens.verdict(), + burdens, + }); + } + let verdict = authority_verdict(&contexts); + Ok(AuthorityCertification { + symbol: graph.state_symbol(), + node_count: graph.node_count(), + context_count: graph.context_count(), + journal_len: graph.journal_len(), + canonical_dna: true, + contexts, + verdict, + }) +} + +fn authority_verdict(contexts: &[ContextCertification]) -> CertificationVerdict { + if contexts + .iter() + .any(|context| context.verdict == CertificationVerdict::Invalid) + { + CertificationVerdict::Invalid + } else if contexts + .iter() + .any(|context| context.verdict == CertificationVerdict::Incomplete) + { + CertificationVerdict::Incomplete + } else if contexts + .iter() + .any(|context| context.verdict == CertificationVerdict::Open) + { + CertificationVerdict::Open + } else { + CertificationVerdict::Certified + } +} diff --git a/l64-certification/tests/architecture.rs b/l64-certification/tests/architecture.rs new file mode 100644 index 0000000..001db54 --- /dev/null +++ b/l64-certification/tests/architecture.rs @@ -0,0 +1,55 @@ +use std::{fs, path::Path}; + +#[test] +fn certification_depends_only_on_current_native_carriers() { + let manifest = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml")) + .expect("read certification manifest"); + let dependency_block = manifest + .split_once("[dependencies]") + .map(|(_, tail)| tail) + .expect("dependency block"); + let dependencies = dependency_block + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .collect::>(); + assert_eq!( + dependencies, + vec![ + "l64-native = { path = \"../l64-native\" }", + "l64-projection = { path = \"../l64-projection\" }", + ] + ); +} + +#[test] +fn certification_source_contains_no_schema_forest() { + let source = fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("lib.rs"), + ) + .expect("read certification source"); + for forbidden in [ + "serde", + "bincode", + "HashMap", + "std::fs", + "thread", + "Mutex", + "RwLock", + "cache", + "Registry", + "BundleWorld", + "Policy", + "Campaign", + "Receipt", + "digest", + "blake3", + ] { + assert!( + !source.contains(forbidden), + "native certification source contains forbidden token {forbidden}" + ); + } +} diff --git a/l64-certification/tests/certification.rs b/l64-certification/tests/certification.rs new file mode 100644 index 0000000..7e78cdb --- /dev/null +++ b/l64-certification/tests/certification.rs @@ -0,0 +1,100 @@ +use l64_certification::{ + CertificationError, CertificationVerdict, certify_dna, certify_graph, + certify_graph_with_root_projection, +}; +use l64_native::{ + ConstraintKind, Dimension, Graph, LocusWord, Proposal, ROOT_CONTEXT, Route, dna_bytes, + rna_to_dna, +}; + +const CERTIFIED_RNA: &[u8] = b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n"; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x4345525449465931)).composed(LocusWord(index)) +} + +fn open_graph() -> (Graph, u32) { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let quantity = graph + .declare_quantity_type(route(2), scalar, Dimension::new([0, 0, 0, 0, 0, 0, 0])) + .unwrap(); + let subject = graph + .insert_value(route(3), ROOT_CONTEXT, quantity) + .unwrap(); + graph + .transact(Proposal::square_root( + route(4), + ROOT_CONTEXT, + subject, + quantity, + )) + .unwrap(); + (graph, subject) +} + +#[test] +fn canonical_native_authority_certifies_from_direct_burdens() { + let dna = rna_to_dna(CERTIFIED_RNA).unwrap(); + let certification = certify_dna(&dna).unwrap(); + assert!(certification.canonical_dna); + assert_eq!(certification.verdict, CertificationVerdict::Certified); + assert_eq!(certification.contexts.len(), 1); + assert!(certification.contexts[0].projection_verified); + assert_eq!(certification.contexts[0].burdens.discharged, 1); + assert!( + certification + .render_text() + .contains("authority=exact_canonical_l64d") + ); +} + +#[test] +fn open_native_burden_remains_open() { + let (graph, _) = open_graph(); + let certification = certify_dna(&dna_bytes(&graph).unwrap()).unwrap(); + assert_eq!(certification.verdict, CertificationVerdict::Open); + assert_eq!(certification.contexts[0].burdens.open, 1); +} + +#[test] +fn invalid_child_context_invalidates_the_authority_certification() { + let (mut graph, subject) = open_graph(); + let cause = graph + .declare_constraint( + route(5), + ROOT_CONTEXT, + subject, + ConstraintKind::NonNegative, + false, + ) + .unwrap(); + let child = graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let certification = certify_dna(&dna_bytes(&graph).unwrap()).unwrap(); + assert_eq!(certification.context_count, 2); + assert_eq!(certification.verdict, CertificationVerdict::Invalid); + assert_eq!( + certification.contexts[child as usize].verdict, + CertificationVerdict::Invalid + ); +} + +#[test] +fn trailing_dna_bytes_are_rejected() { + let mut dna = rna_to_dna(CERTIFIED_RNA).unwrap(); + dna.push(0); + assert!(matches!(certify_dna(&dna), Err(CertificationError::Dna(_)))); +} + +#[test] +fn shared_fresh_root_projection_matches_direct_certification_exactly() { + let graph = l64_native::decode_dna(&rna_to_dna(CERTIFIED_RNA).unwrap()).unwrap(); + let direct = certify_graph(&graph).unwrap(); + let (shared, projection) = certify_graph_with_root_projection(&graph, 16).unwrap(); + assert_eq!(shared, direct); + assert_eq!(projection.certification.source.context, ROOT_CONTEXT); + assert_eq!( + shared.contexts[0].burdens.total, + projection.certification.burdens.len() + ); +} diff --git a/l64-change/Cargo.toml b/l64-change/Cargo.toml new file mode 100644 index 0000000..09fbd75 --- /dev/null +++ b/l64-change/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "l64-change" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +l64-native = { path = "../l64-native" } +l64-transport = { path = "../l64-transport" } +l64-certification = { path = "../l64-certification" } +l64-observation = { path = "../l64-observation" } diff --git a/l64-change/README.md b/l64-change/README.md new file mode 100644 index 0000000..3443132 --- /dev/null +++ b/l64-change/README.md @@ -0,0 +1,7 @@ +# l64-change + +Direct comparison over current Locus64 authority. + +`compare_dna` compares two exact canonical `L64D` authorities and reports structural section movement, count movement, certification movement, and verified per-context projection movement. `compare_bundle` compares ordered `L64B` members independently by transport index. + +The crate persists nothing and creates no diff authority, prediction, plan, cache, policy graph, campaign, registry, receipt, or composite bundle verdict. diff --git a/l64-change/src/lib.rs b/l64-change/src/lib.rs new file mode 100644 index 0000000..b4beb69 --- /dev/null +++ b/l64-change/src/lib.rs @@ -0,0 +1,348 @@ +#![forbid(unsafe_code)] + +use l64_certification::{BurdenCounts, CertificationVerdict}; +use l64_native::{DnaError, StateSymbol}; +use l64_observation::{AuthorityObservation, ObservationError, observe_dna}; +use l64_transport::{BundleError, decode_bundle}; +use std::fmt::{self, Write as _}; + +pub const CHANGE_VERSION: u16 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ContactChange { + Unchanged, + Changed, + Added, + Removed, +} + +impl ContactChange { + fn label(self) -> &'static str { + match self { + Self::Unchanged => "UNCHANGED", + Self::Changed => "CHANGED", + Self::Added => "ADDED", + Self::Removed => "REMOVED", + } + } +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SectionChanges { + pub nodes: bool, + pub ports: bool, + pub contexts: bool, + pub routes: bool, +} + +impl SectionChanges { + fn between(before: StateSymbol, after: StateSymbol) -> Self { + let [nodes, ports, contexts, routes] = before.changed_sections(after); + Self { + nodes, + ports, + contexts, + routes, + } + } + + pub fn any(self) -> bool { + self.nodes || self.ports || self.contexts || self.routes + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CountMovement { + pub before: usize, + pub after: usize, +} + +impl CountMovement { + pub fn delta(self) -> i128 { + self.after as i128 - self.before as i128 + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ContextChange { + pub context: usize, + pub contact: ContactChange, + pub before_verdict: Option, + pub after_verdict: Option, + pub before_burdens: Option, + pub after_burdens: Option, + pub closed: CountMovement, + pub open: CountMovement, + pub invalid: CountMovement, + pub replay_steps: CountMovement, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorityChange { + pub exact_equal: bool, + pub before_symbol: StateSymbol, + pub after_symbol: StateSymbol, + pub sections: SectionChanges, + pub nodes: CountMovement, + pub contexts: CountMovement, + pub journal: CountMovement, + pub before_verdict: CertificationVerdict, + pub after_verdict: CertificationVerdict, + pub context_changes: Vec, +} + +impl AuthorityChange { + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE AUTHORITY CHANGE v{CHANGE_VERSION}"); + self.render_into(&mut out, ""); + out + } + + pub fn render_into(&self, out: &mut String, prefix: &str) { + render_authority(out, self, prefix); + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BundleMemberChange { + pub index: usize, + pub contact: ContactChange, + pub authority: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BundleChange { + pub before_members: usize, + pub after_members: usize, + pub members: Vec, +} + +impl BundleChange { + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE BUNDLE CHANGE v{CHANGE_VERSION}"); + let _ = writeln!(out, "transport=canonical_l64b"); + let _ = writeln!(out, "ordering=transport_sequence"); + let _ = writeln!(out, "before_members={}", self.before_members); + let _ = writeln!(out, "after_members={}", self.after_members); + let _ = writeln!(out, "composite_authority=none"); + let _ = writeln!(out, "composite_change_verdict=none"); + for member in &self.members { + let prefix = format!("member.{}.", member.index); + let _ = writeln!(out, "{prefix}contact={}", member.contact.label()); + if let Some(authority) = &member.authority { + render_authority(&mut out, authority, &prefix); + } + } + out + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ChangeError { + Dna(DnaError), + Observation(ObservationError), + Bundle(BundleError), +} + +impl fmt::Display for ChangeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Dna(error) => write!(f, "DNA comparison failed: {error}"), + Self::Observation(error) => write!(f, "authority comparison failed: {error}"), + Self::Bundle(error) => write!(f, "bundle comparison failed: {error}"), + } + } +} + +impl std::error::Error for ChangeError {} + +pub fn compare_dna(before: &[u8], after: &[u8]) -> Result { + let before_observation = observe_dna(before).map_err(ChangeError::Observation)?; + let after_observation = observe_dna(after).map_err(ChangeError::Observation)?; + Ok(compare_observations( + before == after, + &before_observation, + &after_observation, + )) +} + +pub fn compare_bundle(before: &[u8], after: &[u8]) -> Result { + let before_bundle = decode_bundle(before).map_err(ChangeError::Bundle)?; + let after_bundle = decode_bundle(after).map_err(ChangeError::Bundle)?; + let width = before_bundle.len().max(after_bundle.len()); + let mut members = Vec::with_capacity(width); + for index in 0..width { + let before_member = before_bundle.members().get(index); + let after_member = after_bundle.members().get(index); + let (contact, authority) = match (before_member, after_member) { + (Some(before_member), Some(after_member)) => { + let before_observation = + observe_dna(before_member.dna()).map_err(ChangeError::Observation)?; + let after_observation = + observe_dna(after_member.dna()).map_err(ChangeError::Observation)?; + let authority = compare_observations( + before_member.dna() == after_member.dna(), + &before_observation, + &after_observation, + ); + let contact = if authority.exact_equal { + ContactChange::Unchanged + } else { + ContactChange::Changed + }; + (contact, Some(authority)) + } + (None, Some(_)) => (ContactChange::Added, None), + (Some(_), None) => (ContactChange::Removed, None), + (None, None) => unreachable!(), + }; + members.push(BundleMemberChange { + index, + contact, + authority, + }); + } + Ok(BundleChange { + before_members: before_bundle.len(), + after_members: after_bundle.len(), + members, + }) +} + +fn compare_observations( + exact_equal: bool, + before: &AuthorityObservation, + after: &AuthorityObservation, +) -> AuthorityChange { + let width = before.contexts.len().max(after.contexts.len()); + let mut context_changes = Vec::with_capacity(width); + for context in 0..width { + let before_context = before.contexts.get(context); + let after_context = after.contexts.get(context); + let contact = match (before_context, after_context) { + (Some(left), Some(right)) if left == right => ContactChange::Unchanged, + (Some(_), Some(_)) => ContactChange::Changed, + (None, Some(_)) => ContactChange::Added, + (Some(_), None) => ContactChange::Removed, + (None, None) => unreachable!(), + }; + context_changes.push(ContextChange { + context, + contact, + before_verdict: before_context.map(|item| item.certification.verdict), + after_verdict: after_context.map(|item| item.certification.verdict), + before_burdens: before_context.map(|item| item.certification.burdens), + after_burdens: after_context.map(|item| item.certification.burdens), + closed: movement( + before_context.map_or(0, |item| item.report.closed), + after_context.map_or(0, |item| item.report.closed), + ), + open: movement( + before_context.map_or(0, |item| item.report.open), + after_context.map_or(0, |item| item.report.open), + ), + invalid: movement( + before_context.map_or(0, |item| item.report.invalid), + after_context.map_or(0, |item| item.report.invalid), + ), + replay_steps: movement( + before_context.map_or(0, |item| item.replay.steps.len()), + after_context.map_or(0, |item| item.replay.steps.len()), + ), + }); + } + let before_certification = &before.certification; + let after_certification = &after.certification; + AuthorityChange { + exact_equal, + before_symbol: before_certification.symbol, + after_symbol: after_certification.symbol, + sections: SectionChanges::between(before_certification.symbol, after_certification.symbol), + nodes: movement( + before_certification.node_count, + after_certification.node_count, + ), + contexts: movement( + before_certification.context_count, + after_certification.context_count, + ), + journal: movement( + before_certification.journal_len, + after_certification.journal_len, + ), + before_verdict: before_certification.verdict, + after_verdict: after_certification.verdict, + context_changes, + } +} + +fn movement(before: usize, after: usize) -> CountMovement { + CountMovement { before, after } +} + +fn render_authority(out: &mut String, change: &AuthorityChange, prefix: &str) { + let _ = writeln!(out, "{prefix}scope=exact_native_authority_change"); + let _ = writeln!(out, "{prefix}before_authority=exact_canonical_l64d"); + let _ = writeln!(out, "{prefix}after_authority=exact_canonical_l64d"); + let _ = writeln!(out, "{prefix}exact_equal={}", change.exact_equal); + let _ = writeln!(out, "{prefix}symbol_authority=non_authoritative"); + let _ = writeln!(out, "{prefix}before_symbol={}", change.before_symbol); + let _ = writeln!(out, "{prefix}after_symbol={}", change.after_symbol); + let _ = writeln!( + out, + "{prefix}section.nodes.changed={}", + change.sections.nodes + ); + let _ = writeln!( + out, + "{prefix}section.ports.changed={}", + change.sections.ports + ); + let _ = writeln!( + out, + "{prefix}section.contexts.changed={}", + change.sections.contexts + ); + let _ = writeln!( + out, + "{prefix}section.routes.changed={}", + change.sections.routes + ); + render_movement(out, prefix, "nodes", change.nodes); + render_movement(out, prefix, "contexts", change.contexts); + render_movement(out, prefix, "journal", change.journal); + let _ = writeln!(out, "{prefix}before_verdict={}", change.before_verdict); + let _ = writeln!(out, "{prefix}after_verdict={}", change.after_verdict); + for context in &change.context_changes { + let context_prefix = format!("{prefix}context.{}.", context.context); + let _ = writeln!(out, "{context_prefix}contact={}", context.contact.label()); + let _ = writeln!( + out, + "{context_prefix}before_verdict={}", + optional_verdict(context.before_verdict) + ); + let _ = writeln!( + out, + "{context_prefix}after_verdict={}", + optional_verdict(context.after_verdict) + ); + render_movement(out, &context_prefix, "closed", context.closed); + render_movement(out, &context_prefix, "open", context.open); + render_movement(out, &context_prefix, "invalid", context.invalid); + render_movement(out, &context_prefix, "replay_steps", context.replay_steps); + } +} + +fn render_movement(out: &mut String, prefix: &str, label: &str, value: CountMovement) { + let _ = writeln!(out, "{prefix}{label}.before={}", value.before); + let _ = writeln!(out, "{prefix}{label}.after={}", value.after); + let _ = writeln!(out, "{prefix}{label}.delta={:+}", value.delta()); +} + +fn optional_verdict(value: Option) -> String { + value + .map(|verdict| verdict.to_string()) + .unwrap_or_else(|| "NONE".to_string()) +} diff --git a/l64-change/tests/architecture.rs b/l64-change/tests/architecture.rs new file mode 100644 index 0000000..e6e7c16 --- /dev/null +++ b/l64-change/tests/architecture.rs @@ -0,0 +1,106 @@ +use std::{fs, path::Path}; + +#[test] +fn change_depends_only_on_current_native_carriers() { + let manifest = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml")) + .expect("read change manifest"); + let dependency_block = manifest + .split_once("[dependencies]") + .map(|(_, tail)| tail) + .expect("dependency block"); + let dependencies = dependency_block + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .collect::>(); + assert_eq!( + dependencies, + vec![ + "l64-native = { path = \"../l64-native\" }", + "l64-transport = { path = \"../l64-transport\" }", + "l64-certification = { path = \"../l64-certification\" }", + "l64-observation = { path = \"../l64-observation\" }", + ] + ); +} + +#[test] +fn change_source_contains_no_schema_forest() { + let source = fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("lib.rs"), + ) + .expect("read change source"); + for forbidden in [ + "serde", + "bincode", + "serde_json", + "std::fs", + "HashMap", + "thread", + "Mutex", + "RwLock", + "cache", + "Registry", + "BundleWorld", + "Policy", + "Campaign", + "Receipt", + "Prediction", + "PlanRecompute", + "digest", + "blake3", + ] { + assert!( + !source.contains(forbidden), + "native change source contains forbidden token {forbidden}" + ); + } +} + +#[test] +fn retired_legacy_authority_island_is_absent() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("workspace root"); + for deleted in [ + "l64-core", + "l64-locus", + "l64-research", + "l64-kernel", + "l64-command", + "l64-registry", + "l64-selector", + "l64-runtime", + "l64-canon", + "l64-atlas", + "l64-cert", + "l64-testkit", + ] { + assert!( + !root.join(deleted).exists(), + "legacy crate {deleted} still exists" + ); + } + + let membrane = fs::read_to_string(root.join("l64-cli/src/native_membrane.rs")) + .expect("read native membrane"); + for command in [ + "run-theorem", + "research-status", + "tower-step", + "replay-report", + ] { + assert!( + membrane.contains(&format!("\"{command}\"")), + "retired authority command {command} is not rejected by the membrane" + ); + } + assert!(membrane.contains("permanently deleted after historical export")); + + let wrapper = + fs::read_to_string(root.join("l64/src/main.rs")).expect("read wrapper entry point"); + assert!(wrapper.contains("legacy theorem/campaign/research/registry/tower execution island")); + assert!(!wrapper.contains("REMOVED_ADMIN_COMMANDS")); +} diff --git a/l64-change/tests/change.rs b/l64-change/tests/change.rs new file mode 100644 index 0000000..05b717b --- /dev/null +++ b/l64-change/tests/change.rs @@ -0,0 +1,112 @@ +use l64_certification::CertificationVerdict; +use l64_change::{ContactChange, compare_bundle, compare_dna}; +use l64_native::{ + ConstraintKind, Dimension, Graph, LocusWord, Proposal, ROOT_CONTEXT, Route, dna_bytes, + rna_to_dna, +}; +use l64_transport::bundle_bytes; + +const CERTIFIED_RNA: &[u8] = b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n"; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x4348414e47453031)).composed(LocusWord(index)) +} + +fn open_graph() -> (Graph, u32) { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let quantity = graph + .declare_quantity_type(route(2), scalar, Dimension::new([0, 0, 0, 0, 0, 0, 0])) + .unwrap(); + let subject = graph + .insert_value(route(3), ROOT_CONTEXT, quantity) + .unwrap(); + graph + .transact(Proposal::square_root( + route(4), + ROOT_CONTEXT, + subject, + quantity, + )) + .unwrap(); + (graph, subject) +} + +#[test] +fn identical_dna_is_exactly_unchanged() { + let dna = rna_to_dna(CERTIFIED_RNA).unwrap(); + let change = compare_dna(&dna, &dna).unwrap(); + assert!(change.exact_equal); + assert!(!change.sections.any()); + assert_eq!(change.before_verdict, CertificationVerdict::Certified); + assert_eq!(change.after_verdict, CertificationVerdict::Certified); + assert!( + change + .context_changes + .iter() + .all(|context| context.contact == ContactChange::Unchanged) + ); +} + +#[test] +fn structural_and_verdict_movement_is_directly_visible() { + let before = rna_to_dna(CERTIFIED_RNA).unwrap(); + let (open, _) = open_graph(); + let after = dna_bytes(&open).unwrap(); + let change = compare_dna(&before, &after).unwrap(); + assert!(!change.exact_equal); + assert!(change.sections.any()); + assert_eq!(change.before_verdict, CertificationVerdict::Certified); + assert_eq!(change.after_verdict, CertificationVerdict::Open); + assert!(change.nodes.delta() != 0); + let rendered = change.render_text(); + assert!(rendered.contains("scope=exact_native_authority_change")); + assert!(rendered.contains("after_verdict=OPEN")); + assert!(!rendered.contains("prediction_id")); +} + +#[test] +fn invalid_child_context_appears_as_context_movement() { + let (mut before_graph, subject) = open_graph(); + let before = dna_bytes(&before_graph).unwrap(); + let cause = before_graph + .declare_constraint( + route(5), + ROOT_CONTEXT, + subject, + ConstraintKind::NonNegative, + false, + ) + .unwrap(); + let child = before_graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let after = dna_bytes(&before_graph).unwrap(); + let change = compare_dna(&before, &after).unwrap(); + assert_eq!(change.after_verdict, CertificationVerdict::Invalid); + assert_eq!( + change.context_changes[child as usize].contact, + ContactChange::Added + ); + assert_eq!( + change.context_changes[child as usize].after_verdict, + Some(CertificationVerdict::Invalid) + ); +} + +#[test] +fn bundle_members_remain_independent_change_contacts() { + let certified = rna_to_dna(CERTIFIED_RNA).unwrap(); + let (open, _) = open_graph(); + let open = dna_bytes(&open).unwrap(); + let before = bundle_bytes(&[&certified, &certified]).unwrap(); + let after = bundle_bytes(&[&certified, &open, &certified]).unwrap(); + let change = compare_bundle(&before, &after).unwrap(); + assert_eq!(change.before_members, 2); + assert_eq!(change.after_members, 3); + assert_eq!(change.members[0].contact, ContactChange::Unchanged); + assert_eq!(change.members[1].contact, ContactChange::Changed); + assert_eq!(change.members[2].contact, ContactChange::Added); + let rendered = change.render_text(); + assert!(rendered.contains("composite_authority=none")); + assert!(rendered.contains("composite_change_verdict=none")); + assert!(!rendered.contains("bundle_prediction=")); +} diff --git a/l64-cli/Cargo.toml b/l64-cli/Cargo.toml index 6e1a8f1..db5e3c5 100644 --- a/l64-cli/Cargo.toml +++ b/l64-cli/Cargo.toml @@ -1,27 +1,20 @@ [package] name = "l64-cli" -version = "0.1.0" -edition = "2024" +version.workspace = true +edition.workspace = true +license.workspace = true +autobins = false -[dependencies] -anyhow = { workspace = true } -clap = { workspace = true } -l64-core = { path = "../l64-core" } -l64-locus = { path = "../l64-locus" } -l64-research = { path = "../l64-research" } -l64-kernel = { path = "../l64-kernel" } -l64-command = { path = "../l64-command" } -l64-registry = { path = "../l64-registry" } -l64-selector = { path = "../l64-selector" } -l64-runtime = { path = "../l64-runtime" } -l64-canon = { path = "../l64-canon" } -l64-atlas = { path = "../l64-atlas" } -l64-cert = { path = "../l64-cert" } -l64-bundle = { path = "../l64-bundle" } -l64-policy = { path = "../l64-policy" } -serde_json = { workspace = true } -bincode = { workspace = true } -hex = { workspace = true } +[[bin]] +name = "l64-cli" +path = "src/native_main.rs" -[dev-dependencies] -assert_cmd = "2.0" +[dependencies] +l64-native = { path = "../l64-native" } +l64-projection = { path = "../l64-projection" } +l64-release = { path = "../l64-release" } +l64-execution = { path = "../l64-execution" } +l64-transport = { path = "../l64-transport" } +l64-certification = { path = "../l64-certification" } +l64-observation = { path = "../l64-observation" } +l64-change = { path = "../l64-change" } diff --git a/l64-cli/src/golden_tests.rs b/l64-cli/src/golden_tests.rs new file mode 100644 index 0000000..c590003 --- /dev/null +++ b/l64-cli/src/golden_tests.rs @@ -0,0 +1,280 @@ +use super::{ProcessStatus, dispatch}; +use std::{ + ffi::OsString, + fs, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, +}; + +static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); + +struct Case { + name: &'static str, + status: ProcessStatus, +} + +const CASES: &[Case] = &[ + Case { + name: "certified_triangle", + status: ProcessStatus::Success, + }, + Case { + name: "equality_chain", + status: ProcessStatus::Success, + }, + Case { + name: "open_obligation", + status: ProcessStatus::Open, + }, + Case { + name: "invalid_child_context", + status: ProcessStatus::Invalid, + }, + Case { + name: "matrix_multiply", + status: ProcessStatus::Success, + }, +]; + +fn corpus() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("samples") + .join("golden") +} + +fn fixture(name: &str) -> PathBuf { + corpus().join(format!("{name}.rna")) +} + +fn expected(name: &str) -> Vec { + fs::read(corpus().join("expected").join(name)).unwrap() +} + +fn temp_root(label: &str) -> PathBuf { + let serial = NEXT_TEMP.fetch_add(1, Ordering::Relaxed); + let root = std::env::temp_dir().join(format!( + "l64 golden π {label} {} {serial}", + std::process::id() + )); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + root +} + +fn run(args: Vec) -> (ProcessStatus, Vec) { + let mut output = Vec::new(); + let status = dispatch(&args, &mut output).unwrap(); + (status, output) +} + +fn command(command: &str, path: &Path) -> Vec { + vec![ + OsString::from("l64-cli"), + OsString::from(command), + path.as_os_str().to_owned(), + ] +} + +fn command_out(command: &str, input: &Path, out: &Path) -> Vec { + vec![ + OsString::from("l64-cli"), + OsString::from(command), + input.as_os_str().to_owned(), + OsString::from("--out"), + out.as_os_str().to_owned(), + ] +} + +fn hex(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2 + 1); + for byte in bytes { + use std::fmt::Write as _; + write!(out, "{byte:02x}").unwrap(); + } + out.push('\n'); + out +} + +#[test] +fn golden_portability_authority_snapshots_are_exact() { + let root = temp_root("authority snapshots"); + for case in CASES { + let rna = fixture(case.name); + let dna = root.join(format!("{}.dna", case.name)); + + let (run_status, run_output) = run(command("run-rna", &rna)); + assert_eq!(run_status, case.status, "{} run status", case.name); + assert_eq!( + run_output, + expected(&format!("{}.run.txt", case.name)), + "{} run snapshot", + case.name + ); + + let (normalize_status, normalized) = run(command("normalize-rna", &rna)); + assert_eq!(normalize_status, ProcessStatus::Success); + assert_eq!( + normalized, + expected(&format!("{}.normalized.rna", case.name)), + "{} normalized RNA", + case.name + ); + + let (compile_status, _) = run(command_out("compile-rna", &rna, &dna)); + assert_eq!(compile_status, ProcessStatus::Success); + assert_eq!( + hex(&fs::read(&dna).unwrap()).as_bytes(), + expected(&format!("{}.dna.hex", case.name)), + "{} canonical DNA", + case.name + ); + + let (sequence_status, sequenced) = run(command("sequence-dna", &dna)); + assert_eq!(sequence_status, ProcessStatus::Success); + assert_eq!(sequenced, normalized, "{} RNA/DNA fixed point", case.name); + + let (certify_status, certification) = run(command("certify-dna", &dna)); + assert_eq!( + certify_status, case.status, + "{} certification status", + case.name + ); + assert_eq!( + certification, + expected(&format!("{}.certify.txt", case.name)), + "{} certification snapshot", + case.name + ); + } + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn golden_portability_crlf_and_unicode_paths_preserve_authority() { + let root = temp_root("CRLF and Unicode"); + for case in CASES { + let source = fs::read(fixture(case.name)).unwrap(); + let crlf = String::from_utf8(source) + .unwrap() + .replace("\n", "\r\n") + .into_bytes(); + let crlf_rna = root.join(format!("{} portable source.rna", case.name)); + let crlf_dna = root.join(format!("{} portable authority.dna", case.name)); + fs::write(&crlf_rna, crlf).unwrap(); + + let (_, normalized) = run(command("normalize-rna", &crlf_rna)); + assert_eq!( + normalized, + expected(&format!("{}.normalized.rna", case.name)), + "{} CRLF normalization", + case.name + ); + let _ = run(command_out("compile-rna", &crlf_rna, &crlf_dna)); + assert_eq!( + hex(&fs::read(&crlf_dna).unwrap()).as_bytes(), + expected(&format!("{}.dna.hex", case.name)), + "{} CRLF canonical DNA", + case.name + ); + } + fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn golden_portability_product_journey_is_exact() { + let root = temp_root("product journey"); + let triangle = root.join("triangle authority.dna"); + let equality = root.join("equality authority.dna"); + let open = root.join("open authority.dna"); + let bundle = root.join("mixed ordered transport.l64b"); + let release = root.join("triangle native release"); + + for (name, out) in [ + ("certified_triangle", &triangle), + ("equality_chain", &equality), + ("open_obligation", &open), + ] { + let _ = run(command_out("compile-rna", &fixture(name), out)); + } + + let (compare_status, compare) = run(vec![ + OsString::from("l64-cli"), + OsString::from("compare-dna"), + triangle.as_os_str().to_owned(), + equality.as_os_str().to_owned(), + ]); + assert_eq!(compare_status, ProcessStatus::Success); + assert_eq!(compare, expected("triangle_to_equality.compare.txt")); + + let (bundle_status, _) = run(vec![ + OsString::from("l64-cli"), + OsString::from("compile-bundle"), + triangle.as_os_str().to_owned(), + open.as_os_str().to_owned(), + OsString::from("--out"), + bundle.as_os_str().to_owned(), + ]); + assert_eq!(bundle_status, ProcessStatus::Success); + + for (command_name, snapshot) in [ + ("run-bundle", "mixed_bundle.run.txt"), + ("certify-bundle", "mixed_bundle.certify.txt"), + ("observe-bundle", "mixed_bundle.observe.txt"), + ] { + let (status, output) = run(vec![ + OsString::from("l64-cli"), + OsString::from(command_name), + OsString::from("--file"), + bundle.as_os_str().to_owned(), + ]); + assert_eq!(status, ProcessStatus::Open, "{command_name} status"); + assert_eq!(output, expected(snapshot), "{command_name} snapshot"); + } + + let (release_status, _) = run(vec![ + OsString::from("l64-cli"), + OsString::from("export-genome-release"), + OsString::from("--rna"), + fixture("certified_triangle").into_os_string(), + OsString::from("--out"), + release.as_os_str().to_owned(), + ]); + assert_eq!(release_status, ProcessStatus::Success); + assert_eq!( + fs::read(release.join("source.rna")).unwrap(), + expected("certified_triangle.normalized.rna") + ); + assert_eq!( + hex(&fs::read(release.join("authority.dna")).unwrap()).as_bytes(), + expected("triangle.release.authority.dna.hex") + ); + assert_eq!( + fs::read(release.join("projection.txt")).unwrap(), + expected("triangle.release.projection.txt") + ); + assert_eq!( + fs::read(release.join("release.record")).unwrap(), + expected("triangle.release.record") + ); + + let mut names = fs::read_dir(&release) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect::>(); + names.sort(); + assert_eq!( + names, + [ + "authority.dna", + "projection.txt", + "release.record", + "source.rna" + ] + .into_iter() + .map(OsString::from) + .collect::>() + ); + + fs::remove_dir_all(root).unwrap(); +} diff --git a/l64-cli/src/main.rs b/l64-cli/src/main.rs deleted file mode 100644 index d843b1f..0000000 --- a/l64-cli/src/main.rs +++ /dev/null @@ -1,1908 +0,0 @@ -use anyhow::{Context, Result, anyhow}; -use clap::{Parser, Subcommand}; -use l64_atlas::{CompiledAtlas, run_seed_theorem}; -use l64_bundle::{ - BundleWorld, bundle_document_from_entry_text, import_bundle_file, load_bundle_world, -}; -use l64_canon::CanonEngine; -use l64_cert::{ - CertificationOptions, build_vertical_compounding_bundle, cache_stats as cert_cache_stats, - certify_derived_campaign_with_options, certify_derived_theorem_with_options, - clear_cache as clear_cert_cache, decode_locus_packet_summary, derive_distress_vector, - derive_help_request, dispatch_proof_coverage, encode_locus_packet_for_report, - explain_invalidation as cert_explain_invalidation, load_report_document_with_registry, - persist_report_document, replay_report as cert_replay_report, - report_to_validation_bundle_with_registry, -}; -use l64_command::{BundlePolicyArg, OptimizerPolicyArg}; -use l64_core::{ - Budget, BundleConflictPolicy, Canonicalize, GenomeArtifactClass, GenomeSurface, - LocusCapabilityMask, LocusDecodeMode, LocusOpcode, LocusPacketKind, OptimizerPolicy, - QaDocument, QaEntry, RegistryLookup, ResearchLineageRecord, SelectRoute, cache_hash_v1_bytes, - cache_hash_v1_str, decode_locus_packet_with_mode, document_for_registry_id, - locus_packet_summary, -}; -use l64_kernel::ConstitutionKernel; -use l64_locus::{ - GenomeReleaseManifest, compile_rna_to_dna_packet, load_bundle_lock, load_execution_manifest, - sequence_dna_to_canonical_rna, sequence_dna_to_rna, verify_rna_dna_roundtrip, -}; -use l64_registry::SeedRegistry; -use l64_research::{ - derive_governed_complete_research_bundle_from_report, - derive_governed_promotion_readiness_from_report, list_benchmark_run_records, - list_benchmark_schemas, list_challenge_records, list_coverage_dispatches, - list_derivation_signatures, list_framework_registry_entries, list_handoff_packets, - list_lineage_records, list_math_claim_packets, list_operator_records, list_producer_host_specs, - list_projection_map_records, list_promotion_queue_entries, list_promotion_readiness_reports, - list_reduction_map_records, list_remediation_entries, list_reproducibility_packets, - list_review_receipts, list_route_assignments, list_strengthening_artifacts, - list_task_envelopes, list_vertical_bundles, load_benchmark_run_record, load_benchmark_schema, - load_challenge_record, load_coverage_dispatch, load_derivation_signature, - load_framework_registry_entry, load_handoff_packet, load_lineage_record, - load_math_claim_packet, load_operator_record, load_producer_host_spec, - load_projection_map_record, load_promotion_queue_entry, load_promotion_readiness_report, - load_reduction_map_record, load_remediation_entry, load_reproducibility_packet, - load_review_receipt, load_route_assignment, load_strengthening_artifact, load_task_envelope, - load_vertical_bundle, persist_benchmark_run_record, persist_benchmark_schema, - persist_challenge_record, persist_coverage_dispatch, persist_derivation_signature, - persist_framework_registry_entry, persist_handoff_packet, persist_lineage_record, - persist_math_claim_packet, persist_operator_record, persist_producer_host_spec, - persist_projection_map_record, persist_promotion_queue_entry, - persist_promotion_readiness_report, persist_reduction_map_record, - persist_reproducibility_packet, persist_research_import, persist_review_receipt, - persist_route_assignment, persist_seeded_export_remediation_entries, - persist_strengthening_artifact, persist_task_envelope, persist_vertical_bundle, - research_status_summary, score_routes_governed, summarize_remediation_entries, -}; -use l64_runtime::{RuntimeWorld, exec_host}; -use l64_selector::{AtlasSelector, CampaignCertifier}; -use std::{fs, path::Path}; - -#[derive(Debug, Parser)] -#[command(name = "l64-cli")] -#[command(about = "Mathematical framework constitution kernel CLI")] -struct Cli { - #[command(subcommand)] - command: Command, -} - -#[derive(Debug, Clone, Copy, clap::ValueEnum)] -enum ResearchKindArg { - Task, - Signature, - Review, - Challenge, - Registry, - Operator, - Benchmark, - BenchmarkRun, - Claim, - Reduction, - Projection, - Handoff, - ProducerHost, - Promotion, - PromotionReport, - RouteAssignment, - Strengthening, - Repro, - Remediation, - Coverage, - Tower, - Lineage, -} - -impl ResearchKindArg { - fn as_str(self) -> &'static str { - match self { - ResearchKindArg::Task => "task", - ResearchKindArg::Signature => "signature", - ResearchKindArg::Review => "review", - ResearchKindArg::Challenge => "challenge", - ResearchKindArg::Registry => "registry", - ResearchKindArg::Operator => "operator", - ResearchKindArg::Benchmark => "benchmark", - ResearchKindArg::BenchmarkRun => "benchmark-run", - ResearchKindArg::Claim => "claim", - ResearchKindArg::Reduction => "reduction", - ResearchKindArg::Projection => "projection", - ResearchKindArg::Handoff => "handoff", - ResearchKindArg::ProducerHost => "producer-host", - ResearchKindArg::Promotion => "promotion", - ResearchKindArg::PromotionReport => "promotion-report", - ResearchKindArg::RouteAssignment => "route-assignment", - ResearchKindArg::Strengthening => "strengthening", - ResearchKindArg::Repro => "repro", - ResearchKindArg::Remediation => "remediation", - ResearchKindArg::Coverage => "coverage", - ResearchKindArg::Tower => "tower", - ResearchKindArg::Lineage => "lineage", - } - } -} - -#[derive(Debug, Subcommand)] -enum Command { - ImportBundle { - file: String, - #[arg(long, value_enum, default_value = "reject")] - conflict_policy: BundlePolicyArg, - #[arg(long)] - namespace: Option, - }, - ReplayReport { - report_id: String, - }, - CacheStats, - ClearCache { - #[arg(long)] - scope: Option, - }, - ExplainInvalidation { - report_id: String, - #[arg(long, default_value = "seed")] - bundle_hash: String, - #[arg(long, default_value = "default")] - policy_hash: String, - }, - DumpBundleGraph { - bundle_id: String, - }, - DumpOverlayWorld { - bundle_id: String, - }, - SelectRoute { - #[arg(long)] - src: String, - #[arg(long)] - tgt: String, - #[arg(long)] - proof_target: Option, - #[arg(long, default_value_t = 8)] - max_loss: usize, - #[arg(long, default_value_t = true)] - allow_lossy_supported: bool, - #[arg(long, default_value_t = false)] - require_proof: bool, - }, - Certify { - #[arg(long)] - campaign: Option, - #[arg(long)] - theorem: Option, - #[arg(long)] - target_profile: Option, - #[arg(long)] - file: Option, - }, - CertifyDerived { - #[arg(long)] - campaign: Option, - #[arg(long)] - theorem: Option, - #[arg(long)] - target_profile: Option, - #[arg(long)] - file: Option, - #[arg(long)] - bundle: Option, - #[arg(long, default_value_t = false)] - overlay_only: bool, - #[arg(long, value_enum, default_value = "conservative")] - optimizer_policy: OptimizerPolicyArg, - #[arg(long)] - surface_policy: Option, - #[arg(long, default_value_t = false)] - strict_surface: bool, - #[arg(long, default_value_t = false)] - strict_derived: bool, - #[arg(long, default_value_t = false)] - replay_only: bool, - #[arg(long, default_value_t = false)] - no_cache: bool, - #[arg(long)] - evaluator_policy: Option, - #[arg(long)] - cache_policy: Option, - #[arg(long, default_value_t = false)] - strict_policy: bool, - }, - RunBundle { - #[arg(long)] - file: String, - #[arg(long, default_value_t = false)] - overlay_only: bool, - #[arg(long, default_value_t = false)] - explain_route: bool, - #[arg(long, value_enum, default_value = "conservative")] - optimizer_policy: OptimizerPolicyArg, - #[arg(long, default_value_t = false)] - replay_only: bool, - #[arg(long, default_value_t = false)] - no_cache: bool, - #[arg(long)] - evaluator_policy: Option, - #[arg(long)] - cache_policy: Option, - #[arg(long, default_value_t = false)] - strict_policy: bool, - #[arg(long, value_enum, default_value = "reject")] - conflict_policy: BundlePolicyArg, - }, - CertifyBundle { - #[arg(long)] - file: String, - #[arg(long, default_value_t = false)] - overlay_only: bool, - #[arg(long, default_value_t = false)] - explain_route: bool, - #[arg(long, value_enum, default_value = "conservative")] - optimizer_policy: OptimizerPolicyArg, - #[arg(long, default_value_t = false)] - strict_derived: bool, - #[arg(long, default_value_t = false)] - replay_only: bool, - #[arg(long, default_value_t = false)] - no_cache: bool, - #[arg(long)] - evaluator_policy: Option, - #[arg(long)] - cache_policy: Option, - #[arg(long, default_value_t = false)] - strict_policy: bool, - #[arg(long, value_enum, default_value = "reject")] - conflict_policy: BundlePolicyArg, - #[arg(long, default_value_t = false)] - strict_surface: bool, - }, - ExportValidationDnaBundle { - #[arg(long)] - id: String, - #[arg(long)] - out: Option, - }, - CompileAtlas, - Canonize { - object_id: String, - }, - ExecHost { - #[arg(long)] - regime: String, - #[arg(long)] - object: Option, - }, - RunTheorem { - #[arg(long)] - id: Option, - #[arg(long)] - file: Option, - #[arg(long)] - bundle: Option, - #[arg(long, default_value_t = false)] - overlay_only: bool, - #[arg(long, default_value_t = false)] - explain_route: bool, - #[arg(long, value_enum, default_value = "conservative")] - optimizer_policy: OptimizerPolicyArg, - #[arg(long)] - surface_policy: Option, - #[arg(long, default_value_t = false)] - strict_surface: bool, - #[arg(long, default_value_t = false)] - replay_only: bool, - #[arg(long, default_value_t = false)] - no_cache: bool, - }, - DumpCanonical { - id: String, - }, - ExportReportDna { - #[arg(long)] - report_id: String, - #[arg(long)] - out: Option, - }, - ImportReportDna { - file: String, - }, - NormalizeRna { - file: String, - }, - CompileRna { - file: String, - #[arg(long)] - out: Option, - #[arg(long, default_value = "gene")] - artifact_class: String, - #[arg(long, default_value_t = false)] - persist_lineage: bool, - }, - CompileBundle { - file: String, - #[arg(long)] - out: Option, - }, - SequenceDna { - file: String, - }, - InspectDna { - file: String, - }, - VerifyRoundtrip { - file: String, - #[arg(long, default_value = "gene")] - artifact_class: String, - }, - ExportGenomeRelease { - #[arg(long)] - rna: String, - #[arg(long)] - out: String, - #[arg(long, default_value = "gene")] - artifact_class: String, - }, - DeriveFrontier { - #[arg(long)] - report_id: String, - }, - TowerStep { - #[arg(long)] - report_id: String, - }, - DispatchCoverage { - #[arg(long)] - report_id: String, - }, - DeriveDistress { - #[arg(long)] - report_id: String, - }, - ResearchImport { - #[arg(long, value_enum)] - kind: ResearchKindArg, - file: String, - }, - ResearchExport { - #[arg(long, value_enum)] - kind: ResearchKindArg, - id: String, - }, - ResearchList { - #[arg(long, value_enum)] - kind: ResearchKindArg, - }, - ResearchRoute { - #[arg(long)] - task_id: String, - #[arg(long)] - signature_id: String, - }, - ResearchDeriveFromReport { - #[arg(long)] - report_id: String, - #[arg(long, default_value_t = false)] - persist: bool, - }, - ResearchGovernReport { - #[arg(long)] - report_id: String, - #[arg(long, default_value_t = false)] - persist: bool, - }, - ResearchSeedExportRemediation { - #[arg(long, default_value_t = false)] - persist: bool, - }, - ResearchRemediationSummary, - ResearchStatus, - ResearchPromotionReadiness { - report_id: String, - }, -} - -fn main() -> Result<()> { - std::thread::Builder::new() - .name("l64-cli-main".into()) - .stack_size(32 * 1024 * 1024) - .spawn(real_main) - .map_err(|err| anyhow!("failed to start l64-cli main thread: {err}"))? - .join() - .map_err(|_| anyhow!("l64-cli main thread panicked"))? -} - -fn real_main() -> Result<()> { - let cli = Cli::parse(); - let registry = SeedRegistry::load().context("failed to load seed registry")?; - let kernel = ConstitutionKernel; - - match cli.command { - Command::ImportBundle { - file, - conflict_policy, - namespace, - } => { - let world = import_bundle_file( - Path::new(&file), - None, - conflict_policy.into(), - namespace.as_deref(), - )?; - println!("{}", serde_json::to_string_pretty(&world.manifest)?); - } - Command::ReplayReport { report_id } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&report)?); - } - Command::CacheStats => { - let stats = cert_cache_stats().map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&stats)?); - } - Command::ClearCache { scope } => { - clear_cert_cache(scope.as_deref()).map_err(anyhow::Error::msg)?; - println!("cache cleared"); - } - Command::ExplainInvalidation { - report_id, - bundle_hash, - policy_hash, - } => { - let explanation = cert_explain_invalidation(&report_id, &bundle_hash, &policy_hash) - .map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&explanation)?); - } - Command::DumpBundleGraph { bundle_id } => { - let world = load_bundle_world(&bundle_id)?; - println!( - "{}", - serde_json::to_string_pretty(&world.manifest.dependencies)? - ); - } - Command::DumpOverlayWorld { bundle_id } => { - let world = load_bundle_world(&bundle_id)?; - println!("{}", serde_json::to_string_pretty(&world.manifest.overlay)?); - } - Command::SelectRoute { - src, - tgt, - proof_target, - max_loss, - allow_lossy_supported, - require_proof, - } => { - let selector = AtlasSelector::new(registry.clone()); - let selection = selector - .select_route( - &src, - &tgt, - proof_target.as_deref(), - Some(&Budget { - max_loss, - allow_lossy_supported, - require_proof, - }), - ) - .map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&selection)?); - } - Command::Certify { - campaign, - theorem, - target_profile, - file, - } => { - let certifier = CampaignCertifier::new(registry.clone()); - let (campaign, theorem, target_profile) = resolve_surface_cert_args_registry( - ®istry, - campaign, - theorem, - target_profile, - file, - )?; - let report = match (campaign.as_deref(), theorem.as_deref(), target_profile.as_deref()) { - (Some(campaign_id), _, _) => certifier.certify_campaign(campaign_id), - (None, Some(theorem_id), Some(target_id)) => { - certifier.certify_theorem_with_target(theorem_id, target_id, None) - } - _ => Err("use either --campaign , --file , or --theorem --target-profile ".into()), - } - .map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&report)?); - } - Command::CertifyDerived { - campaign, - theorem, - target_profile, - file, - bundle, - overlay_only, - optimizer_policy, - surface_policy: _surface_policy, - strict_surface, - strict_derived, - replay_only, - no_cache, - evaluator_policy, - cache_policy, - strict_policy, - } => { - let options = build_cert_options( - optimizer_policy.into(), - file.as_deref(), - bundle.as_deref(), - replay_only, - no_cache, - strict_derived, - evaluator_policy, - cache_policy, - strict_policy, - )?; - let report = if let Some(bundle_id) = bundle { - let world = load_bundle_world(&bundle_id)?; - certify_with_registry( - &world.overlay, - campaign.or_else(|| { - world - .overlay - .local - .campaigns - .first() - .map(|item| item.id.clone()) - }), - theorem.or_else(|| { - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.clone()) - }), - target_profile.or_else(|| { - world - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.clone()) - }), - None, - overlay_only, - &options, - )? - } else if let Some(file) = file { - let world = import_bundle_file( - Path::new(&file), - None, - BundleConflictPolicy::ExactMatch, - None, - )?; - let mut file_options = options.clone(); - file_options.bundle_id = Some(world.manifest.id.clone()); - certify_with_registry( - &world.overlay, - campaign.or_else(|| { - world - .overlay - .local - .campaigns - .first() - .map(|item| item.id.clone()) - }), - theorem.or_else(|| { - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.clone()) - }), - target_profile.or_else(|| { - world - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.clone()) - }), - None, - overlay_only, - &file_options, - )? - } else { - certify_with_registry( - ®istry, - campaign, - theorem, - target_profile, - None, - false, - &options, - )? - }; - if strict_surface && !report.diagnostics.is_empty() { - return Err(anyhow!( - "strict-surface rejected certification due to diagnostics" - )); - } - persist_report_document(&report)?; - println!("{}", serde_json::to_string_pretty(&report)?); - } - Command::RunBundle { - file, - overlay_only, - explain_route, - optimizer_policy, - replay_only, - no_cache, - evaluator_policy, - cache_policy, - strict_policy, - conflict_policy, - } => { - let world = import_bundle_file(Path::new(&file), None, conflict_policy.into(), None)?; - let mut options = build_cert_options( - optimizer_policy.into(), - Some(&file), - None, - replay_only, - no_cache, - false, - evaluator_policy, - cache_policy, - strict_policy, - )?; - options.bundle_id = Some(world.manifest.id.clone()); - let result = run_bundle_world(&world, overlay_only, &options)?; - if explain_route { - eprintln!("route explanation requested for bundle execution"); - } - println!("{}", serde_json::to_string_pretty(&result)?); - } - Command::CertifyBundle { - file, - overlay_only, - explain_route, - optimizer_policy, - strict_derived, - replay_only, - no_cache, - evaluator_policy, - cache_policy, - strict_policy, - conflict_policy, - strict_surface, - } => { - let world = import_bundle_file(Path::new(&file), None, conflict_policy.into(), None)?; - let mut options = build_cert_options( - optimizer_policy.into(), - Some(&file), - None, - replay_only, - no_cache, - strict_derived, - evaluator_policy, - cache_policy, - strict_policy, - )?; - options.bundle_id = Some(world.manifest.id.clone()); - let reports = certify_bundle_world(&world, overlay_only, &options)?; - if strict_surface && reports.iter().any(|report| !report.diagnostics.is_empty()) { - return Err(anyhow!( - "strict-surface rejected certify-bundle due to diagnostics" - )); - } - for report in &reports { - persist_report_document(report)?; - } - if explain_route { - eprintln!("route explanation requested for certify-bundle"); - } - println!("{}", serde_json::to_string_pretty(&reports)?); - } - Command::ExportValidationDnaBundle { id, out } => { - let registry = SeedRegistry::load()?; - let document = validation_bundle_document(&id, ®istry)?; - let bytes = l64_locus::encode_section_packet( - LocusPacketKind::CanonicalTransfer, - LocusOpcode::CanonicalPayload, - &id, - "bundle_document.v1", - &document, - LocusCapabilityMask::default(), - 2, - ) - .map_err(anyhow::Error::msg)?; - let out_path = out.unwrap_or_else(|| format!("{id}.validation.dna")); - fs::write(&out_path, &bytes) - .with_context(|| format!("failed to write `{out_path}`"))?; - let packet = decode_locus_packet_with_mode(&bytes, LocusDecodeMode::CurrentAuthority) - .map_err(anyhow::Error::msg)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "report_id": id, - "out": out_path, - "bytes": bytes.len(), - "entry_count": document.entries.len(), - "summary": locus_packet_summary(&packet) - }))? - ); - } - Command::CompileAtlas => { - let atlas = CompiledAtlas::compile(®istry).map_err(anyhow::Error::msg)?; - let summary = atlas.compile_summary(); - let encoded = bincode::serialize(&summary)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "summary": summary, - "binary_cache_bytes": encoded.len() - }))? - ); - } - Command::Canonize { object_id } => { - let mut canon = CanonEngine::compile(®istry); - let runtime = RuntimeWorld::compile_seed(®istry); - let object = runtime - .lookup_object(&object_id) - .ok_or_else(|| anyhow!("unknown runtime object `{object_id}`"))?; - let canonical = canon.canonicalize(object).map_err(anyhow::Error::msg)?; - let eq_class = canon.eq_class(object).map_err(anyhow::Error::msg)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "object_id": object_id, - "runtime_object_id": object.0, - "canonical_id": canonical, - "eq_class_id": eq_class - }))? - ); - } - Command::ExecHost { regime, object } => { - let result = exec_host(®ime, object.as_deref()).map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&result)?); - } - Command::RunTheorem { - id, - file, - bundle, - overlay_only, - explain_route, - optimizer_policy, - surface_policy: _surface_policy, - strict_surface, - replay_only, - no_cache, - } => { - let options = build_cert_options( - optimizer_policy.into(), - file.as_deref(), - bundle.as_deref(), - replay_only, - no_cache, - false, - None, - None, - false, - )?; - let result = if let Some(bundle_id) = bundle { - let world = load_bundle_world(&bundle_id)?; - let theorem_id = id.unwrap_or_else(|| { - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.clone()) - .unwrap_or_default() - }); - if overlay_only { - let local = world.overlay.local_only(); - let atlas = CompiledAtlas::compile(&local).map_err(anyhow::Error::msg)?; - run_seed_theorem(&local, &theorem_id, &atlas).map_err(anyhow::Error::msg)? - } else { - let atlas = - CompiledAtlas::compile(&world.overlay).map_err(anyhow::Error::msg)?; - run_seed_theorem(&world.overlay, &theorem_id, &atlas) - .map_err(anyhow::Error::msg)? - } - } else if let Some(file) = file { - let world = import_bundle_file( - Path::new(&file), - None, - BundleConflictPolicy::ExactMatch, - None, - )?; - let theorem_id = id.unwrap_or_else(|| { - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.clone()) - .unwrap_or_default() - }); - if overlay_only { - let local = world.overlay.local_only(); - let atlas = CompiledAtlas::compile(&local).map_err(anyhow::Error::msg)?; - run_seed_theorem(&local, &theorem_id, &atlas).map_err(anyhow::Error::msg)? - } else { - let atlas = - CompiledAtlas::compile(&world.overlay).map_err(anyhow::Error::msg)?; - run_seed_theorem(&world.overlay, &theorem_id, &atlas) - .map_err(anyhow::Error::msg)? - } - } else { - let theorem_id = id.ok_or_else(|| { - anyhow!( - "use either --id , --file , or --bundle " - ) - })?; - let atlas = CompiledAtlas::compile(®istry).map_err(anyhow::Error::msg)?; - run_seed_theorem(®istry, &theorem_id, &atlas).map_err(anyhow::Error::msg)? - }; - if strict_surface && result.selected_route.is_empty() { - return Err(anyhow!("strict-surface rejected empty surfaced route")); - } - if explain_route { - eprintln!("optimizer policy: {:?}", options.optimizer_policy); - } - println!("{}", serde_json::to_string_pretty(&result)?); - } - Command::ExportReportDna { report_id, out } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - let bytes = encode_locus_packet_for_report(&report).map_err(anyhow::Error::msg)?; - if let Some(path) = out { - fs::write(&path, &bytes).with_context(|| format!("failed to write `{path}`"))?; - let packet = - decode_locus_packet_with_mode(&bytes, LocusDecodeMode::CurrentAuthority) - .map_err(anyhow::Error::msg)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "report_id": report_id, - "bytes": bytes.len(), - "summary": locus_packet_summary(&packet) - }))? - ); - } else { - println!("{}", hex::encode(bytes)); - } - } - Command::ImportReportDna { file } => { - let bytes = fs::read(&file).with_context(|| format!("failed to read `{file}`"))?; - let summary = decode_locus_packet_summary(&bytes).map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&summary)?); - } - Command::NormalizeRna { file } => { - let input = - fs::read_to_string(&file).with_context(|| format!("failed to read `{file}`"))?; - let (normalized, receipt) = - l64_core::normalize_rna(&input).map_err(anyhow::Error::msg)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "normalized": normalized, - "receipt": receipt - }))? - ); - } - Command::CompileRna { - file, - out, - artifact_class, - persist_lineage, - } => { - let input = - fs::read_to_string(&file).with_context(|| format!("failed to read `{file}`"))?; - let artifact_class = parse_genome_artifact_class(&artifact_class)?; - let subject_id = Path::new(&file) - .file_stem() - .and_then(|item| item.to_str()) - .unwrap_or("RNA_ARTIFACT"); - let (bytes, artifact) = - compile_rna_to_dna_packet(subject_id, &input, artifact_class, vec!["core".into()]) - .map_err(anyhow::Error::msg)?; - if let Some(path) = out { - fs::write(&path, &bytes).with_context(|| format!("failed to write `{path}`"))?; - } - let packet = decode_locus_packet_with_mode(&bytes, LocusDecodeMode::CurrentAuthority) - .map_err(anyhow::Error::msg)?; - let lineage_id = format!("LIN_{}", subject_id); - let lineage = ResearchLineageRecord { - id: lineage_id.clone(), - subject_id: subject_id.into(), - artifact_class, - source_surface: GenomeSurface::Rna, - target_surface: GenomeSurface::Dna, - grammar_id: packet.header.grammar_id.clone(), - canonical_hash: artifact.lowering_receipt.canonical_hash.clone(), - lowering_receipt_id: artifact.lowering_receipt.id.clone(), - phase_ids: artifact - .phase_ledger - .iter() - .map(|entry| entry.phase_id) - .collect(), - phase_ledger: artifact.phase_ledger.clone(), - notes: vec![ - format!("root_subject_id={}", packet.header.root_subject_id), - format!("integrity_hash={}", packet.header.integrity_hash), - ], - }; - if persist_lineage { - persist_lineage_record(&lineage)?; - } - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "bytes": bytes.len(), - "packet_summary": locus_packet_summary(&packet), - "artifact": artifact, - "lineage": lineage, - "persisted_lineage": persist_lineage - }))? - ); - } - Command::CompileBundle { file, out } => { - let subject_id = Path::new(&file) - .file_stem() - .and_then(|item| item.to_str()) - .unwrap_or("BUNDLE_ARTIFACT"); - let document = if Path::new(&file).extension().and_then(|ext| ext.to_str()) - == Some("dna") - { - let bytes = fs::read(&file).with_context(|| format!("failed to read `{file}`"))?; - l64_locus::decode_section_payload::( - &bytes, - LocusOpcode::CanonicalPayload, - ) - .map_err(anyhow::Error::msg)? - } else { - let text = fs::read_to_string(&file) - .with_context(|| format!("failed to read `{file}`"))?; - bundle_document_from_entry_text(&text)? - }; - let bytes = l64_locus::encode_section_packet( - LocusPacketKind::CanonicalTransfer, - LocusOpcode::CanonicalPayload, - subject_id, - "bundle_document.v1", - &document, - LocusCapabilityMask::default(), - 1, - ) - .map_err(anyhow::Error::msg)?; - let out_path = out.unwrap_or_else(|| { - Path::new(&file) - .with_extension("dna") - .to_string_lossy() - .into_owned() - }); - fs::write(&out_path, &bytes) - .with_context(|| format!("failed to write `{out_path}`"))?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "out": out_path, - "bytes": bytes.len(), - "entries": document.entries.len() - }))? - ); - } - Command::SequenceDna { file } => { - let bytes = fs::read(&file).with_context(|| format!("failed to read `{file}`"))?; - let canonical_rna = - sequence_dna_to_canonical_rna(&bytes).map_err(anyhow::Error::msg)?; - println!("{canonical_rna}"); - } - Command::InspectDna { file } => { - let bytes = fs::read(&file).with_context(|| format!("failed to read `{file}`"))?; - let artifact = sequence_dna_to_rna(&bytes).map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&artifact)?); - } - Command::VerifyRoundtrip { - file, - artifact_class, - } => { - let input = - fs::read_to_string(&file).with_context(|| format!("failed to read `{file}`"))?; - let artifact_class = parse_genome_artifact_class(&artifact_class)?; - let subject_id = Path::new(&file) - .file_stem() - .and_then(|item| item.to_str()) - .unwrap_or("RNA_ARTIFACT"); - let report = - verify_rna_dna_roundtrip(subject_id, &input, artifact_class, vec!["core".into()]) - .map_err(anyhow::Error::msg)?; - if !report.dna_bytes_equal || !report.canonical_hash_equal { - anyhow::bail!("RNA/DNA roundtrip failed to preserve canonical identity"); - } - println!("{}", serde_json::to_string_pretty(&report)?); - } - Command::ExportGenomeRelease { - rna, - out, - artifact_class, - } => { - let artifact_class = parse_genome_artifact_class(&artifact_class)?; - let manifest = - export_genome_release_from_rna(Path::new(&rna), Path::new(&out), artifact_class)?; - println!("{}", serde_json::to_string_pretty(&manifest)?); - } - Command::DeriveFrontier { report_id } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - let bundle = build_vertical_compounding_bundle(®istry, &report); - println!("{}", serde_json::to_string_pretty(&bundle)?); - } - Command::TowerStep { report_id } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - let bundle = build_vertical_compounding_bundle(®istry, &report); - let bytes = encode_locus_packet_for_report(&report).map_err(anyhow::Error::msg)?; - let summary = decode_locus_packet_summary(&bytes).map_err(anyhow::Error::msg)?; - let coverage = dispatch_proof_coverage(&report); - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "frontier": bundle.frontier_ledger, - "generated_counts": { - "semantic_leaves": bundle.semantic_leaves.len(), - "adequacy_clauses": bundle.adequacy_clauses.len(), - "checker_extensions": bundle.checker_extensions.len(), - "campaigns": bundle.campaigns.len(), - "atlas_cells": bundle.atlas_cells.len(), - "payoff_tasks": bundle.payoff_tasks.len(), - "compartments": bundle.compartments.len(), - "help_requests": bundle.help_requests.len(), - "recipes": bundle.recipes.len(), - "promotion_candidates": bundle.promotion_candidates.len() - }, - "distress": bundle.distress, - "help_requests": bundle.help_requests, - "calibration_pressure": bundle.calibration_pressure, - "coverage_dispatch": coverage, - "packet_summary": summary - }))? - ); - } - Command::DispatchCoverage { report_id } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - let dispatch = dispatch_proof_coverage(&report); - println!("{}", serde_json::to_string_pretty(&dispatch)?); - } - Command::DeriveDistress { report_id } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - let bundle = build_vertical_compounding_bundle(®istry, &report); - let distress = derive_distress_vector(&report, &bundle); - let help_request = derive_help_request(&report, &distress); - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "distress": distress, - "help_request": help_request, - "frontier": bundle.frontier_ledger - }))? - ); - } - Command::ResearchImport { kind, file } => { - let id = persist_research_import(kind.as_str(), Path::new(&file))?; - println!( - "{}", - serde_json::to_string_pretty( - &serde_json::json!({"kind": kind.as_str(), "id": id, "file": file}) - )? - ); - } - Command::ResearchExport { kind, id } => match kind { - ResearchKindArg::Task => println!( - "{}", - serde_json::to_string_pretty(&load_task_envelope(&id)?)? - ), - ResearchKindArg::Signature => println!( - "{}", - serde_json::to_string_pretty(&load_derivation_signature(&id)?)? - ), - ResearchKindArg::Review => println!( - "{}", - serde_json::to_string_pretty(&load_review_receipt(&id)?)? - ), - ResearchKindArg::Challenge => println!( - "{}", - serde_json::to_string_pretty(&load_challenge_record(&id)?)? - ), - ResearchKindArg::Registry => println!( - "{}", - serde_json::to_string_pretty(&load_framework_registry_entry(&id)?)? - ), - ResearchKindArg::Operator => println!( - "{}", - serde_json::to_string_pretty(&load_operator_record(&id)?)? - ), - ResearchKindArg::Benchmark => println!( - "{}", - serde_json::to_string_pretty(&load_benchmark_schema(&id)?)? - ), - ResearchKindArg::BenchmarkRun => println!( - "{}", - serde_json::to_string_pretty(&load_benchmark_run_record(&id)?)? - ), - ResearchKindArg::Claim => println!( - "{}", - serde_json::to_string_pretty(&load_math_claim_packet(&id)?)? - ), - ResearchKindArg::Reduction => println!( - "{}", - serde_json::to_string_pretty(&load_reduction_map_record(&id)?)? - ), - ResearchKindArg::Projection => println!( - "{}", - serde_json::to_string_pretty(&load_projection_map_record(&id)?)? - ), - ResearchKindArg::Handoff => println!( - "{}", - serde_json::to_string_pretty(&load_handoff_packet(&id)?)? - ), - ResearchKindArg::ProducerHost => println!( - "{}", - serde_json::to_string_pretty(&load_producer_host_spec(&id)?)? - ), - ResearchKindArg::Promotion => println!( - "{}", - serde_json::to_string_pretty(&load_promotion_queue_entry(&id)?)? - ), - ResearchKindArg::PromotionReport => println!( - "{}", - serde_json::to_string_pretty(&load_promotion_readiness_report(&id)?)? - ), - ResearchKindArg::RouteAssignment => println!( - "{}", - serde_json::to_string_pretty(&load_route_assignment(&id)?)? - ), - ResearchKindArg::Strengthening => println!( - "{}", - serde_json::to_string_pretty(&load_strengthening_artifact(&id)?)? - ), - ResearchKindArg::Repro => println!( - "{}", - serde_json::to_string_pretty(&load_reproducibility_packet(&id)?)? - ), - ResearchKindArg::Remediation => println!( - "{}", - serde_json::to_string_pretty(&load_remediation_entry(&id)?)? - ), - ResearchKindArg::Coverage => println!( - "{}", - serde_json::to_string_pretty(&load_coverage_dispatch(&id)?)? - ), - ResearchKindArg::Tower => println!( - "{}", - serde_json::to_string_pretty(&load_vertical_bundle(&id)?)? - ), - ResearchKindArg::Lineage => println!( - "{}", - serde_json::to_string_pretty(&load_lineage_record(&id)?)? - ), - }, - Command::ResearchList { kind } => { - let ids = match kind { - ResearchKindArg::Task => list_task_envelopes()?, - ResearchKindArg::Signature => list_derivation_signatures()?, - ResearchKindArg::Review => list_review_receipts()?, - ResearchKindArg::Challenge => list_challenge_records()?, - ResearchKindArg::Registry => list_framework_registry_entries()?, - ResearchKindArg::Operator => list_operator_records()?, - ResearchKindArg::Benchmark => list_benchmark_schemas()?, - ResearchKindArg::BenchmarkRun => list_benchmark_run_records()?, - ResearchKindArg::Claim => list_math_claim_packets()?, - ResearchKindArg::Reduction => list_reduction_map_records()?, - ResearchKindArg::Projection => list_projection_map_records()?, - ResearchKindArg::Handoff => list_handoff_packets()?, - ResearchKindArg::ProducerHost => list_producer_host_specs()?, - ResearchKindArg::Promotion => list_promotion_queue_entries()?, - ResearchKindArg::PromotionReport => list_promotion_readiness_reports()?, - ResearchKindArg::RouteAssignment => list_route_assignments()?, - ResearchKindArg::Strengthening => list_strengthening_artifacts()?, - ResearchKindArg::Repro => list_reproducibility_packets()?, - ResearchKindArg::Remediation => list_remediation_entries()?, - ResearchKindArg::Coverage => list_coverage_dispatches()?, - ResearchKindArg::Tower => list_vertical_bundles()?, - ResearchKindArg::Lineage => list_lineage_records()?, - }; - println!( - "{}", - serde_json::to_string_pretty( - &serde_json::json!({"kind": kind.as_str(), "ids": ids}) - )? - ); - } - Command::ResearchRoute { - task_id, - signature_id, - } => { - let task = load_task_envelope(&task_id)?; - let signature = load_derivation_signature(&signature_id)?; - let assignment = score_routes_governed(&task, &signature)?; - println!("{}", serde_json::to_string_pretty(&assignment)?); - } - Command::ResearchDeriveFromReport { report_id, persist } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - let ( - bundle, - entry, - operator, - strengthening, - repro, - review, - challenge, - readiness, - handoff, - route_assignment, - ) = derive_governed_complete_research_bundle_from_report(&report)?; - let benchmark_schemas = l64_research::derive_benchmark_schemas_from_report(&report); - let coverage = dispatch_proof_coverage(&report); - let tower_bundle = build_vertical_compounding_bundle(®istry, &report); - if persist { - persist_framework_registry_entry(&entry)?; - persist_operator_record(&operator)?; - persist_reproducibility_packet(&repro)?; - persist_review_receipt(&review)?; - if let Some(item) = &challenge { - persist_challenge_record(item)?; - } - for item in &strengthening { - persist_strengthening_artifact(item)?; - } - for item in &benchmark_schemas { - persist_benchmark_schema(item)?; - } - for item in &bundle.tasks { - persist_task_envelope(item)?; - } - for item in &bundle.signatures { - persist_derivation_signature(item)?; - } - for item in &bundle.route_assignments { - persist_route_assignment(item)?; - } - for item in &bundle.claims { - persist_math_claim_packet(item)?; - } - for item in &bundle.reduction_maps { - persist_reduction_map_record(item)?; - } - for item in &bundle.projection_maps { - persist_projection_map_record(item)?; - } - for item in &bundle.benchmark_runs { - persist_benchmark_run_record(item)?; - } - for item in &bundle.handoff_packets { - persist_handoff_packet(item)?; - } - for item in &bundle.producer_hosts { - persist_producer_host_spec(item)?; - } - for item in &bundle.promotion_queue { - persist_promotion_queue_entry(item)?; - } - for item in &bundle.promotion_reports { - persist_promotion_readiness_report(item)?; - } - for item in &bundle.lineage_records { - persist_lineage_record(item)?; - } - persist_coverage_dispatch(&coverage)?; - persist_vertical_bundle(&report.theorem_id, &tower_bundle)?; - } - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "task": bundle.tasks.first(), - "signature": bundle.signatures.first(), - "route_assignment": route_assignment, - "registry_entry": entry, - "operator_record": operator, - "reproducibility_packet": repro, - "review_receipt": review, - "challenge_record": challenge, - "benchmark_schemas": benchmark_schemas, - "producer_hosts": bundle.producer_hosts.clone(), - "lineage_records": bundle.lineage_records.clone(), - "strengthening": strengthening, - "handoff_packet": handoff, - "bundle": bundle, - "promotion_readiness": readiness, - "coverage_dispatch": coverage, - "tower_bundle": tower_bundle, - "persisted": persist, - }))? - ); - } - Command::ResearchGovernReport { report_id, persist } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - let (task, signature, route_assignment, readiness, handoff) = - l64_research::govern_report_from_cold_result(&report)?; - if persist { - persist_task_envelope(&task)?; - persist_derivation_signature(&signature)?; - persist_route_assignment(&route_assignment)?; - persist_promotion_readiness_report(&readiness)?; - persist_handoff_packet(&handoff)?; - } - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "task": task, - "signature": signature, - "route_assignment": route_assignment, - "promotion_readiness": readiness, - "handoff_packet": handoff, - "persisted": persist, - }))? - ); - } - Command::ResearchSeedExportRemediation { persist } => { - let entries = if persist { - persist_seeded_export_remediation_entries()? - } else { - l64_research::seed_export_remediation_entries() - }; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "persisted": persist, - "summary": summarize_remediation_entries(&entries), - "entries": entries, - }))? - ); - } - Command::ResearchRemediationSummary => { - let ids = list_remediation_entries()?; - let entries = ids - .into_iter() - .filter_map(|id| load_remediation_entry(&id).ok()) - .collect::>(); - println!( - "{}", - serde_json::to_string_pretty(&summarize_remediation_entries(&entries))? - ); - } - Command::ResearchStatus => { - println!( - "{}", - serde_json::to_string_pretty(&research_status_summary()?)? - ); - } - Command::ResearchPromotionReadiness { report_id } => { - let report = cert_replay_report(&report_id).map_err(anyhow::Error::msg)?; - let readiness = derive_governed_promotion_readiness_from_report(&report)?; - println!("{}", serde_json::to_string_pretty(&readiness)?); - } - Command::DumpCanonical { id } => { - dump_canonical(&kernel, ®istry, &id)?; - } - } - - Ok(()) -} - -fn certify_with_registry( - registry: &(impl RegistryLookup + Sync), - campaign: Option, - theorem: Option, - target_profile: Option, - file: Option, - overlay_only: bool, - options: &CertificationOptions, -) -> Result { - let atlas = CompiledAtlas::compile(registry).map_err(anyhow::Error::msg)?; - let (campaign, theorem, target_profile) = - resolve_surface_cert_args_registry(registry, campaign, theorem, target_profile, file)?; - let report = match ( - campaign.as_deref(), - theorem.as_deref(), - target_profile.as_deref(), - ) { - (Some(campaign_id), _, _) => { - certify_derived_campaign_with_options(registry, &atlas, campaign_id, options) - } - (None, Some(theorem_id), Some(target_id)) => certify_derived_theorem_with_options( - registry, &atlas, theorem_id, target_id, None, options, - ), - _ => Err(l64_cert::CertError::Message( - "use either --campaign , --file , or --theorem --target-profile " - .into(), - )), - } - .map_err(anyhow::Error::msg)?; - let mut report = report; - if overlay_only { - report - .reasons - .push("executed against overlay-only bundle world".into()); - } - Ok(report) -} - -fn resolve_surface_cert_args_registry( - registry: &(impl RegistryLookup + Sync), - campaign: Option, - theorem: Option, - target_profile: Option, - file: Option, -) -> Result<(Option, Option, Option)> { - if file.is_none() { - return Ok((campaign, theorem, target_profile)); - } - let world = import_bundle_file( - Path::new(file.as_deref().unwrap_or_default()), - None, - BundleConflictPolicy::ExactMatch, - None, - )?; - let document = bundle_document(&world); - let _ = registry; - Ok(( - campaign.or_else(|| { - document.entries.iter().find_map(|entry| match entry { - QaEntry::Campaign(item) => Some(item.id.clone()), - _ => None, - }) - }), - theorem.or_else(|| { - document.entries.iter().find_map(|entry| match entry { - QaEntry::TheoremSpec(item) => Some(item.id.clone()), - QaEntry::Campaign(item) => Some(item.theorem.clone()), - _ => None, - }) - }), - target_profile.or_else(|| { - document.entries.iter().find_map(|entry| match entry { - QaEntry::TargetProfile(item) => Some(item.id.clone()), - QaEntry::Campaign(item) => Some(item.target_profile.clone()), - _ => None, - }) - }), - )) -} - -fn bundle_document(world: &BundleWorld) -> QaDocument { - let mut entries = Vec::new(); - entries.extend( - world - .overlay - .local - .objects - .iter() - .cloned() - .map(QaEntry::Object), - ); - entries.extend( - world - .overlay - .local - .regimes - .iter() - .cloned() - .map(QaEntry::Regime), - ); - entries.extend( - world - .overlay - .local - .bridges - .iter() - .cloned() - .map(QaEntry::Bridge), - ); - entries.extend( - world - .overlay - .local - .proof_shapes - .iter() - .cloned() - .map(QaEntry::ProofShape), - ); - entries.extend( - world - .overlay - .local - .atlas_cells - .iter() - .cloned() - .map(QaEntry::AtlasCell), - ); - entries.extend( - world - .overlay - .local - .theorem_specs - .iter() - .cloned() - .map(QaEntry::TheoremSpec), - ); - entries.extend( - world - .overlay - .local - .obligations - .iter() - .cloned() - .map(QaEntry::Obligation), - ); - entries.extend( - world - .overlay - .local - .target_profiles - .iter() - .cloned() - .map(QaEntry::TargetProfile), - ); - entries.extend( - world - .overlay - .local - .route_ledgers - .iter() - .cloned() - .map(QaEntry::RouteLedger), - ); - entries.extend( - world - .overlay - .local - .certificates - .iter() - .cloned() - .map(QaEntry::Certificate), - ); - entries.extend( - world - .overlay - .local - .campaigns - .iter() - .cloned() - .map(QaEntry::Campaign), - ); - QaDocument { entries } -} - -fn run_bundle_world( - world: &BundleWorld, - overlay_only: bool, - options: &CertificationOptions, -) -> Result> { - if overlay_only { - run_bundle_with_registry(&world.overlay.local_only(), world, options) - } else { - run_bundle_with_registry(&world.overlay, world, options) - } -} - -fn certify_bundle_world( - world: &BundleWorld, - overlay_only: bool, - options: &CertificationOptions, -) -> Result> { - if overlay_only { - certify_bundle_with_registry(&world.overlay.local_only(), world, options) - } else { - certify_bundle_with_registry(&world.overlay, world, options) - } -} - -fn run_bundle_with_registry( - registry: &R, - world: &BundleWorld, - options: &CertificationOptions, -) -> Result> { - let atlas = CompiledAtlas::compile(registry).map_err(anyhow::Error::msg)?; - let mut results = Vec::new(); - for campaign in &world.overlay.local.campaigns { - let report = certify_derived_campaign_with_options(registry, &atlas, &campaign.id, options) - .map_err(anyhow::Error::msg)?; - persist_report_document(&report)?; - results.push(serde_json::to_value(report)?); - } - if results.is_empty() { - for theorem in &world.overlay.local.theorem_specs { - let result = - run_seed_theorem(registry, &theorem.id, &atlas).map_err(anyhow::Error::msg)?; - results.push(serde_json::to_value(result)?); - } - } - Ok(results) -} - -fn certify_bundle_with_registry( - registry: &R, - world: &BundleWorld, - options: &CertificationOptions, -) -> Result> { - let atlas = CompiledAtlas::compile(registry).map_err(anyhow::Error::msg)?; - let mut reports = Vec::new(); - for campaign in &world.overlay.local.campaigns { - reports.push( - certify_derived_campaign_with_options(registry, &atlas, &campaign.id, options) - .map_err(anyhow::Error::msg)?, - ); - } - if reports.is_empty() { - for theorem in &world.overlay.local.theorem_specs { - let target = world - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.clone()) - .ok_or_else(|| { - anyhow!("bundle-local theorem certification requires a target profile") - })?; - reports.push( - certify_derived_theorem_with_options( - registry, - &atlas, - &theorem.id, - &target, - None, - options, - ) - .map_err(anyhow::Error::msg)?, - ); - } - } - Ok(reports) -} - -fn build_cert_options( - optimizer_policy: OptimizerPolicy, - file: Option<&str>, - bundle: Option<&str>, - replay_only: bool, - no_cache: bool, - strict_derived: bool, - evaluator_policy: Option, - cache_policy: Option, - strict_policy: bool, -) -> Result { - let bundle_hash = if let Some(file) = file { - let input = fs::read(file).with_context(|| format!("failed to read `{file}`"))?; - cache_hash_v1_bytes(&input) - } else if let Some(bundle) = bundle { - cache_hash_v1_str(bundle) - } else { - "seed".into() - }; - Ok(CertificationOptions { - optimizer_policy: optimizer_policy.clone(), - bundle_hash, - policy_hash: cache_hash_v1_str(&format!( - "{optimizer_policy:?}|evaluator={:?}|cache={:?}|strict={strict_policy}", - evaluator_policy, cache_policy - )), - bundle_id: bundle.map(ToString::to_string), - evaluator_policy, - cache_policy, - no_cache, - replay_only, - strict_derived, - strict_policy, - force_parallel_obligations: false, - max_obligation_workers: None, - }) -} - -fn validation_bundle_document(registry_id: &str, registry: &SeedRegistry) -> Result { - let report = cert_replay_report(registry_id).map_err(anyhow::Error::msg)?; - if let Some(bundle_id) = report - .execution_envelope - .as_ref() - .and_then(|item| item.bundle_id.clone()) - { - if let Ok(world) = load_bundle_world(&bundle_id) { - return Ok(report_to_validation_bundle_with_registry( - &report, - &world.overlay, - )?); - } - } - Ok(report_to_validation_bundle_with_registry( - &report, registry, - )?) -} - -fn document_for_id(registry: &SeedRegistry, id: &str) -> Result { - if let Some(document) = document_for_registry_id(registry, id) { - return Ok(document); - } - let entry = if let Ok(manifest) = load_execution_manifest(id) { - QaEntry::ExecutionManifest(manifest) - } else if let Ok(lock) = load_bundle_lock(id) { - QaEntry::BundleLock(lock) - } else if let Ok(document) = load_report_document_with_registry(id, registry) { - return Ok(document); - } else { - return Err(anyhow!("no registry entity found for `{id}`")); - }; - Ok(QaDocument { - entries: vec![entry], - }) -} - -fn export_genome_release_from_rna( - rna_path: &Path, - out_root: &Path, - artifact_class: GenomeArtifactClass, -) -> Result { - let input = fs::read_to_string(rna_path) - .with_context(|| format!("failed to read `{}`", rna_path.display()))?; - let subject_id = rna_path - .file_stem() - .and_then(|item| item.to_str()) - .unwrap_or("RNA_ARTIFACT"); - let (dna_bytes, artifact) = - compile_rna_to_dna_packet(subject_id, &input, artifact_class, vec!["core".into()]) - .map_err(anyhow::Error::msg)?; - let roundtrip = - verify_rna_dna_roundtrip(subject_id, &input, artifact_class, vec!["core".into()]) - .map_err(anyhow::Error::msg)?; - if !roundtrip.canonical_hash_equal { - anyhow::bail!("genome release export requires fixed-point canonical hash preservation"); - } - - let genome_dir = out_root.join("genome"); - let spine_dir = out_root.join("spine"); - let claims_dir = out_root.join("claims"); - let frontier_dir = out_root.join("frontier"); - let replay_dir = out_root.join("replay"); - let views_dir = out_root.join("views"); - let view_receipts_dir = views_dir.join("view_receipts"); - for dir in [ - &genome_dir, - &spine_dir, - &claims_dir, - &frontier_dir, - &replay_dir, - &views_dir, - &view_receipts_dir, - ] { - fs::create_dir_all(dir)?; - } - - let dna_name = format!("{subject_id}.genome.dna"); - let source_name = format!("{subject_id}.source.rna"); - let canonical_name = format!("{subject_id}.canonical.rna"); - let claim_name = format!("{subject_id}.claim"); - let view_name = "overview.md".to_string(); - let view_receipt_name = "overview.view.rcp".to_string(); - - fs::write(genome_dir.join(&dna_name), dna_bytes)?; - fs::write(genome_dir.join(&source_name), input.as_bytes())?; - fs::write( - genome_dir.join(&canonical_name), - roundtrip.canonical_rna.as_bytes(), - )?; - - let claim_page = format!( - "l64_release_artifact: claim_page\nartifact_role: Projection\nsurface_kind: ClaimPage\nclaim_id: {subject_id}\nstatus: fixed_point_checked\ncanonical_id: {}\ncanonical_hash: {}\ndependencies: source_sequence,canonical_genome,replay_record\nopen_dependencies: none_declared\nstress_points: projection_mistaken_for_source,non_reproducible_computation\nreceipt_ids: {},{},{}\n", - artifact.canonical_structure.canonical_id.0, - artifact.canonical_structure.canonical_hash, - artifact.rn_receipt.id, - artifact.ssr_receipt.id, - artifact.cnorm_receipt.id - ); - fs::write(claims_dir.join(&claim_name), claim_page)?; - - let dependency_spine = format!( - "l64_release_artifact: dependency_spine\nartifact_role: Projection\nsurface_kind: DependencySpine\nroot: {subject_id}\nedges: source_sequence -> canonical_genome; canonical_genome -> replay_record; canonical_genome -> claim_page\ncanonical_hash: {}\n", - artifact.canonical_structure.canonical_hash - ); - fs::write( - spine_dir.join("dependency_spine.projection"), - dependency_spine, - )?; - - let closure_map = format!( - "l64_release_artifact: closure_map\nartifact_role: Projection\nsurface_kind: ClosureMap\nroot: {subject_id}\nfixed_point: {}\ncanonical_hash_equal: {}\nopen_edges: 0\nprojection_only_views: true\n", - roundtrip.dna_bytes_equal, roundtrip.canonical_hash_equal - ); - fs::write(spine_dir.join("closure_map.projection"), closure_map)?; - - let lineage = format!( - "l64_release_artifact: lineage\nartifact_role: Record\nsurface_kind: Lineage\nsource: genome/{source_name}\ncanonical_genome: genome/{dna_name}\ncanonical_rna: genome/{canonical_name}\ncanonical_hash: {}\n", - artifact.canonical_structure.canonical_hash - ); - fs::write(spine_dir.join("lineage.record"), lineage)?; - - let closure_frontier = "l64_release_artifact: closure_frontier\nartifact_role: Projection\nsurface_kind: ClosureFrontier\nopen_obligations: none_declared\nnote: absence_of_declared_open_obligations_is_not_external_proof\n"; - fs::write( - frontier_dir.join("closure_frontier.projection"), - closure_frontier, - )?; - - let stress_map = "l64_release_artifact: stress_map\nartifact_role: Projection\nsurface_kind: StressMap\nprojection_mistaken_for_source: compile-rna rejection gate\nnon_reproducible_computation: verify-roundtrip replay gate\nhidden_assumption: claim page assumption field required by future semantic slice\n"; - fs::write(frontier_dir.join("stress_map.projection"), stress_map)?; - - let replay_record = format!( - "l64_release_artifact: replay_record\nartifact_role: Record\nsurface_kind: ReplayRecord\ncommand_1: l64 compile-rna {} --out genome/{}\ncommand_2: l64 sequence-dna genome/{} > genome/{}\ncommand_3: l64 verify-roundtrip {}\ncanonical_hash: {}\ncanonical_hash_equal: {}\ndna_bytes_equal_same_subject: {}\n", - rna_path.display(), - dna_name, - dna_name, - canonical_name, - rna_path.display(), - roundtrip.canonical_hash, - roundtrip.canonical_hash_equal, - roundtrip.dna_bytes_equal - ); - fs::write(replay_dir.join("replay_record.record"), replay_record)?; - - let overview = format!( - "\n# {subject_id} Genome Release\n\nCanonical hash: `{}`\n\nThis view is projection-only. Authority lives in `genome/{dna_name}`.\n\nSee `claims/{claim_name}`, `spine/dependency_spine.projection`, `spine/closure_map.projection`, `frontier/closure_frontier.projection`, and `replay/replay_record.record`.\n", - artifact.canonical_structure.canonical_hash - ); - fs::write(views_dir.join(&view_name), overview)?; - let view_receipt = format!( - "l64_release_artifact: view_receipt\nartifact_role: Receipt\nsurface_kind: ViewReceipt\nview: ../{view_name}\ncanonical_genome: ../../genome/{dna_name}\ncanonical_hash: {}\nprojection_only: true\n", - artifact.canonical_structure.canonical_hash - ); - fs::write(view_receipts_dir.join(&view_receipt_name), view_receipt)?; - - let manifest = GenomeReleaseManifest { - release_id: subject_id.into(), - canonical_hash: artifact.canonical_structure.canonical_hash.clone(), - canonical_id: artifact.canonical_structure.canonical_id.0.clone(), - source_sequence: format!("genome/{source_name}"), - canonical_genome: format!("genome/{dna_name}"), - claim_pages: vec![format!("claims/{claim_name}")], - dependency_spine: "spine/dependency_spine.projection".into(), - closure_map: "spine/closure_map.projection".into(), - closure_frontier: "frontier/closure_frontier.projection".into(), - stress_map: "frontier/stress_map.projection".into(), - lineage: "spine/lineage.record".into(), - replay_record: "replay/replay_record.record".into(), - view_receipts: vec![format!("views/view_receipts/{view_receipt_name}")], - }; - let manifest_record = format!( - "l64_release_artifact: release_manifest\nartifact_role: Record\nsurface_kind: ReleaseManifest\nrelease_id: {}\ncanonical_id: {}\ncanonical_hash: {}\nsource_sequence: {}\ncanonical_genome: {}\nclaim_pages: {}\ndependency_spine: {}\nclosure_map: {}\nclosure_frontier: {}\nstress_map: {}\nlineage: {}\nreplay_record: {}\nview_receipts: {}\n", - manifest.release_id, - manifest.canonical_id, - manifest.canonical_hash, - manifest.source_sequence, - manifest.canonical_genome, - manifest.claim_pages.join(","), - manifest.dependency_spine, - manifest.closure_map, - manifest.closure_frontier, - manifest.stress_map, - manifest.lineage, - manifest.replay_record, - manifest.view_receipts.join(",") - ); - fs::write(out_root.join("release_manifest.record"), manifest_record)?; - Ok(manifest) -} - -fn parse_genome_artifact_class(value: &str) -> Result { - match value.to_ascii_lowercase().as_str() { - "gene" => Ok(GenomeArtifactClass::Gene), - "hap" | "haplotype" => Ok(GenomeArtifactClass::Haplotype), - "chrom" | "chromosome" => Ok(GenomeArtifactClass::Chromosome), - "genome" => Ok(GenomeArtifactClass::Genome), - _ => Err(anyhow!("unknown genome artifact class `{value}`")), - } -} - -fn dump_canonical(kernel: &ConstitutionKernel, registry: &SeedRegistry, id: &str) -> Result<()> { - if let Some(object) = registry.get_object(id) { - let canonical = kernel - .canonicalize_object(&object, registry) - .map_err(anyhow::Error::msg)?; - println!("{}", serde_json::to_string_pretty(&canonical)?); - return Ok(()); - } - let document = document_for_id(registry, id)?; - println!("{}", serde_json::to_string_pretty(&document.entries[0])?); - Ok(()) -} diff --git a/l64-cli/src/native_main.rs b/l64-cli/src/native_main.rs new file mode 100644 index 0000000..7bbc4a8 --- /dev/null +++ b/l64-cli/src/native_main.rs @@ -0,0 +1,16 @@ +mod native_membrane; + +fn main() { + match native_membrane::run_env() { + Ok(status) => { + let code = status.code(); + if code != 0 { + std::process::exit(code); + } + } + Err(error) => { + eprintln!("{error}"); + std::process::exit(2); + } + } +} diff --git a/l64-cli/src/native_membrane.rs b/l64-cli/src/native_membrane.rs new file mode 100644 index 0000000..31ec113 --- /dev/null +++ b/l64-cli/src/native_membrane.rs @@ -0,0 +1,1322 @@ +use std::{ + ffi::OsString, + fs::{self, File, OpenOptions}, + io::{BufReader, ErrorKind, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, +}; + +const RETIRED_LEGACY_COMMANDS: &[&str] = &[ + "legacy", + "certify", + "certify-derived", + "run-theorem", + "compile-atlas", + "canonize", + "exec-host", + "dump-canonical", + "select-route", + "derive-frontier", + "tower-step", + "dispatch-coverage", + "derive-distress", + "research-import", + "research-export", + "research-list", + "research-route", + "research-derive-from-report", + "research-govern-report", + "research-seed-export-remediation", + "research-remediation-summary", + "research-status", + "research-promotion-readiness", + "replay-report", + "cache-stats", + "clear-cache", + "explain-invalidation", + "export-report-dna", + "import-report-dna", + "export-validation-dna-bundle", + "import-bundle", + "dump-bundle-graph", + "dump-overlay-world", +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub(crate) enum ProcessStatus { + Success = 0, + Open = 10, + Incomplete = 11, + Invalid = 12, +} + +impl ProcessStatus { + pub const fn code(self) -> i32 { + self as i32 + } + + const fn from_verdict(verdict: l64_certification::CertificationVerdict) -> Self { + match verdict { + l64_certification::CertificationVerdict::Certified => Self::Success, + l64_certification::CertificationVerdict::Open => Self::Open, + l64_certification::CertificationVerdict::Incomplete => Self::Incomplete, + l64_certification::CertificationVerdict::Invalid => Self::Invalid, + } + } + + const fn severity(self) -> u8 { + match self { + Self::Success => 0, + Self::Open => 1, + Self::Incomplete => 2, + Self::Invalid => 3, + } + } + + fn merge(self, other: Self) -> Self { + if other.severity() > self.severity() { + other + } else { + self + } + } +} + +pub(super) fn run_env() -> Result { + let args = std::env::args_os().collect::>(); + let stdout = std::io::stdout(); + let mut stdout = stdout.lock(); + dispatch(&args, &mut stdout) +} + +pub(crate) fn dispatch( + args: &[OsString], + stdout: &mut impl Write, +) -> Result { + let Some(command) = args.get(1).and_then(|item| item.to_str()) else { + print_help(stdout)?; + return Ok(ProcessStatus::Success); + }; + if matches!(command, "-V" | "--version" | "version") { + require_arity(args, 2, "--version")?; + writeln!(stdout, "l64-cli {}", env!("CARGO_PKG_VERSION")).map_err(io_error)?; + return Ok(ProcessStatus::Success); + } + if command == "help" { + match args.get(2).and_then(|item| item.to_str()) { + None => print_help(stdout)?, + Some(topic) if args.len() == 3 => print_command_help(topic, stdout)?, + Some(_) => return Err("usage: l64-cli help [command]".into()), + } + return Ok(ProcessStatus::Success); + } + if matches!(command, "-h" | "--help") { + require_arity(args, 2, "--help")?; + print_help(stdout)?; + return Ok(ProcessStatus::Success); + } + if args.len() == 3 + && args[2] + .to_str() + .is_some_and(|value| matches!(value, "-h" | "--help")) + { + print_command_help(command, stdout)?; + return Ok(ProcessStatus::Success); + } + if RETIRED_LEGACY_COMMANDS.contains(&command) { + return Err(format!( + "legacy authority command `{command}` was permanently deleted after historical export; use current RNA/DNA, release, transport, certification, observation, or change carriers" + )); + } + + match command { + "compile-bundle" => compile_bundle(args, stdout).map(|()| ProcessStatus::Success), + "run-bundle" => run_bundle(args, stdout), + "certify-bundle" => certify_bundle(args, stdout), + "observe-bundle" => observe_bundle(args, stdout), + "compare-bundle" => compare_bundle(args, stdout).map(|()| ProcessStatus::Success), + "normalize-rna" | "compile-rna" | "sequence-dna" | "inspect-dna" | "verify-roundtrip" + | "run-rna" | "run-dna" | "certify-dna" | "observe-dna" | "compare-dna" => { + let file = args + .get(2) + .map(PathBuf::from) + .ok_or_else(|| format!("usage: l64-cli {command} "))?; + match command { + "normalize-rna" => normalize(args, &file, stdout).map(|()| ProcessStatus::Success), + "compile-rna" => compile(args, &file, stdout).map(|()| ProcessStatus::Success), + "sequence-dna" => sequence(args, &file, stdout).map(|()| ProcessStatus::Success), + "inspect-dna" => inspect(args, &file, stdout).map(|()| ProcessStatus::Success), + "verify-roundtrip" => verify(args, &file, stdout).map(|()| ProcessStatus::Success), + "run-rna" => run_rna(args, &file, stdout), + "run-dna" => run_dna(args, &file, stdout), + "certify-dna" => certify_dna(args, &file, stdout), + "observe-dna" => observe_dna(args, &file, stdout), + "compare-dna" => compare_dna(args, &file, stdout).map(|()| ProcessStatus::Success), + _ => unreachable!(), + } + } + "export-genome-release" => export_release(args, stdout).map(|()| ProcessStatus::Success), + _ => Err(format!( + "unknown native command `{command}`; run `l64-cli --help`" + )), + } +} + +fn print_help(stdout: &mut impl Write) -> Result<(), String> { + writeln!( + stdout, + "l64-cli {} — dependency-free native Locus64", + env!("CARGO_PKG_VERSION") + ) + .map_err(io_error)?; + writeln!(stdout, "usage: l64-cli [arguments]").map_err(io_error)?; + writeln!(stdout).map_err(io_error)?; + writeln!(stdout, "AUTHORING").map_err(io_error)?; + writeln!( + stdout, + " normalize-rna write canonical L64R1 RNA to stdout" + ) + .map_err(io_error)?; + writeln!( + stdout, + " compile-rna compile L64R1 RNA into a new L64D authority file" + ) + .map_err(io_error)?; + writeln!( + stdout, + " sequence-dna reconstruct canonical L64R1 RNA from L64D" + ) + .map_err(io_error)?; + writeln!( + stdout, + " verify-roundtrip verify the exact RNA/DNA fixed point" + ) + .map_err(io_error)?; + writeln!(stdout).map_err(io_error)?; + writeln!(stdout, "EXECUTION AND DERIVATION").map_err(io_error)?; + writeln!( + stdout, + " run-rna execute structural authority from RNA" + ) + .map_err(io_error)?; + writeln!( + stdout, + " run-dna execute structural authority from DNA" + ) + .map_err(io_error)?; + writeln!( + stdout, + " inspect-dna render the verified root projection" + ) + .map_err(io_error)?; + writeln!( + stdout, + " certify-dna certify every native context" + ) + .map_err(io_error)?; + writeln!( + stdout, + " observe-dna render certification, replay, and report views" + ) + .map_err(io_error)?; + writeln!( + stdout, + " compare-dna compare two exact DNA authorities" + ) + .map_err(io_error)?; + writeln!(stdout).map_err(io_error)?; + writeln!(stdout, "TRANSPORT AND RELEASE").map_err(io_error)?; + writeln!( + stdout, + " compile-bundle create a new ordered L64B transport" + ) + .map_err(io_error)?; + writeln!( + stdout, + " run-bundle execute each ordered member independently" + ) + .map_err(io_error)?; + writeln!( + stdout, + " certify-bundle certify each ordered member independently" + ) + .map_err(io_error)?; + writeln!( + stdout, + " observe-bundle observe each ordered member independently" + ) + .map_err(io_error)?; + writeln!( + stdout, + " compare-bundle compare members by transport index" + ) + .map_err(io_error)?; + writeln!( + stdout, + " export-genome-release atomically export one native release" + ) + .map_err(io_error)?; + writeln!(stdout).map_err(io_error)?; + writeln!(stdout, "Run `l64-cli help ` for exact usage.").map_err(io_error)?; + writeln!(stdout).map_err(io_error)?; + writeln!(stdout, "PROCESS STATUS").map_err(io_error)?; + writeln!( + stdout, + " 0 command succeeded; certification is CERTIFIED when applicable" + ) + .map_err(io_error)?; + writeln!( + stdout, + " 10 command succeeded with OPEN certification burdens" + ) + .map_err(io_error)?; + writeln!( + stdout, + " 11 command succeeded with INCOMPLETE certification evidence" + ) + .map_err(io_error)?; + writeln!( + stdout, + " 12 command succeeded with INVALID certification burdens" + ) + .map_err(io_error)?; + writeln!( + stdout, + " 2 usage, input, filesystem, or processing failure" + ) + .map_err(io_error) +} + +fn print_command_help(command: &str, stdout: &mut impl Write) -> Result<(), String> { + let (usage, summary) = match command { + "normalize-rna" => ( + "normalize-rna ", + "write canonical L64R1 RNA to stdout", + ), + "compile-rna" => ( + "compile-rna [--out ]", + "compile into a new canonical L64D authority; existing outputs are never overwritten", + ), + "sequence-dna" => ( + "sequence-dna ", + "write canonical reconstructable L64R1 RNA to stdout", + ), + "inspect-dna" => ( + "inspect-dna ", + "derive and verify the root projection", + ), + "verify-roundtrip" => ( + "verify-roundtrip ", + "verify RNA -> DNA -> RNA -> DNA exact equality", + ), + "run-rna" => ( + "run-rna ", + "compile transiently and evaluate structural authority", + ), + "run-dna" => ( + "run-dna ", + "validate and evaluate canonical DNA authority", + ), + "export-genome-release" => ( + "export-genome-release --rna --out ", + "atomically export source, authority, projection, and release record", + ), + "compile-bundle" => ( + "compile-bundle ... --out ", + "create a new ordered transport; existing outputs are never overwritten", + ), + "run-bundle" => ( + "run-bundle --file ", + "execute every member independently in transport order", + ), + "certify-dna" => ("certify-dna ", "certify all native contexts"), + "certify-bundle" => ( + "certify-bundle --file ", + "certify every member independently", + ), + "observe-dna" => ( + "observe-dna ", + "render verified certification, replay, and report projections", + ), + "observe-bundle" => ( + "observe-bundle --file ", + "observe every member independently", + ), + "compare-dna" => ( + "compare-dna ", + "compare exact authorities and derived structural movement", + ), + "compare-bundle" => ( + "compare-bundle ", + "compare ordered member contacts by transport index", + ), + "authority-audit" => { + return Err( + "`authority-audit` belongs to the `l64` wrapper: run `l64 authority-audit`".into(), + ); + } + _ => { + return Err(format!( + "unknown native command `{command}`; run `l64-cli --help`" + )); + } + }; + writeln!(stdout, "usage: l64-cli {usage}").map_err(io_error)?; + writeln!(stdout, "{summary}").map_err(io_error) +} + +fn compile_bundle(args: &[OsString], stdout: &mut impl Write) -> Result<(), String> { + let options = BundleCompileOptions::parse(&args[2..])?; + write_new_with(&options.out, |file| { + let mut encoder = l64_transport::BundleEncoder::new(file) + .map_err(|error| format!("failed to begin native bundle output: {error}"))?; + for path in &options.members { + let dna = read_dna(path)?; + require_magic(path, &dna, b"L64D", "current L64D authority")?; + encoder.push_member(&dna).map_err(|error| { + format!( + "native bundle member `{}` rejected: {error}", + path.display() + ) + })?; + } + encoder + .finish() + .map_err(|error| format!("failed to finish native bundle output: {error}"))?; + Ok(()) + })?; + writeln!(stdout, "{}", options.out.display()).map_err(io_error)?; + Ok(()) +} + +fn run_bundle(args: &[OsString], stdout: &mut impl Write) -> Result { + let options = BundleFileOptions::parse(&args[2..], "run-bundle")?; + let mut decoder = open_bundle(&options.file)?; + writeln!( + stdout, + "L64 NATIVE BUNDLE EXECUTION v{}", + l64_transport::BUNDLE_VERSION + ) + .map_err(io_error)?; + writeln!(stdout, "members={}", decoder.member_count()).map_err(io_error)?; + writeln!(stdout, "composite_authority=none").map_err(io_error)?; + writeln!(stdout, "composite_execution=none").map_err(io_error)?; + writeln!(stdout, "ordering=transport_sequence").map_err(io_error)?; + let mut status = ProcessStatus::Success; + while let Some(member) = decoder + .next_member() + .map_err(|error| format!("native bundle execution rejected input: {error}"))? + { + let execution = l64_execution::execute_canonical_graph( + member.graph(), + l64_execution::ExecutionSource::BundleMember, + ) + .map_err(|error| { + format!( + "native bundle member {} execution failed: {error}", + member.index() + ) + })?; + let mut rendered = String::new(); + execution.render_into(&mut rendered, &format!("member.{}.", member.index())); + stdout.write_all(rendered.as_bytes()).map_err(io_error)?; + status = status.merge(ProcessStatus::from_verdict(execution.certification.verdict)); + } + Ok(status) +} + +fn certify_bundle(args: &[OsString], stdout: &mut impl Write) -> Result { + let options = BundleFileOptions::parse(&args[2..], "certify-bundle")?; + let mut decoder = open_bundle(&options.file)?; + writeln!(stdout, "L64 NATIVE BUNDLE CERTIFICATION v1").map_err(io_error)?; + writeln!(stdout, "transport=canonical_l64b").map_err(io_error)?; + writeln!(stdout, "transport_verified=true").map_err(io_error)?; + writeln!(stdout, "members={}", decoder.member_count()).map_err(io_error)?; + writeln!(stdout, "composite_authority=none").map_err(io_error)?; + writeln!(stdout, "composite_certificate=none").map_err(io_error)?; + let mut status = ProcessStatus::Success; + while let Some(member) = decoder + .next_member() + .map_err(|error| format!("native bundle certification rejected input: {error}"))? + { + let certification = l64_certification::certify_graph(member.graph()).map_err(|error| { + format!( + "native bundle member {} certification failed: {error}", + member.index() + ) + })?; + let mut rendered = String::new(); + certification.render_into(&mut rendered, &format!("member.{}.", member.index())); + stdout.write_all(rendered.as_bytes()).map_err(io_error)?; + status = status.merge(ProcessStatus::from_verdict(certification.verdict)); + } + Ok(status) +} + +fn observe_bundle(args: &[OsString], stdout: &mut impl Write) -> Result { + let options = BundleFileOptions::parse(&args[2..], "observe-bundle")?; + let mut decoder = open_bundle(&options.file)?; + writeln!( + stdout, + "L64 NATIVE BUNDLE OBSERVATION v{}", + l64_observation::OBSERVATION_VERSION + ) + .map_err(io_error)?; + writeln!(stdout, "transport=canonical_l64b").map_err(io_error)?; + writeln!(stdout, "transport_verified=true").map_err(io_error)?; + writeln!(stdout, "members={}", decoder.member_count()).map_err(io_error)?; + writeln!(stdout, "composite_authority=none").map_err(io_error)?; + writeln!(stdout, "composite_verdict=none").map_err(io_error)?; + writeln!(stdout, "composite_observation=none").map_err(io_error)?; + let mut status = ProcessStatus::Success; + while let Some(member) = decoder + .next_member() + .map_err(|error| format!("native bundle observation rejected input: {error}"))? + { + let observation = + l64_observation::observe_canonical_graph(member.graph()).map_err(|error| { + format!( + "native bundle member {} observation failed: {error}", + member.index() + ) + })?; + let mut rendered = String::new(); + observation.render_into(&mut rendered, &format!("member.{}.", member.index())); + stdout.write_all(rendered.as_bytes()).map_err(io_error)?; + status = status.merge(ProcessStatus::from_verdict( + observation.certification.verdict, + )); + } + Ok(status) +} + +fn compare_bundle(args: &[OsString], stdout: &mut impl Write) -> Result<(), String> { + require_arity(args, 4, "compare-bundle ")?; + let before_path = PathBuf::from(&args[2]); + let after_path = PathBuf::from(&args[3]); + let mut before = open_bundle(&before_path)?; + let mut after = open_bundle(&after_path)?; + let before_members = before.member_count(); + let after_members = after.member_count(); + writeln!( + stdout, + "L64 NATIVE BUNDLE CHANGE v{}", + l64_change::CHANGE_VERSION + ) + .map_err(io_error)?; + writeln!(stdout, "transport=canonical_l64b").map_err(io_error)?; + writeln!(stdout, "ordering=transport_sequence").map_err(io_error)?; + writeln!(stdout, "before_members={before_members}").map_err(io_error)?; + writeln!(stdout, "after_members={after_members}").map_err(io_error)?; + writeln!(stdout, "composite_authority=none").map_err(io_error)?; + writeln!(stdout, "composite_change_verdict=none").map_err(io_error)?; + + for index in 0..before_members.max(after_members) { + let before_member = if index < before_members { + before + .next_member() + .map_err(|error| format!("before bundle rejected input: {error}"))? + } else { + None + }; + let after_member = if index < after_members { + after + .next_member() + .map_err(|error| format!("after bundle rejected input: {error}"))? + } else { + None + }; + let prefix = format!("member.{index}."); + match (before_member, after_member) { + (Some(left), Some(right)) => { + let change = l64_change::compare_dna(left.dna(), right.dna()).map_err(|error| { + format!("native bundle member {index} comparison failed: {error}") + })?; + writeln!( + stdout, + "{prefix}contact={}", + if change.exact_equal { + "UNCHANGED" + } else { + "CHANGED" + } + ) + .map_err(io_error)?; + let mut rendered = String::new(); + change.render_into(&mut rendered, &prefix); + stdout.write_all(rendered.as_bytes()).map_err(io_error)?; + } + (Some(_), None) => writeln!(stdout, "{prefix}contact=REMOVED").map_err(io_error)?, + (None, Some(_)) => writeln!(stdout, "{prefix}contact=ADDED").map_err(io_error)?, + (None, None) => unreachable!(), + } + } + before + .finish() + .map_err(|error| format!("before bundle rejected input: {error}"))?; + after + .finish() + .map_err(|error| format!("after bundle rejected input: {error}"))?; + Ok(()) +} + +fn compare_dna( + args: &[OsString], + before_path: &Path, + stdout: &mut impl Write, +) -> Result<(), String> { + require_arity(args, 4, "compare-dna ")?; + let before = read(before_path)?; + require_magic(before_path, &before, b"L64D", "current L64D authority")?; + let after_path = PathBuf::from(&args[3]); + let after = read(&after_path)?; + require_magic(&after_path, &after, b"L64D", "current L64D authority")?; + let change = l64_change::compare_dna(&before, &after) + .map_err(|error| format!("native DNA comparison rejected input: {error}"))?; + stdout + .write_all(change.render_text().as_bytes()) + .map_err(io_error)?; + Ok(()) +} + +fn export_release(args: &[OsString], stdout: &mut impl Write) -> Result<(), String> { + let options = ReleaseOptions::parse(&args[2..])?; + let source = read(&options.rna)?; + require_rna(&options.rna, &source)?; + let release = l64_release::export_native_release(&source, &options.out).map_err(|error| { + if let Some(rna) = error.rna_error() { + rna_input_error(&options.rna, &source, "native release rejected RNA", rna) + } else { + format!("native release rejected input: {error}") + } + })?; + writeln!(stdout, "{}", release.root.display()).map_err(io_error)?; + Ok(()) +} + +fn run_rna( + args: &[OsString], + file: &Path, + stdout: &mut impl Write, +) -> Result { + let source = read(file)?; + require_rna(file, &source)?; + require_arity(args, 3, "run-rna ")?; + let execution = l64_execution::execute_rna(&source).map_err(|error| { + if let Some(rna) = error.rna_error() { + rna_input_error(file, &source, "native RNA execution rejected input", rna) + } else { + format!("native RNA execution rejected input: {error}") + } + })?; + stdout + .write_all(execution.render_text().as_bytes()) + .map_err(io_error)?; + Ok(ProcessStatus::from_verdict(execution.certification.verdict)) +} + +fn run_dna( + args: &[OsString], + file: &Path, + stdout: &mut impl Write, +) -> Result { + let dna = read(file)?; + require_magic(file, &dna, b"L64D", "current L64D authority")?; + require_arity(args, 3, "run-dna ")?; + let execution = l64_execution::execute_dna(&dna) + .map_err(|error| format!("native DNA execution rejected input: {error}"))?; + stdout + .write_all(execution.render_text().as_bytes()) + .map_err(io_error)?; + Ok(ProcessStatus::from_verdict(execution.certification.verdict)) +} + +fn normalize(args: &[OsString], file: &Path, stdout: &mut impl Write) -> Result<(), String> { + let source = read(file)?; + require_rna(file, &source)?; + require_arity(args, 3, "normalize-rna ")?; + let normalized = l64_native::normalize_rna(&source).map_err(|error| { + rna_input_error( + file, + &source, + "native RNA normalization rejected input", + error, + ) + })?; + stdout.write_all(&normalized).map_err(io_error)?; + Ok(()) +} + +fn compile(args: &[OsString], file: &Path, stdout: &mut impl Write) -> Result<(), String> { + let source = read(file)?; + require_rna(file, &source)?; + let options = CompileOptions::parse(&args[3..])?; + let dna = l64_native::rna_to_dna(&source).map_err(|error| { + rna_input_error( + file, + &source, + "native RNA compilation rejected input", + error, + ) + })?; + let out = options.out.unwrap_or_else(|| file.with_extension("dna")); + write_new(&out, &dna)?; + writeln!(stdout, "{}", out.display()).map_err(io_error)?; + Ok(()) +} + +fn sequence(args: &[OsString], file: &Path, stdout: &mut impl Write) -> Result<(), String> { + let dna = read(file)?; + require_magic(file, &dna, b"L64D", "current L64D authority")?; + require_arity(args, 3, "sequence-dna ")?; + let rna = l64_native::dna_to_rna(&dna).map_err(native_error)?; + stdout.write_all(&rna).map_err(io_error)?; + Ok(()) +} + +fn inspect(args: &[OsString], file: &Path, stdout: &mut impl Write) -> Result<(), String> { + let dna = read(file)?; + require_magic(file, &dna, b"L64D", "current L64D authority")?; + require_arity(args, 3, "inspect-dna ")?; + let graph = l64_native::decode_dna(&dna).map_err(native_error)?; + let projection = l64_projection::ProjectionSet::derive(&graph, l64_native::ROOT_CONTEXT, 16) + .map_err(native_error)?; + projection.verify(&graph).map_err(native_error)?; + stdout + .write_all(projection.render_text().as_bytes()) + .map_err(io_error)?; + Ok(()) +} + +fn certify_dna( + args: &[OsString], + file: &Path, + stdout: &mut impl Write, +) -> Result { + let dna = read(file)?; + require_magic(file, &dna, b"L64D", "current L64D authority")?; + require_arity(args, 3, "certify-dna ")?; + let certification = l64_certification::certify_dna(&dna) + .map_err(|error| format!("native DNA certification rejected input: {error}"))?; + stdout + .write_all(certification.render_text().as_bytes()) + .map_err(io_error)?; + Ok(ProcessStatus::from_verdict(certification.verdict)) +} + +fn observe_dna( + args: &[OsString], + file: &Path, + stdout: &mut impl Write, +) -> Result { + let dna = read(file)?; + require_magic(file, &dna, b"L64D", "current L64D authority")?; + require_arity(args, 3, "observe-dna ")?; + let observation = l64_observation::observe_dna(&dna) + .map_err(|error| format!("native DNA observation rejected input: {error}"))?; + stdout + .write_all(observation.render_text().as_bytes()) + .map_err(io_error)?; + Ok(ProcessStatus::from_verdict( + observation.certification.verdict, + )) +} + +fn verify(args: &[OsString], file: &Path, stdout: &mut impl Write) -> Result<(), String> { + let source = read(file)?; + require_rna(file, &source)?; + require_arity(args, 3, "verify-roundtrip ")?; + let first_dna = l64_native::rna_to_dna(&source) + .map_err(|error| rna_input_error(file, &source, "native roundtrip rejected RNA", error))?; + let canonical_rna = l64_native::dna_to_rna(&first_dna).map_err(native_error)?; + let second_dna = l64_native::rna_to_dna(&canonical_rna).map_err(|error| { + rna_input_error( + file, + &canonical_rna, + "native roundtrip resequencing failed", + error, + ) + })?; + if first_dna != second_dna { + return Err("native RNA/DNA fixed point failed".into()); + } + stdout + .write_all(b"native RNA/DNA fixed point verified\n") + .map_err(io_error)?; + Ok(()) +} + +struct BundleCompileOptions { + members: Vec, + out: PathBuf, +} + +impl BundleCompileOptions { + fn parse(args: &[OsString]) -> Result { + let mut members = Vec::new(); + let mut out = None; + let mut index = 0; + while index < args.len() { + let argument = args[index].to_string_lossy(); + match argument.as_ref() { + "--out" => { + index += 1; + out = Some(PathBuf::from( + args.get(index).ok_or("--out requires a path")?, + )); + } + value if value.starts_with("--out=") => { + out = Some(PathBuf::from(&value[6..])); + } + value if value.starts_with('-') => { + return Err(format!( + "unsupported native compile-bundle option `{value}`" + )); + } + _ => members.push(PathBuf::from(&args[index])), + } + index += 1; + } + if members.is_empty() { + return Err("usage: l64-cli compile-bundle ... --out ".into()); + } + Ok(Self { + members, + out: out.ok_or("usage: l64-cli compile-bundle ... --out ")?, + }) + } +} + +struct BundleFileOptions { + file: PathBuf, +} + +impl BundleFileOptions { + fn parse(args: &[OsString], command: &str) -> Result { + let mut file = None; + let mut index = 0; + while index < args.len() { + let argument = args[index].to_string_lossy(); + match argument.as_ref() { + "--file" => { + index += 1; + file = Some(PathBuf::from( + args.get(index).ok_or("--file requires a path")?, + )); + } + value if value.starts_with("--file=") => { + file = Some(PathBuf::from(&value[7..])); + } + _ => { + return Err(format!( + "unsupported native {command} option `{argument}`; native contact accepts only --file" + )); + } + } + index += 1; + } + Ok(Self { + file: file.ok_or_else(|| format!("usage: l64-cli {command} --file "))?, + }) + } +} + +#[derive(Default)] +struct CompileOptions { + out: Option, +} + +impl CompileOptions { + fn parse(args: &[OsString]) -> Result { + let mut options = Self::default(); + let mut index = 0; + while index < args.len() { + let argument = args[index].to_string_lossy(); + match argument.as_ref() { + "--out" => { + index += 1; + let value = args + .get(index) + .ok_or_else(|| "--out requires a path".to_string())?; + options.out = Some(PathBuf::from(value)); + } + value if value.starts_with("--out=") => { + options.out = Some(PathBuf::from(&value[6..])); + } + "--artifact-class" => { + return Err("--artifact-class was permanently deleted; native RNA is structural authority without a legacy class selector".into()); + } + value if value.starts_with("--artifact-class=") => { + return Err("--artifact-class was permanently deleted; native RNA is structural authority without a legacy class selector".into()); + } + "--persist-lineage" => { + return Err( + "--persist-lineage was permanently deleted after historical export".into(), + ); + } + _ => { + return Err(format!( + "unsupported native compile-rna option `{argument}`" + )); + } + } + index += 1; + } + Ok(options) + } +} + +struct ReleaseOptions { + rna: PathBuf, + out: PathBuf, +} + +impl ReleaseOptions { + fn parse(args: &[OsString]) -> Result { + let mut rna = None; + let mut out = None; + let mut index = 0; + while index < args.len() { + let argument = args[index].to_string_lossy(); + match argument.as_ref() { + "--rna" => { + index += 1; + rna = Some(PathBuf::from( + args.get(index).ok_or("--rna requires a path")?, + )); + } + value if value.starts_with("--rna=") => rna = Some(PathBuf::from(&value[6..])), + "--out" => { + index += 1; + out = Some(PathBuf::from( + args.get(index).ok_or("--out requires a path")?, + )); + } + value if value.starts_with("--out=") => out = Some(PathBuf::from(&value[6..])), + "--artifact-class" => { + return Err("--artifact-class was permanently deleted; native RNA is structural authority without a legacy class selector".into()); + } + value if value.starts_with("--artifact-class=") => { + return Err("--artifact-class was permanently deleted; native RNA is structural authority without a legacy class selector".into()); + } + _ => { + return Err(format!( + "unsupported native export-genome-release option `{argument}`" + )); + } + } + index += 1; + } + Ok(Self { + rna: rna.ok_or("usage: l64-cli export-genome-release --rna --out ")?, + out: out.ok_or("usage: l64-cli export-genome-release --rna --out ")?, + }) + } +} + +fn require_arity(args: &[OsString], expected: usize, usage: &str) -> Result<(), String> { + if args.len() == expected { + Ok(()) + } else { + Err(format!("usage: l64-cli {usage}")) + } +} + +fn is_native_rna(source: &[u8]) -> bool { + source + .iter() + .position(|byte| !byte.is_ascii_whitespace()) + .is_some_and(|start| source[start..].starts_with(b"L64R1")) +} + +static STAGE_COUNTER: AtomicU64 = AtomicU64::new(0); + +fn require_rna(path: &Path, source: &[u8]) -> Result<(), String> { + if is_native_rna(source) { + Ok(()) + } else { + Err(format!("`{}` is not current L64R1 RNA", path.display())) + } +} + +fn require_magic(path: &Path, bytes: &[u8], magic: &[u8], description: &str) -> Result<(), String> { + if bytes.starts_with(magic) { + Ok(()) + } else { + Err(format!("`{}` is not {description}", path.display())) + } +} + +fn write_new(path: &Path, bytes: &[u8]) -> Result<(), String> { + write_new_with(path, |file| { + file.write_all(bytes).map_err(|error| { + format!( + "failed to write staging output `{}`: {error}", + path.display() + ) + }) + }) +} + +fn write_new_with( + path: &Path, + write: impl FnOnce(&mut File) -> Result<(), String>, +) -> Result<(), String> { + if path.exists() { + return Err(format!( + "refusing to overwrite existing output `{}`", + path.display() + )); + } + let parent = path + .parent() + .filter(|value| !value.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + fs::create_dir_all(parent) + .map_err(|error| format!("failed to create `{}`: {error}", parent.display()))?; + let name = path + .file_name() + .ok_or_else(|| format!("invalid output path `{}`", path.display()))?; + let stage_id = STAGE_COUNTER.fetch_add(1, Ordering::Relaxed); + let stage = parent.join(format!( + ".{}.l64-stage-{}-{stage_id}", + name.to_string_lossy(), + std::process::id() + )); + let result = (|| { + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(&stage) + .map_err(|error| { + format!( + "failed to create staging file `{}`: {error}", + stage.display() + ) + })?; + write(&mut file)?; + file.sync_all().map_err(|error| { + format!("failed to sync staging file `{}`: {error}", stage.display()) + })?; + fs::hard_link(&stage, path).map_err(|error| { + if error.kind() == ErrorKind::AlreadyExists { + format!("refusing to overwrite existing output `{}`", path.display()) + } else { + format!("failed to promote new output `{}`: {error}", path.display()) + } + })?; + Ok(()) + })(); + let _ = fs::remove_file(&stage); + result +} + +fn open_bundle(path: &Path) -> Result>, String> { + let file = File::open(path) + .map_err(|error| format!("failed to open `{}`: {error}", path.display()))?; + l64_transport::BundleDecoder::new(BufReader::new(file)).map_err(|error| { + format!( + "`{}` is not current L64B transport: {error}", + path.display() + ) + }) +} + +fn read_dna(path: &Path) -> Result, String> { + const MAX_DNA_FILE_BYTES: u64 = l64_native::MAX_NATIVE_DNA_PAYLOAD_BYTES as u64 + 44; + let metadata = fs::metadata(path) + .map_err(|error| format!("failed to inspect `{}`: {error}", path.display()))?; + if metadata.len() > MAX_DNA_FILE_BYTES { + return Err(format!( + "`{}` exceeds the native L64D file-size limit", + path.display() + )); + } + read(path) +} + +fn read(path: &Path) -> Result, String> { + fs::read(path).map_err(|error| format!("failed to read `{}`: {error}", path.display())) +} + +fn rna_input_error( + path: &Path, + source: &[u8], + prefix: &str, + error: l64_native::RnaError, +) -> String { + format!( + "{prefix} in `{}`:\n{}", + path.display(), + l64_native::rna_diagnostic(source, error) + ) +} + +fn native_error(error: impl core::fmt::Display) -> String { + format!("native authority rejected input: {error}") +} + +fn io_error(error: std::io::Error) -> String { + error.to_string() +} + +#[cfg(test)] +#[path = "golden_tests.rs"] +mod golden_tests; + +#[cfg(test)] +mod tests { + use super::{ProcessStatus, dispatch}; + use std::{ffi::OsString, fs}; + + fn args(items: &[&str]) -> Vec { + items.iter().map(OsString::from).collect() + } + + #[test] + fn help_exposes_only_current_native_commands() { + let mut output = Vec::new(); + dispatch(&args(&["l64-cli", "--help"]), &mut output).unwrap(); + let text = String::from_utf8(output).unwrap(); + assert!(text.contains("compile-rna")); + assert!(text.contains("run-rna")); + assert!(text.contains("run-dna")); + assert!(text.contains("certify-dna")); + assert!(!text.contains("run-theorem")); + assert!(!text.contains("research-import")); + } + + #[test] + fn run_rna_and_run_dna_share_the_same_execution_symbol() { + let root = std::env::temp_dir().join(format!("l64-cli-run-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let rna = root.join("sample.rna"); + let dna = root.join("sample.dna"); + fs::write( + &rna, + b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n", + ) + .unwrap(); + + let mut rna_output = Vec::new(); + dispatch( + &[ + OsString::from("l64-cli"), + OsString::from("run-rna"), + rna.clone().into_os_string(), + ], + &mut rna_output, + ) + .unwrap(); + + dispatch( + &[ + OsString::from("l64-cli"), + OsString::from("compile-rna"), + rna.into_os_string(), + OsString::from("--out"), + dna.clone().into_os_string(), + ], + &mut Vec::new(), + ) + .unwrap(); + + let mut dna_output = Vec::new(); + dispatch( + &[ + OsString::from("l64-cli"), + OsString::from("run-dna"), + dna.into_os_string(), + ], + &mut dna_output, + ) + .unwrap(); + + let rna_text = String::from_utf8(rna_output).unwrap(); + let dna_text = String::from_utf8(dna_output).unwrap(); + let rna_symbol = rna_text + .lines() + .find(|line| line.starts_with("symbol=")) + .unwrap(); + let dna_symbol = dna_text + .lines() + .find(|line| line.starts_with("symbol=")) + .unwrap(); + assert_eq!(rna_symbol, dna_symbol); + assert!(rna_text.contains("source=rna")); + assert!(dna_text.contains("source=dna")); + assert!(rna_text.contains("authority_mutation=none")); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn retired_authority_island_is_a_permanent_tombstone() { + for command in ["legacy", "run-theorem", "research-status", "tower-step"] { + let error = dispatch(&args(&["l64-cli", command]), &mut Vec::new()).unwrap_err(); + assert!(error.contains("permanently deleted after historical export")); + } + } + + #[test] + fn command_help_and_version_are_direct() { + let mut version = Vec::new(); + dispatch(&args(&["l64-cli", "--version"]), &mut version).unwrap(); + assert_eq!( + String::from_utf8(version).unwrap(), + format!("l64-cli {}\n", env!("CARGO_PKG_VERSION")) + ); + + let mut help = Vec::new(); + dispatch(&args(&["l64-cli", "help", "run-rna"]), &mut help).unwrap(); + let text = String::from_utf8(help).unwrap(); + assert!(text.contains("usage: l64-cli run-rna ")); + assert!(text.contains("compile transiently")); + } + + #[test] + fn wrong_native_format_fails_at_the_requested_contact() { + let root = std::env::temp_dir().join(format!("l64-cli-format-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let file = root.join("not-rna.txt"); + fs::write(&file, b"not native authority\n").unwrap(); + let error = dispatch( + &[ + OsString::from("l64-cli"), + OsString::from("run-rna"), + file.into_os_string(), + ], + &mut Vec::new(), + ) + .unwrap_err(); + assert!(error.contains("is not current L64R1 RNA")); + assert!(!error.contains("legacy theorem")); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn compile_rna_refuses_overwrite_and_preserves_existing_bytes() { + let root = std::env::temp_dir().join(format!("l64-cli-output-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let rna = root.join("sample.rna"); + let dna = root.join("sample.dna"); + fs::write( + &rna, + b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n", + ) + .unwrap(); + fs::write(&dna, b"sentinel").unwrap(); + let error = dispatch( + &[ + OsString::from("l64-cli"), + OsString::from("compile-rna"), + rna.into_os_string(), + OsString::from("--out"), + dna.clone().into_os_string(), + ], + &mut Vec::new(), + ) + .unwrap_err(); + assert!(error.contains("refusing to overwrite")); + assert_eq!(fs::read(&dna).unwrap(), b"sentinel"); + assert!(fs::read_dir(&root).unwrap().all(|entry| { + !entry + .unwrap() + .file_name() + .to_string_lossy() + .contains(".l64-stage-") + })); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn dead_artifact_class_option_is_not_silently_accepted() { + let root = std::env::temp_dir().join(format!("l64-cli-class-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let rna = root.join("sample.rna"); + fs::write(&rna, b"L64R1 0x4c36344e41544956\na 1 0x41\n").unwrap(); + let error = dispatch( + &[ + OsString::from("l64-cli"), + OsString::from("compile-rna"), + rna.into_os_string(), + OsString::from("--artifact-class"), + OsString::from("gene"), + ], + &mut Vec::new(), + ) + .unwrap_err(); + assert!(error.contains("--artifact-class was permanently deleted")); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn verdicts_map_to_stable_process_statuses() { + assert_eq!( + ProcessStatus::from_verdict(l64_certification::CertificationVerdict::Certified).code(), + 0 + ); + assert_eq!( + ProcessStatus::from_verdict(l64_certification::CertificationVerdict::Open).code(), + 10 + ); + assert_eq!( + ProcessStatus::from_verdict(l64_certification::CertificationVerdict::Incomplete).code(), + 11 + ); + assert_eq!( + ProcessStatus::from_verdict(l64_certification::CertificationVerdict::Invalid).code(), + 12 + ); + } + + #[test] + fn run_rna_returns_verdict_status_and_exact_source_span() { + let root = std::env::temp_dir().join(format!("l64-cli-status-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let open = root.join("open.rna"); + fs::write( + &open, + b"L64R1 0x4345525449465931\na 1 0x52\nq 2 1 0 0 0 0 0 0 0\nv 3 2\nr 4 3 2\n", + ) + .unwrap(); + let mut output = Vec::new(); + let status = dispatch( + &[ + OsString::from("l64-cli"), + OsString::from("run-rna"), + open.into_os_string(), + ], + &mut output, + ) + .unwrap(); + assert_eq!(status, ProcessStatus::Open); + assert!( + String::from_utf8(output) + .unwrap() + .contains("certification_verdict=OPEN") + ); + + let malformed = root.join("malformed.rna"); + fs::write(&malformed, b"L64R1 0x1\na nope 0x41\n").unwrap(); + let error = dispatch( + &[ + OsString::from("l64-cli"), + OsString::from("run-rna"), + malformed.into_os_string(), + ], + &mut Vec::new(), + ) + .unwrap_err(); + assert!(error.contains("invalid number at RNA 2:3")); + assert!(error.contains("2 | a nope 0x41")); + assert!(error.contains("| ^^^^")); + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/l64-cli/tests/cli.rs b/l64-cli/tests/cli.rs deleted file mode 100644 index 680fd03..0000000 --- a/l64-cli/tests/cli.rs +++ /dev/null @@ -1,1370 +0,0 @@ -use assert_cmd::Command; -use l64_core::{ - LocusCapabilityMask, LocusOpcode, LocusPacketKind, QaDocument, QaEntry, decode_locus_packet, -}; -use std::{ - fs, - path::PathBuf, - time::{SystemTime, UNIX_EPOCH}, -}; - -fn workspace_root() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .to_path_buf() -} - -fn write_fixture(name: &str, content: &str) -> PathBuf { - let dir = std::env::temp_dir().join("l64_cli_tests"); - fs::create_dir_all(&dir).unwrap(); - let path = dir.join(format!( - "{}_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(), - name - )); - fs::write(&path, content).unwrap(); - path -} - -fn write_bundle_dna_fixture(name: &str, document: &QaDocument) -> PathBuf { - let bytes = l64_locus::encode_section_packet( - LocusPacketKind::CanonicalTransfer, - LocusOpcode::CanonicalPayload, - "BND_TEST", - "bundle_document.v1", - document, - LocusCapabilityMask::default(), - 1, - ) - .unwrap(); - let path = write_fixture(name, ""); - fs::write(&path, bytes).unwrap(); - path -} - -fn qa_entry(kind: &str, payload: &str) -> QaEntry { - QaEntry::from_surface_json(kind, payload).unwrap() -} - -fn bundle_document_from_text(bundle: &str) -> QaDocument { - let entries = bundle - .lines() - .filter_map(|line| { - let line = line.trim(); - if line.is_empty() || line.starts_with("!l64-bundle") { - return None; - } - let (kind, payload) = line.split_once(' ').unwrap(); - Some(qa_entry(kind, payload)) - }) - .collect(); - QaDocument { entries } -} - -fn chain_rule_bundle() -> &'static str { - concat!( - "!l64-bundle v1\n", - "policy-object {\"id\":\"MOP_BND_CHAIN_RULE_CLI_SCHED\",\"kind\":\"ReportExport\",\"scope\":{\"Bundle\":\"BND_CHAIN_RULE_CLI\"},\"extends\":null,\"optimizer\":null,\"evaluator\":null,\"replay_cache\":null,\"report\":{\"export_surfaces\":[],\"include_policy_trace\":true,\"include_route_explanation\":true,\"include_obligation_logs\":true},\"scheduler\":{\"parallelization\":\"ParallelIndependent\",\"max_workers\":2,\"allow_parallel_replay\":true,\"allow_parallel_certification\":true,\"allow_parallel_exports\":true,\"deterministic_ordering\":true,\"allow_parallel_obligations\":true,\"max_obligation_workers\":3,\"allow_parallel_obligation_replay\":true,\"serialize_canonicalization_sensitive\":true},\"canonicalizer_mode\":null,\"merge_policy\":null,\"notes\":[\"cli flagship chain rule scheduler\"]}\n", - "theorem {\"id\":\"THS_CHAIN_RULE\",\"statement\":\"DER(g∘f,x) ≈1 DER(g,f(x))∘DER(f,x)\",\"hosts\":[\"R_TOP\",\"R_CALC\"],\"bridges\":[\"B_TOP_TO_CALC\"],\"operators\":[\"OPR.Chain1\"],\"target_equivalence\":\"first-order jet equivalence\",\"obligations\":[\"OblEq\",\"OblAdm\",\"OblLoc\",\"OblRed\"],\"primary_zone\":\"PmzStructural\",\"verdict\":\"Benchmarked\",\"proof_shapes\":[\"PS_SQUARE_TOPO\"]}\n", - "obligation {\"id\":\"OBL_CHAIN_EQ\",\"kind\":\"OblEq\",\"description\":\"first-order slack equivalence preserved under composition\",\"status\":\"Benchmarked\"}\n", - "obligation {\"id\":\"OBL_CHAIN_ADM\",\"kind\":\"OblAdm\",\"description\":\"both derivatives admitted in R_CALC\",\"status\":\"Benchmarked\"}\n", - "obligation {\"id\":\"OBL_CHAIN_LOC\",\"kind\":\"OblLoc\",\"description\":\"same brace-localization at x\",\"status\":\"Benchmarked\"}\n", - "obligation {\"id\":\"OBL_CHAIN_RED\",\"kind\":\"OblRed\",\"description\":\"reduction of remainder terms preserves first-order equivalence\",\"status\":\"RouteFound\"}\n", - "target {\"id\":\"TGT_CHAIN_RULE\",\"burden_class\":\"DerivativeLocalWitnessExtraction\",\"host_cluster\":[\"R_TOP\",\"R_CALC\"],\"target_equivalence\":\"first-order jet equivalence\",\"allowed_bridge_classes\":[\"Enriching\",\"Conservative\"],\"loss_ceiling\":1,\"rollback_ceiling\":1,\"required_receipt_class\":\"RC_ths\",\"required_proof_shape_family\":\"MixedBattery\",\"promotion_goal\":\"PromoteOperator\",\"primary_zone\":\"PmzStructural\",\"surface_requirement\":null,\"preferred_surface_target\":null,\"optimizer_policy\":null,\"policy_binding_ids\":[]}\n", - "ledger {\"id\":\"TRL_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"paths\":[[\"B_TOP_TO_CALC\"]],\"budget\":{\"max_loss\":1,\"allow_lossy_supported\":false,\"require_proof\":true},\"losses\":[],\"receipts\":[\"Ref_1\",\"Can\",\"Red\"],\"normalized_path\":[\"B_TOP_TO_CALC\"]}\n", - "certificate {\"id\":\"CRT_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"route_ledger\":\"TRL_CHAIN_RULE\",\"proof_shapes\":[\"PS_SQUARE_TOPO\"],\"receipts\":[\"RC_ths\",\"TR_chain\",\"BENCH\"],\"verdict\":\"Benchmarked\"}\n", - "campaign {\"id\":\"CPG_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"target_profile\":\"TGT_CHAIN_RULE\",\"route_ledger\":\"TRL_CHAIN_RULE\",\"obligations\":[\"OBL_CHAIN_EQ\",\"OBL_CHAIN_ADM\",\"OBL_CHAIN_LOC\",\"OBL_CHAIN_RED\"],\"certificates\":[\"CRT_CHAIN_RULE\"],\"dependencies\":[],\"campaign_class\":\"COperator\",\"verdict\":\"Benchmarked\",\"payoff\":[\"OPR.Chain1\",\"ATL.RouteClass.Chain\"]}\n", - "diagnostic {\"id\":\"DGN_CHAIN_RULE_ADEQUACY\",\"class\":\"DNoAdequacy\",\"atlas_cell\":\"A_TOP_TO_CALC\",\"theorem\":\"THS_CHAIN_RULE\",\"message\":\"semantic adequacy remains scaffolded rather than discharged\"}\n" - ) -} - -fn integrated_chain_rule_bundle() -> String { - format!(concat!( - "!l64-bundle v1\n", - "policy-object {{\"id\":\"MOP_BND_CHAIN_RULE_INT_SCHED\",\"kind\":\"ReportExport\",\"scope\":{{\"Bundle\":\"BND_CHAIN_RULE_INT\"}},\"extends\":null,\"optimizer\":null,\"evaluator\":null,\"replay_cache\":null,\"report\":{{\"export_surfaces\":[],\"include_policy_trace\":true,\"include_route_explanation\":true,\"include_obligation_logs\":true}},\"scheduler\":{{\"parallelization\":\"ParallelIndependent\",\"max_workers\":2,\"allow_parallel_replay\":true,\"allow_parallel_certification\":true,\"allow_parallel_exports\":true,\"deterministic_ordering\":true,\"allow_parallel_obligations\":true,\"max_obligation_workers\":3,\"allow_parallel_obligation_replay\":true,\"serialize_canonicalization_sensitive\":true}},\"canonicalizer_mode\":null,\"merge_policy\":null,\"notes\":[\"cli integrated chain rule scheduler\"]}}\n", - "object {{\"id\":\"OPR_PROMOTED_OPR_CHAIN1\",\"identity\":{{\"tag\":\"OPR\",\"cid\":\"cid:OPR_PROMOTED_OPR_CHAIN1\",\"codebook\":\"QC0_CORE\",\"remap\":\"none\",\"lineage\":\"derived-from:THS_CHAIN_RULE\"}},\"structural\":{{\"head\":\"operator\",\"args\":[\"THS_CHAIN_RULE\",\"CPG_CHAIN_RULE\"],\"local_sections\":[\"first-order derivative composition\"],\"morphism_hooks\":[\"B_TOP_TO_CALC\"]}},\"constraint\":{{\"regime\":\"R_CALC\",\"contracts\":[\"chain-rule\",\"first-order\"],\"invariants\":[\"jet-compose\",\"reduction-exact\"],\"equivalence\":\"first-order jet equivalence\",\"admissibility\":\"promoted after exact certified discharge\"}},\"evidence\":{{\"evidence_class\":\"DerivedPromotion\",\"traces\":[\"THS_CHAIN_RULE\"],\"receipts\":[\"CRT_CHAIN_RULE\",\"REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE\"],\"maturity\":\"Certified\",\"gate_verdict\":\"Pass\"}},\"alias\":{{\"aliases\":[\"OPR.Chain1\"],\"profile_pack\":[\"STD\",\"chain-rule\"],\"qm_binding\":\"THS·ChainRule\",\"qa_binding\":\"OPR.Chain1\",\"projection_policy\":\"canonical-authored\"}}}}\n", - "theorem {{\"id\":\"THS_CHAIN_RULE\",\"statement\":\"DER(g∘f,x) ≈1 DER(g,f(x))∘DER(f,x)\",\"hosts\":[\"R_TOP\",\"R_CALC\"],\"bridges\":[\"B_TOP_TO_CALC\"],\"operators\":[\"OPR.Chain1\"],\"target_equivalence\":\"first-order jet equivalence\",\"obligations\":[\"OblEq\",\"OblAdm\",\"OblLoc\",\"OblRed\"],\"primary_zone\":\"PmzStructural\",\"verdict\":\"Benchmarked\",\"proof_shapes\":[\"PS_SQUARE_TOPO\"]}}\n", - "obligation {{\"id\":\"OBL_CHAIN_EQ\",\"kind\":\"OblEq\",\"description\":\"first-order slack equivalence preserved under composition\",\"status\":\"Benchmarked\"}}\n", - "obligation {{\"id\":\"OBL_CHAIN_ADM\",\"kind\":\"OblAdm\",\"description\":\"both derivatives admitted in R_CALC\",\"status\":\"Benchmarked\"}}\n", - "obligation {{\"id\":\"OBL_CHAIN_LOC\",\"kind\":\"OblLoc\",\"description\":\"same brace-localization at x\",\"status\":\"Benchmarked\"}}\n", - "obligation {{\"id\":\"OBL_CHAIN_RED\",\"kind\":\"OblRed\",\"description\":\"reduction of remainder terms preserves first-order equivalence\",\"status\":\"RouteFound\"}}\n", - "target {{\"id\":\"TGT_CHAIN_RULE\",\"burden_class\":\"DerivativeLocalWitnessExtraction\",\"host_cluster\":[\"R_TOP\",\"R_CALC\"],\"target_equivalence\":\"first-order jet equivalence\",\"allowed_bridge_classes\":[\"Enriching\",\"Conservative\"],\"loss_ceiling\":1,\"rollback_ceiling\":1,\"required_receipt_class\":\"RC_ths\",\"required_proof_shape_family\":\"MixedBattery\",\"promotion_goal\":\"PromoteOperator\",\"primary_zone\":\"PmzStructural\",\"surface_requirement\":null,\"preferred_surface_target\":null,\"optimizer_policy\":null,\"policy_binding_ids\":[]}}\n", - "ledger {{\"id\":\"TRL_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"paths\":[[\"B_TOP_TO_CALC\"]],\"budget\":{{\"max_loss\":1,\"allow_lossy_supported\":false,\"require_proof\":true}},\"losses\":[],\"receipts\":[\"Ref_1\",\"Can\",\"Red\"],\"normalized_path\":[\"B_TOP_TO_CALC\"]}}\n", - "certificate {{\"id\":\"CRT_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"route_ledger\":\"TRL_CHAIN_RULE\",\"proof_shapes\":[\"PS_SQUARE_TOPO\"],\"receipts\":[\"RC_ths\",\"TR_chain\",\"BENCH\"],\"verdict\":\"Benchmarked\"}}\n", - "campaign {{\"id\":\"CPG_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"target_profile\":\"TGT_CHAIN_RULE\",\"route_ledger\":\"TRL_CHAIN_RULE\",\"obligations\":[\"OBL_CHAIN_EQ\",\"OBL_CHAIN_ADM\",\"OBL_CHAIN_LOC\",\"OBL_CHAIN_RED\"],\"certificates\":[\"CRT_CHAIN_RULE\"],\"dependencies\":[],\"campaign_class\":\"COperator\",\"verdict\":\"Benchmarked\",\"payoff\":[\"OPR.Chain1\",\"ATL.RouteClass.Chain\"]}}\n", - "diagnostic {{\"id\":\"DGN_CHAIN_RULE_ADEQUACY\",\"class\":\"DNoAdequacy\",\"atlas_cell\":\"A_TOP_TO_CALC\",\"theorem\":\"THS_CHAIN_RULE\",\"message\":\"semantic adequacy remains scaffolded rather than discharged\"}}\n" - )) -} - -fn broken_chain_rule_bridge_bundle() -> &'static str { - concat!( - "!l64-bundle v1\n", - "theorem {\"id\":\"THS_CHAIN_RULE\",\"statement\":\"DER(g∘f,x) ≈1 DER(g,f(x))∘DER(f,x)\",\"hosts\":[\"R_TOP\",\"R_CALC\"],\"bridges\":[\"B_TOP_TO_CALC\"],\"operators\":[\"OPR.Chain1\"],\"target_equivalence\":\"first-order jet equivalence\",\"obligations\":[\"OblEq\",\"OblAdm\",\"OblLoc\",\"OblRed\"],\"primary_zone\":\"PmzStructural\",\"verdict\":\"Benchmarked\",\"proof_shapes\":[\"PS_SQUARE_TOPO\"]}\n", - "obligation {\"id\":\"OBL_CHAIN_EQ\",\"kind\":\"OblEq\",\"description\":\"first-order slack equivalence preserved under composition\",\"status\":\"Benchmarked\"}\n", - "obligation {\"id\":\"OBL_CHAIN_ADM\",\"kind\":\"OblAdm\",\"description\":\"both derivatives admitted in R_CALC\",\"status\":\"Benchmarked\"}\n", - "obligation {\"id\":\"OBL_CHAIN_LOC\",\"kind\":\"OblLoc\",\"description\":\"same brace-localization at x\",\"status\":\"Benchmarked\"}\n", - "obligation {\"id\":\"OBL_CHAIN_RED\",\"kind\":\"OblRed\",\"description\":\"reduction of remainder terms preserves first-order equivalence\",\"status\":\"RouteFound\"}\n", - "target {\"id\":\"TGT_CHAIN_RULE\",\"burden_class\":\"DerivativeLocalWitnessExtraction\",\"host_cluster\":[\"R_TOP\",\"R_CALC\"],\"target_equivalence\":\"first-order jet equivalence\",\"allowed_bridge_classes\":[\"Enriching\",\"Conservative\"],\"loss_ceiling\":1,\"rollback_ceiling\":1,\"required_receipt_class\":\"RC_ths\",\"required_proof_shape_family\":\"MixedBattery\",\"promotion_goal\":\"PromoteOperator\",\"primary_zone\":\"PmzStructural\",\"surface_requirement\":null,\"preferred_surface_target\":null,\"optimizer_policy\":null,\"policy_binding_ids\":[]}\n", - "ledger {\"id\":\"TRL_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"paths\":[[\"B_TOP_TO_CALC\"]],\"budget\":{\"max_loss\":1,\"allow_lossy_supported\":false,\"require_proof\":true},\"losses\":[],\"receipts\":[\"Can\",\"Red\"],\"normalized_path\":[\"B_TOP_TO_CALC\"]}\n", - "certificate {\"id\":\"CRT_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"route_ledger\":\"TRL_CHAIN_RULE\",\"proof_shapes\":[\"PS_SQUARE_TOPO\"],\"receipts\":[\"RC_ths\",\"TR_chain\",\"BENCH\"],\"verdict\":\"Benchmarked\"}\n", - "campaign {\"id\":\"CPG_CHAIN_RULE\",\"theorem\":\"THS_CHAIN_RULE\",\"target_profile\":\"TGT_CHAIN_RULE\",\"route_ledger\":\"TRL_CHAIN_RULE\",\"obligations\":[\"OBL_CHAIN_EQ\",\"OBL_CHAIN_ADM\",\"OBL_CHAIN_LOC\",\"OBL_CHAIN_RED\"],\"certificates\":[\"CRT_CHAIN_RULE\"],\"dependencies\":[],\"campaign_class\":\"COperator\",\"verdict\":\"Benchmarked\",\"payoff\":[\"OPR.Chain1\",\"ATL.RouteClass.Chain\"]}\n" - ) -} - -fn test_namespace(prefix: &str) -> String { - format!( - "{}_{}", - prefix, - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - ) -} - -#[test] -fn standalone_projection_leaf_commands_are_removed() { - let path = write_fixture( - "sample.projection", - "object [tag=CTX;cid=OBJ_CTX_SET;codebook=GEN1;remap=none;lineage=seed][regime=R_SET;contracts=carrier-total;invariants=extensional-stable;equivalence=eq-set;admissibility=admit-basic]{evidence_class=Seed;traces=T_set;receipts=RC_set;maturity=Validated;gate_verdict=Pass}<>\n", - ); - - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args(["normalize", path.to_str().unwrap(), "--as", "qa0"]) - .output() - .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("unrecognized subcommand")); -} - -#[test] -fn select_route_uses_seed_atlas_winner() { - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "select-route", - "--src", - "R_TYP", - "--tgt", - "R_SET", - "--proof-target", - "extensional carrier reasoning", - ]) - .assert() - .success(); -} - -#[test] -fn certify_campaign_returns_report() { - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args(["certify", "--campaign", "CPG_CHAIN_RULE"]) - .assert() - .success(); -} - -#[test] -fn certify_derived_campaign_returns_report() { - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args(["certify-derived", "--campaign", "CPG_CHAIN_RULE"]) - .assert() - .success(); -} - -#[test] -fn compile_atlas_succeeds() { - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args(["compile-atlas"]) - .assert() - .success(); -} - -#[test] -fn rna_dna_primary_authority_commands_work() { - let rna_path = write_fixture("primary.gene.rna", "ι ≔ σ ‖ κ\n"); - let dna_path = rna_path.with_extension("gene.dna"); - let canonical_rna_path = rna_path.with_extension("canonical.gene.rna"); - let recompiled_dna_path = rna_path.with_extension("recompiled.gene.dna"); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-rna", - rna_path.to_str().unwrap(), - "--out", - dna_path.to_str().unwrap(), - ]) - .assert() - .success(); - - assert!(dna_path.exists()); - assert!(!fs::read(&dna_path).unwrap().is_empty()); - - let sequence_output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args(["sequence-dna", dna_path.to_str().unwrap()]) - .assert() - .success() - .get_output() - .stdout - .clone(); - let canonical_rna = String::from_utf8(sequence_output).unwrap(); - assert!(!canonical_rna.trim_start().starts_with('{')); - fs::write(&canonical_rna_path, canonical_rna).unwrap(); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-rna", - canonical_rna_path.to_str().unwrap(), - "--out", - recompiled_dna_path.to_str().unwrap(), - ]) - .assert() - .success(); - - let original_packet = decode_locus_packet(&fs::read(&dna_path).unwrap()).unwrap(); - let recompiled_packet = decode_locus_packet(&fs::read(&recompiled_dna_path).unwrap()).unwrap(); - assert_eq!( - original_packet.header.integrity_hash, - recompiled_packet.header.integrity_hash - ); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args(["verify-roundtrip", rna_path.to_str().unwrap()]) - .assert() - .success(); -} - -#[test] -fn cki_registry_fixture_preserves_rna_dna_fixed_point() { - let source_path = workspace_root() - .join("fixtures") - .join("cki_registry.genome.rna"); - assert!(source_path.exists(), "controlled CKI fixture is missing"); - let out_dir = std::env::temp_dir().join(format!( - "l64_cki_fixture_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir_all(&out_dir).unwrap(); - let dna_path = out_dir.join("cki_registry.genome.dna"); - let canonical_rna_path = out_dir.join("cki_registry.canonical.rna"); - let recompiled_dna_path = out_dir.join("cki_registry.recompiled.dna"); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-rna", - source_path.to_str().unwrap(), - "--artifact-class", - "genome", - "--out", - dna_path.to_str().unwrap(), - ]) - .assert() - .success(); - - let canonical_rna = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args(["sequence-dna", dna_path.to_str().unwrap()]) - .assert() - .success() - .get_output() - .stdout - .clone(); - let canonical_rna = String::from_utf8(canonical_rna).unwrap(); - assert!(!canonical_rna.trim_start().starts_with('{')); - fs::write(&canonical_rna_path, canonical_rna).unwrap(); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-rna", - canonical_rna_path.to_str().unwrap(), - "--artifact-class", - "genome", - "--out", - recompiled_dna_path.to_str().unwrap(), - ]) - .assert() - .success(); - - let original_packet = decode_locus_packet(&fs::read(&dna_path).unwrap()).unwrap(); - let recompiled_packet = decode_locus_packet(&fs::read(&recompiled_dna_path).unwrap()).unwrap(); - assert_eq!( - original_packet.header.integrity_hash, - recompiled_packet.header.integrity_hash - ); -} - -#[test] -fn inspect_dna_output_is_not_rna_source() { - let rna_path = write_fixture("inspect-source.gene.rna", "ι ≔ σ ‖ κ\n"); - let dna_path = rna_path.with_extension("gene.dna"); - let inspection_path = rna_path.with_extension("inspection.gene.rna"); - let rejected_dna_path = rna_path.with_extension("rejected.gene.dna"); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-rna", - rna_path.to_str().unwrap(), - "--out", - dna_path.to_str().unwrap(), - ]) - .assert() - .success(); - - let inspection_output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args(["inspect-dna", dna_path.to_str().unwrap()]) - .assert() - .success() - .get_output() - .stdout - .clone(); - let inspection = String::from_utf8(inspection_output).unwrap(); - assert!(inspection.trim_start().starts_with('{')); - fs::write(&inspection_path, inspection).unwrap(); - - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-rna", - inspection_path.to_str().unwrap(), - "--out", - rejected_dna_path.to_str().unwrap(), - ]) - .output() - .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("source RNA only") || stderr.contains("projection/report")); -} - -#[test] -fn genome_release_exports_coordinate_spine_and_rejects_views_as_source() { - let rna_path = write_fixture("release-source.gene.rna", "ι ≔ σ ‖ κ\n"); - let release_dir = std::env::temp_dir().join(format!( - "l64_release_test_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - let rejected_dna_path = release_dir.join("rejected.dna"); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "export-genome-release", - "--rna", - rna_path.to_str().unwrap(), - "--out", - release_dir.to_str().unwrap(), - ]) - .assert() - .success(); - - let manifest = release_dir.join("release_manifest.record"); - let subject_id = rna_path.file_stem().unwrap().to_str().unwrap(); - let source_rna = release_dir - .join("genome") - .join(format!("{subject_id}.source.rna")); - let canonical_rna = release_dir - .join("genome") - .join(format!("{subject_id}.canonical.rna")); - let non_source_artifacts = [ - manifest, - release_dir - .join("claims") - .join(format!("{subject_id}.claim")), - release_dir - .join("spine") - .join("dependency_spine.projection"), - release_dir.join("spine").join("closure_map.projection"), - release_dir.join("spine").join("lineage.record"), - release_dir - .join("frontier") - .join("closure_frontier.projection"), - release_dir.join("frontier").join("stress_map.projection"), - release_dir.join("replay").join("replay_record.record"), - release_dir.join("views").join("overview.md"), - release_dir - .join("views") - .join("view_receipts") - .join("overview.view.rcp"), - ]; - assert!(source_rna.exists()); - assert!(canonical_rna.exists()); - - for source in [&source_rna, &canonical_rna] { - let accepted_dna_path = release_dir.join("accepted.dna"); - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-rna", - source.to_str().unwrap(), - "--out", - accepted_dna_path.to_str().unwrap(), - ]) - .assert() - .success(); - } - - for artifact in &non_source_artifacts { - assert!( - artifact.exists(), - "missing release artifact: {}", - artifact.display() - ); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-rna", - artifact.to_str().unwrap(), - "--out", - rejected_dna_path.to_str().unwrap(), - ]) - .output() - .unwrap(); - assert!( - !output.status.success(), - "release artifact should not compile as source: {}", - artifact.display() - ); - } -} - -#[test] -fn compile_bundle_moves_projection_fixture_to_dna() { - let namespace = test_namespace("cli_compile_bundle"); - let source_path = write_fixture("chain_rule_bundle.locus.rna", chain_rule_bundle()); - let dna_path = source_path.with_extension("dna"); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "compile-bundle", - source_path.to_str().unwrap(), - "--out", - dna_path.to_str().unwrap(), - ]) - .assert() - .success(); - - assert!(dna_path.exists()); - assert!(!fs::read(&dna_path).unwrap().is_empty()); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args([ - "certify-bundle", - "--file", - dna_path.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ]) - .assert() - .success(); -} - -#[test] -fn theorem_and_campaign_dna_bundle_execution_work() { - let namespace = test_namespace("cli_theorem_campaign"); - let document = bundle_document_from_text(chain_rule_bundle()); - let bundle_path = write_bundle_dna_fixture("theorem_campaign.dna", &document); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["run-theorem", "--file", bundle_path.to_str().unwrap()]) - .assert() - .success(); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--file", bundle_path.to_str().unwrap()]) - .assert() - .success(); -} - -#[test] -fn bundle_commands_work_for_overlay_bundle() { - let namespace = test_namespace("cli_overlay_bundle"); - let overlay_document = QaDocument { - entries: vec![ - qa_entry( - "regime", - r#"{"id":"R_TOP","ctx_law":"ctx","cut_law":"cut","thr_law":"thr","brc_law":"brc","slk_law":"slk","tol_law":"tol","knt_law":"knt","eq_law":"eq","adm_law":"adm","promoted_ops":[]}"#, - ), - qa_entry( - "regime", - r#"{"id":"R_CALC","ctx_law":"ctx","cut_law":"cut","thr_law":"thr","brc_law":"brc","slk_law":"slk","tol_law":"tol","knt_law":"knt","eq_law":"eq","adm_law":"adm","promoted_ops":[]}"#, - ), - qa_entry( - "bridge", - r#"{"id":"B_LOCAL_TOP_TO_CALC","src":"R_TOP","tgt":"R_CALC","id_pres":"local-identity","eq_pres":"local-eq","forget":[],"enrich":["derivative witness"],"loss":[],"reversibility":"Enriching","receipts":["RC_LOCAL"],"rollback":"allowed"}"#, - ), - qa_entry( - "proof", - r#"{"id":"PS_LOCAL_SQUARE","kind":"Square","nodes":["top","calc"],"edges":[{"from":"top","to":"calc","label":"derive"}],"equations":["derive=derive"],"target_equivalence":"eq","receipts":["RC_LOCAL"],"gate":"Pass"}"#, - ), - qa_entry( - "theorem", - r#"{"id":"THS_LOCAL_BUNDLE","statement":"local overlay theorem","hosts":["R_TOP","R_CALC"],"bridges":["B_LOCAL_TOP_TO_CALC"],"operators":["OPR.Local"],"target_equivalence":"eq","obligations":["OblLoc"],"primary_zone":"PmzStructural","verdict":"RouteFound","proof_shapes":["PS_LOCAL_SQUARE"]}"#, - ), - qa_entry( - "obligation", - r#"{"id":"OBL_LOCAL_LOC","kind":"OblLoc","description":"local compatibility","status":"RouteFound"}"#, - ), - qa_entry( - "target", - r#"{"id":"TGT_LOCAL_BUNDLE","burden_class":"DerivativeLocalWitnessExtraction","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"PromoteOperator","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]}"#, - ), - qa_entry( - "atlas", - r#"{"id":"A_LOCAL_BUNDLE","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"DerivativeLocalWitnessExtraction","proof_target":"local derivative witness extraction","candidate_paths":[["B_LOCAL_TOP_TO_CALC"]],"normalized_winner":["B_LOCAL_TOP_TO_CALC"],"winner_state":"Candidate","loss_profile":{"items":[]},"proof_shapes_checked":["PS_LOCAL_SQUARE"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":["surface-preserving"],"surface_transition":{"compatibility":"SymbolicFidelityPreserving","penalties":[],"total_penalty":0}}"#, - ), - qa_entry( - "campaign", - r#"{"id":"CPG_LOCAL_BUNDLE","theorem":"THS_LOCAL_BUNDLE","target_profile":"TGT_LOCAL_BUNDLE","route_ledger":"TRL_LOCAL_BUNDLE","obligations":["OBL_LOCAL_LOC"],"certificates":[],"dependencies":[],"campaign_class":"CBridge","verdict":"RouteFound","payoff":["portable-overlay"]}"#, - ), - ], - }; - let bundle_path = write_bundle_dna_fixture("overlay_bundle.dna", &overlay_document); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args([ - "run-bundle", - "--file", - bundle_path.to_str().unwrap(), - "--overlay-only", - "--conflict-policy", - "exact-match", - ]) - .assert() - .success(); - - Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args([ - "certify-bundle", - "--file", - bundle_path.to_str().unwrap(), - "--overlay-only", - "--conflict-policy", - "exact-match", - ]) - .assert() - .success(); -} - -#[test] -fn surfaced_chain_rule_bundle_certifies_through_cli() { - let document = bundle_document_from_text(chain_rule_bundle()); - let bundle_path = write_bundle_dna_fixture("chain_rule_cli.dna", &document); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", test_namespace("cli_chain_rule")) - .args([ - "certify-bundle", - "--file", - bundle_path.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json[0]["campaign_id"], "CPG_CHAIN_RULE"); - assert_eq!(json[0]["verdict"], "Integrated"); - let eq = json[0]["obligations"] - .as_array() - .unwrap() - .iter() - .find(|item| item["obligation_id"] == "OBL_CHAIN_EQ") - .unwrap(); - assert_eq!(eq["evaluation_mode"], "RecomputedExact"); - assert!( - eq["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - ); - assert!( - json[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["obligation_id"] == "OBL_CHAIN_RED" - && item["evaluation_mode"] == "RecomputedExact" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "RED_CHAIN_OPERATOR_DEFAULT_SELECTION") - }) - ); - assert!( - !json[0]["deficiencies"] - .as_array() - .unwrap() - .iter() - .any(|item| item["id"] == "DGN_CHAIN_RULE_ADEQUACY") - ); - assert!( - json[0]["promotion_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - json[0]["default_selected_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); -} - -#[test] -fn integrated_chain_rule_bundle_reuses_promoted_operator_through_cli() { - let document = bundle_document_from_text(&integrated_chain_rule_bundle()); - let bundle_path = write_bundle_dna_fixture("chain_rule_integrated_cli.dna", &document); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env( - "MF_CACHE_NAMESPACE", - test_namespace("cli_chain_rule_integrated"), - ) - .args([ - "certify-bundle", - "--file", - bundle_path.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json[0]["verdict"], "Integrated"); - assert!( - json[0]["reused_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - json[0]["default_selected_artifact_ids"] - .as_array() - .unwrap() - .is_empty() - ); - assert!( - json[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["obligation_id"] == "OBL_CHAIN_EQ" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "EQR_CHAIN_OPERATOR_REUSE") - }) - ); - assert!( - json[0]["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["obligation_id"] == "OBL_CHAIN_RED" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "RED_CHAIN_OPERATOR_REUSE") - }) - ); -} - -#[test] -fn chain_rule_recipe_campaign_auto_reuses_default_operator_with_payoff() { - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env( - "MF_CACHE_NAMESPACE", - test_namespace("cli_chain_rule_recipe"), - ) - .args(["certify-derived", "--campaign", "CPG_CHAIN_RULE_RECIPE"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["campaign_id"], "CPG_CHAIN_RULE_RECIPE"); - assert_eq!(json["verdict"], "Integrated"); - assert!( - json["default_selected_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - json["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_SECOND_BURDEN_DEFAULT_REUSE") - ); - assert!( - json["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_OBLIGATION_COUNT_REDUCTION_4_TO_2") - ); - assert_eq!(json["obligations"].as_array().unwrap().len(), 2); - assert!(json["obligations"].as_array().unwrap().iter().any(|item| { - item["obligation_id"] == "OBL_CHAIN_EQ" - && item["receipts"] - .as_array() - .unwrap() - .iter() - .any(|receipt| receipt["id"] == "EQR_CHAIN_OPERATOR_DEFAULT_SELECTION") - })); -} - -#[test] -fn chain_rule_transport_campaign_auto_reuses_default_operator_with_payoff() { - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env( - "MF_CACHE_NAMESPACE", - test_namespace("cli_chain_rule_transport"), - ) - .args(["certify-derived", "--campaign", "CPG_CHAIN_RULE_TRANSPORT"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["campaign_id"], "CPG_CHAIN_RULE_TRANSPORT"); - assert_eq!(json["verdict"], "Integrated"); - assert!( - json["default_selected_artifact_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "OPR_PROMOTED_OPR_CHAIN1") - ); - assert!( - json["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_ADJACENT_TRANSPORT_DEFAULT_REUSE") - ); - assert!( - json["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_LOCALITY_WITNESS_RETAINED") - ); - assert!( - json["payoff_receipt_ids"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "PAY_CHAIN1_OBLIGATION_COUNT_REDUCTION_4_TO_3") - ); - assert_eq!(json["obligations"].as_array().unwrap().len(), 3); - assert!( - json["obligations"] - .as_array() - .unwrap() - .iter() - .any(|item| item["obligation_id"] == "OBL_CHAIN_LOC") - ); -} - -#[test] -fn bayes_brace_campaign_certifies_with_active_adequacy_on_top_prob_cluster() { - let namespace = test_namespace("cli_bayes_brace"); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--campaign", "CPG_BAYES_BRACE"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["campaign_id"], "CPG_BAYES_BRACE"); - assert_eq!(json["verdict"], "Certified"); - assert_eq!(json["selected_atlas_cell"], "A_TOP_TO_PROB"); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_BAYES_TOP_PROB_BRIDGE") - ); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .all(|item| item["verdict"] == "Certified") - ); - assert!(json["deficiencies"].as_array().unwrap().is_empty()); - let adequacy = json["obligations"] - .as_array() - .unwrap() - .iter() - .find(|item| item["obligation_id"] == "OBL_BAYES_ADE") - .unwrap(); - assert_eq!(adequacy["evaluation_mode"], "RecomputedExact"); -} - -#[test] -fn ch_norm_campaign_certifies_with_exact_type_normalization_witness() { - let namespace = test_namespace("cli_ch_norm"); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--campaign", "CPG_CH_NORM"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["campaign_id"], "CPG_CH_NORM"); - assert_eq!(json["verdict"], "Certified"); - assert_eq!(json["selected_atlas_cell"], "A_TYPE_TO_SET"); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_CH_TYP_SET_BRIDGE") - ); - assert!(json["deficiencies"].as_array().unwrap().is_empty()); - let adequacy = json["obligations"] - .as_array() - .unwrap() - .iter() - .find(|item| item["obligation_id"] == "OBL_CH_ADE") - .unwrap(); - assert_eq!(adequacy["evaluation_mode"], "RecomputedExact"); - assert!( - adequacy["receipts"] - .as_array() - .unwrap() - .iter() - .any(|item| item["id"] == "CHN_ADE_CARRIER_COLLAPSE") - ); -} - -#[test] -fn exec_infer_campaign_certifies_with_active_adequacy_on_prob_comp_cluster() { - let namespace = test_namespace("cli_exec_infer"); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--campaign", "CPG_EXEC_INFER"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["campaign_id"], "CPG_EXEC_INFER"); - assert_eq!(json["verdict"], "Certified"); - assert_eq!(json["selected_atlas_cell"], "A_PROB_TO_COMP"); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_EXEC_PROB_COMP_BRIDGE") - ); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .all(|item| item["verdict"] == "Certified") - ); - assert!(json["deficiencies"].as_array().unwrap().is_empty()); -} - -#[test] -fn prob_judg_campaign_certifies_with_active_adequacy_on_prob_log_cluster() { - let namespace = test_namespace("cli_prob_judg"); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--campaign", "CPG_PROB_JUDG"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["campaign_id"], "CPG_PROB_JUDG"); - assert_eq!(json["verdict"], "Certified"); - assert_eq!(json["selected_atlas_cell"], "A_PROB_TO_LOG"); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_JDG_PROB_LOG_BRIDGE") - ); - assert!(json["deficiencies"].as_array().unwrap().is_empty()); -} - -#[test] -fn cert_prop_campaign_certifies_with_active_adequacy_on_comp_log_cluster() { - let namespace = test_namespace("cli_cert_prop"); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--campaign", "CPG_CERT_PROP"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["campaign_id"], "CPG_CERT_PROP"); - assert_eq!(json["verdict"], "Certified"); - assert_eq!(json["selected_atlas_cell"], "A_COMP_TO_LOG"); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_CERT_COMP_LOG_BRIDGE") - ); - assert!(json["deficiencies"].as_array().unwrap().is_empty()); - assert!( - json["checker_receipts"] - .as_array() - .unwrap() - .iter() - .any(|item| item["subject_id"] == "CPG_CERT_PROP") - ); - assert!( - json["checker_receipts"] - .as_array() - .unwrap() - .iter() - .all(|item| item["verdict"] == "Certified") - ); -} - -#[test] -fn ch_inh_campaign_certifies_with_exact_type_algebra_witness() { - let namespace = test_namespace("cli_ch_inh"); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--campaign", "CPG_CH_INH"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json["campaign_id"], "CPG_CH_INH"); - assert_eq!(json["verdict"], "Certified"); - assert_eq!(json["selected_atlas_cell"], "A_TYPE_TO_ALG"); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_CHI_TYP_ALG_BRIDGE") - ); - let adequacy = json["obligations"] - .as_array() - .unwrap() - .iter() - .find(|item| item["obligation_id"] == "OBL_CHI_ADE") - .unwrap(); - assert_eq!(adequacy["evaluation_mode"], "RecomputedExact"); - assert!(json["deficiencies"].as_array().unwrap().is_empty()); - let eq = json["obligations"] - .as_array() - .unwrap() - .iter() - .find(|item| item["obligation_id"] == "OBL_CHI_EQ") - .unwrap(); - assert_eq!(eq["evaluation_mode"], "RecomputedExact"); - assert!(eq["receipts"].as_array().unwrap().iter().any(|item| { - item["id"] == "CHI_EQ_INHERITANCE" - && item["subreceipts"] - .as_array() - .unwrap() - .iter() - .any(|sub| sub["id"] == "CHI_EQ_PROOF_TERM_TRANSPORT") - && item["subreceipts"] - .as_array() - .unwrap() - .iter() - .any(|sub| sub["id"] == "CHI_EQ_PROOF_TERM_NORMAL_FORM") - })); - assert!( - json["checker_receipts"] - .as_array() - .unwrap() - .iter() - .any(|item| { - item["kind"] == "ObligationVerdict" && item["subject_id"] == "OBL_CHI_EQ" - }) - ); -} - -#[test] -fn chain_rule_reports_active_adequacy_records() { - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env( - "MF_CACHE_NAMESPACE", - test_namespace("cli_chain_rule_adequacy"), - ) - .args(["certify-derived", "--campaign", "CPG_CHAIN_RULE"]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .any(|item| item["clause_id"] == "ADQ_CHAIN_TOP_CALC_BRIDGE") - ); - assert!( - json["adequacy_records"] - .as_array() - .unwrap() - .iter() - .all(|item| item["verdict"] == "Certified") - ); -} - -#[test] -fn broken_bridge_adequacy_blocks_campaign_and_promotion() { - let document = bundle_document_from_text(broken_chain_rule_bridge_bundle()); - let bundle_path = write_bundle_dna_fixture("chain_rule_broken_bridge.dna", &document); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env( - "MF_CACHE_NAMESPACE", - test_namespace("cli_chain_rule_broken_bridge"), - ) - .args([ - "certify-bundle", - "--file", - bundle_path.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ]) - .output() - .unwrap(); - assert!(output.status.success()); - let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(json[0]["verdict"], "BlockedOpen"); - assert!( - json[0]["promotion_artifact_ids"] - .as_array() - .unwrap() - .is_empty() - ); - let deficiency = json[0]["deficiencies"] - .as_array() - .unwrap() - .iter() - .find(|item| item["class"] == "DBridge") - .unwrap(); - assert_eq!(deficiency["blocking_scope"], "Campaign"); - assert!( - deficiency["control_effects"] - .as_array() - .unwrap() - .iter() - .any(|item| item == "BlockPromotion") - ); -} - -#[test] -fn validation_dna_bundle_carries_certification_artifacts() { - let namespace = test_namespace("cli_chain_rule_export_adequacy"); - let _ = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--campaign", "CPG_CHAIN_RULE"]) - .output() - .unwrap(); - let report_id = "REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE"; - let report_dir = workspace_root() - .join(".l64-cache") - .join("namespaces") - .join(&namespace) - .join("reports"); - assert!(report_dir.join(format!("{report_id}.dna")).exists()); - assert!(!report_dir.join(format!("{report_id}.locus")).exists()); - let out = std::env::temp_dir() - .join("l64_cli_tests") - .join(format!("{namespace}.adequacy.validation.dna")); - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args([ - "export-validation-dna-bundle", - "--id", - report_id, - "--out", - out.to_str().unwrap(), - ]) - .output() - .unwrap(); - assert!(output.status.success()); - let bytes = fs::read(out).unwrap(); - let document: QaDocument = - l64_locus::decode_section_payload(&bytes, LocusOpcode::CanonicalPayload).unwrap(); - for id in [ - "THS_CHAIN_RULE", - "CPG_CHAIN_RULE", - "CRT_REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE", - "TRL_REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE", - ] { - assert!(document.entries.iter().any(|entry| entry.id() == id)); - } -} - -#[test] -fn export_validation_dna_bundle_imports_without_projection_surface() { - let namespace = test_namespace("cli_validation_dna_bundle"); - let report_id = "REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE"; - let out = std::env::temp_dir() - .join("l64_cli_tests") - .join(format!("{namespace}.validation.dna")); - let _ = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args(["certify-derived", "--campaign", "CPG_CHAIN_RULE"]) - .output() - .unwrap(); - let export = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args([ - "export-validation-dna-bundle", - "--id", - report_id, - "--out", - out.to_str().unwrap(), - ]) - .output() - .unwrap(); - assert!(export.status.success()); - assert!(out.exists()); - let bytes = fs::read(&out).unwrap(); - let document: QaDocument = - l64_locus::decode_section_payload(&bytes, LocusOpcode::CanonicalPayload).unwrap(); - assert!( - document - .entries - .iter() - .any(|entry| entry.id() == "THS_CHAIN_RULE") - ); - - let import = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args([ - "import-bundle", - out.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ]) - .output() - .unwrap(); - assert!(import.status.success()); -} - -#[test] -fn textual_validation_bundle_export_command_is_removed() { - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "export-validation-bundle", - "--id", - "REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE", - "--to", - "qc0", - ]) - .output() - .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("export-validation-dna-bundle")); -} - -#[test] -fn textual_report_projection_commands_are_removed() { - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "export-report", - "--id", - "REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE", - "--to", - "qc0", - ]) - .output() - .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("export-report-dna")); - - let output = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .args([ - "export-report-projection", - "--id", - "REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE", - "--to", - "qc0", - ]) - .output() - .unwrap(); - assert!(!output.status.success()); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("export-report-dna")); -} - -#[test] -fn validation_dna_bundle_surfaces_imported_claim_entries() { - let namespace = test_namespace("cli_export_imported_claim"); - let imported_claim_bundle = r#"!l64-bundle v1 -proof {"id":"PS_X","kind":"Square","nodes":["a","b","c","d"],"edges":[{"from":"a","to":"b","label":"f"},{"from":"b","to":"d","label":"g"},{"from":"a","to":"c","label":"h"},{"from":"c","to":"d","label":"i"}],"equations":["g∘f=i∘h"],"target_equivalence":"eq","receipts":["r"],"gate":"Pass"} -bridge {"id":"B_X","src":"R_TOP","tgt":"R_CALC","id_pres":"pres","eq_pres":"eq","forget":[],"enrich":["der"],"loss":[],"reversibility":"Enriching","receipts":["r"],"rollback":"allowed"} -atlas {"id":"A_X","source_regime":"R_TOP","target_regime":"R_CALC","burden_class":"ImportedKernelClaim","proof_target":"kernel-claim","candidate_paths":[["B_X"]],"normalized_winner":["B_X"],"winner_state":"Candidate","loss_profile":{"items":[]},"proof_shapes_checked":["PS_X"],"recipe_maturity":"Stable","failure_signatures":[],"side_conditions":[],"surface_transition":{"compatibility":"AuthorityPreserving","penalties":[],"total_penalty":0}} -theorem {"id":"THS_X","statement":"imported kernel claim","hosts":["R_TOP","R_CALC"],"bridges":["B_X"],"operators":["OPR.X"],"target_equivalence":"eq","obligations":["OblAdm"],"primary_zone":"PmzStructural","verdict":"Benchmarked","proof_shapes":["PS_X"]} -obligation {"id":"OBL_X","kind":"OblAdm","description":"imported admissibility","status":"Benchmarked"} -target {"id":"TGT_X","burden_class":"ImportedKernelClaim","host_cluster":["R_TOP","R_CALC"],"target_equivalence":"eq","allowed_bridge_classes":["Enriching"],"loss_ceiling":1,"rollback_ceiling":1,"required_receipt_class":"RC","required_proof_shape_family":"Square","promotion_goal":"OpenBlocked","primary_zone":"PmzStructural","surface_requirement":null,"preferred_surface_target":null,"optimizer_policy":null,"policy_binding_ids":[]} -ledger {"id":"TRL_X","theorem":"THS_X","paths":[["B_X"]],"budget":{"max_loss":1,"allow_lossy_supported":false,"require_proof":true},"losses":[],"receipts":["Trace_X"],"normalized_path":["B_X"]} -campaign {"id":"CPG_X","theorem":"THS_X","target_profile":"TGT_X","route_ledger":"TRL_X","obligations":["OBL_X"],"certificates":[],"dependencies":[],"campaign_class":"CBasic","verdict":"Benchmarked","payoff":["kernel-claim"]} -burden-pack {"id":"BPK_X","allowed_host_cluster":["R_TOP","R_CALC"],"obligation_ids":["OBL_X"],"adequacy_clause_ids":["ADQ_X_EVID"],"required_proof_shape_family":"Square","route_class_constraints":[],"evidence_contract_ids":["ECT_X"],"promotion_ceiling":"Certified","blocker_taxonomy":["DEvidenceContract"]} -claim-packet {"id":"CLM_X","claim_class":"Kernel","authority_state":"Evidence","target_sector":"kernel-claim","statement":"X imported claim","assumptions":["A1"],"open_caveats":[]} -evidence-contract {"id":"ECT_X","required_evidence_kinds":["kernel-claim"],"required_benchmark_roles":["TargetCase"],"requires_stress":false,"requires_challenge":false,"admissibility_thresholds":["stable"],"promotion_ceiling":"Certified"} -benchmark-receipt {"id":"BMR_X","claim_packet_id":"CLM_X","role":"TargetCase","verdict":"Certified","metrics":{"score":"1.0"},"reproducibility_ref":"RPK_X"} -reproducibility-packet {"id":"RPK_X","claim_packet_id":"CLM_X","derivation_path":["lab"],"code_refs":["src"],"benchmark_refs":["BMR_X"],"artifact_refs":["CLM_X"]} -adequacy {"id":"ADQ_X_EVID","kind":"EvidenceContractInterpretation","regime_ids":["R_TOP","R_CALC"],"bridge_ids":[],"theorem_ids":["THS_X"],"burden_pack_ids":["BPK_X"],"claim_packet_ids":["CLM_X"],"evidence_contract_ids":["ECT_X"],"benchmark_receipt_ids":["BMR_X"],"challenge_receipt_ids":[],"reproducibility_packet_ids":["RPK_X"],"description":"evidence contract present","blocking":true}"#; - let document = bundle_document_from_text(imported_claim_bundle); - let bundle_path = write_bundle_dna_fixture("imported_claim.dna", &document); - - let certify = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args([ - "certify-bundle", - "--file", - bundle_path.to_str().unwrap(), - "--conflict-policy", - "exact-match", - ]) - .output() - .unwrap(); - assert!(certify.status.success()); - - let out = std::env::temp_dir() - .join("l64_cli_tests") - .join(format!("{namespace}.imported.validation.dna")); - let export = Command::cargo_bin("l64-cli") - .unwrap() - .current_dir(workspace_root()) - .env("MF_CACHE_NAMESPACE", &namespace) - .args([ - "export-validation-dna-bundle", - "--id", - "REPORT_THS_X_CPG_X", - "--out", - out.to_str().unwrap(), - ]) - .output() - .unwrap(); - assert!(export.status.success()); - let bytes = fs::read(out).unwrap(); - let document: QaDocument = - l64_locus::decode_section_payload(&bytes, LocusOpcode::CanonicalPayload).unwrap(); - for id in ["BPK_X", "CLM_X", "ECT_X", "BMR_X", "RPK_X", "ADQ_X_EVID"] { - assert!(document.entries.iter().any(|entry| entry.id() == id)); - } -} diff --git a/l64-command/src/lib.rs b/l64-command/src/lib.rs deleted file mode 100644 index f3b582a..0000000 --- a/l64-command/src/lib.rs +++ /dev/null @@ -1,42 +0,0 @@ -use clap::ValueEnum; -use l64_core::{BundleConflictPolicy, OptimizerPolicy}; - -#[derive(Debug, Clone, ValueEnum)] -pub enum BundlePolicyArg { - ExactMatch, - Shadow, - Reject, - NamespacedImport, -} - -impl From for BundleConflictPolicy { - fn from(value: BundlePolicyArg) -> Self { - match value { - BundlePolicyArg::ExactMatch => BundleConflictPolicy::ExactMatch, - BundlePolicyArg::Shadow => BundleConflictPolicy::Shadow, - BundlePolicyArg::Reject => BundleConflictPolicy::Reject, - BundlePolicyArg::NamespacedImport => BundleConflictPolicy::NamespacedImport, - } - } -} - -#[derive(Debug, Clone, ValueEnum)] -pub enum OptimizerPolicyArg { - Conservative, - SymbolicFidelityFirst, - ExecutionFirst, - LowLoss, - BenchmarkFriendly, -} - -impl From for OptimizerPolicy { - fn from(value: OptimizerPolicyArg) -> Self { - match value { - OptimizerPolicyArg::Conservative => OptimizerPolicy::Conservative, - OptimizerPolicyArg::SymbolicFidelityFirst => OptimizerPolicy::SymbolicFidelityFirst, - OptimizerPolicyArg::ExecutionFirst => OptimizerPolicy::ExecutionFirst, - OptimizerPolicyArg::LowLoss => OptimizerPolicy::LowLoss, - OptimizerPolicyArg::BenchmarkFriendly => OptimizerPolicy::BenchmarkFriendly, - } - } -} diff --git a/l64-core/.gitignore b/l64-core/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/l64-core/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/l64-core/Cargo.toml b/l64-core/Cargo.toml deleted file mode 100644 index 2c01bb9..0000000 --- a/l64-core/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "l64-core" -version = "0.1.0" -edition = "2024" - -[dependencies] -serde = { workspace = true } -serde_json = { workspace = true } -blake3 = { workspace = true } -bincode = { workspace = true } diff --git a/l64-core/src/codons.rs b/l64-core/src/codons.rs deleted file mode 100644 index 8b013da..0000000 --- a/l64-core/src/codons.rs +++ /dev/null @@ -1,609 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::collections::{HashMap, HashSet}; - -use crate::{lexon_specs, macro_codon_specs}; - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum CodonClass { - Molecule, - Role, - State, - Relation, - Process, - ExpressionControl, - WitnessForm, - Machine, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum CodonArity { - Nullary, - Unary, - Binary, - Variadic, - Transform, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum CodonPhase { - SourceRna, - CanonicalRna, - DnaAuthority, - Product, - Projection, - Receipt, - ForeignDebug, - MachineMemo, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CodonSpec { - pub symbol: String, - pub ascii_aliases: Vec, - pub class: CodonClass, - pub arity: CodonArity, - pub admitted_phases: Vec, - pub opcode: u16, - pub canonical: bool, - pub tombstoned: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct OpcodeRangeSpec { - pub name: String, - pub start: u16, - pub end: u16, - pub purpose: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TombstoneSpec { - pub opcode: u16, - pub symbol: String, - pub reason: String, - pub replacement: Option, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum NativeStructuralRegion { - Header, - CodonBody, - StructuralToken, - RoleField, - Gloss, - Comment, - HumanView, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct NativeStructuralSegment { - pub region: NativeStructuralRegion, - pub text: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CodonHeader { - pub protocol: String, - pub version: u16, - pub phase: CodonPhase, - pub class_symbol: String, - pub role_symbol: String, - pub subject: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PhaseAdmissionRule { - pub phase: CodonPhase, - pub admits_source_compile: bool, - pub admits_authority_decode: bool, - pub admits_product_expression: bool, - pub admits_debug_export: bool, - pub explanation: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CodonLexonLawReport { - pub codon_count: usize, - pub lexon_count: usize, - pub macro_codon_count: usize, - pub generated_word_ban_count: usize, - pub valid: bool, - pub failures: Vec, -} - -pub fn codon_specs() -> Vec { - use CodonArity::*; - use CodonClass::*; - use CodonPhase::*; - vec![ - CodonSpec { - symbol: "<-".into(), - ascii_aliases: vec!["dep".into(), "depends_on".into()], - class: Relation, - arity: Binary, - admitted_phases: vec![SourceRna, CanonicalRna, DnaAuthority, Product, Receipt], - opcode: 0x1100, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "|-".into(), - ascii_aliases: vec!["derives".into(), "proves".into()], - class: WitnessForm, - arity: Binary, - admitted_phases: vec![DnaAuthority, Product, Receipt], - opcode: 0x1101, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "[]".into(), - ascii_aliases: vec!["frontier".into(), "obligation".into()], - class: State, - arity: Variadic, - admitted_phases: vec![DnaAuthority, Product, Receipt], - opcode: 0x1102, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "R!".into(), - ascii_aliases: vec!["receipt".into()], - class: Role, - arity: Unary, - admitted_phases: vec![Receipt, Product], - opcode: 0x1103, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "+>".into(), - ascii_aliases: vec!["integrates".into()], - class: Process, - arity: Transform, - admitted_phases: vec![DnaAuthority, Receipt], - opcode: 0x1105, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: ">>".into(), - ascii_aliases: vec!["expresses".into()], - class: ExpressionControl, - arity: Transform, - admitted_phases: vec![DnaAuthority, Product, Receipt], - opcode: 0x1106, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "G#".into(), - ascii_aliases: vec!["genome".into()], - class: Molecule, - arity: Unary, - admitted_phases: vec![DnaAuthority, Product], - opcode: 0x1107, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "P#".into(), - ascii_aliases: vec!["plasmid".into()], - class: Molecule, - arity: Unary, - admitted_phases: vec![DnaAuthority, Product], - opcode: 0x1108, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "A#".into(), - ascii_aliases: vec!["atom".into()], - class: Molecule, - arity: Unary, - admitted_phases: vec![DnaAuthority, Product], - opcode: 0x1109, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "B#".into(), - ascii_aliases: vec!["bond".into()], - class: Relation, - arity: Binary, - admitted_phases: vec![DnaAuthority, Product], - opcode: 0x110a, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "X>".into(), - ascii_aliases: vec!["reaction".into()], - class: Process, - arity: Transform, - admitted_phases: vec![DnaAuthority, Receipt], - opcode: 0x110b, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "W!".into(), - ascii_aliases: vec!["witness".into()], - class: WitnessForm, - arity: Unary, - admitted_phases: vec![Product, Receipt], - opcode: 0x110c, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "C#".into(), - ascii_aliases: vec!["chassis".into()], - class: Molecule, - arity: Unary, - admitted_phases: vec![DnaAuthority, Product], - opcode: 0x110d, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "K#".into(), - ascii_aliases: vec!["cassette".into()], - class: Molecule, - arity: Unary, - admitted_phases: vec![DnaAuthority, Product], - opcode: 0x110e, - canonical: true, - tombstoned: false, - }, - CodonSpec { - symbol: "M#".into(), - ascii_aliases: vec!["memo".into(), "digest".into(), "hash".into()], - class: Machine, - arity: Unary, - admitted_phases: vec![MachineMemo], - opcode: 0x11ff, - canonical: false, - tombstoned: false, - }, - ] -} - -pub fn opcode_range_specs() -> Vec { - vec![ - OpcodeRangeSpec { - name: "core-relations".into(), - start: 0x1100, - end: 0x113f, - purpose: "active structural codons".into(), - }, - OpcodeRangeSpec { - name: "macro-patterns".into(), - start: 0x1200, - end: 0x12ff, - purpose: "macro-codon pattern/reaction codons".into(), - }, - OpcodeRangeSpec { - name: "tombstones".into(), - start: 0x1f00, - end: 0x1ffe, - purpose: "retired opcode tombstones; never reused".into(), - }, - OpcodeRangeSpec { - name: "machine-memo".into(), - start: 0x11ff, - end: 0x11ff, - purpose: "machine memo/cache binding only".into(), - }, - ] -} - -pub fn tombstone_specs() -> Vec { - vec![TombstoneSpec { - opcode: 0x1f00, - symbol: "Q!".into(), - reason: "retired Q-surface authority marker".into(), - replacement: Some("header codon phase law".into()), - }] -} - -pub fn phase_admission_matrix() -> Vec { - use CodonPhase::*; - vec![ - PhaseAdmissionRule { - phase: SourceRna, - admits_source_compile: true, - admits_authority_decode: false, - admits_product_expression: false, - admits_debug_export: false, - explanation: "authored source may enter compile-rna".into(), - }, - PhaseAdmissionRule { - phase: CanonicalRna, - admits_source_compile: true, - admits_authority_decode: false, - admits_product_expression: false, - admits_debug_export: false, - explanation: "canonical reconstruction may re-enter compile-rna for fixed-point checks".into(), - }, - PhaseAdmissionRule { - phase: DnaAuthority, - admits_source_compile: false, - admits_authority_decode: true, - admits_product_expression: true, - admits_debug_export: false, - explanation: "DNA authority can decode and feed witnessed expression, not source compilation".into(), - }, - PhaseAdmissionRule { - phase: Product, - admits_source_compile: false, - admits_authority_decode: false, - admits_product_expression: false, - admits_debug_export: false, - explanation: "products are expressed outputs and cannot act as source".into(), - }, - PhaseAdmissionRule { - phase: Projection, - admits_source_compile: false, - admits_authority_decode: false, - admits_product_expression: false, - admits_debug_export: false, - explanation: "projections are views and cannot act as source or authority".into(), - }, - PhaseAdmissionRule { - phase: Receipt, - admits_source_compile: false, - admits_authority_decode: false, - admits_product_expression: false, - admits_debug_export: false, - explanation: "receipts validate lineage but cannot act as source".into(), - }, - PhaseAdmissionRule { - phase: ForeignDebug, - admits_source_compile: false, - admits_authority_decode: false, - admits_product_expression: false, - admits_debug_export: true, - explanation: "foreign/debug output is inspection-only unless explicitly imported by another adapter".into(), - }, - PhaseAdmissionRule { - phase: MachineMemo, - admits_source_compile: false, - admits_authority_decode: false, - admits_product_expression: false, - admits_debug_export: false, - explanation: "machine memo/cache bindings are never public proof/source identity".into(), - }, - ] -} - -pub fn phase_admission_rule(phase: CodonPhase) -> Option { - phase_admission_matrix() - .into_iter() - .find(|rule| rule.phase == phase) -} - -pub fn codon_header_admits_source_compile(header: &CodonHeader) -> bool { - phase_admission_rule(header.phase) - .map(|rule| rule.admits_source_compile) - .unwrap_or(false) -} - -pub fn generated_structural_word_ban_list() -> Vec<&'static str> { - vec![ - "claim_page", - "dependency_spine", - "closure_map", - "roundtrip_report", - "view_receipt", - "artifact_class", - "payload_json", - "metadata", - "theorem", - "campaign", - "adequacy", - ] -} - -pub fn generated_structural_word_violations(text: &str) -> Vec { - generated_structural_word_violations_in_segments(&[NativeStructuralSegment { - region: NativeStructuralRegion::CodonBody, - text: text.into(), - }]) -} - -pub fn generated_structural_word_violations_in_segments( - segments: &[NativeStructuralSegment], -) -> Vec { - let mut violations = Vec::new(); - for segment in segments { - if matches!( - segment.region, - NativeStructuralRegion::Gloss - | NativeStructuralRegion::Comment - | NativeStructuralRegion::HumanView - ) { - continue; - } - let lower = segment.text.to_ascii_lowercase(); - for word in generated_structural_word_ban_list() { - if lower.contains(word) { - violations.push(format!("{:?}:{word}", segment.region)); - } - } - } - violations -} - -pub fn resolve_codon_symbol_or_alias(value: &str) -> Option { - let normalized = value.trim().to_ascii_lowercase(); - codon_specs().into_iter().find(|codon| { - codon.symbol == value - || codon - .ascii_aliases - .iter() - .any(|alias| alias.eq_ignore_ascii_case(&normalized)) - }) -} - -pub fn codon_admitted_in_phase(codon: &CodonSpec, phase: CodonPhase) -> bool { - codon.admitted_phases.contains(&phase) -} - -pub fn parse_codon_header(text: &str) -> Result { - let mut lines = text.lines().map(str::trim).filter(|line| !line.is_empty()); - let protocol = lines - .next() - .ok_or_else(|| "missing codon protocol header".to_string())?; - if protocol != "!λ64/2" && protocol != "!l64/2" { - return Err("codon header must start with !λ64/2 or !l64/2".into()); - } - let frame = lines - .next() - .ok_or_else(|| "missing codon frame header".to_string())?; - let frame = frame - .strip_prefix('⟦') - .and_then(|value| value.strip_suffix('⟧')) - .ok_or_else(|| "codon frame header must be enclosed in ⟦...⟧".to_string())?; - let (phase_alias, rest) = frame - .split_once(' ') - .ok_or_else(|| "codon frame header missing phase".to_string())?; - let phase = match phase_alias { - "τ" | "src" | "source" => CodonPhase::SourceRna, - "τ̂" | "canonical-rna" => CodonPhase::CanonicalRna, - "γ" | "dna" | "authority" => CodonPhase::DnaAuthority, - "ξ" | "product" => CodonPhase::Product, - "π" | "projection" => CodonPhase::Projection, - "ρ" | "receipt" => CodonPhase::Receipt, - "μ" | "memo" => CodonPhase::MachineMemo, - _ => return Err(format!("unknown codon header phase {phase_alias}")), - }; - let (class_role, subject) = rest - .split_once('·') - .ok_or_else(|| "codon frame header missing subject separator".to_string())?; - let mut class_role = class_role.split_whitespace(); - let class_symbol = class_role - .next() - .ok_or_else(|| "missing class symbol".to_string())? - .to_string(); - let role_symbol = class_role.next().unwrap_or("").to_string(); - let subject = subject.trim().to_string(); - if subject.is_empty() { - return Err("codon header subject is empty".into()); - } - Ok(CodonHeader { - protocol: protocol.into(), - version: 2, - phase, - class_symbol, - role_symbol, - subject, - }) -} - -pub fn validate_codon_lexon_law() -> CodonLexonLawReport { - let codons = codon_specs(); - let lexons = lexon_specs(); - let macro_codons = macro_codon_specs(); - let tombstones = tombstone_specs(); - let mut failures = Vec::new(); - let mut codon_symbols = HashSet::new(); - let mut active_opcodes = HashMap::new(); - let mut reserved_opcodes = HashSet::new(); - let mut aliases = HashSet::new(); - - for tombstone in &tombstones { - if !reserved_opcodes.insert(tombstone.opcode) { - failures.push(format!( - "duplicate tombstone opcode {:#06x}", - tombstone.opcode - )); - } - } - - for codon in &codons { - if !codon_symbols.insert(codon.symbol.clone()) { - failures.push(format!("duplicate codon symbol {}", codon.symbol)); - } - if reserved_opcodes.contains(&codon.opcode) { - failures.push(format!( - "active codon {} reuses tombstoned opcode {:#06x}", - codon.symbol, codon.opcode - )); - } - if !codon.tombstoned { - if let Some(prior) = active_opcodes.insert(codon.opcode, codon.symbol.clone()) { - failures.push(format!( - "duplicate active opcode {:#06x} for {} and {}", - codon.opcode, prior, codon.symbol - )); - } - } - if codon.class == CodonClass::Machine - && codon.admitted_phases != vec![CodonPhase::MachineMemo] - { - failures.push(format!( - "machine codon {} admitted outside machine memo phase", - codon.symbol - )); - } - for alias in &codon.ascii_aliases { - if !aliases.insert(alias.to_ascii_lowercase()) { - failures.push(format!("duplicate alias {}", alias)); - } - } - } - - let lexon_symbols = lexons - .iter() - .map(|lexon| lexon.symbol.clone()) - .collect::>(); - for lexon in &lexons { - if lexon.symbol.is_empty() - || lexon.canonical_target.is_empty() - || lexon.binding_receipt.is_empty() - { - failures.push(format!("incomplete lexon binding {}", lexon.symbol)); - } - for alias in &lexon.aliases { - if !aliases.insert(alias.to_ascii_lowercase()) { - failures.push(format!("duplicate alias {}", alias)); - } - } - } - - for macro_codon in ¯o_codons { - if lexon_symbols.contains(¯o_codon.symbol) { - failures.push(format!( - "macro-codon {} collides with lexon registry", - macro_codon.symbol - )); - } - if reserved_opcodes.contains(¯o_codon.opcode) { - failures.push(format!( - "macro-codon {} reuses tombstoned opcode {:#06x}", - macro_codon.symbol, macro_codon.opcode - )); - } - if let Some(prior) = active_opcodes.insert(macro_codon.opcode, macro_codon.symbol.clone()) { - failures.push(format!( - "duplicate active opcode {:#06x} for {} and {}", - macro_codon.opcode, prior, macro_codon.symbol - )); - } - for alias in ¯o_codon.ascii_aliases { - if !aliases.insert(alias.to_ascii_lowercase()) { - failures.push(format!("duplicate alias {}", alias)); - } - } - } - - CodonLexonLawReport { - codon_count: codons.len(), - lexon_count: lexons.len(), - macro_codon_count: macro_codons.len(), - generated_word_ban_count: generated_structural_word_ban_list().len(), - valid: failures.is_empty(), - failures, - } -} diff --git a/l64-core/src/lexons.rs b/l64-core/src/lexons.rs deleted file mode 100644 index 2d191c8..0000000 --- a/l64-core/src/lexons.rs +++ /dev/null @@ -1,96 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum LexonClass { - Claim, - Definition, - Composition, - Sector, - Bridge, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum LexonScope { - GlobalPattern, - Genome, - Plasmid, - Cassette, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LexonSpec { - pub symbol: String, - pub scope: LexonScope, - pub class: LexonClass, - pub canonical_target: String, - pub aliases: Vec, - pub gloss: String, - pub binding_receipt: String, -} - -pub fn lexon_specs() -> Vec { - vec![ - LexonSpec { - symbol: "φ_chain".into(), - scope: LexonScope::GlobalPattern, - class: LexonClass::Claim, - canonical_target: "chain-rule-claim-pattern".into(), - aliases: vec!["chain rule".into(), "chain_rule".into()], - gloss: "chain rule claim pattern".into(), - binding_receipt: "lexon-binding.chain-rule.v1".into(), - }, - LexonSpec { - symbol: "δ_deriv".into(), - scope: LexonScope::GlobalPattern, - class: LexonClass::Definition, - canonical_target: "derivative-definition-pattern".into(), - aliases: vec!["derivative".into(), "derivative_definition".into()], - gloss: "derivative definition pattern".into(), - binding_receipt: "lexon-binding.derivative.v1".into(), - }, - LexonSpec { - symbol: "δ_comp".into(), - scope: LexonScope::GlobalPattern, - class: LexonClass::Composition, - canonical_target: "composition-definition-pattern".into(), - aliases: vec!["composition".into(), "function_composition".into()], - gloss: "composition definition pattern".into(), - binding_receipt: "lexon-binding.composition.v1".into(), - }, - LexonSpec { - symbol: "β_tri".into(), - scope: LexonScope::GlobalPattern, - class: LexonClass::Sector, - canonical_target: "triadic-bridge-sector-pattern".into(), - aliases: vec![ - "triadic bridge sector".into(), - "triadic_bridge_sector".into(), - ], - gloss: "triadic bridge-sector structural pattern".into(), - binding_receipt: "lexon-binding.triadic-bridge-sector.v1".into(), - }, - LexonSpec { - symbol: "β_spec".into(), - scope: LexonScope::GlobalPattern, - class: LexonClass::Bridge, - canonical_target: "spectral-generation-bridge-pattern".into(), - aliases: vec![ - "spectral generation bridge".into(), - "spectral_generation_bridge".into(), - ], - gloss: "spectral generation bridge pattern".into(), - binding_receipt: "lexon-binding.spectral-generation-bridge.v1".into(), - }, - ] -} - -pub fn resolve_lexon_symbol_or_alias(value: &str) -> Option { - let normalized = value.trim().to_ascii_lowercase(); - lexon_specs().into_iter().find(|lexon| { - lexon.symbol == value - || lexon - .aliases - .iter() - .any(|alias| alias.eq_ignore_ascii_case(&normalized)) - }) -} diff --git a/l64-core/src/lib.rs b/l64-core/src/lib.rs deleted file mode 100644 index acfdc58..0000000 --- a/l64-core/src/lib.rs +++ /dev/null @@ -1,7967 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::fs; -use std::path::{Path, PathBuf}; - -pub mod codons; -pub mod lexons; -pub mod macro_codons; -pub mod molecular; -pub mod witness; - -pub use codons::*; -pub use lexons::*; -pub use macro_codons::*; -pub use molecular::*; -pub use witness::*; - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum ArtifactClass { - Rna, - TokenStream, - NormalizedRna, - KGraph, - CanonicalTopology, - Dna, - ExecutionReport, - Lineage, - ReuseReceipt, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum AuthorityClass { - SubstrateAuthority, - DerivedSemantic, - ExtractionSource, - DeletionTarget, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum FailureKind { - StructuralError, - ArityError, - ScopeError, - CanonicalizationError, - EncodingError, - ValidationError, - ExecutionError, - ReuseViolation, - AuthorityViolation, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum ExactnessClass { - Exact, - Approximate, - WitnessBacked, - CounterexampleCandidate, - Undischarged, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct CanonicalId(pub String); - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct DnaDigest(pub String); - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum DigestRole { - AuthorityId, - PayloadCommitment, - ReceiptId, - CacheKey, - DisplayShortId, - WitnessId, - CodecDigest, -} - -impl DigestRole { - pub fn domain_label(self) -> &'static [u8] { - match self { - DigestRole::AuthorityId => b"authority-id", - DigestRole::PayloadCommitment => b"payload-commitment", - DigestRole::ReceiptId => b"receipt-id", - DigestRole::CacheKey => b"cache-key", - DigestRole::DisplayShortId => b"display-short-id", - DigestRole::WitnessId => b"witness-id", - DigestRole::CodecDigest => b"codec-digest", - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct RoleDigest { - pub role: DigestRole, - pub value: String, -} - -impl RoleDigest { - pub fn new(role: DigestRole, value: String) -> Self { - Self { role, value } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct LineageId(pub String); - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct LedgerEntryId(pub String); - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PhaseFailure { - pub phase_id: PhaseId, - pub kind: FailureKind, - pub message: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PhaseReceipt { - pub phase_id: PhaseId, - pub input_artifact: ArtifactClass, - pub output_artifact: ArtifactClass, - pub authority: AuthorityClass, - pub canonical_id: Option, - pub failures: Vec, -} - -pub fn canonical_id_from_binary_structure(bytes: &[u8]) -> CanonicalId { - CanonicalId(blake3::hash(bytes).to_hex().to_string()) -} - -pub fn dna_digest_from_bytes(bytes: &[u8]) -> DnaDigest { - DnaDigest(role_digest_bytes(DigestRole::PayloadCommitment, bytes).value) -} - -pub type ObjectId = String; -pub type RegimeId = String; -pub type BridgeId = String; -pub type ProofId = String; -pub type AtlasCellId = String; -pub type TheoremId = String; -pub type ObligationId = String; -pub type CertificateId = String; -pub type RouteLedgerId = String; -pub type CampaignId = String; -pub type TargetProfileId = String; -pub type RouteClassId = String; -pub type SurfacePolicyId = String; -pub type TransformReceiptId = String; -pub type RoundTripReportId = String; -pub type CapabilityMatrixId = String; -pub type SurfaceBudgetId = String; -pub type CodebookPackId = String; -pub type GlyphPackId = String; -pub type ComboPackId = String; -pub type ProjectionPolicyId = String; -pub type AliasExpansionPolicyId = String; -pub type EqClassId = u32; -pub type CanonId = u32; -pub type RouteId = u32; -pub type CertId = u32; - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ProjectRoot { - pub absolute_path: String, - pub resolution_source: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CacheRoot { - pub absolute_path: String, - pub resolution_source: String, - #[serde(default)] - pub namespace: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PathNormalizationReceipt { - pub id: String, - pub original_path: String, - pub normalized_path: String, - pub project_relative_path: Option, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ArtifactLocator { - pub artifact_id: String, - pub artifact_kind: String, - pub absolute_path: String, - pub normalized_path: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RootResolutionReport { - pub project_root: ProjectRoot, - pub cache_root: CacheRoot, - pub receipts: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum ObjectTag { - Ctx, - Cut, - Thr, - Brc, - Slk, - Tol, - Knt, - Wit, - Can, - Prm, - Car, - Rel, - Map, - Opr, - Inv, - Qot, - Loc, - Glb, - Der, - Int, - Msr, - Prf, - Jdg, - Typ, - Mor, - Ftr, - Cmp, - Red, - Cst, - Brg, - Brp, - Bud, - Blaw, - Bheu, - Brec, - Prs, - Cnz, - Rgy, - Sel, - Chk, - Mec, - Ade, - Tcm, - Ths, - Obl, - Prmz, - Cpg, - Crt, - Vrt, - Dgn, - Trl, - Tgt, - Cmpa, - Atl, - Atlx, - Rtc, - Rcc, - Pol, - Xfr, - Rtp, - Cap, - Sbd, - Doc, - Hdr, - Pkg, - Sfc, - Fmt, - Bnd, - Bent, - Bidx, - Bdep, - Bmer, - Bcon, - Bovr, - Mop, - Mpg, - Mpn, - Mpe, - Mpb, - Mpc, - Mpr, - Mpt, - Mpa, - Mps, - Mpv, - Blk, - Exm, - Pmf, - Rlm, - Lrc, - Ldf, - Obs, - Obg, - Obn, - Obe, - Evt, - Chc, - Otr, - Rte, - Cce, - Dif, - Drf, - Imp, - Prd, - Rcp, - Rsk, - Exc, - Odg, - Odn, - Ode, - Ogr, - Ocl, - Obr, - Opl, - Oxr, - Olan, - Oord, - Omer, - Oskp, - Orer, - Orpl, - Rog, - Rlc, - Rbr, - Rmr, - Rdr, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum SurfaceKind { - Sc0, - Gs0, - As0, - Qc0, - Qm0, - Qa0, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum TransformKind { - Import, - Export, - Transcode, - Normalize, - RoundTrip, - Expand, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum TransformVerdict { - Identity, - Lossless, - ReceiptedLoss, - Unsupported, - Invalid, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ProjectionPolicyKind { - StrictAuthority, - CanonicalAuthored, - InputProjectionOnly, - DebugMirrorOnly, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum AliasExpansionPolicyKind { - ForbidImplicit, - ExpandDeclared, - ExpandAndReceipt, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum SurfaceDeficiencyKind { - MissingHeader, - MissingCodebook, - MissingProfile, - MissingComboPack, - MissingGlyphPack, - UnsupportedSymbol, - UnsupportedCombo, - QkAuthorityConfusion, - RoundtripUnverified, - SurfacePackMismatch, - SilentDefaultingRisk, - DebugCollapseUnreceipted, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum SurfaceCompatibilityClass { - AuthorityPreserving, - SymbolicFidelityPreserving, - DebugMirrorOnly, - IngressProjectionOnly, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SurfaceRequirement { - pub required_input: Option, - pub preferred_output: Option, - pub require_symbolic_fidelity: bool, - pub keyboard_projection_ingress_only: bool, - pub transform_receipts_mandatory: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SurfaceRoutePenalty { - pub reason: String, - pub amount: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SurfaceTransitionCost { - pub compatibility: SurfaceCompatibilityClass, - pub penalties: Vec, - pub total_penalty: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SurfacePreferredTarget { - pub surface_kind: SurfaceKind, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum SupportedPack { - Core, - PackA, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum EvidenceMaturity { - Candidate, - Registered, - Validated, - Certified, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum GateVerdict { - Pass, - Fail, - Review, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct IdentityFace { - pub tag: ObjectTag, - pub cid: String, - pub codebook: String, - pub remap: String, - pub lineage: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct StructuralFace { - pub head: String, - pub args: Vec, - pub local_sections: Vec, - pub morphism_hooks: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ConstraintFace { - pub regime: RegimeId, - pub contracts: Vec, - pub invariants: Vec, - pub equivalence: String, - pub admissibility: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct EvidenceFace { - pub evidence_class: String, - pub traces: Vec, - pub receipts: Vec, - pub maturity: EvidenceMaturity, - pub gate_verdict: GateVerdict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct AliasFace { - pub aliases: Vec, - pub profile_pack: Vec, - pub qm_binding: String, - pub qa_binding: String, - pub projection_policy: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CodebookPack { - pub id: CodebookPackId, - pub version: String, - pub symbols: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct GlyphPack { - pub id: GlyphPackId, - pub version: String, - pub pack: SupportedPack, - pub delimiters: BTreeMap, - pub operators: BTreeMap, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ComboPack { - pub id: ComboPackId, - pub version: String, - pub pack: SupportedPack, - pub combos: BTreeMap, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ProjectionPolicy { - pub id: ProjectionPolicyId, - pub kind: ProjectionPolicyKind, - pub allow_qa0_downgrade: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct AliasExpansionPolicy { - pub id: AliasExpansionPolicyId, - pub kind: AliasExpansionPolicyKind, - pub allowed_aliases: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SurfacePolicy { - pub id: SurfacePolicyId, - pub codebook_pack: CodebookPackId, - pub profile: String, - pub projection_policy: ProjectionPolicyId, - pub combo_pack: Option, - pub glyph_pack: Option, - pub alias_expansion_policy: AliasExpansionPolicyId, - pub allowed_loss_classes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SurfaceBudget { - pub id: SurfaceBudgetId, - pub max_loss_classes: usize, - pub forbid_silent_defaulting: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct FormatTransformReceipt { - pub id: TransformReceiptId, - pub src_surface: SurfaceKind, - pub dst_surface: SurfaceKind, - pub object_ids: Vec, - pub transform_kind: TransformKind, - pub policy_id: SurfacePolicyId, - pub defaults_used: Vec, - pub alias_expansions: Vec, - pub loss_classes: Vec, - pub hash_before: String, - pub hash_after: String, - pub verdict: TransformVerdict, - pub rollback_ref: Option, - pub replay_ref: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RoundTripReport { - pub id: RoundTripReportId, - pub surface_kind: SurfaceKind, - pub policy_id: SurfacePolicyId, - pub object_ids: Vec, - pub receipt_ids: Vec, - pub verdict: TransformVerdict, - pub fragility_vector: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CapabilityMatrix { - pub id: CapabilityMatrixId, - pub surface_kind: SurfaceKind, - pub supported_packs: Vec, - pub import_support: bool, - pub export_support: bool, - pub transcode_support: Vec, - pub roundtrip_support: bool, - pub known_limits: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SurfaceDeficiency { - pub id: String, - pub kind: SurfaceDeficiencyKind, - pub surface_kind: SurfaceKind, - pub message: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct HeaderEnvelope { - pub surface_kind: SurfaceKind, - pub version: String, - pub policy_id: SurfacePolicyId, - pub capability_id: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct QcObject { - pub id: ObjectId, - pub identity: IdentityFace, - pub structural: StructuralFace, - pub constraint: ConstraintFace, - pub evidence: EvidenceFace, - pub alias: AliasFace, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RegimePack { - pub id: RegimeId, - pub ctx_law: String, - pub cut_law: String, - pub thr_law: String, - pub brc_law: String, - pub slk_law: String, - pub tol_law: String, - pub knt_law: String, - pub eq_law: String, - pub adm_law: String, - pub promoted_ops: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ReversibilityClass { - Exact, - Conservative, - Enriching, - Forgetting, - LossySupported, - Invalid, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BridgeContract { - pub id: BridgeId, - pub src: RegimeId, - pub tgt: RegimeId, - pub id_pres: String, - pub eq_pres: String, - pub forget: Vec, - pub enrich: Vec, - pub loss: Vec, - pub reversibility: ReversibilityClass, - pub receipts: Vec, - pub rollback: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ProofShapeKind { - Square, - Triangle, - Diamond, - Pentagon, - Hexagon, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ProofEdge { - pub from: String, - pub to: String, - pub label: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ProofShape { - pub id: ProofId, - pub kind: ProofShapeKind, - pub nodes: Vec, - pub edges: Vec, - pub equations: Vec, - pub target_equivalence: String, - pub receipts: Vec, - pub gate: GateVerdict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum KernelRuleId { - K1, - K2, - K3, - K4, - K5, - K6, - K7, - K8, - K9, - K10, - K11, - K12, - K13, - K14, - K15, - K16, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum Judgment { - Ctx { - object: ObjectId, - }, - Cut { - object: ObjectId, - }, - Thr { - object: ObjectId, - }, - Brc { - object: ObjectId, - }, - Slk { - left: ObjectId, - right: ObjectId, - rank: u32, - }, - Tol { - object: ObjectId, - carrier: String, - }, - Knt { - object: ObjectId, - }, - Wit { - object: ObjectId, - }, - Can { - object: ObjectId, - canonical: ObjectId, - }, - Prm { - object: ObjectId, - }, - Brg { - bridge: BridgeId, - }, - Path { - bridges: Vec, - }, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum BurdenClass { - ExtensionalCarrierReasoning, - ProofRelevantAlgebra, - DerivativeLocalWitnessExtraction, - MeasurableNormalizedBranching, - ProbabilisticJudgment, - SimulationExecutableInference, - CertifiedPropertyWitness, - ImportedKernelClaim, - ProjectionClosure, - Containment, - RunningLaw, - General, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum WinnerState { - SeedWinner, - Candidate, - Alternative, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct Budget { - pub max_loss: usize, - pub allow_lossy_supported: bool, - pub require_proof: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LossProfile { - pub items: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct FailureSignature { - pub code: String, - pub message: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum RecipeMaturity { - Prototype, - Seeded, - Stable, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum CertificationVerdict { - Invalid, - Underspecified, - RouteFound, - Benchmarked, - Certified, - Integrated, - BlockedOpen, - BlockedContradiction, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ArtifactOrigin { - Seed, - Overlay, - Unknown, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ProofMechanismZone { - PmzStructural, - PmzBridge, - PmzLocalToGlobal, - PmzAggregation, - PmzReduction, - PmzCanonicalization, - PmzSemantic, - PmzSpectral, - PmzObstruction, - PmzProbabilistic, - PmzOperational, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ObligationKind { - OblEq, - OblAdm, - OblLoc, - OblGlu, - OblTol, - OblRed, - OblBrg, - OblRbk, - OblAde, - OblFin, - OblObs, - OblKnt, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum RequiredProofShapeFamily { - Minimal, - Triangle, - Square, - Diamond, - Pentagon, - Hexagon, - MixedBattery, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum PromotionGoal { - PromoteOperator, - PromoteBridge, - PromoteRouteClass, - Retire, - OpenBlocked, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum CampaignClass { - CBasic, - CBridge, - CWelded, - COperator, - CAtlas, - COpen, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum AtlasDeficiencyClass { - DNoRoute, - DHighLoss, - DBadEqTransport, - DRollbackCliff, - DNoAdequacy, - DBridge, - DEq, - DSelector, - DRoundtrip, - DPromo, - DNoCommutingProof, - DNoOperatorPayoff, - DOpenConjectural, - DProjection, - DContainment, - DClosure, - DRunningLaw, - DEvidenceContract, - DBenchmarkGap, - DStressGap, - DChallengeGap, - DHostPackMissing, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum DeficiencyBlockingScope { - Campaign, - Promotion, - Planning, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum DeficiencyControlEffect { - BlockCampaign, - BlockPromotion, - BlockPlanning, - SuggestNextSeam, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct AtlasCell { - pub id: AtlasCellId, - pub source_regime: RegimeId, - pub target_regime: RegimeId, - pub burden_class: BurdenClass, - pub proof_target: String, - pub candidate_paths: Vec>, - pub normalized_winner: Vec, - pub winner_state: WinnerState, - pub loss_profile: LossProfile, - pub proof_shapes_checked: Vec, - pub recipe_maturity: RecipeMaturity, - pub failure_signatures: Vec, - pub side_conditions: Vec, - #[serde(default)] - pub surface_transition: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ParserObject { - pub id: String, - pub supported_surfaces: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CanonicalizerObject { - pub id: String, - pub regime_scope: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RegistryObject { - pub id: String, - pub domains: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SelectorObject { - pub id: String, - pub burden_axes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CheckerObject { - pub id: String, - pub proof_shapes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct MechanizationPackage { - pub id: String, - pub parser: ParserObject, - pub canonicalizer: CanonicalizerObject, - pub registry: RegistryObject, - pub selector: SelectorObject, - pub checker: CheckerObject, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TheoremSpec { - pub id: TheoremId, - pub statement: String, - pub hosts: Vec, - pub bridges: Vec, - pub operators: Vec, - pub target_equivalence: String, - pub obligations: Vec, - pub primary_zone: ProofMechanismZone, - pub verdict: CertificationVerdict, - pub proof_shapes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct Obligation { - pub id: ObligationId, - pub kind: ObligationKind, - pub description: String, - pub status: CertificationVerdict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TargetProfile { - pub id: TargetProfileId, - pub burden_class: BurdenClass, - pub host_cluster: Vec, - pub target_equivalence: String, - pub allowed_bridge_classes: Vec, - pub loss_ceiling: usize, - pub rollback_ceiling: usize, - pub required_receipt_class: String, - pub required_proof_shape_family: RequiredProofShapeFamily, - pub promotion_goal: PromotionGoal, - pub primary_zone: ProofMechanismZone, - #[serde(default)] - pub surface_requirement: Option, - #[serde(default)] - pub preferred_surface_target: Option, - #[serde(default)] - pub optimizer_policy: Option, - #[serde(default)] - pub policy_binding_ids: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RouteLedger { - pub id: RouteLedgerId, - pub theorem: TheoremId, - pub paths: Vec>, - pub budget: Budget, - pub losses: Vec, - pub receipts: Vec, - pub normalized_path: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct Certificate { - pub id: CertificateId, - pub theorem: TheoremId, - pub route_ledger: RouteLedgerId, - pub proof_shapes: Vec, - pub receipts: Vec, - pub verdict: CertificationVerdict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct Campaign { - pub id: CampaignId, - pub theorem: TheoremId, - pub target_profile: TargetProfileId, - pub route_ledger: RouteLedgerId, - pub obligations: Vec, - pub certificates: Vec, - pub dependencies: Vec, - pub campaign_class: CampaignClass, - pub verdict: CertificationVerdict, - pub payoff: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CampaignPortfolio { - pub id: String, - pub campaigns: Vec, - pub normalized: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RouteClass { - pub id: RouteClassId, - pub theorem: TheoremId, - pub target_profile: TargetProfileId, - pub equivalent_paths: Vec>, - pub canonical_path: Vec, - pub verdict: CertificationVerdict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct AtlasDeficiency { - pub id: String, - pub class: AtlasDeficiencyClass, - pub atlas_cell: Option, - pub theorem: Option, - pub message: String, - #[serde(default)] - pub blocking_scope: Option, - #[serde(default)] - pub control_effects: Vec, - #[serde(default)] - pub suggested_seam: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum AdequacyClauseKind { - ObjectInterpretation, - ThreadInterpretation, - EquivalenceInterpretation, - TollInterpretation, - KnotInterpretation, - BridgeSoundness, - ProjectionInterpretation, - ContainmentInterpretation, - ClosureInterpretation, - RunningLawInterpretation, - EvidenceContractInterpretation, - BenchmarkInterpretation, - StressInterpretation, - ChallengeInterpretation, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ClaimClass { - Kernel, - Interoperability, - Host, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum AuthorityState { - Derived, - Benchmark, - Evidence, - Projection, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum BenchmarkRole { - TargetCase, - Control, - Stress, - Trace, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ChallengeStatus { - Open, - Addressed, - Retired, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BurdenPack { - pub id: String, - #[serde(default)] - pub allowed_host_cluster: Vec, - #[serde(default)] - pub obligation_ids: Vec, - #[serde(default)] - pub adequacy_clause_ids: Vec, - pub required_proof_shape_family: RequiredProofShapeFamily, - #[serde(default)] - pub route_class_constraints: Vec, - #[serde(default)] - pub evidence_contract_ids: Vec, - pub promotion_ceiling: CertificationVerdict, - #[serde(default)] - pub blocker_taxonomy: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ClaimPacket { - pub id: String, - pub claim_class: ClaimClass, - pub authority_state: AuthorityState, - pub target_sector: String, - pub statement: String, - #[serde(default)] - pub assumptions: Vec, - #[serde(default)] - pub open_caveats: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct EvidenceContract { - pub id: String, - #[serde(default)] - pub required_evidence_kinds: Vec, - #[serde(default)] - pub required_benchmark_roles: Vec, - #[serde(default)] - pub requires_stress: bool, - #[serde(default)] - pub requires_challenge: bool, - #[serde(default)] - pub admissibility_thresholds: Vec, - pub promotion_ceiling: CertificationVerdict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BenchmarkReceipt { - pub id: String, - pub claim_packet_id: String, - pub role: BenchmarkRole, - pub verdict: CertificationVerdict, - #[serde(default)] - pub metrics: BTreeMap, - pub reproducibility_ref: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ChallengeReceipt { - pub id: String, - pub claim_packet_id: String, - #[serde(default)] - pub grounds: Vec, - pub required_response: String, - pub status: ChallengeStatus, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReproducibilityPacket { - pub id: String, - pub claim_packet_id: String, - #[serde(default)] - pub derivation_path: Vec, - #[serde(default)] - pub code_refs: Vec, - #[serde(default)] - pub benchmark_refs: Vec, - #[serde(default)] - pub artifact_refs: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct AdequacyClause { - pub id: String, - pub kind: AdequacyClauseKind, - pub regime_ids: Vec, - #[serde(default)] - pub bridge_ids: Vec, - #[serde(default)] - pub theorem_ids: Vec, - #[serde(default)] - pub burden_pack_ids: Vec, - #[serde(default)] - pub claim_packet_ids: Vec, - #[serde(default)] - pub evidence_contract_ids: Vec, - #[serde(default)] - pub benchmark_receipt_ids: Vec, - #[serde(default)] - pub challenge_receipt_ids: Vec, - #[serde(default)] - pub reproducibility_packet_ids: Vec, - pub description: String, - #[serde(default)] - pub blocking: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct AdequacyRecord { - pub id: String, - pub clause_id: String, - pub kind: AdequacyClauseKind, - pub verdict: CertificationVerdict, - pub computed: bool, - pub blocking: bool, - pub detail: String, - #[serde(default)] - pub receipt_ids: Vec, -} - -pub fn adequacy_kind_deficiency_class(kind: &AdequacyClauseKind) -> AtlasDeficiencyClass { - match kind { - AdequacyClauseKind::BridgeSoundness => AtlasDeficiencyClass::DBridge, - AdequacyClauseKind::EquivalenceInterpretation => AtlasDeficiencyClass::DEq, - AdequacyClauseKind::ProjectionInterpretation => AtlasDeficiencyClass::DProjection, - AdequacyClauseKind::ContainmentInterpretation => AtlasDeficiencyClass::DContainment, - AdequacyClauseKind::ClosureInterpretation => AtlasDeficiencyClass::DClosure, - AdequacyClauseKind::RunningLawInterpretation => AtlasDeficiencyClass::DRunningLaw, - AdequacyClauseKind::EvidenceContractInterpretation => { - AtlasDeficiencyClass::DEvidenceContract - } - AdequacyClauseKind::BenchmarkInterpretation => AtlasDeficiencyClass::DBenchmarkGap, - AdequacyClauseKind::StressInterpretation => AtlasDeficiencyClass::DStressGap, - AdequacyClauseKind::ChallengeInterpretation => AtlasDeficiencyClass::DChallengeGap, - _ => AtlasDeficiencyClass::DNoAdequacy, - } -} - -pub fn adequacy_kind_suggested_seam(kind: &AdequacyClauseKind) -> &'static str { - match kind { - AdequacyClauseKind::BridgeSoundness => { - "bridge soundness clause for the active route remains open" - } - AdequacyClauseKind::EquivalenceInterpretation => { - "equivalence interpretation clause remains open" - } - AdequacyClauseKind::ProjectionInterpretation => { - "projection interpretation clause remains open" - } - AdequacyClauseKind::ContainmentInterpretation => { - "containment interpretation clause remains open" - } - AdequacyClauseKind::ClosureInterpretation => "closure interpretation clause remains open", - AdequacyClauseKind::RunningLawInterpretation => { - "running-law interpretation clause remains open" - } - AdequacyClauseKind::EvidenceContractInterpretation => { - "evidence-contract clause remains open" - } - AdequacyClauseKind::BenchmarkInterpretation => "benchmark coverage remains open", - AdequacyClauseKind::StressInterpretation => "stress coverage remains open", - AdequacyClauseKind::ChallengeInterpretation => "challenge coverage remains open", - _ => "adequacy clause remains open on the touched regime cluster", - } -} - -pub fn blocking_control_effects(blocking: bool) -> Vec { - if blocking { - vec![ - DeficiencyControlEffect::BlockCampaign, - DeficiencyControlEffect::BlockPromotion, - DeficiencyControlEffect::SuggestNextSeam, - ] - } else { - vec![DeficiencyControlEffect::SuggestNextSeam] - } -} - -pub fn blocking_scope(blocking: bool) -> Option { - if blocking { - Some(DeficiencyBlockingScope::Campaign) - } else { - None - } -} - -pub fn adequacy_record_deficiency( - theorem_id: &str, - atlas_cell_id: Option<&str>, - deficiency_id: String, - record: &AdequacyRecord, -) -> AtlasDeficiency { - AtlasDeficiency { - id: deficiency_id, - class: if record.verdict == CertificationVerdict::Certified { - AtlasDeficiencyClass::DNoAdequacy - } else { - adequacy_kind_deficiency_class(&record.kind) - }, - atlas_cell: atlas_cell_id.map(ToString::to_string), - theorem: Some(theorem_id.to_string()), - message: format!( - "adequacy clause {} {:?} {:?}: {}", - record.clause_id, record.kind, record.verdict, record.detail - ), - blocking_scope: if record.verdict != CertificationVerdict::Certified { - blocking_scope(record.blocking) - } else { - None - }, - control_effects: if record.verdict != CertificationVerdict::Certified { - blocking_control_effects(record.blocking) - } else { - vec![DeficiencyControlEffect::SuggestNextSeam] - }, - suggested_seam: Some(adequacy_kind_suggested_seam(&record.kind).into()), - } -} - -pub fn obligation_status_deficiency( - theorem_id: &str, - atlas_cell_id: Option<&str>, - deficiency_id: String, - obligation: &ObligationStatus, - blocking: bool, - suggested_seam: Option, -) -> AtlasDeficiency { - AtlasDeficiency { - id: deficiency_id, - class: if obligation.evaluation_mode == ObligationEvaluationMode::Unsupported { - AtlasDeficiencyClass::DOpenConjectural - } else { - AtlasDeficiencyClass::DNoAdequacy - }, - atlas_cell: atlas_cell_id.map(ToString::to_string), - theorem: Some(theorem_id.to_string()), - message: format!( - "obligation {} {:?} {:?}: {}", - obligation.obligation_id, - obligation.kind, - obligation.evaluation_mode, - obligation.detail - ), - blocking_scope: blocking_scope(blocking), - control_effects: if blocking { - blocking_control_effects(true) - } else { - Vec::new() - }, - suggested_seam, - } -} - -pub fn receipt_deficiency( - theorem_id: &str, - atlas_cell_id: Option<&str>, - deficiency_id: String, - receipt: &ObligationEvidenceReceipt, - computed_class: AtlasDeficiencyClass, - open_class: AtlasDeficiencyClass, - suggested_seam: String, -) -> AtlasDeficiency { - AtlasDeficiency { - id: deficiency_id, - class: if receipt.computed { - computed_class - } else { - open_class - }, - atlas_cell: atlas_cell_id.map(ToString::to_string), - theorem: Some(theorem_id.to_string()), - message: format!( - "equivalence receipt {} {} {:?}: {}", - receipt.id, receipt.label, receipt.verdict, receipt.detail - ), - blocking_scope: Some(DeficiencyBlockingScope::Campaign), - control_effects: blocking_control_effects(true), - suggested_seam: Some(suggested_seam), - } -} - -pub fn route_explanation_deficiency( - theorem_id: &str, - atlas_cell_id: Option<&str>, - deficiency_id: String, - explanation: &RouteExplanation, - blocking: bool, -) -> AtlasDeficiency { - AtlasDeficiency { - id: deficiency_id, - class: AtlasDeficiencyClass::DNoOperatorPayoff, - atlas_cell: atlas_cell_id.map(ToString::to_string), - theorem: Some(theorem_id.to_string()), - message: format!( - "optimizer={:?}; backend={:?}; winner={:?}; dominated={}", - explanation.optimizer_policy, - explanation.optimizer_backend, - explanation.winner_atlas_cell_id, - explanation.dominated_candidates.join("|") - ), - blocking_scope: blocking_scope(blocking), - control_effects: if blocking { - blocking_control_effects(true) - } else { - Vec::new() - }, - suggested_seam: None, - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum CheckerReceiptKind { - TheoremSpec, - TargetProfile, - RouteLedger, - Campaign, - Certificate, - ProofShape, - AdequacyClause, - ObligationVerdict, - BurdenPack, - ClaimPacket, - EvidenceContract, - BenchmarkReceipt, - ChallengeReceipt, - ReproducibilityPacket, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CheckerReceipt { - pub id: String, - pub kind: CheckerReceiptKind, - pub subject_id: String, - pub verdict: CertificationVerdict, - pub detail: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct EquivalenceClass { - pub id: String, - pub regime: RegimeId, - pub canonical_id: ObjectId, - pub members: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct RegistryBundle { - #[serde(default)] - pub version: String, - #[serde(default)] - pub objects: Vec, - #[serde(default)] - pub regimes: Vec, - #[serde(default)] - pub bridges: Vec, - #[serde(default)] - pub proof_shapes: Vec, - #[serde(default)] - pub atlas_cells: Vec, - #[serde(default)] - pub mechanization_packages: Vec, - #[serde(default)] - pub equivalence_classes: Vec, - #[serde(default)] - pub theorem_specs: Vec, - #[serde(default)] - pub obligations: Vec, - #[serde(default)] - pub target_profiles: Vec, - #[serde(default)] - pub route_ledgers: Vec, - #[serde(default)] - pub certificates: Vec, - #[serde(default)] - pub campaigns: Vec, - #[serde(default)] - pub campaign_portfolios: Vec, - #[serde(default)] - pub route_classes: Vec, - #[serde(default)] - pub atlas_deficiencies: Vec, - #[serde(default)] - pub adequacy_clauses: Vec, - #[serde(default)] - pub burden_packs: Vec, - #[serde(default)] - pub claim_packets: Vec, - #[serde(default)] - pub evidence_contracts: Vec, - #[serde(default)] - pub benchmark_receipts: Vec, - #[serde(default)] - pub challenge_receipts: Vec, - #[serde(default)] - pub reproducibility_packets: Vec, - #[serde(default)] - pub codebook_packs: Vec, - #[serde(default)] - pub glyph_packs: Vec, - #[serde(default)] - pub combo_packs: Vec, - #[serde(default)] - pub projection_policies: Vec, - #[serde(default)] - pub alias_expansion_policies: Vec, - #[serde(default)] - pub surface_policies: Vec, - #[serde(default)] - pub capability_matrices: Vec, - #[serde(default)] - pub roundtrip_reports: Vec, - #[serde(default)] - pub transform_receipts: Vec, - #[serde(default)] - pub surface_deficiencies: Vec, - #[serde(default)] - pub policy_objects: Vec, - #[serde(default)] - pub policy_bindings: Vec, - #[serde(default)] - pub policy_resolutions: Vec, - #[serde(default)] - pub bundle_locks: Vec, - #[serde(default)] - pub execution_manifests: Vec, - #[serde(default)] - pub replay_lock_manifests: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum BundleConflictPolicy { - ExactMatch, - Shadow, - Reject, - NamespacedImport, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BundleDependency { - pub id: String, - pub depends_on: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BundleEntry { - pub id: String, - pub kind: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BundleConflict { - pub id: String, - pub kind: String, - pub policy: BundleConflictPolicy, - pub message: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BundleMergeReport { - pub id: String, - pub policy: BundleConflictPolicy, - pub imported_entries: usize, - pub namespaced_entries: usize, - pub conflicts: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct OverlayRegistryDescriptor { - pub id: String, - pub parent: String, - pub bundle_id: String, - pub local_entries: usize, - pub shadowed_entries: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BundleExecutionReceipt { - pub id: String, - pub bundle_id: String, - pub theorem_ids: Vec, - pub campaign_ids: Vec, - pub overlay_id: String, - pub import_receipt_ids: Vec, - pub merge_report_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BundleManifest { - pub id: String, - pub entries: Vec, - pub dependencies: Vec, - pub merge_report: BundleMergeReport, - pub overlay: OverlayRegistryDescriptor, - pub execution_receipt: BundleExecutionReceipt, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum QaEntry { - Object(QcObject), - Regime(RegimePack), - Bridge(BridgeContract), - ProofShape(ProofShape), - AtlasCell(AtlasCell), - MechanizationPackage(MechanizationPackage), - TheoremSpec(TheoremSpec), - Obligation(Obligation), - TargetProfile(TargetProfile), - RouteLedger(RouteLedger), - Certificate(Certificate), - Campaign(Campaign), - CampaignPortfolio(CampaignPortfolio), - RouteClass(RouteClass), - AtlasDeficiency(AtlasDeficiency), - AdequacyClause(AdequacyClause), - BurdenPack(BurdenPack), - ClaimPacket(ClaimPacket), - EvidenceContract(EvidenceContract), - BenchmarkReceipt(BenchmarkReceipt), - ChallengeReceipt(ChallengeReceipt), - ReproducibilityPacket(ReproducibilityPacket), - SurfacePolicy(SurfacePolicy), - TransformReceipt(FormatTransformReceipt), - RoundTripReport(RoundTripReport), - CapabilityMatrix(CapabilityMatrix), - SurfaceBudget(SurfaceBudget), - PolicyObject(MechanizationPolicyObject), - PolicyBinding(PolicyBinding), - PolicyResolution(PolicyResolution), - BundleLock(BundleLock), - ExecutionManifest(ExecutionManifest), - ReplayLockManifest(ReplayLockManifest), - LockReceipt(LockReceipt), - LockDiff(LockDiff), - RecomputationPlan(RecomputationPlan), - PlanExecution(PlanExecutionRecord), - PredictionAssessment(PredictionAssessment), - Reconciliation(ReconciliationRecord), - RootResolution(RootResolutionReport), -} - -impl QaEntry { - pub fn id(&self) -> String { - match self { - QaEntry::Object(item) => item.id.clone(), - QaEntry::Regime(item) => item.id.clone(), - QaEntry::Bridge(item) => item.id.clone(), - QaEntry::ProofShape(item) => item.id.clone(), - QaEntry::AtlasCell(item) => item.id.clone(), - QaEntry::MechanizationPackage(item) => item.id.clone(), - QaEntry::TheoremSpec(item) => item.id.clone(), - QaEntry::Obligation(item) => item.id.clone(), - QaEntry::TargetProfile(item) => item.id.clone(), - QaEntry::RouteLedger(item) => item.id.clone(), - QaEntry::Certificate(item) => item.id.clone(), - QaEntry::Campaign(item) => item.id.clone(), - QaEntry::CampaignPortfolio(item) => item.id.clone(), - QaEntry::RouteClass(item) => item.id.clone(), - QaEntry::AtlasDeficiency(item) => item.id.clone(), - QaEntry::AdequacyClause(item) => item.id.clone(), - QaEntry::BurdenPack(item) => item.id.clone(), - QaEntry::ClaimPacket(item) => item.id.clone(), - QaEntry::EvidenceContract(item) => item.id.clone(), - QaEntry::BenchmarkReceipt(item) => item.id.clone(), - QaEntry::ChallengeReceipt(item) => item.id.clone(), - QaEntry::ReproducibilityPacket(item) => item.id.clone(), - QaEntry::SurfacePolicy(item) => item.id.clone(), - QaEntry::TransformReceipt(item) => item.id.clone(), - QaEntry::RoundTripReport(item) => item.id.clone(), - QaEntry::CapabilityMatrix(item) => item.id.clone(), - QaEntry::SurfaceBudget(item) => item.id.clone(), - QaEntry::PolicyObject(item) => item.id.clone(), - QaEntry::PolicyBinding(item) => item.id.clone(), - QaEntry::PolicyResolution(item) => item.id.clone(), - QaEntry::BundleLock(item) => item.id.clone(), - QaEntry::ExecutionManifest(item) => item.id.clone(), - QaEntry::ReplayLockManifest(item) => item.id.clone(), - QaEntry::LockReceipt(item) => item.id.clone(), - QaEntry::LockDiff(item) => item.id.clone(), - QaEntry::RecomputationPlan(item) => item.id.clone(), - QaEntry::PlanExecution(item) => item.id.clone(), - QaEntry::PredictionAssessment(item) => item.id.clone(), - QaEntry::Reconciliation(item) => item.id.clone(), - QaEntry::RootResolution(item) => item.project_root.absolute_path.clone(), - } - } - - pub fn kind_tag(&self) -> &'static str { - match self { - QaEntry::Object(_) => "object", - QaEntry::Regime(_) => "regime", - QaEntry::Bridge(_) => "bridge", - QaEntry::ProofShape(_) => "proof", - QaEntry::AtlasCell(_) => "atlas", - QaEntry::MechanizationPackage(_) => "mechanization", - QaEntry::TheoremSpec(_) => "theorem", - QaEntry::Obligation(_) => "obligation", - QaEntry::TargetProfile(_) => "target", - QaEntry::RouteLedger(_) => "ledger", - QaEntry::Certificate(_) => "certificate", - QaEntry::Campaign(_) => "campaign", - QaEntry::CampaignPortfolio(_) => "portfolio", - QaEntry::RouteClass(_) => "route-class", - QaEntry::AtlasDeficiency(_) => "diagnostic", - QaEntry::AdequacyClause(_) => "adequacy", - QaEntry::BurdenPack(_) => "burden-pack", - QaEntry::ClaimPacket(_) => "claim-packet", - QaEntry::EvidenceContract(_) => "evidence-contract", - QaEntry::BenchmarkReceipt(_) => "benchmark-receipt", - QaEntry::ChallengeReceipt(_) => "challenge-receipt", - QaEntry::ReproducibilityPacket(_) => "reproducibility-packet", - QaEntry::SurfacePolicy(_) => "surface-policy", - QaEntry::TransformReceipt(_) => "transform-receipt", - QaEntry::RoundTripReport(_) => "roundtrip-report", - QaEntry::CapabilityMatrix(_) => "capability", - QaEntry::SurfaceBudget(_) => "surface-budget", - QaEntry::PolicyObject(_) => "policy-object", - QaEntry::PolicyBinding(_) => "policy-binding", - QaEntry::PolicyResolution(_) => "policy-resolution", - QaEntry::BundleLock(_) => "bundle-lock", - QaEntry::ExecutionManifest(_) => "execution-manifest", - QaEntry::ReplayLockManifest(_) => "replay-lock", - QaEntry::LockReceipt(_) => "lock-receipt", - QaEntry::LockDiff(_) => "lock-diff", - QaEntry::RecomputationPlan(_) => "recompute-plan", - QaEntry::PlanExecution(_) => "plan-execution", - QaEntry::PredictionAssessment(_) => "prediction-assessment", - QaEntry::Reconciliation(_) => "reconciliation", - QaEntry::RootResolution(_) => "root-resolution", - } - } - - pub fn from_surface_json(kind: &str, payload: &str) -> Result { - match kind { - "object" => serde_json::from_str(payload).map(QaEntry::Object), - "regime" => serde_json::from_str(payload).map(QaEntry::Regime), - "bridge" => serde_json::from_str(payload).map(QaEntry::Bridge), - "proof" => serde_json::from_str(payload).map(QaEntry::ProofShape), - "atlas" => serde_json::from_str(payload).map(QaEntry::AtlasCell), - "mechanization" => serde_json::from_str(payload).map(QaEntry::MechanizationPackage), - "theorem" => serde_json::from_str(payload).map(QaEntry::TheoremSpec), - "obligation" => serde_json::from_str(payload).map(QaEntry::Obligation), - "target" => serde_json::from_str(payload).map(QaEntry::TargetProfile), - "ledger" => serde_json::from_str(payload).map(QaEntry::RouteLedger), - "certificate" => serde_json::from_str(payload).map(QaEntry::Certificate), - "campaign" => serde_json::from_str(payload).map(QaEntry::Campaign), - "portfolio" => serde_json::from_str(payload).map(QaEntry::CampaignPortfolio), - "route-class" => serde_json::from_str(payload).map(QaEntry::RouteClass), - "diagnostic" => serde_json::from_str(payload).map(QaEntry::AtlasDeficiency), - "adequacy" => serde_json::from_str(payload).map(QaEntry::AdequacyClause), - "burden-pack" => serde_json::from_str(payload).map(QaEntry::BurdenPack), - "claim-packet" => serde_json::from_str(payload).map(QaEntry::ClaimPacket), - "evidence-contract" => serde_json::from_str(payload).map(QaEntry::EvidenceContract), - "benchmark-receipt" => serde_json::from_str(payload).map(QaEntry::BenchmarkReceipt), - "challenge-receipt" => serde_json::from_str(payload).map(QaEntry::ChallengeReceipt), - "reproducibility-packet" => { - serde_json::from_str(payload).map(QaEntry::ReproducibilityPacket) - } - "surface-policy" | "transform-receipt" | "format-receipt" | "roundtrip-report" - | "capability" | "capability-matrix" | "surface-budget" | "surface-deficiency" => { - Err(serde_json::Error::io(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("deprecated surface-schema entry `{kind}` is not admitted"), - ))) - } - "policy-object" => serde_json::from_str(payload).map(QaEntry::PolicyObject), - "policy-binding" => serde_json::from_str(payload).map(QaEntry::PolicyBinding), - "policy-resolution" => serde_json::from_str(payload).map(QaEntry::PolicyResolution), - "bundle-lock" => serde_json::from_str(payload).map(QaEntry::BundleLock), - "execution-manifest" => serde_json::from_str(payload).map(QaEntry::ExecutionManifest), - "replay-lock" => serde_json::from_str(payload).map(QaEntry::ReplayLockManifest), - "lock-receipt" => serde_json::from_str(payload).map(QaEntry::LockReceipt), - "lock-diff" => serde_json::from_str(payload).map(QaEntry::LockDiff), - "recompute-plan" => serde_json::from_str(payload).map(QaEntry::RecomputationPlan), - "plan-execution" => serde_json::from_str(payload).map(QaEntry::PlanExecution), - "prediction-assessment" => { - serde_json::from_str(payload).map(QaEntry::PredictionAssessment) - } - "reconciliation" => serde_json::from_str(payload).map(QaEntry::Reconciliation), - "root-resolution" => serde_json::from_str(payload).map(QaEntry::RootResolution), - _ => Err(serde_json::Error::io(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("unknown qa entry kind `{kind}`"), - ))), - } - } - - pub fn to_surface_json(&self) -> Result<(&'static str, String), serde_json::Error> { - Ok(match self { - QaEntry::Object(item) => ("object", serde_json::to_string(item)?), - QaEntry::Regime(item) => ("regime", serde_json::to_string(item)?), - QaEntry::Bridge(item) => ("bridge", serde_json::to_string(item)?), - QaEntry::ProofShape(item) => ("proof", serde_json::to_string(item)?), - QaEntry::AtlasCell(item) => ("atlas", serde_json::to_string(item)?), - QaEntry::MechanizationPackage(item) => ("mechanization", serde_json::to_string(item)?), - QaEntry::TheoremSpec(item) => ("theorem", serde_json::to_string(item)?), - QaEntry::Obligation(item) => ("obligation", serde_json::to_string(item)?), - QaEntry::TargetProfile(item) => ("target", serde_json::to_string(item)?), - QaEntry::RouteLedger(item) => ("ledger", serde_json::to_string(item)?), - QaEntry::Certificate(item) => ("certificate", serde_json::to_string(item)?), - QaEntry::Campaign(item) => ("campaign", serde_json::to_string(item)?), - QaEntry::CampaignPortfolio(item) => ("portfolio", serde_json::to_string(item)?), - QaEntry::RouteClass(item) => ("route-class", serde_json::to_string(item)?), - QaEntry::AtlasDeficiency(item) => ("diagnostic", serde_json::to_string(item)?), - QaEntry::AdequacyClause(item) => ("adequacy", serde_json::to_string(item)?), - QaEntry::BurdenPack(item) => ("burden-pack", serde_json::to_string(item)?), - QaEntry::ClaimPacket(item) => ("claim-packet", serde_json::to_string(item)?), - QaEntry::EvidenceContract(item) => ("evidence-contract", serde_json::to_string(item)?), - QaEntry::BenchmarkReceipt(item) => ("benchmark-receipt", serde_json::to_string(item)?), - QaEntry::ChallengeReceipt(item) => ("challenge-receipt", serde_json::to_string(item)?), - QaEntry::ReproducibilityPacket(item) => { - ("reproducibility-packet", serde_json::to_string(item)?) - } - QaEntry::SurfacePolicy(_) - | QaEntry::TransformReceipt(_) - | QaEntry::RoundTripReport(_) - | QaEntry::CapabilityMatrix(_) - | QaEntry::SurfaceBudget(_) => { - return Err(serde_json::Error::io(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!( - "deprecated surface-schema entry `{}` is not exported", - self.kind_tag() - ), - ))); - } - QaEntry::PolicyObject(item) => ("policy-object", serde_json::to_string(item)?), - QaEntry::PolicyBinding(item) => ("policy-binding", serde_json::to_string(item)?), - QaEntry::PolicyResolution(item) => ("policy-resolution", serde_json::to_string(item)?), - QaEntry::BundleLock(item) => ("bundle-lock", serde_json::to_string(item)?), - QaEntry::ExecutionManifest(item) => { - ("execution-manifest", serde_json::to_string(item)?) - } - QaEntry::ReplayLockManifest(item) => ("replay-lock", serde_json::to_string(item)?), - QaEntry::LockReceipt(item) => ("lock-receipt", serde_json::to_string(item)?), - QaEntry::LockDiff(item) => ("lock-diff", serde_json::to_string(item)?), - QaEntry::RecomputationPlan(item) => ("recompute-plan", serde_json::to_string(item)?), - QaEntry::PlanExecution(item) => ("plan-execution", serde_json::to_string(item)?), - QaEntry::PredictionAssessment(item) => { - ("prediction-assessment", serde_json::to_string(item)?) - } - QaEntry::Reconciliation(item) => ("reconciliation", serde_json::to_string(item)?), - QaEntry::RootResolution(item) => ("root-resolution", serde_json::to_string(item)?), - }) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct QaDocument { - pub entries: Vec, -} - -pub trait Canonicalize { - fn canonicalize_object( - &self, - object: &QcObject, - registry: &dyn RegistryLookup, - ) -> Result; -} - -pub trait Promote { - fn promote(&self, object: &QcObject, registry: &dyn RegistryLookup) -> Result<(), String>; -} - -pub trait ValidateJudgment { - fn validate_judgment( - &self, - judgment: &Judgment, - registry: &dyn RegistryLookup, - ) -> Result<(), String>; -} - -pub trait CheckProofShape { - fn check_proof_shape( - &self, - shape: &ProofShape, - registry: &dyn RegistryLookup, - ) -> Result<(), String>; -} - -pub trait ComposeBridge { - fn compose_bridge_path( - &self, - bridges: &[BridgeContract], - budget: Option<&Budget>, - ) -> Result<(), String>; -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RouteSelection { - pub candidates: Vec, - pub winner: Option, - pub reasons: Vec, - #[serde(default)] - pub route_explanation: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationStatus { - pub obligation_id: ObligationId, - pub kind: ObligationKind, - pub verdict: CertificationVerdict, - pub evaluation_mode: ObligationEvaluationMode, - pub detail: String, - #[serde(default)] - pub receipts: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ObligationEvaluationMode { - StoredReceiptUsed, - RecomputedExact, - RecomputedApproximate, - RecomputedPartial, - RecomputedFailed, - Unsupported, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationEvidenceReceipt { - pub id: String, - pub label: String, - pub verdict: CertificationVerdict, - pub computed: bool, - pub detail: String, - #[serde(default)] - pub subreceipts: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum OptimizationAxis { - Lawfulness, - IdentityPreservation, - LossCompliance, - RollbackViability, - ProofShapeSatisfiability, - BundleResolution, - SurfaceTransitionPenalty, - ExecutionCost, - DerivedObligationDepth, - MaturityConfidence, - SymbolicFidelity, - ReceiptCompleteness, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum OptimizerPolicy { - Conservative, - SymbolicFidelityFirst, - ExecutionFirst, - LowLoss, - BenchmarkFriendly, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum PolicyKind { - Optimizer, - Evaluator, - Canonicalizer, - Surface, - BundleMerge, - ReplayCache, - ReportExport, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum PolicyScope { - Global, - Bundle(String), - Theorem(String), - Campaign(String), - TargetProfile(String), -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum PolicyVerdict { - Applied, - Rejected, - Conflict, - Invalid, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum OptimizerBackend { - Lexicographic, - ParetoBounded, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum EvidencePreference { - PreferRecompute, - PreferStored, - RecomputeIfSupported, - StoredOnlyWhenUnavailable, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum UnsupportedHandlingMode { - Permit, - StrictFail, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ReplayTrustClass { - ExactPolicyOnly, - AllowSurfaceOnlyChanges, - AllowApproximateReuse, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct OptimizerPolicyConfig { - pub optimizer_policy: OptimizerPolicy, - pub backend: OptimizerBackend, - pub active_axes: Vec, - pub route_explanation_verbosity: String, - pub symbolic_fidelity_preferred: bool, - pub tie_break_rules: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct EvaluatorPolicyConfig { - pub evidence_preference: EvidencePreference, - pub allow_approximation: bool, - pub unsupported_mode: UnsupportedHandlingMode, - pub require_symbolic_fidelity_route: bool, - pub prefer_comp_replay: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReplayCachePolicyConfig { - pub replay_allowed: bool, - pub exact_policy_match_required: bool, - pub survive_surface_only_changes: bool, - pub reuse_approximate_results: bool, - pub optimizer_change_invalidates: bool, - pub surface_pack_change_invalidates: bool, - pub trust_class: ReplayTrustClass, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReportPolicyConfig { - pub export_surfaces: Vec, - pub include_policy_trace: bool, - pub include_route_explanation: bool, - pub include_obligation_logs: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SchedulerPolicyConfig { - pub parallelization: ParallelizationPolicy, - pub max_workers: usize, - pub allow_parallel_replay: bool, - pub allow_parallel_certification: bool, - pub allow_parallel_exports: bool, - pub deterministic_ordering: bool, - #[serde(default)] - pub allow_parallel_obligations: bool, - #[serde(default = "default_max_workers")] - pub max_obligation_workers: usize, - #[serde(default)] - pub allow_parallel_obligation_replay: bool, - #[serde(default = "default_true")] - pub serialize_canonicalization_sensitive: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct MechanizationPolicyObject { - pub id: String, - pub kind: PolicyKind, - pub scope: PolicyScope, - pub extends: Option, - pub optimizer: Option, - pub evaluator: Option, - pub replay_cache: Option, - pub report: Option, - pub scheduler: Option, - pub canonicalizer_mode: Option, - pub merge_policy: Option, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PolicyBinding { - pub id: String, - pub policy_id: String, - pub scope: PolicyScope, - pub target_id: Option, - pub priority: u32, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PolicyConflict { - pub id: String, - pub kind: PolicyKind, - pub left_policy_id: String, - pub right_policy_id: String, - pub message: String, - pub illegal: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PolicyTrace { - pub id: String, - pub steps: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PolicyResolution { - pub id: String, - pub scope: PolicyScope, - pub applied_policy_ids: Vec, - pub conflicts: Vec, - pub trace: PolicyTrace, - pub optimizer: OptimizerPolicyConfig, - pub evaluator: EvaluatorPolicyConfig, - pub replay_cache: ReplayCachePolicyConfig, - pub report: ReportPolicyConfig, - pub scheduler: SchedulerPolicyConfig, - pub verdict: PolicyVerdict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BundleLock { - pub id: String, - pub bundle_id: String, - pub bundle_hash: String, - pub policy_resolution_id: String, - pub report_ids: Vec, - pub manifest_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PolicyManifest { - pub id: String, - pub resolution_id: String, - pub policy_ids: Vec, - pub policy_hash: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReplayLockManifest { - pub id: String, - pub report_id: String, - pub report_hash: String, - pub route_winner_hash: String, - pub policy_hash: String, - pub bundle_hash: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LockReceipt { - pub id: String, - pub lock_id: String, - pub manifest_id: String, - pub bundle_id: String, - pub receipt_ids: Vec, - pub verdict: PolicyVerdict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LockDiff { - pub id: String, - pub left_lock_id: String, - pub right_lock_id: String, - pub changed_fields: Vec, - pub semantic_changes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ObservationNodeKind { - Bundle, - PolicyResolution, - PolicyObject, - Theorem, - Campaign, - TargetProfile, - RouteWinner, - RouteCandidate, - Obligation, - Report, - Manifest, - Lock, - ReplayEvent, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObservationNode { - pub id: String, - pub kind: ObservationNodeKind, - pub ref_id: String, - pub label: String, - pub attributes: BTreeMap, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObservationEdge { - pub id: String, - pub from: String, - pub to: String, - pub relation: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ExecutionEventKind { - CertificationRun, - ReplayRun, - LockReplay, - CacheHit, - CacheMiss, - RouteSelected, - ObligationEvaluated, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ExecutionEvent { - pub id: String, - pub kind: ExecutionEventKind, - pub summary: String, - pub related_ids: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ChoiceRecord { - pub id: String, - pub choice_kind: String, - pub selected_id: String, - pub alternatives: Vec, - pub reasons: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationTraceRecord { - pub id: String, - pub theorem_id: String, - pub obligation_id: String, - pub verdict: CertificationVerdict, - pub evaluation_mode: ObligationEvaluationMode, - pub detail: String, - #[serde(default)] - pub receipts: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RouteTraceEvent { - pub id: String, - pub theorem_id: String, - pub winner_id: Option, - pub optimizer_backend: OptimizerBackend, - pub axes: Vec, - pub explanation: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CacheReplayEvent { - pub id: String, - pub report_id: String, - pub replay_status: ReplayStatus, - pub reason: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObservationGraph { - pub id: String, - pub record_id: String, - pub nodes: Vec, - pub edges: Vec, - pub choices: Vec, - pub obligation_traces: Vec, - pub route_events: Vec, - pub cache_events: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObservationRecord { - pub id: String, - pub report_id: String, - pub theorem_id: String, - pub campaign_id: Option, - pub bundle_id: Option, - pub manifest_id: Option, - pub lock_id: Option, - pub graph_id: String, - pub events: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum SemanticDiffClass { - NoSemanticChange, - PolicyOnly, - RouteOnly, - ObligationOnly, - ReplayOnly, - SurfaceOnly, - BundleDependencyOnly, - Mixed, - Inconclusive, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationDrift { - pub obligation_id: String, - pub verdict_before: Option, - pub verdict_after: Option, - pub mode_before: Option, - pub mode_after: Option, - pub meaning: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TheoremDrift { - pub theorem_id: String, - pub verdict_before: Option, - pub verdict_after: Option, - pub route_before: Option, - pub route_after: Option, - pub obligation_drifts: Vec, - pub summary: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SemanticDiff { - pub id: String, - pub left_id: String, - pub right_id: String, - pub class: SemanticDiffClass, - pub summary: Vec, - pub theorem_drifts: Vec, - pub changed_policy_ids: Vec, - pub changed_route_ids: Vec, - pub changed_dependency_ids: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DriftReport { - pub id: String, - pub diff_id: String, - pub summary: Vec, - pub theorem_drifts: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum RiskClassification { - Exact, - Strong, - Moderate, - Weak, - Unknown, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum PredictionClass { - NoImpactPredicted, - ReplayOnlyImpact, - ReportHashChangeLikely, - RouteWinnerChangeLikely, - ObligationOutcomeChangeLikely, - CertificationVerdictChangeLikely, - BundleConflictRisk, - InconclusivePrediction, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ImpactPrediction { - pub id: String, - pub baseline_id: String, - pub proposed_id: String, - pub class: PredictionClass, - pub confidence: RiskClassification, - pub reasons: Vec, - pub affected_theorems: Vec, - pub affected_reports: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum RecomputationStepKind { - Reuse, - Replay, - ReEvaluateObligation, - ReRoute, - ReCertifyTheorem, - ReRunCampaign, - ReExportReport, - RebuildManifestLock, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RecomputationStep { - pub id: String, - pub kind: RecomputationStepKind, - pub target_id: String, - pub reason: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RecomputationPlan { - pub id: String, - pub prediction_id: Option, - pub diff_id: Option, - pub reusable_artifacts: Vec, - pub invalidated_artifacts: Vec, - pub steps: Vec, - pub explanation: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum StepImpactClass { - NoOpReuse, - ReplayOnly, - ObligationScoped, - RouteScoped, - ManifestScoped, - CampaignScoped, - FullRun, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ReuseEligibilityReason { - SemanticIdentityPreserved, - ReplayPolicyAllowsReuse, - SurfaceOnlyChange, - PolicyRequiresFreshRun, - BundleChanged, - EvaluatorChanged, - RouteChanged, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum DriftCriticality { - None, - Low, - Medium, - High, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SchedulerDiffHint { - pub step_id: String, - pub impact: StepImpactClass, - pub reuse_reason: Option, - pub criticality: DriftCriticality, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum StepStrictness { - BestEffort, - PolicyGoverned, - Strict, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ReuseTrustClass { - ExactOnly, - SurfaceStable, - ApproximateAllowed, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ParallelizationPolicy { - Serialize, - ParallelIndependent, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CacheNamespace { - pub id: String, - pub root: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ExecutionScope { - pub id: String, - pub cache_namespace: CacheNamespace, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LaneExecutionRecord { - pub lane_id: String, - pub step_ids: Vec, - pub task_ids: Vec, - pub serialized_reason: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ExecutionScheduleHash { - pub id: String, - pub hash: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ConcurrencyCoherenceReceipt { - pub id: String, - pub namespace_id: String, - pub merged_artifact_ids: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct OrderingReceipt { - pub id: String, - pub ordered_step_ids: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ObligationConcurrencyClass { - ParallelSafe, - ReplaySafeWriteSensitive, - CacheSensitive, - CanonicalizationSensitive, - StrictlySerialized, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationDagNode { - pub id: String, - pub obligation_id: String, - pub concurrency_class: ObligationConcurrencyClass, - pub barrier_after: bool, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationDagEdge { - pub id: String, - pub from: String, - pub to: String, - pub reason: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationGroup { - pub id: String, - pub concurrency_class: ObligationConcurrencyClass, - pub obligation_ids: Vec, - pub serialized_reason: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationPlan { - pub id: String, - pub theorem_id: String, - pub campaign_id: Option, - pub nodes: Vec, - pub edges: Vec, - pub groups: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationLaneRecord { - pub lane_id: String, - pub group_ids: Vec, - pub obligation_ids: Vec, - pub serialized_reason: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationOrderingReceipt { - pub id: String, - pub ordered_group_ids: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationMergeReceipt { - pub id: String, - pub merged_obligation_ids: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReplayLegalityCheck { - pub id: String, - pub obligation_id: String, - pub allowed: bool, - pub reasons: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReplayBarrierReceipt { - pub id: String, - pub obligation_ids: Vec, - pub reason: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReplayMergeReceipt { - pub id: String, - pub reused_obligation_ids: Vec, - pub rerun_obligation_ids: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReplayDivergenceRecord { - pub id: String, - pub obligation_id: String, - pub reason: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationCacheShard { - pub id: String, - pub obligation_ids: Vec, - pub namespace_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationWriteSet { - pub id: String, - pub artifact_ids: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationCollisionReport { - pub id: String, - pub obligation_ids: Vec, - pub reasons: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObligationNamespaceReceipt { - pub id: String, - pub namespace_id: String, - pub shard_ids: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SchedulerPolicy { - pub id: String, - pub replay_allowed: bool, - pub strict_recomputation: bool, - pub strict_unsupported: bool, - pub parallelization: ParallelizationPolicy, - #[serde(default = "default_max_workers")] - pub max_workers: usize, - #[serde(default)] - pub allow_parallel_replay: bool, - #[serde(default = "default_true")] - pub allow_parallel_certification: bool, - #[serde(default = "default_true")] - pub allow_parallel_exports: bool, - #[serde(default = "default_true")] - pub deterministic_ordering: bool, - #[serde(default)] - pub allow_parallel_obligations: bool, - #[serde(default = "default_max_workers")] - pub max_obligation_workers: usize, - #[serde(default)] - pub allow_parallel_obligation_replay: bool, - #[serde(default = "default_true")] - pub serialize_canonicalization_sensitive: bool, - pub reuse_trust: ReuseTrustClass, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SchedulerDecisionReceipt { - pub id: String, - pub step_id: String, - pub policy_resolution_id: Option, - pub decision: String, - pub reasons: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ScheduledStepStatus { - DryRun, - Reused, - Replayed, - Executed, - Failed, - Skipped, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct StepExecutionOutcome { - pub step_id: String, - pub kind: RecomputationStepKind, - pub status: ScheduledStepStatus, - pub produced_artifact_ids: Vec, - pub receipt: SchedulerDecisionReceipt, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PlanExecutionRecord { - pub id: String, - pub plan_id: String, - pub prediction_id: Option, - pub scheduler_policy: SchedulerPolicy, - pub root_resolution: RootResolutionReport, - #[serde(default)] - pub execution_scope: Option, - #[serde(default)] - pub lane_records: Vec, - #[serde(default)] - pub schedule_hash: Option, - #[serde(default)] - pub coherence_receipts: Vec, - #[serde(default)] - pub ordering_receipt: Option, - #[serde(default)] - pub obligation_plans: Vec, - #[serde(default)] - pub obligation_lanes: Vec, - #[serde(default)] - pub obligation_ordering_receipts: Vec, - #[serde(default)] - pub obligation_merge_receipts: Vec, - #[serde(default)] - pub replay_legality_checks: Vec, - #[serde(default)] - pub replay_barrier_receipts: Vec, - #[serde(default)] - pub replay_merge_receipts: Vec, - #[serde(default)] - pub replay_divergence_records: Vec, - #[serde(default)] - pub obligation_cache_shards: Vec, - #[serde(default)] - pub obligation_write_sets: Vec, - #[serde(default)] - pub obligation_collision_reports: Vec, - #[serde(default)] - pub obligation_namespace_receipts: Vec, - pub outcomes: Vec, - pub reused_artifacts: Vec, - pub rerun_artifacts: Vec, - pub resulting_report_ids: Vec, - #[serde(default)] - pub resulting_reports: Vec, - pub manifest_ids: Vec, - pub lock_ids: Vec, - pub explanation: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ExplanationObject { - pub id: String, - pub title: String, - pub details: Vec, - pub related_ids: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum PredictionAssessmentOutcome { - PredictionConfirmed, - PredictionUnderestimated, - PredictionOverestimated, - PredictionMissed, - PredictionUncheckable, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PredictionAssessment { - pub id: String, - pub prediction_id: String, - pub actual_diff_id: String, - pub outcome: PredictionAssessmentOutcome, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReconciliationRecord { - pub id: String, - pub prediction_id: String, - pub plan_id: String, - pub execution_id: String, - pub assessment: PredictionAssessment, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ExecutionManifest { - pub id: String, - pub bundle_id: String, - pub bundle_hash: String, - pub dependency_graph: Vec, - pub policy_manifest: PolicyManifest, - pub route_winner_ids: Vec, - pub evaluator_versions: Vec, - pub pack_versions: Vec, - pub report_ids: Vec, - #[serde(default)] - pub executed_plan_hash: Option, - #[serde(default)] - pub executed_steps: Vec, - #[serde(default)] - pub reused_artifacts: Vec, - #[serde(default)] - pub rerun_artifacts: Vec, - #[serde(default)] - pub reconciliation_summary: Vec, - #[serde(default)] - pub root_resolution: Option, - #[serde(default)] - pub scheduler_policy: Option, - #[serde(default)] - pub execution_scope: Option, - #[serde(default)] - pub lane_records: Vec, - #[serde(default)] - pub schedule_hash: Option, - #[serde(default)] - pub coherence_receipts: Vec, - #[serde(default)] - pub ordering_receipt: Option, - #[serde(default)] - pub obligation_plans: Vec, - #[serde(default)] - pub obligation_lanes: Vec, - #[serde(default)] - pub obligation_ordering_receipts: Vec, - #[serde(default)] - pub obligation_merge_receipts: Vec, - #[serde(default)] - pub replay_legality_checks: Vec, - #[serde(default)] - pub replay_barrier_receipts: Vec, - #[serde(default)] - pub replay_merge_receipts: Vec, - #[serde(default)] - pub replay_divergence_records: Vec, - #[serde(default)] - pub obligation_cache_shards: Vec, - #[serde(default)] - pub obligation_write_sets: Vec, - #[serde(default)] - pub obligation_collision_reports: Vec, - #[serde(default)] - pub obligation_namespace_receipts: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RouteScoreVector { - pub lawfulness: usize, - pub identity_preservation: usize, - pub loss_compliance: usize, - pub rollback_viability: usize, - pub proof_shape_satisfiability: usize, - pub bundle_resolution: usize, - pub surface_transition_penalty: usize, - pub execution_cost: usize, - pub derived_obligation_depth: usize, - pub maturity_confidence: usize, - pub symbolic_fidelity: usize, - pub receipt_completeness: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RouteExplanation { - pub optimizer_policy: OptimizerPolicy, - #[serde(default = "default_optimizer_backend")] - pub optimizer_backend: OptimizerBackend, - #[serde(default)] - pub policy_resolution_id: Option, - pub winner_atlas_cell_id: Option, - pub winner_score: Option, - pub dominated_candidates: Vec, - pub rejected_candidates: Vec, - pub axes_used: Vec, - pub explanation: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DeterministicExecutionEnvelope { - pub bundle_hash: String, - #[serde(default)] - pub bundle_id: Option, - pub policy_hash: String, - #[serde(default)] - pub policy_resolution_id: Option, - #[serde(default)] - pub manifest_id: Option, - #[serde(default)] - pub lock_id: Option, - pub route_winner_hash: String, - pub obligation_replay_keys: Vec, - pub report_hash: String, - pub replay_status: ReplayStatus, - #[serde(default)] - pub executed_plan_id: Option, - #[serde(default)] - pub reconciliation_id: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum ReplayStatus { - Fresh, - CacheHit, - ReplayOnly, - Invalidated, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CertificationCandidate { - pub atlas_cell_id: AtlasCellId, - pub path: Vec, - pub loss_count: usize, - pub proof_shapes: Vec, - pub route_class_id: Option, - pub score: Vec, - #[serde(default)] - pub route_score: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CertificationReport { - pub theorem_id: TheoremId, - pub campaign_id: Option, - pub target_profile_id: TargetProfileId, - pub verdict: CertificationVerdict, - pub selected_atlas_cell: Option, - pub selected_path: Vec, - pub route_class_id: Option, - pub certificate_id: Option, - pub candidates: Vec, - pub obligations: Vec, - pub reasons: Vec, - pub diagnostics: Vec, - #[serde(default)] - pub deficiencies: Vec, - #[serde(default)] - pub adequacy_records: Vec, - #[serde(default)] - pub checker_receipts: Vec, - #[serde(default)] - pub burden_pack_ids: Vec, - #[serde(default)] - pub claim_packet_ids: Vec, - #[serde(default)] - pub evidence_contract_ids: Vec, - #[serde(default)] - pub benchmark_receipt_ids: Vec, - #[serde(default)] - pub challenge_receipt_ids: Vec, - #[serde(default)] - pub reproducibility_packet_ids: Vec, - #[serde(default)] - pub promotion_artifact_ids: Vec, - #[serde(default)] - pub reused_artifact_ids: Vec, - #[serde(default)] - pub default_selected_artifact_ids: Vec, - #[serde(default)] - pub payoff_receipt_ids: Vec, - #[serde(default)] - pub policy_resolution: Option, - #[serde(default)] - pub route_explanation: Option, - #[serde(default)] - pub execution_envelope: Option, - #[serde(default)] - pub reconciliation_summary: Vec, - #[serde(default)] - pub obligation_plan: Option, - #[serde(default)] - pub obligation_lanes: Vec, - #[serde(default)] - pub obligation_ordering_receipt: Option, - #[serde(default)] - pub obligation_merge_receipt: Option, - #[serde(default)] - pub replay_legality_checks: Vec, - #[serde(default)] - pub replay_barrier_receipts: Vec, - #[serde(default)] - pub replay_merge_receipt: Option, - #[serde(default)] - pub replay_divergence_records: Vec, - #[serde(default)] - pub obligation_cache_shards: Vec, - #[serde(default)] - pub reuse_legality_receipts: Vec, - #[serde(default)] - pub reuse_decision_receipts: Vec, - #[serde(default)] - pub residual_verification_receipts: Vec, - #[serde(default)] - pub obligation_write_sets: Vec, - #[serde(default)] - pub obligation_collision_reports: Vec, - #[serde(default)] - pub obligation_namespace_receipt: Option, -} - -pub trait SelectRoute { - fn select_route( - &self, - src: &str, - tgt: &str, - proof_target: Option<&str>, - budget: Option<&Budget>, - ) -> Result; -} - -pub trait RegistryLookup { - fn get_object(&self, id: &str) -> Option; - fn get_object_origin(&self, id: &str) -> ArtifactOrigin { - let _ = id; - ArtifactOrigin::Unknown - } - fn get_regime(&self, id: &str) -> Option; - fn get_bridge(&self, id: &str) -> Option; - fn get_proof_shape(&self, id: &str) -> Option; - fn get_atlas_cell(&self, id: &str) -> Option; - fn get_mechanization_package(&self, id: &str) -> Option; - fn get_theorem_spec(&self, id: &str) -> Option; - fn get_obligation(&self, id: &str) -> Option; - fn get_target_profile(&self, id: &str) -> Option; - fn get_route_ledger(&self, id: &str) -> Option; - fn get_certificate(&self, id: &str) -> Option; - fn get_campaign(&self, id: &str) -> Option; - fn get_campaign_portfolio(&self, id: &str) -> Option; - fn get_route_class(&self, id: &str) -> Option; - fn get_atlas_deficiency(&self, id: &str) -> Option; - fn atlas_deficiencies(&self) -> Vec; - fn get_adequacy_clause(&self, id: &str) -> Option; - fn adequacy_clauses(&self) -> Vec; - fn get_burden_pack(&self, id: &str) -> Option { - let _ = id; - None - } - fn burden_packs(&self) -> Vec { - Vec::new() - } - fn get_claim_packet(&self, id: &str) -> Option { - let _ = id; - None - } - fn claim_packets(&self) -> Vec { - Vec::new() - } - fn get_evidence_contract(&self, id: &str) -> Option { - let _ = id; - None - } - fn evidence_contracts(&self) -> Vec { - Vec::new() - } - fn get_benchmark_receipt(&self, id: &str) -> Option { - let _ = id; - None - } - fn benchmark_receipts(&self) -> Vec { - Vec::new() - } - fn get_challenge_receipt(&self, id: &str) -> Option { - let _ = id; - None - } - fn challenge_receipts(&self) -> Vec { - Vec::new() - } - fn get_reproducibility_packet(&self, id: &str) -> Option { - let _ = id; - None - } - fn reproducibility_packets(&self) -> Vec { - Vec::new() - } - fn get_codebook_pack(&self, id: &str) -> Option; - fn get_glyph_pack(&self, id: &str) -> Option; - fn get_combo_pack(&self, id: &str) -> Option; - fn get_projection_policy(&self, id: &str) -> Option; - fn get_alias_expansion_policy(&self, id: &str) -> Option; - fn get_surface_deficiency(&self, id: &str) -> Option; - fn get_policy_object(&self, id: &str) -> Option; - fn policy_objects(&self) -> Vec; - fn policy_bindings(&self) -> Vec; - fn find_equivalence_class(&self, object_id: &str, regime: &str) -> Option; - fn atlas_cells(&self) -> Vec; -} - -pub fn document_for_registry_id(registry: &dyn RegistryLookup, id: &str) -> Option { - let entry = if let Some(item) = registry.get_object(id) { - QaEntry::Object(item) - } else if let Some(item) = registry.get_regime(id) { - QaEntry::Regime(item) - } else if let Some(item) = registry.get_bridge(id) { - QaEntry::Bridge(item) - } else if let Some(item) = registry.get_proof_shape(id) { - QaEntry::ProofShape(item) - } else if let Some(item) = registry.get_atlas_cell(id) { - QaEntry::AtlasCell(item) - } else if let Some(item) = registry.get_mechanization_package(id) { - QaEntry::MechanizationPackage(item) - } else if let Some(item) = registry.get_theorem_spec(id) { - QaEntry::TheoremSpec(item) - } else if let Some(item) = registry.get_obligation(id) { - QaEntry::Obligation(item) - } else if let Some(item) = registry.get_target_profile(id) { - QaEntry::TargetProfile(item) - } else if let Some(item) = registry.get_route_ledger(id) { - QaEntry::RouteLedger(item) - } else if let Some(item) = registry.get_certificate(id) { - QaEntry::Certificate(item) - } else if let Some(item) = registry.get_campaign(id) { - QaEntry::Campaign(item) - } else if let Some(item) = registry.get_campaign_portfolio(id) { - QaEntry::CampaignPortfolio(item) - } else if let Some(item) = registry.get_route_class(id) { - QaEntry::RouteClass(item) - } else if let Some(item) = registry.get_atlas_deficiency(id) { - QaEntry::AtlasDeficiency(item) - } else if let Some(item) = registry.get_adequacy_clause(id) { - QaEntry::AdequacyClause(item) - } else if let Some(item) = registry.get_burden_pack(id) { - QaEntry::BurdenPack(item) - } else if let Some(item) = registry.get_claim_packet(id) { - QaEntry::ClaimPacket(item) - } else if let Some(item) = registry.get_evidence_contract(id) { - QaEntry::EvidenceContract(item) - } else if let Some(item) = registry.get_benchmark_receipt(id) { - QaEntry::BenchmarkReceipt(item) - } else if let Some(item) = registry.get_challenge_receipt(id) { - QaEntry::ChallengeReceipt(item) - } else if let Some(item) = registry.get_reproducibility_packet(id) { - QaEntry::ReproducibilityPacket(item) - } else if let Some(item) = registry.get_policy_object(id) { - QaEntry::PolicyObject(item) - } else { - return None; - }; - Some(QaDocument { - entries: vec![entry], - }) -} - -pub fn resolve_project_root() -> Result { - if let Ok(explicit) = std::env::var("MF_PROJECT_ROOT") { - let path = canonicalize_or_clean(PathBuf::from(&explicit))?; - return Ok(ProjectRoot { - absolute_path: path.display().to_string(), - resolution_source: "env:MF_PROJECT_ROOT".into(), - }); - } - - let mut cursor = std::env::current_dir().map_err(|err| err.to_string())?; - let cwd = cursor.clone(); - let mut nearest_manifest_dir: Option = None; - loop { - let manifest = cursor.join("Cargo.toml"); - if manifest.exists() { - nearest_manifest_dir.get_or_insert_with(|| cursor.clone()); - let content = fs::read_to_string(&manifest).map_err(|err| err.to_string())?; - if content.contains("[workspace]") && content.contains("\"l64-core\"") { - let path = canonicalize_or_clean(cursor)?; - return Ok(ProjectRoot { - absolute_path: path.display().to_string(), - resolution_source: "workspace-scan".into(), - }); - } - } - if !cursor.pop() { - break; - } - } - - if let Some(path) = nearest_manifest_dir { - let path = canonicalize_or_clean(path)?; - return Ok(ProjectRoot { - absolute_path: path.display().to_string(), - resolution_source: "nearest-cargo-manifest".into(), - }); - } - - let path = canonicalize_or_clean(cwd)?; - Ok(ProjectRoot { - absolute_path: path.display().to_string(), - resolution_source: "cwd-fallback".into(), - }) -} - -pub fn resolve_cache_root() -> Result { - if let Ok(explicit) = std::env::var("MF_CACHE_ROOT") { - let mut path = canonicalize_or_clean(PathBuf::from(&explicit))?; - let namespace = std::env::var("MF_CACHE_NAMESPACE") - .ok() - .filter(|value| !value.trim().is_empty()); - if let Some(namespace) = &namespace { - path = path.join("namespaces").join(sanitize_namespace(namespace)); - } - fs::create_dir_all(&path).map_err(|err| err.to_string())?; - return Ok(CacheRoot { - absolute_path: path.display().to_string(), - resolution_source: "env:MF_CACHE_ROOT".into(), - namespace, - }); - } - let project = resolve_project_root()?; - let mut path = PathBuf::from(&project.absolute_path).join(".l64-cache"); - let namespace = std::env::var("MF_CACHE_NAMESPACE") - .ok() - .filter(|value| !value.trim().is_empty()); - if let Some(namespace) = &namespace { - path = path.join("namespaces").join(sanitize_namespace(namespace)); - } - fs::create_dir_all(&path).map_err(|err| err.to_string())?; - Ok(CacheRoot { - absolute_path: path.display().to_string(), - resolution_source: "project-root/.l64-cache".into(), - namespace, - }) -} - -pub fn ensure_cache_subdir(name: &str) -> Result { - let root = PathBuf::from(resolve_cache_root()?.absolute_path).join(name); - fs::create_dir_all(&root).map_err(|err| err.to_string())?; - Ok(root) -} - -pub fn normalize_path_receipt(path: &Path) -> Result { - let original = path.display().to_string(); - let normalized = canonicalize_or_clean(path.to_path_buf())?; - let project_root = PathBuf::from(resolve_project_root()?.absolute_path); - let relative = normalized - .strip_prefix(&project_root) - .ok() - .map(|item| item.to_string_lossy().replace('\\', "/")); - let mut notes = Vec::new(); - if relative.is_some() { - notes.push("stored relative to project root".into()); - } else { - notes.push("path remains external to project root".into()); - } - Ok(PathNormalizationReceipt { - id: receipt_id("PNR", &normalized.display().to_string()), - original_path: original, - normalized_path: normalized.display().to_string(), - project_relative_path: relative, - notes, - }) -} - -pub fn locate_artifact(id: &str, kind: &str, path: &Path) -> Result { - let receipt = normalize_path_receipt(path)?; - Ok(ArtifactLocator { - artifact_id: id.to_string(), - artifact_kind: kind.to_string(), - absolute_path: receipt.normalized_path.clone(), - normalized_path: receipt - .project_relative_path - .clone() - .unwrap_or(receipt.normalized_path), - }) -} - -pub fn runtime_root_report(extra_paths: &[&Path]) -> Result { - let project_root = resolve_project_root()?; - let cache_root = resolve_cache_root()?; - let mut receipts = Vec::new(); - for path in extra_paths { - receipts.push(normalize_path_receipt(path)?); - } - let note = match project_root.resolution_source.as_str() { - "workspace-scan" => "workspace root and cache root resolved deterministically", - "nearest-cargo-manifest" => { - "project root resolved from the nearest Cargo manifest; cache root follows that project root" - } - "cwd-fallback" => { - "project root fell back to the current working directory; set MF_PROJECT_ROOT to pin it explicitly" - } - "env:MF_PROJECT_ROOT" => { - "project root pinned by MF_PROJECT_ROOT; cache root follows that project root unless MF_CACHE_ROOT overrides it" - } - _ => "project and cache roots resolved from the active runtime environment", - }; - Ok(RootResolutionReport { - project_root, - cache_root, - receipts, - notes: vec![note.into()], - }) -} - -pub fn summary_map() -> BTreeMap<&'static str, &'static str> { - BTreeMap::from([ - ("qm_0", "reserved"), - ("qk_0", "reserved"), - ("qa_0", "active"), - ]) -} - -fn default_optimizer_backend() -> OptimizerBackend { - OptimizerBackend::Lexicographic -} - -fn canonicalize_or_clean(path: PathBuf) -> Result { - if path.exists() { - path.canonicalize().map_err(|err| err.to_string()) - } else if path.is_absolute() { - Ok(path) - } else { - Ok(std::env::current_dir() - .map_err(|err| err.to_string())? - .join(path)) - } -} - -fn structural_value_fallback_u64(input: &str) -> u64 { - let mut hash: u64 = 0xcbf29ce484222325; - for byte in input.as_bytes() { - hash ^= u64::from(*byte); - hash = hash.wrapping_mul(0x100000001b3); - } - hash -} - -pub fn role_digest_bytes(role: DigestRole, input: &[u8]) -> RoleDigest { - let mut hasher = blake3::Hasher::new(); - hasher.update(b"l64-role-digest-v1\0"); - hasher.update(role.domain_label()); - hasher.update(b"\0"); - hasher.update(input); - RoleDigest::new(role, hasher.finalize().to_hex().to_string()) -} - -pub fn role_digest_str(role: DigestRole, input: &str) -> RoleDigest { - role_digest_bytes(role, input.as_bytes()) -} - -pub fn role_digest_serialized(role: DigestRole, value: &T) -> RoleDigest { - let encoded = serde_json::to_vec(value).unwrap_or_else(|_| b"".to_vec()); - role_digest_bytes(role, &encoded) -} - -pub fn role_digest_value(role: DigestRole, value: &T) -> String { - role_digest_serialized(role, value).value -} - -fn prefixed_role_digest(prefix: &str, role: DigestRole, value: &T) -> String { - format!("{prefix}_{}", role_digest_value(role, value)) -} - -fn receipt_id(prefix: &str, value: &T) -> String { - prefixed_role_digest(prefix, DigestRole::ReceiptId, value) -} - -fn authority_id(prefix: &str, value: &T) -> String { - prefixed_role_digest(prefix, DigestRole::AuthorityId, value) -} - -fn payload_commitment(value: &T) -> String { - role_digest_value(DigestRole::PayloadCommitment, value) -} - -pub fn cache_hash_v1_str(input: &str) -> String { - cache_hash_v1_bytes(input.as_bytes()) -} - -pub fn cache_hash_v1_bytes(input: &[u8]) -> String { - let mut hasher = blake3::Hasher::new(); - hasher.update(b"l64-cache-v1\0"); - hasher.update(input); - hasher.finalize().to_hex().to_string() -} - -fn sanitize_namespace(input: &str) -> String { - input - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' { - ch - } else { - '_' - } - }) - .collect() -} - -fn default_max_workers() -> usize { - 1 -} - -fn default_true() -> bool { - true -} - -pub trait TollValue: Clone + Eq + Ord { - fn zero() -> Self; - fn one() -> Self; - fn add(&self, other: &Self) -> Self; - fn mul(&self, other: &Self) -> Self; - fn compare(&self, other: &Self) -> Ordering { - self.cmp(other) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -pub struct NatToll(pub u64); - -impl TollValue for NatToll { - fn zero() -> Self { - Self(0) - } - fn one() -> Self { - Self(1) - } - fn add(&self, other: &Self) -> Self { - Self(self.0 + other.0) - } - fn mul(&self, other: &Self) -> Self { - Self(self.0 * other.0) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -pub struct RationalToll { - pub num: u64, - pub den: u64, -} - -impl TollValue for RationalToll { - fn zero() -> Self { - Self { num: 0, den: 1 } - } - fn one() -> Self { - Self { num: 1, den: 1 } - } - fn add(&self, other: &Self) -> Self { - Self { - num: self.num * other.den + other.num * self.den, - den: self.den * other.den, - } - } - fn mul(&self, other: &Self) -> Self { - Self { - num: self.num * other.num, - den: self.den * other.den, - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -pub struct TropicalToll(pub u64); - -impl TollValue for TropicalToll { - fn zero() -> Self { - Self(u64::MAX / 4) - } - fn one() -> Self { - Self(0) - } - fn add(&self, other: &Self) -> Self { - Self(self.0.min(other.0)) - } - fn mul(&self, other: &Self) -> Self { - Self(self.0.saturating_add(other.0)) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -pub struct LexicographicToll(pub T, pub U); - -impl TollValue for LexicographicToll { - fn zero() -> Self { - Self(T::zero(), U::zero()) - } - fn one() -> Self { - Self(T::one(), U::one()) - } - fn add(&self, other: &Self) -> Self { - Self(self.0.add(&other.0), self.1.add(&other.1)) - } - fn mul(&self, other: &Self) -> Self { - Self(self.0.mul(&other.0), self.1.mul(&other.1)) - } - fn compare(&self, other: &Self) -> Ordering { - self.0 - .compare(&other.0) - .then_with(|| self.1.compare(&other.1)) - } -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum LocusPacketKind { - CanonicalTransfer = 1, - CertificationEnvelope = 2, - CheckerEnvelope = 3, - FrontierEnvelope = 4, - TowerBundle = 5, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum GenomeArtifactClass { - Gene = 1, - Haplotype = 2, - Chromosome = 3, - Genome = 4, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum GenomeSurface { - Rna = 1, - Dna = 2, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum LocusDecodeMode { - CurrentAuthority, - Migration, - Forensic, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum LocusOpcode { - Header = 1, - CanonicalPayload = 2, - ReceiptTable = 3, - AdequacyTable = 4, - RouteLedger = 5, - Campaign = 6, - Certificate = 7, - Checker = 8, - Frontier = 9, - Proposal = 10, - Coverage = 11, - SymbolTable = 12, - Forensic = 13, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct StructuralOpcodeSpec { - pub opcode: LocusOpcode, - pub name: String, - pub structural_only: bool, - pub compatible_skip_allowed: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DnaHeaderReceipt { - pub id: String, - pub surface: GenomeSurface, - pub grammar_id: String, - pub schema_hash: String, - pub integrity_hash: String, - pub structural_opcode_table_hash: String, - pub header_truth_complete: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DnaSectionCommitment { - pub opcode: LocusOpcode, - pub subject_id: String, - pub payload_commitment: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DnaValidationReport { - pub id: String, - pub reversible: bool, - pub header_truth_complete: bool, - #[serde(default)] - pub canonical_payload_digest_valid: bool, - #[serde(default)] - pub section_payload_commitments_valid: bool, - #[serde(default)] - pub section_payload_commitments: Vec, - pub symbol_table_semantic_authority: bool, - #[serde(default)] - pub failures: Vec, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum GeneratedStatus { - Suggestion = 1, - Scaffold = 2, - VerifiedCandidate = 3, - PromotedTruth = 4, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum ProposalKind { - SemanticLeaf = 1, - AdequacyClause = 2, - CheckerExtension = 3, - Campaign = 4, - AtlasCell = 5, - PayoffTask = 6, - SearchCompartment = 7, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum CoverageDecision { - Exact = 1, - Subsumed = 2, - TransportEquivalent = 3, - Fallback = 4, - Unsupported = 5, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum ArtifactKind { - RegistryEntity = 1, - Report = 2, - ExecutionManifest = 3, - BundleLock = 4, - ObservationRecord = 5, - PredictionRecord = 6, - RecomputationPlan = 7, - PlanExecution = 8, - InspectionReport = 9, - ValidationBundle = 10, - ForensicBundle = 11, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum NamespaceScope { - Any = 1, - SameNamespace = 2, - CrossNamespaceUnsupported = 3, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum CapabilityReadiness { - Declared = 1, - HelpRoutable = 2, - ContractKnown = 3, - SmokeExecuted = 4, - FullyExercised = 5, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -#[repr(u8)] -pub enum AuthorityTier { - Inspection = 0, - Candidate = 1, - Validated = 2, - Promoted = 3, -} - -impl AuthorityTier { - pub fn from_u8(value: u8) -> Option { - match value { - 0 => Some(Self::Inspection), - 1 => Some(Self::Candidate), - 2 => Some(Self::Validated), - 3 => Some(Self::Promoted), - _ => None, - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ArtifactContract { - pub kind: ArtifactKind, - pub class: String, - pub standalone_validation_complete: bool, - pub namespace_scope: NamespaceScope, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CommandContract { - pub command: String, - pub accepted_inputs: Vec, - pub produces: Vec, - pub readiness: CapabilityReadiness, - pub namespace_scope: NamespaceScope, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct LocusCapabilityMask { - pub has_checker: bool, - pub has_adequacy: bool, - pub has_route: bool, - pub has_certificate: bool, - pub has_frontier: bool, - pub has_forensic: bool, -} - -impl LocusCapabilityMask { - pub fn encode_bits(&self) -> u16 { - let mut bits = 0u16; - if self.has_checker { - bits |= 1 << 0; - } - if self.has_adequacy { - bits |= 1 << 1; - } - if self.has_route { - bits |= 1 << 2; - } - if self.has_certificate { - bits |= 1 << 3; - } - if self.has_frontier { - bits |= 1 << 4; - } - if self.has_forensic { - bits |= 1 << 5; - } - bits - } - - pub fn from_bits(bits: u16) -> Self { - Self { - has_checker: bits & (1 << 0) != 0, - has_adequacy: bits & (1 << 1) != 0, - has_route: bits & (1 << 2) != 0, - has_certificate: bits & (1 << 3) != 0, - has_frontier: bits & (1 << 4) != 0, - has_forensic: bits & (1 << 5) != 0, - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LocusPacketHeader { - pub artifact_class: GenomeArtifactClass, - pub surface: GenomeSurface, - pub kind: LocusPacketKind, - pub version_major: u8, - pub version_minor: u8, - pub authority_tier: u8, - pub capabilities: LocusCapabilityMask, - pub grammar_id: String, - pub schema_hash: String, - pub integrity_hash: String, - #[serde(default)] - pub strand_manifest: Vec, - pub feature_flags: u16, - pub root_subject_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LocusSection { - pub opcode: LocusOpcode, - pub flags: u16, - pub subject_id: String, - pub payload: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LocusPacket { - pub header: LocusPacketHeader, - pub sections: Vec, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum RnaState { - Raw, - Spliced, - Expressed, - Stabilized, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum RnaIssueClass { - Ambiguity, - GroupingFailure, - ArityMismatch, - SpliceClosureFailure, - UnknownOperator, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum RnormFailureKind { - Ambiguity, - GroupingFailure, - ArityMismatch, - SpliceClosureFailure, - UnknownOperator, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RnormDiagnosticSpec { - pub class: RnaIssueClass, - pub failure_kind: RnormFailureKind, - pub code: String, - pub repair_hint_template: String, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum TokenClass { - Atom, - Binder, - Operator, - GroupLeft, - GroupRight, - Separator, - StrandRef, - Meta, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TokenClassSpec { - pub class: TokenClass, - pub name: String, - pub rule: String, - pub semantic_authority: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TokenMapEntry { - pub sample: String, - pub class: TokenClass, - pub rule: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RnaToken { - pub class: TokenClass, - pub value: u32, - pub flags: u8, - pub span_start: usize, - pub span_end: usize, - pub text: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TokenStream { - pub source_text: String, - pub byte_len: usize, - #[serde(default)] - pub tokens: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TokenizationIssue { - pub offset: usize, - pub message: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TokenizationReceipt { - pub id: String, - pub token_count: usize, - pub byte_len: usize, - #[serde(default)] - pub issues: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RnaNormalizationIssue { - pub class: RnaIssueClass, - pub offset: usize, - pub message: String, - #[serde(default)] - pub repair_hints: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RnaNormalizationReceipt { - pub id: String, - #[serde(default)] - pub token_stream_id: String, - pub state: RnaState, - pub normalized_text: String, - #[serde(default)] - pub shorthand_eliminated: bool, - #[serde(default)] - pub splice_regions: Vec<(usize, usize)>, - #[serde(default)] - pub issues: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct NormalizedRna { - pub raw_text: String, - pub normalized_text: String, - pub state: RnaState, - #[serde(default)] - pub splice_regions: Vec<(usize, usize)>, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum SsrNodeKind { - Root, - Atom, - Group, - Splice, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SsrNode { - pub id: String, - pub kind: SsrNodeKind, - pub text: String, - #[serde(default)] - pub children: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SsrGraph { - pub root_id: String, - #[serde(default)] - pub nodes: Vec, - #[serde(default)] - pub strand_partition: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SsrReceipt { - pub id: String, - pub root_id: String, - pub node_count: usize, - #[serde(default)] - pub transition_count: usize, - #[serde(default)] - pub transition_table_hash: String, - pub ephemeral: bool, - pub normalized_rna_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SsrTransitionSpec { - pub token_class: TokenClass, - pub action: String, - pub persists_state: bool, - pub semantic_inference: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CnormReceipt { - pub id: String, - pub root_id: String, - pub canonical_hash: String, - #[serde(default)] - pub rule_table_hash: String, - #[serde(default)] - pub idempotent: bool, - pub erased_variations: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CanonicalRuleSpec { - pub id: String, - pub description: String, - pub deterministic: bool, - pub semantic_lookup_required: bool, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum StructuralRelationKind { - OrderedSequence, - UnorderedSet, - AssociativeGroup, - CommutativeGroup, - ReferenceIdentity, - NonCollapsible, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct EquivalenceLawSpec { - pub id: String, - pub relation: StructuralRelationKind, - pub transition_law_id: String, - pub ordering_significant: bool, - pub grouping_significant: bool, - pub flattening_allowed: bool, - pub sorting_allowed: bool, - pub reference_identity_preserved: bool, - pub preserved_distinctions: Vec, - pub collapsed_distinctions: Vec, - pub minimal_invariants: Vec, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum DistinctionClass { - AuthorityBearing, - ProjectionOnly, - FormatLocal, - CollapseEligible, - CollapseForbidden, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DistinctionLawSpec { - pub id: String, - pub class: DistinctionClass, - pub carrier: String, - pub collapse_allowed: bool, - pub preserved_invariants: Vec, - pub transition_law_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TransitionLawSpec { - pub id: String, - pub source_phase: PhaseId, - pub target_phase: PhaseId, - pub allowed_distinction_classes: Vec, - pub forbidden_distinction_classes: Vec, - pub required_receipts: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CanonicalStructureItem { - pub kind: SsrNodeKind, - pub structural_value: u64, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum CanonicalInstructionTag { - HeaderV1 = 1, - ItemV1 = 2, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CanonicalInstruction { - pub tag: CanonicalInstructionTag, - pub version: u8, - pub ordinal: u64, - pub kind: Option, - pub structural_value: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CanonicalStructure { - pub root_id: String, - pub canonical_id: CanonicalId, - pub canonical_hash: String, - pub canonical_bytes: Vec, - #[serde(default)] - pub items: Vec, - #[serde(default)] - pub instructions: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SemanticStrand { - pub id: String, - pub canonical_structure_id: String, - pub authority_scope: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct AuthorityComplement { - pub id: String, - pub authority_scope: String, - pub admission_law_id: String, - pub exclusions: Vec, - pub invariants: Vec, - pub dependency_burdens: Vec, - pub required_witness_forms: Vec, - pub closure_requirements: Vec, - pub rollback_law_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PairLaw { - pub id: String, - pub required_semantic_scope: String, - pub required_complement_scope: String, - pub required_admission_law_id: String, - pub strand_only_promotion_allowed: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DuplexPair { - pub semantic: SemanticStrand, - pub complement: AuthorityComplement, - pub pair_law: PairLaw, - pub commitment: String, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum DuplexPairStatus { - Unpaired, - Malformed, - LocallyValid, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DuplexPairValidation { - pub status: DuplexPairStatus, - pub pair_commitment: Option, - pub failures: Vec, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum CyclePolicyResult { - Acyclic, - LawfulCycle, - RejectedCycle, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct OpenObligation { - pub id: String, - pub description: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BridgeBurden { - pub id: String, - pub description: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DomainClosureReport { - pub locally_valid_pairs: Vec, - pub open_frontier: Vec, - pub external_burdens: Vec, - pub cycle_result: CyclePolicyResult, - pub promotable: bool, - pub promotion_receipt_required: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CanonicalWorkUnit { - pub coordinate: String, - pub payload_commitment: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DeterministicAuthorityMerge { - pub ordered_coordinates: Vec, - pub ordered_payload_commitments: Vec, - pub report_digest: String, -} - -pub fn canonical_rna_token_for_item(item: &CanonicalStructureItem) -> String { - let kind = match item.kind { - SsrNodeKind::Root => 0_u8, - SsrNodeKind::Atom => 1, - SsrNodeKind::Group => 2, - SsrNodeKind::Splice => 3, - }; - format!("l64c{kind}{:016x}", item.structural_value) -} - -pub fn canonical_rna_from_structure(structure: &CanonicalStructure) -> String { - structure - .items - .iter() - .map(canonical_rna_token_for_item) - .collect::>() - .join(" ") -} - -fn canonical_structure_item_from_rna_token(token: &str) -> Option { - let rest = token.strip_prefix("l64c")?; - if rest.len() != 17 { - return None; - } - let (kind_text, value_text) = rest.split_at(1); - let kind = match kind_text { - "0" => SsrNodeKind::Root, - "1" => SsrNodeKind::Atom, - "2" => SsrNodeKind::Group, - "3" => SsrNodeKind::Splice, - _ => return None, - }; - let structural_value = u64::from_str_radix(value_text, 16).ok()?; - Some(CanonicalStructureItem { - kind, - structural_value, - }) -} - -fn canonical_kind_byte(kind: SsrNodeKind) -> u8 { - match kind { - SsrNodeKind::Root => 0, - SsrNodeKind::Atom => 1, - SsrNodeKind::Group => 2, - SsrNodeKind::Splice => 3, - } -} - -pub fn canonical_instruction_bytes(instructions: &[CanonicalInstruction]) -> Vec { - const CANONICAL_INSTRUCTION_HEADER_BYTES: usize = 6 + 8; - const MAX_CANONICAL_INSTRUCTION_BYTES: usize = 1 + 1 + 8 + 1 + 8; - - let mut bytes = Vec::with_capacity( - CANONICAL_INSTRUCTION_HEADER_BYTES.saturating_add( - instructions - .len() - .saturating_mul(MAX_CANONICAL_INSTRUCTION_BYTES), - ), - ); - bytes.extend_from_slice(b"L64CI1"); - bytes.extend_from_slice(&(instructions.len() as u64).to_le_bytes()); - for instruction in instructions { - bytes.push(instruction.tag as u8); - bytes.push(instruction.version); - bytes.extend_from_slice(&instruction.ordinal.to_le_bytes()); - match instruction.tag { - CanonicalInstructionTag::HeaderV1 => { - bytes.extend_from_slice(&instruction.structural_value.unwrap_or(0).to_le_bytes()); - } - CanonicalInstructionTag::ItemV1 => { - let kind = instruction.kind.unwrap_or(SsrNodeKind::Atom); - bytes.push(canonical_kind_byte(kind)); - bytes.extend_from_slice(&instruction.structural_value.unwrap_or(0).to_le_bytes()); - } - } - } - bytes -} - -pub fn duplex_pair_commitment( - semantic: &SemanticStrand, - complement: &AuthorityComplement, - pair_law: &PairLaw, -) -> String { - role_digest_value(DigestRole::AuthorityId, &(semantic, complement, pair_law)) -} - -pub fn assemble_duplex_pair( - semantic: SemanticStrand, - complement: AuthorityComplement, - pair_law: PairLaw, -) -> DuplexPair { - let commitment = duplex_pair_commitment(&semantic, &complement, &pair_law); - DuplexPair { - semantic, - complement, - pair_law, - commitment, - } -} - -pub fn validate_duplex_pair(pair: Option<&DuplexPair>) -> DuplexPairValidation { - let Some(pair) = pair else { - return DuplexPairValidation { - status: DuplexPairStatus::Unpaired, - pair_commitment: None, - failures: vec!["duplex pair is missing semantic strand or authority complement".into()], - }; - }; - let mut failures = Vec::new(); - if pair.semantic.authority_scope != pair.pair_law.required_semantic_scope { - failures.push("semantic strand authority scope does not satisfy pair law".into()); - } - if pair.complement.authority_scope != pair.pair_law.required_complement_scope { - failures.push("authority complement scope does not satisfy pair law".into()); - } - if pair.complement.admission_law_id != pair.pair_law.required_admission_law_id { - failures.push("authority complement admission law does not satisfy pair law".into()); - } - if pair.pair_law.strand_only_promotion_allowed { - failures.push("pair law illegally permits strand-only promotion".into()); - } - if pair.complement.invariants.is_empty() { - failures.push("authority complement has no invariants".into()); - } - if pair.complement.required_witness_forms.is_empty() { - failures.push("authority complement has no required witness forms".into()); - } - let expected = duplex_pair_commitment(&pair.semantic, &pair.complement, &pair.pair_law); - if pair.commitment != expected { - failures - .push("duplex pair commitment does not match semantic/complement/law payload".into()); - } - DuplexPairValidation { - status: if failures.is_empty() { - DuplexPairStatus::LocallyValid - } else { - DuplexPairStatus::Malformed - }, - pair_commitment: Some(expected), - failures, - } -} - -pub fn evaluate_domain_closure( - pair_validations: &[DuplexPairValidation], - open_frontier: Vec, - external_burdens: Vec, - cycle_result: CyclePolicyResult, -) -> DomainClosureReport { - let locally_valid_pairs = pair_validations - .iter() - .filter(|validation| validation.status == DuplexPairStatus::LocallyValid) - .filter_map(|validation| validation.pair_commitment.clone()) - .collect::>(); - let all_pairs_locally_valid = !pair_validations.is_empty() - && pair_validations - .iter() - .all(|validation| validation.status == DuplexPairStatus::LocallyValid); - let cycle_accepted = matches!( - cycle_result, - CyclePolicyResult::Acyclic | CyclePolicyResult::LawfulCycle - ); - let promotable = all_pairs_locally_valid - && open_frontier.is_empty() - && external_burdens.is_empty() - && cycle_accepted; - DomainClosureReport { - locally_valid_pairs, - open_frontier, - external_burdens, - cycle_result, - promotable, - promotion_receipt_required: promotable, - } -} - -pub fn deterministic_authority_merge( - work_units: &[CanonicalWorkUnit], - _worker_count: usize, -) -> DeterministicAuthorityMerge { - let mut ordered = work_units.to_vec(); - ordered.sort_by(|left, right| { - left.coordinate - .cmp(&right.coordinate) - .then_with(|| left.payload_commitment.cmp(&right.payload_commitment)) - }); - let ordered_coordinates = ordered - .iter() - .map(|unit| unit.coordinate.clone()) - .collect::>(); - let ordered_payload_commitments = ordered - .iter() - .map(|unit| unit.payload_commitment.clone()) - .collect::>(); - let report_digest = role_digest_value( - DigestRole::ReceiptId, - &( - ordered_coordinates.clone(), - ordered_payload_commitments.clone(), - ), - ); - DeterministicAuthorityMerge { - ordered_coordinates, - ordered_payload_commitments, - report_digest, - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SemanticLoweringReceipt { - pub id: String, - pub source_surface: GenomeSurface, - pub target: String, - pub canonical_hash: String, - pub ephemeral_resolver_used: bool, -} - -pub type KernelGraph = SsrGraph; - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum PhaseId { - AuthorityReset, - Tokenization, - RnaNormalization, - StructuralResolution, - CanonicalNormalization, - DnaProtocolFreeze, - DnaParallelRollout, - CliContractMigration, - ResearchHostReconnect, - TowerCoverageReconnect, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum PhaseValidationResult { - Passed, - Failed, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum PromotionSignal { - Promote, - Hold, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum SystemFailureDisposition { - HaltPropagation, - RollbackLocal, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct InvariantCheck { - pub name: String, - pub passed: bool, - pub detail: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct FailureRecord { - pub code: String, - pub message: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ChangeLedgerEntry { - pub phase_id: PhaseId, - pub input_state_hash: String, - pub output_state_hash: Option, - #[serde(default)] - pub dependency_edges: Vec, - #[serde(default)] - pub invariant_checks: Vec, - #[serde(default)] - pub failure_records: Vec, - pub validation_result: PhaseValidationResult, - pub promotion_signal: PromotionSignal, - pub rollback_pointer: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SystemFailureState { - pub phase_id: PhaseId, - pub disposition: SystemFailureDisposition, - #[serde(default)] - pub failure_records: Vec, - pub rollback_pointer: Option, - pub ledger_entry: ChangeLedgerEntry, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct PhaseExecutionKernel { - #[serde(default)] - entries: Vec, -} - -impl PhaseExecutionKernel { - pub fn entries(&self) -> &[ChangeLedgerEntry] { - &self.entries - } - - pub fn execute( - &mut self, - phase_id: PhaseId, - input_state_hash: String, - dependency_edges: Vec, - rollback_pointer: Option, - transform: F, - validate: V, - ) -> Result - where - T: Serialize, - E: ToString, - F: FnOnce() -> Result, - V: FnOnce(&T) -> Vec, - { - match transform() { - Ok(output) => { - let invariant_checks = validate(&output); - let failure_records = invariant_checks - .iter() - .filter(|check| !check.passed) - .map(|check| FailureRecord { - code: format!("{phase_id:?}_InvariantFailed"), - message: format!("{}: {}", check.name, check.detail), - }) - .collect::>(); - let validation_result = if failure_records.is_empty() { - PhaseValidationResult::Passed - } else { - PhaseValidationResult::Failed - }; - let promotion_signal = if failure_records.is_empty() { - PromotionSignal::Promote - } else { - PromotionSignal::Hold - }; - let output_state_hash = Some(hash_serialized(&output)); - let ledger_entry = ChangeLedgerEntry { - phase_id, - input_state_hash, - output_state_hash, - dependency_edges, - invariant_checks, - failure_records: failure_records.clone(), - validation_result, - promotion_signal, - rollback_pointer: rollback_pointer.clone(), - }; - self.entries.push(ledger_entry.clone()); - if failure_records.is_empty() { - Ok(output) - } else { - Err(SystemFailureState { - phase_id, - disposition: SystemFailureDisposition::HaltPropagation, - failure_records, - rollback_pointer, - ledger_entry, - }) - } - } - Err(err) => { - let failure_records = vec![FailureRecord { - code: format!("{phase_id:?}_TransformFailed"), - message: err.to_string(), - }]; - let ledger_entry = ChangeLedgerEntry { - phase_id, - input_state_hash, - output_state_hash: None, - dependency_edges, - invariant_checks: Vec::new(), - failure_records: failure_records.clone(), - validation_result: PhaseValidationResult::Failed, - promotion_signal: PromotionSignal::Hold, - rollback_pointer: rollback_pointer.clone(), - }; - self.entries.push(ledger_entry.clone()); - Err(SystemFailureState { - phase_id, - disposition: SystemFailureDisposition::RollbackLocal, - failure_records, - rollback_pointer, - ledger_entry, - }) - } - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct LowerChainExecution { - pub token_stream: TokenStream, - pub tokenization_receipt: TokenizationReceipt, - pub normalized: NormalizedRna, - pub rn_receipt: RnaNormalizationReceipt, - pub kernel_graph: KernelGraph, - pub ssr_receipt: SsrReceipt, - pub canonical_structure: CanonicalStructure, - pub cnorm_receipt: CnormReceipt, - #[serde(default)] - pub ledger_entries: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ProofCoverageEnvelope { - pub subject_id: String, - pub decision: CoverageDecision, - pub covered_by: Vec, - pub skipped_obligation_ids: Vec, - pub residual_obligation_ids: Vec, - pub reuse_envelope_hash: String, - pub payoff_receipt_ids: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReuseLegalityReceipt { - pub id: String, - pub subject_id: String, - pub lawful: bool, - pub basis: Vec, - #[serde(default)] - pub lineage_refs: Vec, - #[serde(default)] - pub policy_scope: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReuseDecisionReceipt { - pub id: String, - pub subject_id: String, - #[serde(default)] - pub reused_artifact_ids: Vec, - #[serde(default)] - pub skipped_obligation_ids: Vec, - pub fallback_required: bool, - pub reason: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ResidualVerificationReceipt { - pub id: String, - pub subject_id: String, - #[serde(default)] - pub residual_obligation_ids: Vec, - pub fully_discharged: bool, - pub notes: Vec, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum EvidenceExactness { - Exact, - Approximate, - WitnessBacked, - CounterexampleCandidate, - Undischarged, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ExecutionClosureReceipt { - pub id: String, - pub subject_id: String, - pub exactness: EvidenceExactness, - pub lower_lineage_required: bool, - pub reuse_reported: bool, - pub residuals_reported: bool, - pub promotion_gate_visible: bool, - #[serde(default)] - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct Frontier { - pub id: String, - pub title: String, - pub burden_class: String, - pub blocker_ids: Vec, - pub closure_witness: Option, - pub residual_budget: Option, - pub strengthening_value: usize, - pub coldness: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct FrontierLedger { - pub frontiers: Vec, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CandidateSemanticLeaf { - pub id: String, - pub frontier_id: String, - pub description: String, - pub generated_status: GeneratedStatus, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CandidateAdequacyClause { - pub id: String, - pub frontier_id: String, - pub clause_stub: String, - pub generated_status: GeneratedStatus, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CandidateCheckerExtension { - pub id: String, - pub frontier_id: String, - pub object_family: String, - pub generated_status: GeneratedStatus, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CandidateCampaign { - pub id: String, - pub theorem_id: String, - pub target_profile_id: String, - pub generated_status: GeneratedStatus, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CandidateAtlasCell { - pub id: String, - pub src: String, - pub tgt: String, - pub generated_status: GeneratedStatus, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CandidatePayoffTask { - pub id: String, - pub artifact_id: String, - pub burden_hint: String, - pub generated_status: GeneratedStatus, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SearchCompartment { - pub id: String, - pub task_fingerprint: String, - pub allowed_grammars: Vec, - pub budget: String, - pub evaluator_profile: String, - pub admissibility_surface: Vec, - pub kill_criteria: Vec, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct GeneratorContract { - pub id: String, - pub proposal_kind: ProposalKind, - pub seam: String, - pub verifier: String, - pub compatibility_path: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct GenerationReceipt { - pub id: String, - pub generator_contract_id: String, - pub output_ids: Vec, - pub generated_status: GeneratedStatus, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct DistressVector { - pub repeated_blocker_ids: Vec, - pub checker_gaps: Vec, - pub route_scarcity: Vec, - pub payoff_drought: bool, - pub stalled_frontier_motion: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct HelpRequest { - pub id: String, - pub task_ref: String, - pub distress_vector: DistressVector, - pub minimal_reproduction: String, - pub requested_capacity: String, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RecipeRecord { - pub id: String, - pub seam: String, - pub tactic_family: String, - pub generated_status: GeneratedStatus, - pub expected_relief: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RecipeDelta { - pub id: String, - pub recipe_record_id: String, - pub changed_fields: Vec, - pub strengthening_value: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PromotionCandidate { - pub id: String, - pub artifact_id: String, - pub candidate_kind: String, - pub generated_status: GeneratedStatus, - pub proof_grade: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct CalibrationPressureMap { - pub override_pressure: usize, - pub emitted_duplication: usize, - pub conformance_friction: usize, - pub extension_cost: usize, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct OverridePressureReceipt { - pub id: String, - pub source_id: String, - pub pressure_class: String, - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ProofCoverageDispatch { - pub subject_id: String, - pub decision: CoverageDecision, - pub route_fast_path: bool, - pub reason: String, - pub covered_by: Vec, - pub residual_obligation_ids: Vec, - #[serde(default)] - pub lineage_refs: Vec, - #[serde(default)] - pub reuse_legality_receipts: Vec, - #[serde(default)] - pub reuse_decision_receipts: Vec, - #[serde(default)] - pub residual_verification_receipts: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] -pub struct VerticalCompoundingBundle { - pub frontier_ledger: FrontierLedger, - pub semantic_leaves: Vec, - pub adequacy_clauses: Vec, - pub checker_extensions: Vec, - pub campaigns: Vec, - pub atlas_cells: Vec, - pub payoff_tasks: Vec, - pub compartments: Vec, - pub generator_contracts: Vec, - pub generation_receipts: Vec, - pub distress: Option, - pub help_requests: Vec, - pub recipes: Vec, - pub recipe_deltas: Vec, - pub promotion_candidates: Vec, - pub calibration_pressure: Option, - pub override_pressure_receipts: Vec, - #[serde(default)] - pub lineage_refs: Vec, - #[serde(default)] - pub lineage_required: bool, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ResearchSector { - Gravity, - Gauge, - Atomic, - Thermo, - Cosmology, - Topology, - Control, - Crosscut, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ObjectiveKind { - Derive, - Reduce, - Benchmark, - Stress, - Integrate, - Refute, - Crystallize, - Promote, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum DesiredOutputKind { - Theorem, - Operator, - BenchmarkSchema, - ReductionMap, - Battery, - HandoffPacket, - ValidationBundle, - ResearchNote, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum DerivationStructuralType { - Projection, - Closure, - Obstruction, - BenchmarkFit, - Reduction, - Simulation, - ChallengeResponse, - RegistryHardening, - OperationalHardening, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum RiskClass { - Low, - Medium, - High, - Dangerous, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ReviewStatus { - Pass, - Revise, - Fail, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ReviewDecision { - Proceed, - Revise, - Hold, - Reject, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ChallengeGrounds { - Inconsistency, - HiddenAssumption, - BenchmarkMiss, - ProjectionAmbiguity, - RegimeViolation, - PromotionMismatch, - UnsupportedGeneralization, - CapabilityTruthMismatch, - NamespaceContractMismatch, - ArtifactContractMismatch, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ChallengeSeverity { - Low, - Medium, - High, - Blocking, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ResponseClass { - Patch, - NarrowScope, - Benchmark, - Rollback, - Retire, - Document, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum RegistryEntryKind { - Claim, - MathClaim, - Operator, - BenchmarkRun, - Handoff, - PromotionQueue, - Benchmark, - Challenge, - Receipt, - Task, - Signature, - Review, - StrengtheningArtifact, - Remediation, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum RegistryEntryStatus { - Workspace, - Derived, - Benchmarked, - Certified, - Integrated, - Blocked, - Retired, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ResearchRouteClass { - Derive, - Benchmark, - Stress, - ChallengeResponse, - Crystallize, - Integrate, - Retire, - OperationalHardening, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum RemediationClass { - MissingFunctionality, - SemanticBug, - CommandContractBug, - ArtifactTypingBug, - RuntimeBug, - DocumentationGap, - CapabilityTruthGap, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum RemediationStatus { - Open, - InProgress, - Patched, - NeedsCompilePass, - Verified, - Deferred, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TaskEnvelope { - pub id: String, - pub title: String, - pub target_sector: ResearchSector, - pub objective_kind: ObjectiveKind, - pub desired_output: DesiredOutputKind, - #[serde(default)] - pub hard_constraints: Vec, - #[serde(default)] - pub soft_constraints: Vec, - pub promotion_target: CertificationVerdict, - pub rollback_path: String, - #[serde(default)] - pub success_metrics: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct DerivationSignature { - pub id: String, - pub task_ref: String, - pub structural_type: DerivationStructuralType, - pub sector: ResearchSector, - pub risk_class: RiskClass, - pub dependency_depth: usize, - #[serde(default)] - pub likely_failure_modes: Vec, - pub expected_distillate: DesiredOutputKind, - #[serde(default)] - pub evidence_gap: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReviewReceipt { - pub id: String, - pub subject_ref: String, - pub fit_review: ReviewStatus, - pub risk_review: ReviewStatus, - pub capture_review: ReviewStatus, - pub continuity_review: ReviewStatus, - #[serde(default)] - pub notes: Vec, - #[serde(default)] - pub reviewers: Vec, - pub verdict: ReviewDecision, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ChallengeRecord { - pub id: String, - pub target_ref: String, - pub grounds: ChallengeGrounds, - pub severity: ChallengeSeverity, - #[serde(default)] - pub evidence_refs: Vec, - pub required_response: ResponseClass, - pub status: ChallengeStatus, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct OperatorRecord { - pub id: String, - pub name: String, - pub semantics: String, - #[serde(default)] - pub valid_regimes: Vec, - pub evidence_level: CertificationVerdict, - #[serde(default)] - pub dependencies: Vec, - #[serde(default)] - pub failure_modes: Vec, - pub reuse_count: usize, - #[serde(default)] - pub implementation_refs: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BenchmarkSchema { - pub id: String, - pub target_description: String, - pub metric_name: String, - pub tolerance: String, - pub reference_source: String, - pub weight_basis_points: u32, - #[serde(default)] - pub required_evidence: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct StrengtheningArtifact { - pub id: String, - pub source_ref: String, - pub kind: DesiredOutputKind, - #[serde(default)] - pub inheritance_targets: Vec, - pub redistribution_notes: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct FrameworkRegistryEntry { - pub id: String, - pub kind: RegistryEntryKind, - pub host: String, - pub status: RegistryEntryStatus, - pub retained_value: String, - #[serde(default)] - pub open_risks: Vec, - #[serde(default)] - pub dependencies: Vec, - #[serde(default)] - pub last_receipt: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct RouteScore { - pub route: ResearchRouteClass, - pub fit: f64, - pub leverage: f64, - pub risk: f64, - pub cost: f64, - pub debt: f64, - pub total: f64, - #[serde(default)] - pub reasons: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct RouteAssignment { - pub task_id: String, - pub signature_id: String, - pub recommended_route: ResearchRouteClass, - pub scores: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RemediationLedgerEntry { - pub id: String, - pub source_ref: String, - pub class: RemediationClass, - pub summary: String, - #[serde(default)] - pub affected_surfaces: Vec, - #[serde(default)] - pub expected_fix_chain: Vec, - pub status: RemediationStatus, - #[serde(default)] - pub notes: Vec, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum ProducerHostKind { - Reduction, - Projection, - Benchmark, - ChallengeResolution, - Handoff, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum PromotionQueueStatus { - Proposed, - Ready, - Blocked, - Promoted, - Deferred, -} - -fn default_promotion_queue_status_proposed() -> PromotionQueueStatus { - PromotionQueueStatus::Proposed -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct MathClaimPacket { - pub id: String, - pub title: String, - pub statement: String, - pub sector: ResearchSector, - pub truth_class: AuthorityState, - pub claim_class: ClaimClass, - #[serde(default)] - pub assumptions: Vec, - #[serde(default)] - pub projection_refs: Vec, - #[serde(default)] - pub reduction_refs: Vec, - #[serde(default)] - pub benchmark_refs: Vec, - #[serde(default)] - pub blocker_leaves: Vec, - #[serde(default)] - pub report_refs: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ReductionMapRecord { - pub id: String, - pub theorem_id: String, - pub target_profile_id: String, - pub route_class_id: Option, - pub atlas_cell_id: Option, - pub derivation_path: String, - #[serde(default)] - pub residual_obligation_ids: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ProjectionMapRecord { - pub id: String, - pub theorem_id: String, - pub src_hosts: Vec, - pub tgt_hosts: Vec, - pub projection_summary: String, - #[serde(default)] - pub bridge_refs: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct BenchmarkRunRecord { - pub id: String, - pub theorem_id: String, - pub benchmark_schema_id: Option, - #[serde(default)] - pub receipt_ids: Vec, - pub status: RegistryEntryStatus, - pub summary: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct HandoffPacket { - pub id: String, - pub subject_id: String, - pub summary: String, - #[serde(default = "default_promotion_queue_status_proposed")] - pub status: PromotionQueueStatus, - #[serde(default)] - pub claim_refs: Vec, - #[serde(default)] - pub operator_refs: Vec, - #[serde(default)] - pub strengthening_refs: Vec, - #[serde(default)] - pub repro_refs: Vec, - #[serde(default)] - pub benchmark_refs: Vec, - #[serde(default)] - pub benchmark_run_refs: Vec, - #[serde(default)] - pub producer_host_refs: Vec, - #[serde(default)] - pub route_refs: Vec, - #[serde(default)] - pub coverage_refs: Vec, - #[serde(default)] - pub lineage_refs: Vec, - #[serde(default)] - pub tower_refs: Vec, - #[serde(default)] - pub promotion_refs: Vec, - #[serde(default)] - pub readiness_score_basis_points: u16, - #[serde(default)] - pub blockers: Vec, - #[serde(default)] - pub positive_factors: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PromotionQueueEntry { - pub id: String, - pub subject_id: String, - pub status: PromotionQueueStatus, - pub readiness_score_basis_points: u16, - #[serde(default)] - pub blockers: Vec, - #[serde(default)] - pub required_refs: Vec, - #[serde(default)] - pub evidence_refs: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PromotionReadinessReport { - pub subject_id: String, - pub readiness_score_basis_points: u16, - pub status: PromotionQueueStatus, - #[serde(default)] - pub positive_factors: Vec, - #[serde(default)] - pub blockers: Vec, - #[serde(default)] - pub missing_refs: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ProducerHostSpec { - pub id: String, - pub kind: ProducerHostKind, - pub purpose: String, - #[serde(default)] - pub owned_objects: Vec, - #[serde(default)] - pub feeds: Vec, - #[serde(default)] - pub notes: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] -pub struct ResearchBundle { - #[serde(default)] - pub tasks: Vec, - #[serde(default)] - pub signatures: Vec, - #[serde(default)] - pub route_assignments: Vec, - #[serde(default)] - pub claims: Vec, - #[serde(default)] - pub reduction_maps: Vec, - #[serde(default)] - pub projection_maps: Vec, - #[serde(default)] - pub benchmark_runs: Vec, - #[serde(default)] - pub handoff_packets: Vec, - #[serde(default)] - pub producer_hosts: Vec, - #[serde(default)] - pub promotion_queue: Vec, - #[serde(default)] - pub promotion_reports: Vec, - #[serde(default)] - pub lineage_records: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ResearchLineageRecord { - pub id: String, - pub subject_id: String, - pub artifact_class: GenomeArtifactClass, - pub source_surface: GenomeSurface, - pub target_surface: GenomeSurface, - pub grammar_id: String, - pub canonical_hash: String, - pub lowering_receipt_id: String, - #[serde(default)] - pub phase_ids: Vec, - #[serde(default)] - pub phase_ledger: Vec, - #[serde(default)] - pub notes: Vec, -} - -const LOCUS_MAGIC: &[u8; 4] = b"LCS1"; -const MAX_LOCUS_SIZED_FIELD_BYTES: usize = 64 * 1024 * 1024; - -pub fn encode_locus_packet(packet: &LocusPacket) -> Result, String> { - let mut out = Vec::with_capacity(locus_packet_encoded_capacity(packet)); - out.extend_from_slice(LOCUS_MAGIC); - out.push(packet.header.artifact_class as u8); - out.push(packet.header.surface as u8); - out.push(packet.header.kind as u8); - out.push(packet.header.version_major); - out.push(packet.header.version_minor); - out.push(packet.header.authority_tier); - out.extend_from_slice(&packet.header.capabilities.encode_bits().to_le_bytes()); - push_sized_bytes(&mut out, packet.header.grammar_id.as_bytes())?; - push_sized_bytes(&mut out, packet.header.schema_hash.as_bytes())?; - push_sized_bytes(&mut out, packet.header.integrity_hash.as_bytes())?; - let strand_count: u16 = packet - .header - .strand_manifest - .len() - .try_into() - .map_err(|_| "too many strands".to_string())?; - out.extend_from_slice(&strand_count.to_le_bytes()); - for strand in &packet.header.strand_manifest { - push_sized_bytes(&mut out, strand.as_bytes())?; - } - out.extend_from_slice(&packet.header.feature_flags.to_le_bytes()); - push_sized_bytes(&mut out, packet.header.root_subject_id.as_bytes())?; - let section_count: u16 = packet - .sections - .len() - .try_into() - .map_err(|_| "too many sections".to_string())?; - out.extend_from_slice(§ion_count.to_le_bytes()); - for section in &packet.sections { - out.push(section.opcode as u8); - out.extend_from_slice(§ion.flags.to_le_bytes()); - push_sized_bytes(&mut out, section.subject_id.as_bytes())?; - push_sized_bytes(&mut out, §ion.payload)?; - } - Ok(out) -} - -fn locus_packet_encoded_capacity(packet: &LocusPacket) -> usize { - const FIXED_HEADER_BYTES: usize = 4 + 1 + 1 + 1 + 1 + 1 + 1 + 2 + 2 + 8 + 2; - const SECTION_FIXED_BYTES: usize = 1 + 2; - - let sized = |len: usize| 4usize.saturating_add(len); - let mut capacity = FIXED_HEADER_BYTES - .saturating_add(sized(packet.header.grammar_id.len())) - .saturating_add(sized(packet.header.schema_hash.len())) - .saturating_add(sized(packet.header.integrity_hash.len())) - .saturating_add(sized(packet.header.root_subject_id.len())); - - for strand in &packet.header.strand_manifest { - capacity = capacity.saturating_add(sized(strand.len())); - } - for section in &packet.sections { - capacity = capacity - .saturating_add(SECTION_FIXED_BYTES) - .saturating_add(sized(section.subject_id.len())) - .saturating_add(sized(section.payload.len())); - } - capacity -} - -pub fn decode_locus_packet(bytes: &[u8]) -> Result { - decode_locus_packet_with_mode(bytes, LocusDecodeMode::Migration) -} - -pub fn decode_locus_packet_with_mode( - bytes: &[u8], - mode: LocusDecodeMode, -) -> Result { - match mode { - LocusDecodeMode::CurrentAuthority => decode_locus_packet_current(bytes), - LocusDecodeMode::Migration => decode_locus_packet_current(bytes).or_else(|current_err| { - decode_locus_packet_legacy(bytes).map_err(|legacy_err| { - format!("{current_err}; legacy decode also failed: {legacy_err}") - }) - }), - LocusDecodeMode::Forensic => decode_locus_packet_current(bytes).or_else(|current_err| { - decode_locus_packet_legacy(bytes).map_err(|legacy_err| { - format!("{current_err}; forensic legacy decode also failed: {legacy_err}") - }) - }), - } -} - -pub fn dna_header_receipt(packet: &LocusPacket) -> DnaHeaderReceipt { - DnaHeaderReceipt { - id: receipt_id( - "DNA_HDR", - &( - &packet.header.grammar_id, - &packet.header.schema_hash, - &packet.header.integrity_hash, - ), - ), - surface: packet.header.surface, - grammar_id: packet.header.grammar_id.clone(), - schema_hash: packet.header.schema_hash.clone(), - integrity_hash: packet.header.integrity_hash.clone(), - structural_opcode_table_hash: hash_serialized(&structural_opcode_specs()), - header_truth_complete: packet.header.surface == GenomeSurface::Dna - && !packet.header.grammar_id.is_empty() - && !packet.header.schema_hash.is_empty() - && !packet.header.integrity_hash.is_empty() - && !packet.header.root_subject_id.is_empty(), - } -} - -pub fn dna_section_payload_commitments(packet: &LocusPacket) -> Vec { - packet - .sections - .iter() - .map(|section| DnaSectionCommitment { - opcode: section.opcode, - subject_id: section.subject_id.clone(), - payload_commitment: dna_digest_from_bytes(§ion.payload).0, - }) - .collect() -} - -pub fn validate_dna_packet(packet: &LocusPacket) -> DnaValidationReport { - let mut failures = Vec::new(); - let header = dna_header_receipt(packet); - let mut canonical_payload_digest_valid = packet.header.schema_hash != "canonical_structure.v1"; - let section_payload_commitments = dna_section_payload_commitments(packet); - let mut section_payload_commitments_valid = !section_payload_commitments.is_empty(); - if !header.header_truth_complete { - failures.push("header truth is incomplete".into()); - } - if packet.header.surface != GenomeSurface::Dna { - failures.push("packet surface is not DNA".into()); - } - if AuthorityTier::from_u8(packet.header.authority_tier).is_none() { - failures.push("unknown authority tier".into()); - } - if packet - .sections - .iter() - .any(|section| section.opcode == LocusOpcode::SymbolTable && section.flags & 0x0001 != 0) - { - failures.push("symbol table marked as semantic authority".into()); - } - if packet.sections.is_empty() { - failures.push("packet has no structural sections".into()); - section_payload_commitments_valid = false; - } - if packet.header.schema_hash != "canonical_structure.v1" && packet.sections.len() == 1 { - let expected = §ion_payload_commitments[0].payload_commitment; - if packet.header.integrity_hash != *expected { - section_payload_commitments_valid = false; - failures.push("section payload commitment does not match header integrity".into()); - } - } - if packet.header.schema_hash == "canonical_structure.v1" { - match packet - .sections - .iter() - .find(|section| section.opcode == LocusOpcode::CanonicalPayload) - { - Some(section) => match bincode::deserialize::(§ion.payload) { - Ok(structure) => { - canonical_payload_digest_valid = structure.canonical_hash - == packet.header.integrity_hash - && structure.canonical_id.0 == structure.canonical_hash - && canonical_id_from_binary_structure(&structure.canonical_bytes) - == structure.canonical_id; - if !canonical_payload_digest_valid { - failures.push( - "canonical structure payload digest does not match header".into(), - ); - } - } - Err(err) => failures.push(format!( - "canonical structure payload failed to decode: {err}" - )), - }, - None => failures.push("canonical structure packet missing canonical payload".into()), - } - } - let structural_opcode_table = structural_opcode_specs(); - if !structural_opcode_table - .iter() - .all(|spec| spec.structural_only) - { - failures.push("opcode registry contains non-structural opcode".into()); - } - DnaValidationReport { - id: format!( - "DNA_VAL_{}", - role_digest_value(DigestRole::ReceiptId, packet) - ), - reversible: failures.is_empty(), - header_truth_complete: header.header_truth_complete, - canonical_payload_digest_valid, - section_payload_commitments_valid, - section_payload_commitments, - symbol_table_semantic_authority: packet.sections.iter().any(|section| { - section.opcode == LocusOpcode::SymbolTable && section.flags & 0x0001 != 0 - }), - failures, - } -} - -fn decode_locus_packet_current(bytes: &[u8]) -> Result { - let mut cursor = 0usize; - if bytes.len() < LOCUS_MAGIC.len() + 10 { - return Err("packet too small".into()); - } - if &bytes[..4] != LOCUS_MAGIC { - return Err("bad packet magic".into()); - } - cursor += 4; - let artifact_class = decode_genome_artifact_class( - *read_exact(bytes, &mut cursor, 1)? - .first() - .ok_or_else(|| "missing artifact class".to_string())?, - )?; - let surface = decode_genome_surface( - *read_exact(bytes, &mut cursor, 1)? - .first() - .ok_or_else(|| "missing genome surface".to_string())?, - )?; - let kind = decode_packet_kind( - *read_exact(bytes, &mut cursor, 1)? - .first() - .ok_or_else(|| "missing packet kind".to_string())?, - )?; - let version_major = *read_exact(bytes, &mut cursor, 1)?.first().unwrap(); - let version_minor = *read_exact(bytes, &mut cursor, 1)?.first().unwrap(); - let authority_tier = *read_exact(bytes, &mut cursor, 1)?.first().unwrap(); - let cap_bits = u16::from_le_bytes( - read_exact(bytes, &mut cursor, 2)? - .try_into() - .map_err(|_| "bad capability bytes".to_string())?, - ); - let grammar_id = - String::from_utf8(read_sized_bytes(bytes, &mut cursor)?).map_err(|err| err.to_string())?; - let schema_hash = - String::from_utf8(read_sized_bytes(bytes, &mut cursor)?).map_err(|err| err.to_string())?; - let integrity_hash = - String::from_utf8(read_sized_bytes(bytes, &mut cursor)?).map_err(|err| err.to_string())?; - let strand_count = u16::from_le_bytes( - read_exact(bytes, &mut cursor, 2)? - .try_into() - .map_err(|_| "bad strand count".to_string())?, - ); - let mut strand_manifest = Vec::with_capacity(strand_count as usize); - for _ in 0..strand_count { - strand_manifest.push( - String::from_utf8(read_sized_bytes(bytes, &mut cursor)?) - .map_err(|err| err.to_string())?, - ); - } - let feature_flags = u16::from_le_bytes( - read_exact(bytes, &mut cursor, 2)? - .try_into() - .map_err(|_| "bad feature flags".to_string())?, - ); - let root_subject_id = - String::from_utf8(read_sized_bytes(bytes, &mut cursor)?).map_err(|err| err.to_string())?; - let section_count = u16::from_le_bytes( - read_exact(bytes, &mut cursor, 2)? - .try_into() - .map_err(|_| "bad section count".to_string())?, - ); - let mut sections = Vec::with_capacity(section_count as usize); - for _ in 0..section_count { - let opcode = decode_opcode(*read_exact(bytes, &mut cursor, 1)?.first().unwrap())?; - let flags = u16::from_le_bytes( - read_exact(bytes, &mut cursor, 2)? - .try_into() - .map_err(|_| "bad section flags".to_string())?, - ); - let subject_id = String::from_utf8(read_sized_bytes(bytes, &mut cursor)?) - .map_err(|err| err.to_string())?; - let payload = read_sized_bytes(bytes, &mut cursor)?; - sections.push(LocusSection { - opcode, - flags, - subject_id, - payload, - }); - } - Ok(LocusPacket { - header: LocusPacketHeader { - artifact_class, - surface, - kind, - version_major, - version_minor, - authority_tier, - capabilities: LocusCapabilityMask::from_bits(cap_bits), - grammar_id, - schema_hash, - integrity_hash, - strand_manifest, - feature_flags, - root_subject_id, - }, - sections, - }) -} - -fn decode_locus_packet_legacy(bytes: &[u8]) -> Result { - let mut cursor = 0usize; - if bytes.len() < LOCUS_MAGIC.len() + 8 { - return Err("legacy packet too small".into()); - } - if &bytes[..4] != LOCUS_MAGIC { - return Err("bad packet magic".into()); - } - cursor += 4; - let kind = decode_packet_kind( - *read_exact(bytes, &mut cursor, 1)? - .first() - .ok_or_else(|| "missing packet kind".to_string())?, - )?; - let version_major = *read_exact(bytes, &mut cursor, 1)?.first().unwrap(); - let version_minor = *read_exact(bytes, &mut cursor, 1)?.first().unwrap(); - let authority_tier = *read_exact(bytes, &mut cursor, 1)?.first().unwrap(); - let cap_bits = u16::from_le_bytes( - read_exact(bytes, &mut cursor, 2)? - .try_into() - .map_err(|_| "bad capability bytes".to_string())?, - ); - let schema_hash = - String::from_utf8(read_sized_bytes(bytes, &mut cursor)?).map_err(|err| err.to_string())?; - let root_subject_id = - String::from_utf8(read_sized_bytes(bytes, &mut cursor)?).map_err(|err| err.to_string())?; - let section_count = u16::from_le_bytes( - read_exact(bytes, &mut cursor, 2)? - .try_into() - .map_err(|_| "bad section count".to_string())?, - ); - let mut sections = Vec::with_capacity(section_count as usize); - for _ in 0..section_count { - let opcode = decode_opcode(*read_exact(bytes, &mut cursor, 1)?.first().unwrap())?; - let flags = u16::from_le_bytes( - read_exact(bytes, &mut cursor, 2)? - .try_into() - .map_err(|_| "bad section flags".to_string())?, - ); - let subject_id = String::from_utf8(read_sized_bytes(bytes, &mut cursor)?) - .map_err(|err| err.to_string())?; - let payload = read_sized_bytes(bytes, &mut cursor)?; - sections.push(LocusSection { - opcode, - flags, - subject_id, - payload, - }); - } - Ok(LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Gene, - surface: GenomeSurface::Dna, - kind, - version_major, - version_minor, - authority_tier, - capabilities: LocusCapabilityMask::from_bits(cap_bits), - grammar_id: "legacy.locus".into(), - schema_hash, - integrity_hash: String::new(), - strand_manifest: vec!["core".into()], - feature_flags: 0, - root_subject_id, - }, - sections, - }) -} - -pub fn locus_packet_summary(packet: &LocusPacket) -> BTreeMap { - BTreeMap::from([ - ( - "artifact_class".into(), - format!("{:?}", packet.header.artifact_class), - ), - ("surface".into(), format!("{:?}", packet.header.surface)), - ("kind".into(), format!("{:?}", packet.header.kind)), - ("grammar_id".into(), packet.header.grammar_id.clone()), - ( - "root_subject_id".into(), - packet.header.root_subject_id.clone(), - ), - ("schema_hash".into(), packet.header.schema_hash.clone()), - ( - "integrity_hash".into(), - packet.header.integrity_hash.clone(), - ), - ( - "strand_count".into(), - packet.header.strand_manifest.len().to_string(), - ), - ("section_count".into(), packet.sections.len().to_string()), - ( - "capabilities".into(), - format!("0x{:04x}", packet.header.capabilities.encode_bits()), - ), - ]) -} - -fn push_sized_bytes(out: &mut Vec, payload: &[u8]) -> Result<(), String> { - let len: u32 = payload - .len() - .try_into() - .map_err(|_| "payload too large".to_string())?; - out.extend_from_slice(&len.to_le_bytes()); - out.extend_from_slice(payload); - Ok(()) -} - -fn read_exact<'a>(bytes: &'a [u8], cursor: &mut usize, len: usize) -> Result<&'a [u8], String> { - let end = cursor - .checked_add(len) - .ok_or_else(|| "cursor overflow".to_string())?; - let slice = bytes - .get(*cursor..end) - .ok_or_else(|| "packet truncated".to_string())?; - *cursor = end; - Ok(slice) -} - -fn read_sized_bytes(bytes: &[u8], cursor: &mut usize) -> Result, String> { - let len = u32::from_le_bytes( - read_exact(bytes, cursor, 4)? - .try_into() - .map_err(|_| "bad length".to_string())?, - ) as usize; - if len > MAX_LOCUS_SIZED_FIELD_BYTES { - return Err(format!( - "sized field too large: {len} > {MAX_LOCUS_SIZED_FIELD_BYTES}" - )); - } - Ok(read_exact(bytes, cursor, len)?.to_vec()) -} - -fn decode_packet_kind(value: u8) -> Result { - match value { - 1 => Ok(LocusPacketKind::CanonicalTransfer), - 2 => Ok(LocusPacketKind::CertificationEnvelope), - 3 => Ok(LocusPacketKind::CheckerEnvelope), - 4 => Ok(LocusPacketKind::FrontierEnvelope), - 5 => Ok(LocusPacketKind::TowerBundle), - _ => Err(format!("unknown locus packet kind `{value}`")), - } -} - -fn decode_genome_artifact_class(value: u8) -> Result { - match value { - 1 => Ok(GenomeArtifactClass::Gene), - 2 => Ok(GenomeArtifactClass::Haplotype), - 3 => Ok(GenomeArtifactClass::Chromosome), - 4 => Ok(GenomeArtifactClass::Genome), - _ => Err(format!("unknown genome artifact class `{value}`")), - } -} - -fn decode_genome_surface(value: u8) -> Result { - match value { - 1 => Ok(GenomeSurface::Rna), - 2 => Ok(GenomeSurface::Dna), - _ => Err(format!("unknown genome surface `{value}`")), - } -} - -fn decode_opcode(value: u8) -> Result { - match value { - 1 => Ok(LocusOpcode::Header), - 2 => Ok(LocusOpcode::CanonicalPayload), - 3 => Ok(LocusOpcode::ReceiptTable), - 4 => Ok(LocusOpcode::AdequacyTable), - 5 => Ok(LocusOpcode::RouteLedger), - 6 => Ok(LocusOpcode::Campaign), - 7 => Ok(LocusOpcode::Certificate), - 8 => Ok(LocusOpcode::Checker), - 9 => Ok(LocusOpcode::Frontier), - 10 => Ok(LocusOpcode::Proposal), - 11 => Ok(LocusOpcode::Coverage), - 12 => Ok(LocusOpcode::SymbolTable), - 13 => Ok(LocusOpcode::Forensic), - _ => Err(format!("unknown locus opcode `{value}`")), - } -} - -pub fn structural_opcode_specs() -> Vec { - vec![ - (LocusOpcode::Header, "header", false), - (LocusOpcode::CanonicalPayload, "canonical-payload", false), - (LocusOpcode::ReceiptTable, "receipt-table", true), - (LocusOpcode::AdequacyTable, "adequacy-table", true), - (LocusOpcode::RouteLedger, "route-ledger", true), - (LocusOpcode::Campaign, "campaign", true), - (LocusOpcode::Certificate, "certificate", true), - (LocusOpcode::Checker, "checker", true), - (LocusOpcode::Frontier, "frontier", true), - (LocusOpcode::Proposal, "proposal", true), - (LocusOpcode::Coverage, "coverage", true), - ( - LocusOpcode::SymbolTable, - "symbol-table-compression-only", - true, - ), - (LocusOpcode::Forensic, "forensic", true), - ] - .into_iter() - .map( - |(opcode, name, compatible_skip_allowed)| StructuralOpcodeSpec { - opcode, - name: name.into(), - structural_only: true, - compatible_skip_allowed, - }, - ) - .collect() -} - -pub fn token_class_specs() -> Vec { - vec![ - TokenClassSpec { - class: TokenClass::Atom, - name: "ATOM".into(), - rule: "lowercase, digits, and non-control symbolic scalars that are not delimiters/operators".into(), - semantic_authority: false, - }, - TokenClassSpec { - class: TokenClass::Binder, - name: "BINDER".into(), - rule: "uppercase ASCII binder anchors".into(), - semantic_authority: false, - }, - TokenClassSpec { - class: TokenClass::Operator, - name: "OP".into(), - rule: "structural operator characters such as _, |, :, =, +, -, *, /, ^, ≔, ‖, and →".into(), - semantic_authority: false, - }, - TokenClassSpec { - class: TokenClass::GroupLeft, - name: "GROUP_L".into(), - rule: "opening grouping delimiters".into(), - semantic_authority: false, - }, - TokenClassSpec { - class: TokenClass::GroupRight, - name: "GROUP_R".into(), - rule: "closing grouping delimiters".into(), - semantic_authority: false, - }, - TokenClassSpec { - class: TokenClass::Separator, - name: "SEP".into(), - rule: "comma and semicolon structural separators".into(), - semantic_authority: false, - }, - TokenClassSpec { - class: TokenClass::StrandRef, - name: "STRAND_REF".into(), - rule: "period strand-reference marker".into(), - semantic_authority: false, - }, - TokenClassSpec { - class: TokenClass::Meta, - name: "META".into(), - rule: "whitespace and comments/control metadata".into(), - semantic_authority: false, - }, - ] -} - -pub fn rnorm_diagnostic_specs() -> Vec { - vec![ - RnormDiagnosticSpec { - class: RnaIssueClass::Ambiguity, - failure_kind: RnormFailureKind::Ambiguity, - code: "RNORM_AMBIGUITY".into(), - repair_hint_template: "make the conflicting structural region explicit".into(), - }, - RnormDiagnosticSpec { - class: RnaIssueClass::GroupingFailure, - failure_kind: RnormFailureKind::GroupingFailure, - code: "RNORM_GROUPING".into(), - repair_hint_template: "close or remove the unmatched grouping delimiter".into(), - }, - RnormDiagnosticSpec { - class: RnaIssueClass::ArityMismatch, - failure_kind: RnormFailureKind::ArityMismatch, - code: "RNORM_ARITY".into(), - repair_hint_template: "declare the operator arity explicitly".into(), - }, - RnormDiagnosticSpec { - class: RnaIssueClass::SpliceClosureFailure, - failure_kind: RnormFailureKind::SpliceClosureFailure, - code: "RNORM_SPLICE".into(), - repair_hint_template: "close splice payloads with `eie`".into(), - }, - RnormDiagnosticSpec { - class: RnaIssueClass::UnknownOperator, - failure_kind: RnormFailureKind::UnknownOperator, - code: "RNORM_OPERATOR".into(), - repair_hint_template: "replace unknown operator shorthand with structural RNA".into(), - }, - ] -} - -pub fn ssr_transition_specs() -> Vec { - vec![ - (TokenClass::Atom, "emit_leaf"), - (TokenClass::Binder, "emit_binding"), - (TokenClass::Operator, "push_operator_context"), - (TokenClass::GroupLeft, "push_frame"), - (TokenClass::GroupRight, "close_frame"), - (TokenClass::Separator, "finalize_term"), - (TokenClass::StrandRef, "emit_reference_edge"), - (TokenClass::Meta, "ignore"), - ] - .into_iter() - .map(|(token_class, action)| SsrTransitionSpec { - token_class, - action: action.into(), - persists_state: false, - semantic_inference: false, - }) - .collect() -} - -pub fn canonical_rule_specs() -> Vec { - vec![ - CanonicalRuleSpec { - id: "CNORM_SORT_TEXT_ID".into(), - description: "sort structural nodes by text and then stable node id".into(), - deterministic: true, - semantic_lookup_required: false, - }, - CanonicalRuleSpec { - id: "CNORM_ERASE_FORMATTING".into(), - description: - "erase whitespace and splice-layout variation already removed by lower phases" - .into(), - deterministic: true, - semantic_lookup_required: false, - }, - ] -} - -pub fn structural_equivalence_law_specs() -> Vec { - vec![ - EquivalenceLawSpec { - id: "EQ_SEQ_ORDERED_V1".into(), - relation: StructuralRelationKind::OrderedSequence, - transition_law_id: "TR_STRUCTURAL_FORM_TO_CNORM_V1".into(), - ordering_significant: true, - grouping_significant: true, - flattening_allowed: false, - sorting_allowed: false, - reference_identity_preserved: true, - preserved_distinctions: vec![DistinctionClass::AuthorityBearing], - collapsed_distinctions: vec![DistinctionClass::FormatLocal], - minimal_invariants: vec![ - "item-kind".into(), - "item-structural-value".into(), - "item-position".into(), - ], - }, - EquivalenceLawSpec { - id: "EQ_FORMAT_ERASED_V1".into(), - relation: StructuralRelationKind::NonCollapsible, - transition_law_id: "TR_STRUCTURAL_FORM_TO_CNORM_V1".into(), - ordering_significant: false, - grouping_significant: false, - flattening_allowed: false, - sorting_allowed: false, - reference_identity_preserved: true, - preserved_distinctions: vec![DistinctionClass::AuthorityBearing], - collapsed_distinctions: vec![ - DistinctionClass::FormatLocal, - DistinctionClass::ProjectionOnly, - ], - minimal_invariants: vec!["normalized-token-sequence".into()], - }, - ] -} - -pub fn transition_law_specs() -> Vec { - vec![TransitionLawSpec { - id: "TR_STRUCTURAL_FORM_TO_CNORM_V1".into(), - source_phase: PhaseId::StructuralResolution, - target_phase: PhaseId::CanonicalNormalization, - allowed_distinction_classes: vec![ - DistinctionClass::ProjectionOnly, - DistinctionClass::FormatLocal, - DistinctionClass::CollapseEligible, - ], - forbidden_distinction_classes: vec![ - DistinctionClass::AuthorityBearing, - DistinctionClass::CollapseForbidden, - ], - required_receipts: vec!["SSR_RECEIPT".into(), "CNORM_RECEIPT".into()], - }] -} - -pub fn distinction_law_specs() -> Vec { - vec![ - DistinctionLawSpec { - id: "DIST_ITEM_POSITION_AUTHORITY_V1".into(), - class: DistinctionClass::AuthorityBearing, - carrier: "canonical-structure-item-position".into(), - collapse_allowed: false, - preserved_invariants: vec!["item-position".into(), "ordered-sequence".into()], - transition_law_id: "TR_STRUCTURAL_FORM_TO_CNORM_V1".into(), - }, - DistinctionLawSpec { - id: "DIST_ITEM_KIND_AUTHORITY_V1".into(), - class: DistinctionClass::AuthorityBearing, - carrier: "canonical-structure-item-kind".into(), - collapse_allowed: false, - preserved_invariants: vec!["item-kind".into()], - transition_law_id: "TR_STRUCTURAL_FORM_TO_CNORM_V1".into(), - }, - DistinctionLawSpec { - id: "DIST_ITEM_VALUE_AUTHORITY_V1".into(), - class: DistinctionClass::AuthorityBearing, - carrier: "canonical-structure-item-value".into(), - collapse_allowed: false, - preserved_invariants: vec!["item-structural-value".into()], - transition_law_id: "TR_STRUCTURAL_FORM_TO_CNORM_V1".into(), - }, - DistinctionLawSpec { - id: "DIST_RNA_FORMAT_LOCAL_V1".into(), - class: DistinctionClass::FormatLocal, - carrier: "rna-whitespace-and-line-ending-layout".into(), - collapse_allowed: true, - preserved_invariants: vec!["normalized-token-sequence".into()], - transition_law_id: "TR_STRUCTURAL_FORM_TO_CNORM_V1".into(), - }, - DistinctionLawSpec { - id: "DIST_INSPECTION_VIEW_PROJECTION_V1".into(), - class: DistinctionClass::ProjectionOnly, - carrier: "inspection-report-field-order-and-rendering".into(), - collapse_allowed: true, - preserved_invariants: vec!["source-authority-unchanged".into()], - transition_law_id: "TR_STRUCTURAL_FORM_TO_CNORM_V1".into(), - }, - ] -} - -pub fn transition_law_allows_distinction(class: DistinctionClass) -> bool { - transition_law_specs().iter().any(|law| { - law.allowed_distinction_classes.contains(&class) - && !law.forbidden_distinction_classes.contains(&class) - }) -} - -pub fn structural_canonical_law_hash() -> String { - hash_serialized(&( - structural_equivalence_law_specs(), - transition_law_specs(), - distinction_law_specs(), - )) -} - -pub fn validate_structural_equivalence_laws() -> Result<(), String> { - let transitions = transition_law_specs(); - for law in structural_equivalence_law_specs() { - let transition = transitions - .iter() - .find(|candidate| candidate.id == law.transition_law_id) - .ok_or_else(|| { - format!( - "equivalence law `{}` references unknown transition law `{}`", - law.id, law.transition_law_id - ) - })?; - for class in &law.collapsed_distinctions { - if !transition.allowed_distinction_classes.contains(class) - || transition.forbidden_distinction_classes.contains(class) - { - return Err(format!( - "equivalence law `{}` illegally collapses {:?}", - law.id, class - )); - } - } - for class in &law.preserved_distinctions { - if law.collapsed_distinctions.contains(class) { - return Err(format!( - "equivalence law `{}` both preserves and collapses {:?}", - law.id, class - )); - } - } - } - Ok(()) -} - -pub fn token_map_entries() -> Vec { - vec![ - TokenMapEntry { - sample: "a".into(), - class: TokenClass::Atom, - rule: "[a-z0-9]".into(), - }, - TokenMapEntry { - sample: "A".into(), - class: TokenClass::Binder, - rule: "[A-Z]".into(), - }, - TokenMapEntry { - sample: "(".into(), - class: TokenClass::GroupLeft, - rule: "opening delimiter".into(), - }, - TokenMapEntry { - sample: ")".into(), - class: TokenClass::GroupRight, - rule: "closing delimiter".into(), - }, - TokenMapEntry { - sample: ",".into(), - class: TokenClass::Separator, - rule: "separator".into(), - }, - TokenMapEntry { - sample: ".".into(), - class: TokenClass::StrandRef, - rule: "strand reference".into(), - }, - TokenMapEntry { - sample: "_".into(), - class: TokenClass::Operator, - rule: "structural operator".into(), - }, - TokenMapEntry { - sample: " ".into(), - class: TokenClass::Meta, - rule: "whitespace".into(), - }, - ] -} - -pub fn tokenize_rna_bytes(bytes: &[u8]) -> Result<(TokenStream, TokenizationReceipt), String> { - let text = std::str::from_utf8(bytes).map_err(|err| { - format!( - "RNA tokenization failed: input is not valid UTF-8 at byte {}", - err.valid_up_to() - ) - })?; - tokenize_rna(text) -} - -pub fn tokenize_rna(input: &str) -> Result<(TokenStream, TokenizationReceipt), String> { - let source_text = input.replace("\r\n", "\n"); - let mut tokens = Vec::with_capacity(source_text.len()); - let mut issues = Vec::new(); - - for (span_start, ch) in source_text.char_indices() { - let span_end = span_start + ch.len_utf8(); - let class = classify_rna_char(ch); - if ch.is_control() && !ch.is_whitespace() { - issues.push(TokenizationIssue { - offset: span_start, - message: format!("invalid RNA control character U+{:04X}", ch as u32), - }); - } - tokens.push(RnaToken { - class, - value: ch as u32, - flags: 0, - span_start, - span_end, - text: ch.to_string(), - }); - } - - let receipt = TokenizationReceipt { - id: receipt_id("TOK", &source_text), - token_count: tokens.len(), - byte_len: source_text.len(), - issues, - }; - if !receipt.issues.is_empty() { - return Err( - serde_json::to_string(&receipt).unwrap_or_else(|_| "RNA tokenization failed".into()) - ); - } - Ok(( - TokenStream { - source_text, - byte_len: receipt.byte_len, - tokens, - }, - receipt, - )) -} - -fn classify_rna_char(ch: char) -> TokenClass { - match ch { - '(' | '[' | '{' => TokenClass::GroupLeft, - ')' | ']' | '}' => TokenClass::GroupRight, - ',' | ';' => TokenClass::Separator, - '.' => TokenClass::StrandRef, - '_' | '|' | ':' | '=' | '+' | '-' | '*' | '/' | '^' | '≔' | '‖' | '→' => { - TokenClass::Operator - } - c if c.is_whitespace() => TokenClass::Meta, - c if c.is_ascii_uppercase() => TokenClass::Binder, - _ => TokenClass::Atom, - } -} - -pub fn normalize_rna(input: &str) -> Result<(NormalizedRna, RnaNormalizationReceipt), String> { - let (stream, _) = tokenize_rna(input)?; - normalize_token_stream(&stream) -} - -pub fn normalize_token_stream( - stream: &TokenStream, -) -> Result<(NormalizedRna, RnaNormalizationReceipt), String> { - let (normalized, mut receipt) = normalize_rna_text(&stream.source_text)?; - receipt.token_stream_id = receipt_id("TOK", &stream.source_text); - receipt.shorthand_eliminated = !normalized.normalized_text.contains(" "); - Ok((normalized, receipt)) -} - -fn normalize_rna_text(input: &str) -> Result<(NormalizedRna, RnaNormalizationReceipt), String> { - let raw_text = input.replace("\r\n", "\n"); - let chars = raw_text.chars().collect::>(); - let mut normalized = String::with_capacity(raw_text.len()); - let mut issues = Vec::new(); - let mut splice_regions = Vec::new(); - let mut paren_depth = 0usize; - let mut splice_start: Option = None; - let mut prev_was_space = false; - let mut index = 0usize; - - while index < chars.len() { - if index + 2 < chars.len() - && chars[index] == 'i' - && chars[index + 1] == 'e' - && chars[index + 2] == 'i' - { - if splice_start.is_some() { - issues.push(RnaNormalizationIssue { - class: RnaIssueClass::Ambiguity, - offset: index, - message: "nested splice region start".into(), - repair_hints: vec!["close the previous splice before opening a new one".into()], - }); - } - if !normalized.is_empty() && !normalized.ends_with(' ') { - normalized.push(' '); - } - let start = normalized.len(); - normalized.push_str("iei "); - splice_start = Some(start); - index += 3; - prev_was_space = true; - continue; - } - if index + 2 < chars.len() - && chars[index] == 'e' - && chars[index + 1] == 'i' - && chars[index + 2] == 'e' - { - match splice_start.take() { - Some(start) => { - if normalized.ends_with(' ') { - normalized.pop(); - } - if !normalized.is_empty() && !normalized.ends_with(' ') { - normalized.push(' '); - } - normalized.push_str("eie"); - splice_regions.push((start, normalized.len())); - } - None => issues.push(RnaNormalizationIssue { - class: RnaIssueClass::SpliceClosureFailure, - offset: index, - message: "splice close without matching open".into(), - repair_hints: vec!["remove the stray `eie` or add a matching `iei`".into()], - }), - } - index += 3; - prev_was_space = false; - continue; - } - - let ch = chars[index]; - match ch { - '(' | '[' | '{' => { - paren_depth += 1; - normalized.push(ch); - prev_was_space = false; - } - ')' | ']' | '}' => { - if paren_depth == 0 { - issues.push(RnaNormalizationIssue { - class: RnaIssueClass::GroupingFailure, - offset: index, - message: format!("unmatched closing delimiter `{ch}`"), - repair_hints: vec![ - "remove the unmatched closer or add a matching opener".into(), - ], - }); - } else { - paren_depth -= 1; - } - normalized.push(ch); - prev_was_space = false; - } - c if c.is_whitespace() => { - if !prev_was_space && !normalized.is_empty() { - normalized.push(' '); - prev_was_space = true; - } - } - _ => { - normalized.push(ch); - prev_was_space = false; - } - } - index += 1; - } - - if paren_depth > 0 { - issues.push(RnaNormalizationIssue { - class: RnaIssueClass::GroupingFailure, - offset: chars.len(), - message: "unterminated grouping delimiter".into(), - repair_hints: vec!["close all opened grouping delimiters".into()], - }); - } - if let Some(start) = splice_start.take() { - issues.push(RnaNormalizationIssue { - class: RnaIssueClass::SpliceClosureFailure, - offset: start, - message: "unterminated splice region".into(), - repair_hints: vec!["close the splice with `eie`".into()], - }); - } - - let normalized = normalized.trim().to_string(); - let state = if !issues.is_empty() { - RnaState::Raw - } else if !splice_regions.is_empty() - || normalized.contains("iei ") - || normalized.ends_with(" eie") - || normalized.contains(" eie ") - { - RnaState::Spliced - } else if normalized == raw_text.trim() { - RnaState::Stabilized - } else { - RnaState::Expressed - }; - - let receipt = RnaNormalizationReceipt { - id: receipt_id("RNR", &normalized), - token_stream_id: String::new(), - state, - normalized_text: normalized.clone(), - shorthand_eliminated: !normalized.contains(" "), - splice_regions: splice_regions.clone(), - issues, - }; - if !receipt.issues.is_empty() { - return Err( - serde_json::to_string(&receipt).unwrap_or_else(|_| "RNA normalization failed".into()) - ); - } - Ok(( - NormalizedRna { - raw_text, - normalized_text: normalized, - state, - splice_regions, - }, - receipt, - )) -} - -pub fn resolve_spliced_rna(normalized: &NormalizedRna) -> Result<(SsrGraph, SsrReceipt), String> { - let root_id = authority_id("SSR_ROOT", &normalized.normalized_text); - let estimated_token_count = normalized - .normalized_text - .bytes() - .filter(|byte| byte.is_ascii_whitespace()) - .count() - .saturating_add(1); - let mut nodes = vec![SsrNode { - id: root_id.clone(), - kind: SsrNodeKind::Root, - text: normalized.normalized_text.clone(), - children: Vec::with_capacity(estimated_token_count), - }]; - nodes.reserve(estimated_token_count); - - for (idx, token) in normalized.normalized_text.split_whitespace().enumerate() { - let kind = if token == "iei" || token == "eie" { - SsrNodeKind::Splice - } else if token.starts_with('(') - || token.ends_with(')') - || token.starts_with('{') - || token.ends_with('}') - || token.starts_with('[') - || token.ends_with(']') - { - SsrNodeKind::Group - } else { - SsrNodeKind::Atom - }; - let id = authority_id("SSR", &(idx, token)); - nodes[0].children.push(id.clone()); - nodes.push(SsrNode { - id, - kind, - text: token.into(), - children: Vec::new(), - }); - } - - let graph = SsrGraph { - root_id: root_id.clone(), - nodes, - strand_partition: vec!["core".into()], - }; - let receipt = SsrReceipt { - id: receipt_id("SSR_RCP", &graph.root_id), - root_id, - node_count: graph.nodes.len(), - transition_count: graph.nodes.len().saturating_sub(1), - transition_table_hash: hash_serialized(&ssr_transition_specs()), - ephemeral: true, - normalized_rna_id: receipt_id("RNR", &normalized.normalized_text), - }; - Ok((graph, receipt)) -} - -pub fn canonicalize_structural_form( - graph: &SsrGraph, -) -> Result<(CanonicalStructure, CnormReceipt), String> { - let law_specs = structural_equivalence_law_specs(); - let distinction_specs = distinction_law_specs(); - validate_structural_equivalence_laws()?; - if law_specs.iter().any(|law| { - matches!(law.relation, StructuralRelationKind::OrderedSequence) && law.sorting_allowed - }) { - return Err("ordered sequence equivalence law cannot permit sorting".into()); - } - if distinction_specs - .iter() - .any(|law| !law.collapse_allowed && transition_law_allows_distinction(law.class)) - { - return Err( - "transition law cannot permit collapse of authority-bearing distinctions".into(), - ); - } - if distinction_specs - .iter() - .any(|law| law.collapse_allowed && !transition_law_allows_distinction(law.class)) - { - return Err("collapse-eligible distinction is not admitted by transition law".into()); - } - - let root = graph - .nodes - .iter() - .find(|node| node.id == graph.root_id) - .ok_or_else(|| "structural form missing root".to_string())?; - let mut items = Vec::new(); - let mut instructions = vec![CanonicalInstruction { - tag: CanonicalInstructionTag::HeaderV1, - version: 1, - ordinal: 0, - kind: None, - structural_value: Some(root.children.len() as u64), - }]; - - for (ordinal, child_id) in root.children.iter().enumerate() { - let node = graph - .nodes - .iter() - .find(|candidate| &candidate.id == child_id) - .ok_or_else(|| format!("structural form missing child `{child_id}`"))?; - let reconstructed = canonical_structure_item_from_rna_token(&node.text); - let kind = reconstructed - .as_ref() - .map(|item| item.kind) - .unwrap_or(node.kind); - let structural_value = reconstructed - .as_ref() - .map(|item| item.structural_value) - .unwrap_or_else(|| structural_value_fallback_u64(&node.text)); - instructions.push(CanonicalInstruction { - tag: CanonicalInstructionTag::ItemV1, - version: 1, - ordinal: ordinal as u64, - kind: Some(kind), - structural_value: Some(structural_value), - }); - items.push(CanonicalStructureItem { - kind, - structural_value, - }); - } - - let canonical_bytes = canonical_instruction_bytes(&instructions); - let canonical_id = canonical_id_from_binary_structure(&canonical_bytes); - let canonical_hash = canonical_id.0.clone(); - let canonical_root_id = format!("CNS_ROOT_{}", canonical_hash); - let structure = CanonicalStructure { - root_id: canonical_root_id, - canonical_id, - canonical_hash: canonical_hash.clone(), - canonical_bytes, - items, - instructions, - }; - let receipt = CnormReceipt { - id: receipt_id("CNR_STRUCT", &structure.canonical_hash), - root_id: structure.root_id.clone(), - canonical_hash, - rule_table_hash: structural_canonical_law_hash(), - idempotent: true, - erased_variations: vec!["formatting".into()], - }; - Ok((structure, receipt)) -} - -pub fn execute_lower_chain(rna: &str) -> Result { - let mut kernel = PhaseExecutionKernel::default(); - - let token_out = kernel.execute( - PhaseId::Tokenization, - payload_commitment(&rna), - Vec::new(), - Some("retain raw RNA bytes".into()), - || tokenize_rna(rna), - |(stream, receipt)| { - vec![ - InvariantCheck { - name: "all_bytes_classified".into(), - passed: stream.byte_len == rna.replace("\r\n", "\n").len() - && stream - .tokens - .iter() - .all(|token| token.span_end <= stream.byte_len), - detail: "token stream byte coverage must match normalized RNA input bytes" - .into(), - }, - InvariantCheck { - name: "no_tokenization_issues".into(), - passed: receipt.issues.is_empty(), - detail: "tokenization issues must be empty after successful tokenization" - .into(), - }, - InvariantCheck { - name: "no_semantic_token_authority".into(), - passed: token_class_specs() - .iter() - .all(|spec| !spec.semantic_authority), - detail: - "token classes classify structure only and cannot become semantic authority" - .into(), - }, - ] - }, - )?; - let (token_stream, tokenization_receipt) = token_out; - - let rn_out = kernel.execute( - PhaseId::RnaNormalization, - hash_serialized(&token_stream), - vec![tokenization_receipt.id.clone()], - Some("retain raw RNA".into()), - || normalize_token_stream(&token_stream), - |(normalized, receipt)| { - vec![ - InvariantCheck { - name: "no_semantic_mutation".into(), - passed: receipt.issues.is_empty(), - detail: "normalization issues must be empty after successful normalization" - .into(), - }, - InvariantCheck { - name: "deterministic_tokenization".into(), - passed: !normalized.normalized_text.is_empty(), - detail: "normalized RNA must not be empty after successful normalization" - .into(), - }, - InvariantCheck { - name: "token_boundary_preserved".into(), - passed: receipt.token_stream_id == tokenization_receipt.id, - detail: "RNORM must be grounded in the token stream receipt it consumed".into(), - }, - InvariantCheck { - name: "diagnostics_are_table_owned".into(), - passed: !rnorm_diagnostic_specs().is_empty(), - detail: "RNORM diagnostics must be governed by reusable diagnostic specs" - .into(), - }, - ] - }, - )?; - let (normalized, rn_receipt) = rn_out; - let normalized_hash = payload_commitment(&normalized.normalized_text); - - let ssr_out = kernel.execute( - PhaseId::StructuralResolution, - normalized_hash.clone(), - vec![rn_receipt.id.clone()], - Some("discard SSR and retain RNORM receipt".into()), - || resolve_spliced_rna(&normalized), - |(graph, receipt)| { - vec![ - InvariantCheck { - name: "ephemeral_only".into(), - passed: receipt.ephemeral, - detail: "SSR must remain ephemeral".into(), - }, - InvariantCheck { - name: "root_node_present".into(), - passed: graph.nodes.iter().any(|node| { - node.id == graph.root_id && matches!(node.kind, SsrNodeKind::Root) - }), - detail: "SSR graph must contain exactly one root-like entry".into(), - }, - InvariantCheck { - name: "transition_table_structural_only".into(), - passed: ssr_transition_specs() - .iter() - .all(|spec| !spec.persists_state && !spec.semantic_inference), - detail: "SSR transition specs must not persist state or infer semantics".into(), - }, - ] - }, - )?; - let (kernel_graph, ssr_receipt) = ssr_out; - let graph_hash = hash_serialized(&kernel_graph); - - let cnorm_out = kernel.execute( - PhaseId::CanonicalNormalization, - graph_hash, - vec![ssr_receipt.id.clone()], - Some("retain SSR receipt and reject unstable canonical output".into()), - || { - let (structure, receipt) = canonicalize_structural_form(&kernel_graph)?; - Ok::<_, String>((structure, receipt)) - }, - |(structure, receipt)| { - vec![ - InvariantCheck { - name: "canonical_hash_matches".into(), - passed: receipt.canonical_hash == structure.canonical_id.0, - detail: "canonical hash must match canonical structure identity".into(), - }, - InvariantCheck { - name: "canonical_bytes_non_empty".into(), - passed: !structure.canonical_bytes.is_empty(), - detail: "canonical structure must have deterministic binary identity input" - .into(), - }, - InvariantCheck { - name: "equivalence_law_explicit".into(), - passed: receipt.idempotent - && structural_equivalence_law_specs() - .iter() - .all(|spec| !spec.minimal_invariants.is_empty()), - detail: "CNORM must derive identity from explicit equivalence laws".into(), - }, - ] - }, - )?; - let (canonical_structure, cnorm_receipt) = cnorm_out; - - Ok(LowerChainExecution { - token_stream, - tokenization_receipt, - normalized, - rn_receipt, - kernel_graph, - ssr_receipt, - canonical_structure, - cnorm_receipt, - ledger_entries: kernel.entries().to_vec(), - }) -} - -pub fn hash_serialized(value: &T) -> String { - role_digest_value(DigestRole::CacheKey, value) -} - -#[cfg(test)] -mod genome_foundation_tests { - use super::*; - - #[test] - fn role_digests_are_domain_separated() { - let payload = "same structural payload"; - let authority = role_digest_str(DigestRole::AuthorityId, payload); - let receipt = role_digest_str(DigestRole::ReceiptId, payload); - let witness = role_digest_str(DigestRole::WitnessId, payload); - let authority_again = role_digest_str(DigestRole::AuthorityId, payload); - - assert_eq!(authority.role, DigestRole::AuthorityId); - assert_eq!(authority.value, authority_again.value); - assert_ne!(authority.value, receipt.value); - assert_ne!(authority.value, witness.value); - assert_ne!(receipt.value, witness.value); - } - - #[test] - fn substrate_witness_ids_use_witness_digest_role() { - let witness = derive_substrate_witness("subject", vec![], vec![], vec![], "receipt"); - let witness_digest = role_digest_str(DigestRole::WitnessId, "subject:receipt"); - let codec_digest = role_digest_str(DigestRole::CodecDigest, "subject:receipt"); - - assert_eq!(witness.id, format!("WIT_{}", witness_digest.value)); - assert_ne!(witness.id, format!("WIT_{}", codec_digest.value)); - } - - #[test] - fn tokenization_classifies_ascii_and_unicode_without_semantic_authority() { - let (stream, receipt) = tokenize_rna("A.ι ≔ σ ‖ κ").expect("tokenization"); - assert_eq!(receipt.token_count, stream.tokens.len()); - assert!(receipt.issues.is_empty()); - assert!( - stream - .tokens - .iter() - .any(|token| token.class == TokenClass::Binder && token.text == "A") - ); - assert!( - stream - .tokens - .iter() - .any(|token| token.class == TokenClass::StrandRef) - ); - assert!( - stream - .tokens - .iter() - .any(|token| token.class == TokenClass::Operator && token.text == "≔") - ); - assert!( - token_class_specs() - .iter() - .all(|spec| !spec.semantic_authority) - ); - } - - #[test] - fn tokenization_rejects_non_whitespace_control_characters() { - let err = tokenize_rna("a\u{0000}b").expect_err("control character should fail"); - assert!(err.contains("invalid RNA control character")); - } - - #[test] - fn qa_entry_json_rejects_deprecated_surface_schema_admission() { - for kind in [ - "surface-policy", - "transform-receipt", - "format-receipt", - "roundtrip-report", - "capability", - "capability-matrix", - "surface-budget", - "surface-deficiency", - ] { - let err = QaEntry::from_surface_json(kind, "{}").expect_err("deprecated entry"); - assert!( - err.to_string().contains("deprecated surface-schema entry"), - "{kind}: {err}" - ); - } - } - - #[test] - fn qa_entry_json_rejects_deprecated_surface_schema_export() { - let entries = vec![ - QaEntry::SurfacePolicy(SurfacePolicy { - id: "POL_OLD".into(), - codebook_pack: "CB_OLD".into(), - profile: "old".into(), - projection_policy: "PROJ_OLD".into(), - combo_pack: None, - glyph_pack: None, - alias_expansion_policy: "ALIAS_OLD".into(), - allowed_loss_classes: vec![], - }), - QaEntry::TransformReceipt(FormatTransformReceipt { - id: "TR_OLD".into(), - src_surface: SurfaceKind::Qc0, - dst_surface: SurfaceKind::Qa0, - object_ids: vec!["OBJ".into()], - transform_kind: TransformKind::Transcode, - policy_id: "POL_OLD".into(), - defaults_used: vec![], - alias_expansions: vec![], - loss_classes: vec![], - hash_before: "before".into(), - hash_after: "after".into(), - verdict: TransformVerdict::Lossless, - rollback_ref: None, - replay_ref: None, - }), - QaEntry::RoundTripReport(RoundTripReport { - id: "RTR_OLD".into(), - surface_kind: SurfaceKind::Qc0, - policy_id: "POL_OLD".into(), - object_ids: vec!["OBJ".into()], - receipt_ids: vec!["TR_OLD".into()], - verdict: TransformVerdict::Lossless, - fragility_vector: vec![], - }), - QaEntry::CapabilityMatrix(CapabilityMatrix { - id: "CAP_OLD".into(), - surface_kind: SurfaceKind::Qa0, - supported_packs: vec![SupportedPack::Core], - import_support: true, - export_support: true, - transcode_support: vec![SurfaceKind::Qc0], - roundtrip_support: true, - known_limits: vec![], - }), - QaEntry::SurfaceBudget(SurfaceBudget { - id: "BUDGET_OLD".into(), - max_loss_classes: 0, - forbid_silent_defaulting: true, - }), - ]; - - for entry in entries { - let err = entry.to_surface_json().expect_err("deprecated export"); - assert!( - err.to_string().contains("deprecated surface-schema entry"), - "{err}" - ); - } - } - - #[test] - fn cache_hash_v1_is_domain_separated_and_stable() { - assert_eq!(cache_hash_v1_str("abc"), cache_hash_v1_bytes(b"abc")); - assert_ne!(cache_hash_v1_str("abc"), cache_hash_v1_str("abcd")); - assert_eq!(cache_hash_v1_str("abc").len(), 64); - } - - #[test] - fn normalize_rna_is_deterministic_under_spacing_variation() { - let (left, _) = normalize_rna("ι ≔ σ ‖ κ").expect("left normalization"); - let (right, _) = normalize_rna("ι ≔ σ ‖ κ").expect("right normalization"); - assert_eq!(left.normalized_text, right.normalized_text); - } - - #[test] - fn rnorm_receipt_is_token_grounded_and_diagnostic_specs_are_closed() { - let (stream, token_receipt) = tokenize_rna("ι ≔ σ").expect("tokenization"); - let (normalized, receipt) = normalize_token_stream(&stream).expect("rnorm"); - assert_eq!(receipt.token_stream_id, token_receipt.id); - assert!(receipt.shorthand_eliminated); - assert_eq!(normalized.normalized_text, "ι ≔ σ"); - assert!( - rnorm_diagnostic_specs() - .iter() - .all(|spec| !spec.code.is_empty() && !spec.repair_hint_template.is_empty()) - ); - } - - #[test] - fn normalize_rna_reports_unterminated_splice() { - let err = normalize_rna("iei f g").expect_err("unterminated splice should fail"); - assert!(err.contains("SpliceClosureFailure") || err.contains("unterminated splice")); - } - - #[test] - fn equivalence_law_makes_ordering_explicit_before_cnorm() { - let laws = structural_equivalence_law_specs(); - let ordered = laws - .iter() - .find(|law| matches!(law.relation, StructuralRelationKind::OrderedSequence)) - .expect("ordered sequence law"); - assert_eq!(ordered.transition_law_id, "TR_STRUCTURAL_FORM_TO_CNORM_V1"); - assert!(ordered.ordering_significant); - assert!(!ordered.sorting_allowed); - assert!(ordered.reference_identity_preserved); - assert!( - ordered - .preserved_distinctions - .contains(&DistinctionClass::AuthorityBearing) - ); - assert!( - !ordered - .collapsed_distinctions - .contains(&DistinctionClass::AuthorityBearing) - ); - assert!( - ordered - .minimal_invariants - .iter() - .any(|item| item == "item-position") - ); - validate_structural_equivalence_laws().expect("equivalence laws validate"); - } - - #[test] - fn distinction_law_classifies_collapse_before_equivalence() { - let distinctions = distinction_law_specs(); - let transitions = transition_law_specs(); - assert!(transitions.iter().any(|law| { - law.id == "TR_STRUCTURAL_FORM_TO_CNORM_V1" - && law - .forbidden_distinction_classes - .contains(&DistinctionClass::AuthorityBearing) - && law - .allowed_distinction_classes - .contains(&DistinctionClass::FormatLocal) - })); - assert!(distinctions.iter().any(|law| { - law.id == "DIST_ITEM_POSITION_AUTHORITY_V1" - && law.class == DistinctionClass::AuthorityBearing - && !law.collapse_allowed - })); - assert!(distinctions.iter().any(|law| { - law.id == "DIST_RNA_FORMAT_LOCAL_V1" - && law.class == DistinctionClass::FormatLocal - && law.collapse_allowed - && transition_law_allows_distinction(law.class) - })); - assert!(!transition_law_allows_distinction( - DistinctionClass::AuthorityBearing - )); - } - - #[test] - fn canonical_structure_erases_spacing_but_preserves_order() { - let (left_norm, _) = normalize_rna("ι ≔ σ").expect("left normalization"); - let (right_norm, _) = normalize_rna("ι ≔ σ").expect("right normalization"); - let (reordered_norm, _) = normalize_rna("σ ≔ ι").expect("reordered normalization"); - let (left_graph, _) = resolve_spliced_rna(&left_norm).expect("left ssr"); - let (right_graph, _) = resolve_spliced_rna(&right_norm).expect("right ssr"); - let (reordered_graph, _) = resolve_spliced_rna(&reordered_norm).expect("reordered ssr"); - let (left_structure, left_receipt) = - canonicalize_structural_form(&left_graph).expect("left structural cnorm"); - let (right_structure, right_receipt) = - canonicalize_structural_form(&right_graph).expect("right structural cnorm"); - let (reordered_structure, _) = - canonicalize_structural_form(&reordered_graph).expect("reordered structural cnorm"); - - assert_eq!(left_structure.canonical_id, right_structure.canonical_id); - assert_eq!(left_receipt.canonical_hash, right_receipt.canonical_hash); - assert_ne!( - left_structure.canonical_id, - reordered_structure.canonical_id - ); - assert!(!left_structure.canonical_bytes.is_empty()); - assert_eq!( - left_structure.canonical_bytes, - canonical_instruction_bytes(&left_structure.instructions) - ); - assert_eq!( - left_structure - .instructions - .first() - .map(|instruction| instruction.tag), - Some(CanonicalInstructionTag::HeaderV1) - ); - assert!( - left_structure - .instructions - .iter() - .skip(1) - .all(|instruction| instruction.tag == CanonicalInstructionTag::ItemV1) - ); - assert_eq!( - left_receipt.rule_table_hash, - structural_canonical_law_hash() - ); - } - - #[test] - fn duplex_pair_validation_requires_semantic_and_complement_strands() { - let missing = validate_duplex_pair(None); - assert_eq!(missing.status, DuplexPairStatus::Unpaired); - - let semantic = SemanticStrand { - id: "SEM_CKI".into(), - canonical_structure_id: "CNS_1".into(), - authority_scope: "root-structure".into(), - }; - let complement = AuthorityComplement { - id: "CMP_CKI".into(), - authority_scope: "root-structure".into(), - admission_law_id: "ADM_CANONICAL_STRUCTURE_V1".into(), - exclusions: vec!["strand-only-promotion".into()], - invariants: vec!["canonical-instruction-bytes-stable".into()], - dependency_burdens: vec!["domain-closure-pending".into()], - required_witness_forms: vec!["cnorm-receipt".into()], - closure_requirements: vec!["closed-domain-slice".into()], - rollback_law_id: "RBK_REJECT_PAIR_V1".into(), - }; - let pair_law = PairLaw { - id: "PAIR_CANONICAL_STRUCTURE_V1".into(), - required_semantic_scope: "root-structure".into(), - required_complement_scope: "root-structure".into(), - required_admission_law_id: "ADM_CANONICAL_STRUCTURE_V1".into(), - strand_only_promotion_allowed: false, - }; - let pair = assemble_duplex_pair(semantic.clone(), complement.clone(), pair_law.clone()); - let valid = validate_duplex_pair(Some(&pair)); - assert_eq!(valid.status, DuplexPairStatus::LocallyValid); - assert_eq!(valid.pair_commitment, Some(pair.commitment)); - - let mut bad_law = pair_law; - bad_law.strand_only_promotion_allowed = true; - let malformed = assemble_duplex_pair(semantic, complement, bad_law); - let malformed_validation = validate_duplex_pair(Some(&malformed)); - assert_eq!(malformed_validation.status, DuplexPairStatus::Malformed); - assert!( - malformed_validation - .failures - .iter() - .any(|failure| failure.contains("strand-only promotion")) - ); - } - - #[test] - fn authority_complement_must_carry_burdens_not_receipt_only_claims() { - let semantic = SemanticStrand { - id: "SEM_CKI".into(), - canonical_structure_id: "CNS_1".into(), - authority_scope: "root-structure".into(), - }; - let pair_law = PairLaw { - id: "PAIR_CANONICAL_STRUCTURE_V1".into(), - required_semantic_scope: "root-structure".into(), - required_complement_scope: "root-structure".into(), - required_admission_law_id: "ADM_CANONICAL_STRUCTURE_V1".into(), - strand_only_promotion_allowed: false, - }; - let receipt_only_complement = AuthorityComplement { - id: "CMP_RECEIPT_ONLY".into(), - authority_scope: "root-structure".into(), - admission_law_id: "ADM_CANONICAL_STRUCTURE_V1".into(), - exclusions: vec!["strand-only-promotion".into()], - invariants: vec![], - dependency_burdens: vec![], - required_witness_forms: vec![], - closure_requirements: vec!["closed-domain-slice".into()], - rollback_law_id: "RBK_REJECT_PAIR_V1".into(), - }; - let pair = assemble_duplex_pair(semantic, receipt_only_complement, pair_law); - let validation = validate_duplex_pair(Some(&pair)); - - assert_eq!(validation.status, DuplexPairStatus::Malformed); - assert!( - validation - .failures - .iter() - .any(|failure| { failure.contains("authority complement has no invariants") }) - ); - assert!(validation.failures.iter().any(|failure| { - failure.contains("authority complement has no required witness forms") - })); - } - - #[test] - fn domain_closure_blocks_promotion_on_open_frontier() { - let semantic = SemanticStrand { - id: "SEM_CKI".into(), - canonical_structure_id: "CNS_1".into(), - authority_scope: "root-structure".into(), - }; - let complement = AuthorityComplement { - id: "CMP_CKI".into(), - authority_scope: "root-structure".into(), - admission_law_id: "ADM_CANONICAL_STRUCTURE_V1".into(), - exclusions: vec!["strand-only-promotion".into()], - invariants: vec!["canonical-instruction-bytes-stable".into()], - dependency_burdens: vec![], - required_witness_forms: vec!["cnorm-receipt".into()], - closure_requirements: vec!["closed-domain-slice".into()], - rollback_law_id: "RBK_REJECT_PAIR_V1".into(), - }; - let pair_law = PairLaw { - id: "PAIR_CANONICAL_STRUCTURE_V1".into(), - required_semantic_scope: "root-structure".into(), - required_complement_scope: "root-structure".into(), - required_admission_law_id: "ADM_CANONICAL_STRUCTURE_V1".into(), - strand_only_promotion_allowed: false, - }; - let pair = assemble_duplex_pair(semantic, complement, pair_law); - let validation = validate_duplex_pair(Some(&pair)); - assert_eq!(validation.status, DuplexPairStatus::LocallyValid); - - let blocked = evaluate_domain_closure( - &[validation.clone()], - vec![OpenObligation { - id: "OBL_DOMAIN_CLOSURE".into(), - description: "domain closure witness still pending".into(), - }], - vec![], - CyclePolicyResult::Acyclic, - ); - assert!(!blocked.promotable); - assert_eq!(blocked.locally_valid_pairs.len(), 1); - assert_eq!(blocked.open_frontier.len(), 1); - - let closed = - evaluate_domain_closure(&[validation], vec![], vec![], CyclePolicyResult::Acyclic); - assert!(closed.promotable); - assert!(closed.promotion_receipt_required); - } - - #[test] - fn deterministic_authority_merge_excludes_worker_count_and_input_order() { - let units = vec![ - CanonicalWorkUnit { - coordinate: "pair:002".into(), - payload_commitment: "b".into(), - }, - CanonicalWorkUnit { - coordinate: "pair:001".into(), - payload_commitment: "a".into(), - }, - CanonicalWorkUnit { - coordinate: "pair:003".into(), - payload_commitment: "c".into(), - }, - ]; - let mut reversed = units.clone(); - reversed.reverse(); - - let serial = deterministic_authority_merge(&units, 1); - let two_workers = deterministic_authority_merge(&reversed, 2); - let many_workers = deterministic_authority_merge(&units, 16); - - assert_eq!(serial, two_workers); - assert_eq!(serial, many_workers); - assert_eq!( - serial.ordered_coordinates, - vec!["pair:001", "pair:002", "pair:003"] - ); - } - - #[test] - fn ssr_transition_specs_remain_ephemeral_and_lookup_free() { - let (normalized, _) = normalize_rna("A.ι ≔ σ").expect("rnorm"); - let (graph, receipt) = resolve_spliced_rna(&normalized).expect("ssr"); - assert!(receipt.ephemeral); - assert_eq!( - receipt.transition_table_hash, - hash_serialized(&ssr_transition_specs()) - ); - assert_eq!( - receipt.transition_count, - graph.nodes.len().saturating_sub(1) - ); - assert!( - ssr_transition_specs() - .iter() - .all(|spec| !spec.persists_state && !spec.semantic_inference) - ); - } - - #[test] - fn dna_packet_validation_rejects_semantic_symbol_table_flag() { - let packet = LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Gene, - surface: GenomeSurface::Dna, - kind: LocusPacketKind::CanonicalTransfer, - version_major: 1, - version_minor: 0, - authority_tier: 1, - capabilities: LocusCapabilityMask::default(), - grammar_id: "rna.v1".into(), - schema_hash: "legacy_graph_projection.v1".into(), - integrity_hash: "abc".into(), - strand_manifest: vec!["core".into()], - feature_flags: 0, - root_subject_id: "SUBJ".into(), - }, - sections: vec![LocusSection { - opcode: LocusOpcode::SymbolTable, - flags: 0x0001, - subject_id: "SUBJ".into(), - payload: Vec::new(), - }], - }; - let report = validate_dna_packet(&packet); - assert!(report.symbol_table_semantic_authority); - assert!(!report.failures.is_empty()); - } - - #[test] - fn dna_packet_validation_rejects_unknown_authority_tier() { - let payload = b"payload".to_vec(); - let packet = LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Gene, - surface: GenomeSurface::Dna, - kind: LocusPacketKind::CanonicalTransfer, - version_major: 1, - version_minor: 0, - authority_tier: 99, - capabilities: LocusCapabilityMask::default(), - grammar_id: "rna.v1".into(), - schema_hash: "execution_manifest.v1".into(), - integrity_hash: dna_digest_from_bytes(&payload).0, - strand_manifest: vec!["core".into()], - feature_flags: 0, - root_subject_id: "SUBJ".into(), - }, - sections: vec![LocusSection { - opcode: LocusOpcode::CanonicalPayload, - flags: 0, - subject_id: "SUBJ".into(), - payload, - }], - }; - - let report = validate_dna_packet(&packet); - assert!(!report.reversible); - assert!( - report - .failures - .iter() - .any(|failure| { failure.contains("unknown authority tier") }) - ); - } - - #[test] - fn locus_packet_decode_rejects_oversized_fields_before_payload_copy() { - let mut bytes = Vec::new(); - bytes.extend_from_slice(b"LCS1"); - bytes.push(GenomeArtifactClass::Gene as u8); - bytes.push(GenomeSurface::Dna as u8); - bytes.push(LocusPacketKind::CanonicalTransfer as u8); - bytes.push(1); - bytes.push(0); - bytes.push(AuthorityTier::Candidate as u8); - bytes.extend_from_slice(&0u16.to_le_bytes()); - bytes.extend_from_slice(&((MAX_LOCUS_SIZED_FIELD_BYTES as u32) + 1).to_le_bytes()); - - let err = decode_locus_packet_with_mode(&bytes, LocusDecodeMode::CurrentAuthority) - .expect_err("oversized grammar id should be rejected before payload copy"); - assert!(err.contains("sized field too large"), "{err}"); - } - - #[test] - fn dna_packet_validation_checks_canonical_structure_digest() { - let (normalized, _) = normalize_rna("ι ≔ σ").expect("normalization"); - let (graph, _) = resolve_spliced_rna(&normalized).expect("ssr"); - let (structure, _) = canonicalize_structural_form(&graph).expect("canonical structure"); - let payload = bincode::serialize(&structure).expect("payload"); - let mut packet = LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Gene, - surface: GenomeSurface::Dna, - kind: LocusPacketKind::CanonicalTransfer, - version_major: 1, - version_minor: 0, - authority_tier: 1, - capabilities: LocusCapabilityMask::default(), - grammar_id: "rna.v1".into(), - schema_hash: "canonical_structure.v1".into(), - integrity_hash: structure.canonical_hash.clone(), - strand_manifest: vec!["core".into()], - feature_flags: 0, - root_subject_id: "SUBJ".into(), - }, - sections: vec![LocusSection { - opcode: LocusOpcode::CanonicalPayload, - flags: 0, - subject_id: "SUBJ".into(), - payload, - }], - }; - let valid = validate_dna_packet(&packet); - assert!(valid.canonical_payload_digest_valid); - assert!(valid.failures.is_empty()); - - packet.header.integrity_hash = "not-the-structure-hash".into(); - let invalid = validate_dna_packet(&packet); - assert!(!invalid.canonical_payload_digest_valid); - assert!( - invalid - .failures - .iter() - .any(|failure| failure.contains("canonical structure payload digest")) - ); - } - - #[test] - fn dna_validation_report_id_uses_receipt_digest_role() { - let payload = b"payload".to_vec(); - let packet = LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Gene, - surface: GenomeSurface::Dna, - kind: LocusPacketKind::CanonicalTransfer, - version_major: 1, - version_minor: 0, - authority_tier: 1, - capabilities: LocusCapabilityMask::default(), - grammar_id: "rna.v1".into(), - schema_hash: "legacy_graph_projection.v1".into(), - integrity_hash: dna_digest_from_bytes(&payload).0, - strand_manifest: vec!["core".into()], - feature_flags: 0, - root_subject_id: "SUBJ".into(), - }, - sections: vec![LocusSection { - opcode: LocusOpcode::CanonicalPayload, - flags: 0, - subject_id: "SUBJ".into(), - payload, - }], - }; - - let report = validate_dna_packet(&packet); - let receipt_digest = role_digest_value(DigestRole::ReceiptId, &packet); - let payload_digest = role_digest_value(DigestRole::PayloadCommitment, &packet); - let authority_digest = role_digest_value(DigestRole::AuthorityId, &packet); - - assert_eq!(report.id, format!("DNA_VAL_{receipt_digest}")); - assert_ne!(receipt_digest, payload_digest); - assert_ne!(receipt_digest, authority_digest); - } - - #[test] - fn generic_dna_packet_validates_section_payload_commitment() { - let payload = b"payload".to_vec(); - let mut packet = LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Gene, - surface: GenomeSurface::Dna, - kind: LocusPacketKind::CanonicalTransfer, - version_major: 1, - version_minor: 0, - authority_tier: 1, - capabilities: LocusCapabilityMask::default(), - grammar_id: "rna.v1".into(), - schema_hash: "execution_manifest.v1".into(), - integrity_hash: dna_digest_from_bytes(&payload).0, - strand_manifest: vec!["core".into()], - feature_flags: 0, - root_subject_id: "SUBJ".into(), - }, - sections: vec![LocusSection { - opcode: LocusOpcode::CanonicalPayload, - flags: 0, - subject_id: "SUBJ".into(), - payload, - }], - }; - - let valid = validate_dna_packet(&packet); - assert!(valid.section_payload_commitments_valid); - assert_eq!(valid.section_payload_commitments.len(), 1); - assert!(valid.failures.is_empty()); - - packet.sections[0].payload = b"tampered".to_vec(); - let invalid = validate_dna_packet(&packet); - assert!(!invalid.section_payload_commitments_valid); - assert!(invalid.failures.iter().any(|failure| { - failure.contains("section payload commitment does not match header integrity") - })); - } - - #[test] - fn legacy_packet_decode_requires_explicit_migration_or_forensic_mode() { - let mut legacy = Vec::new(); - legacy.extend_from_slice(b"LCS1"); - legacy.push(LocusPacketKind::CanonicalTransfer as u8); - legacy.push(1); - legacy.push(0); - legacy.push(1); - legacy.extend_from_slice(&0u16.to_le_bytes()); - push_sized_bytes(&mut legacy, b"legacy_graph_projection.v1").expect("schema"); - push_sized_bytes(&mut legacy, b"SUBJ").expect("root"); - legacy.extend_from_slice(&1u16.to_le_bytes()); - legacy.push(LocusOpcode::CanonicalPayload as u8); - legacy.extend_from_slice(&0u16.to_le_bytes()); - push_sized_bytes(&mut legacy, b"SUBJ").expect("subject"); - push_sized_bytes(&mut legacy, b"payload").expect("payload"); - - assert!(decode_locus_packet_with_mode(&legacy, LocusDecodeMode::CurrentAuthority).is_err()); - assert!(decode_locus_packet_with_mode(&legacy, LocusDecodeMode::Migration).is_ok()); - assert!(decode_locus_packet_with_mode(&legacy, LocusDecodeMode::Forensic).is_ok()); - } - - #[test] - fn codon_lexon_law_tables_are_unique_and_complete() { - let report = validate_codon_lexon_law(); - assert!(report.valid, "{:?}", report.failures); - assert!(report.codon_count >= 8); - assert!(report.lexon_count >= 5); - assert!(report.macro_codon_count >= 5); - assert!(report.generated_word_ban_count >= 10); - } - - #[test] - fn machine_digest_codon_is_memo_only_not_public_proof_identity() { - let digest = codon_specs() - .into_iter() - .find(|codon| codon.symbol == "M#") - .expect("digest/memo codon"); - assert_eq!(digest.class, CodonClass::Machine); - assert_eq!(digest.admitted_phases, vec![CodonPhase::MachineMemo]); - assert!(!digest.canonical); - } - - #[test] - fn codon_aliases_resolve_to_symbols_but_do_not_change_phase_law() { - let dependency = resolve_codon_symbol_or_alias("depends_on").expect("dependency codon"); - assert_eq!(dependency.symbol, "<-"); - assert!(codon_admitted_in_phase(&dependency, CodonPhase::SourceRna)); - assert!(!codon_admitted_in_phase( - &dependency, - CodonPhase::ForeignDebug - )); - - let digest = resolve_codon_symbol_or_alias("hash").expect("digest codon"); - assert_eq!(digest.symbol, "M#"); - assert!(codon_admitted_in_phase(&digest, CodonPhase::MachineMemo)); - assert!(!codon_admitted_in_phase(&digest, CodonPhase::Product)); - } - - #[test] - fn representative_lexons_bind_scoped_targets_with_receipts() { - let lexons = lexon_specs(); - for symbol in ["φ_chain", "δ_deriv", "δ_comp", "β_tri", "β_spec"] { - let lexon = lexons - .iter() - .find(|candidate| candidate.symbol == symbol) - .unwrap_or_else(|| panic!("missing representative lexon {symbol}")); - assert_eq!(lexon.scope, LexonScope::GlobalPattern); - assert!(!lexon.canonical_target.is_empty()); - assert!(!lexon.aliases.is_empty()); - assert!(lexon.binding_receipt.starts_with("lexon-binding.")); - } - } - - #[test] - fn lexon_aliases_resolve_to_scoped_canonical_targets() { - let chain = resolve_lexon_symbol_or_alias("chain rule").expect("chain rule lexon"); - assert_eq!(chain.symbol, "φ_chain"); - assert_eq!(chain.scope, LexonScope::GlobalPattern); - assert_eq!(chain.canonical_target, "chain-rule-claim-pattern"); - - let derivative = resolve_lexon_symbol_or_alias("derivative").expect("derivative lexon"); - assert_eq!(derivative.symbol, "δ_deriv"); - assert_eq!(derivative.class, LexonClass::Definition); - } - - #[test] - fn macro_codons_are_separate_from_lexons() { - let roundtrip = - resolve_macro_codon_symbol_or_alias("roundtrip_fixed_point").expect("roundtrip macro"); - assert_eq!(roundtrip.symbol, "↻✓"); - assert_eq!(roundtrip.class, MacroCodonClass::RoundTrip); - assert!( - roundtrip - .admitted_phases - .contains(&CodonPhase::DnaAuthority) - ); - - assert!(resolve_lexon_symbol_or_alias("roundtrip_fixed_point").is_none()); - let report = validate_codon_lexon_law(); - assert!(report.valid, "{:?}", report.failures); - } - - #[test] - fn opcode_tombstones_and_ranges_are_explicit_law() { - let ranges = opcode_range_specs(); - assert!(ranges.iter().any(|range| range.name == "core-relations")); - assert!(ranges.iter().any(|range| range.name == "macro-patterns")); - assert!(ranges.iter().any(|range| range.name == "tombstones")); - - let tombstones = tombstone_specs(); - assert!(tombstones.iter().any(|tombstone| { - tombstone.opcode == 0x1f00 - && tombstone.replacement.as_deref() == Some("header codon phase law") - })); - let active_opcodes = codon_specs() - .into_iter() - .map(|codon| codon.opcode) - .chain(macro_codon_specs().into_iter().map(|codon| codon.opcode)) - .collect::>(); - for tombstone in tombstones { - assert!(!active_opcodes.contains(&tombstone.opcode)); - } - } - - #[test] - fn codon_header_phase_controls_source_admission() { - let source = - parse_codon_header("!λ64/2\n⟦τ G# R! · cki_registry⟧\n").expect("source header"); - assert_eq!(source.version, 2); - assert_eq!(source.phase, CodonPhase::SourceRna); - assert_eq!(source.class_symbol, "G#"); - assert_eq!(source.role_symbol, "R!"); - assert_eq!(source.subject, "cki_registry"); - - let product = - parse_codon_header("!l64/2\n⟦ξ G# R! · cki_registry⟧\n").expect("product header"); - assert_eq!(product.phase, CodonPhase::Product); - assert!(codon_header_admits_source_compile(&source)); - assert!(!codon_header_admits_source_compile(&product)); - let receipt = resolve_codon_symbol_or_alias(&product.role_symbol).expect("receipt codon"); - assert!(!codon_admitted_in_phase(&receipt, CodonPhase::SourceRna)); - - let err = parse_codon_header("!l64/2\n⟦unknown G# R! · cki_registry⟧\n") - .expect_err("unknown phase should reject"); - assert!(err.contains("unknown codon header phase")); - } - - #[test] - fn phase_admission_matrix_is_the_membrane_law() { - let matrix = phase_admission_matrix(); - assert_eq!(matrix.len(), 8); - for phase in [ - CodonPhase::SourceRna, - CodonPhase::CanonicalRna, - CodonPhase::DnaAuthority, - CodonPhase::Product, - CodonPhase::Projection, - CodonPhase::Receipt, - CodonPhase::ForeignDebug, - CodonPhase::MachineMemo, - ] { - assert!( - matrix.iter().any(|rule| rule.phase == phase), - "missing phase admission rule for {phase:?}" - ); - } - - assert!( - phase_admission_rule(CodonPhase::SourceRna) - .unwrap() - .admits_source_compile - ); - assert!( - phase_admission_rule(CodonPhase::CanonicalRna) - .unwrap() - .admits_source_compile - ); - for phase in [ - CodonPhase::DnaAuthority, - CodonPhase::Product, - CodonPhase::Projection, - CodonPhase::Receipt, - CodonPhase::ForeignDebug, - CodonPhase::MachineMemo, - ] { - assert!( - !phase_admission_rule(phase).unwrap().admits_source_compile, - "{phase:?} must not be source-compilable" - ); - } - assert!( - phase_admission_rule(CodonPhase::MachineMemo) - .unwrap() - .explanation - .contains("never public proof") - ); - } - - #[test] - fn generated_structural_word_ban_detects_old_label_payloads() { - let violations = generated_structural_word_violations( - "artifact_class: claim_page\npayload_json: {}\nview_receipt: R1\n", - ); - assert!(violations.contains(&"CodonBody:artifact_class".to_string())); - assert!(violations.contains(&"CodonBody:claim_page".to_string())); - assert!(violations.contains(&"CodonBody:payload_json".to_string())); - assert!(violations.contains(&"CodonBody:view_receipt".to_string())); - - let clean = generated_structural_word_violations("R!: VIEW_R! <- G#\n"); - assert!(clean.is_empty()); - - let gloss_allowed = generated_structural_word_violations_in_segments(&[ - NativeStructuralSegment { - region: NativeStructuralRegion::CodonBody, - text: "claim_page".into(), - }, - NativeStructuralSegment { - region: NativeStructuralRegion::Gloss, - text: "claim_page human-facing gloss".into(), - }, - ]); - assert_eq!(gloss_allowed, vec!["CodonBody:claim_page".to_string()]); - } - - #[test] - fn molecular_codec_record_serializes_substrate_primitive_deterministically() { - let record = MolecularCodecRecord { - codon_symbol: "<-".into(), - phase: CodonPhase::DnaAuthority, - origin_authority: "GENOME_DNA_1".into(), - subject: "SUBJ".into(), - primitive_kind: SubstratePrimitiveKind::Bond, - primitive: SubstratePrimitive::Bond(SubstrateBond { - id: "B1".into(), - relation_codon: "<-".into(), - left: "A".into(), - right: "B".into(), - }), - }; - - let report = validate_molecular_codec_record(&record); - assert!(report.valid, "{:?}", report.failures); - let first = encode_molecular_codec_record(&record).expect("first encoding"); - let second = encode_molecular_codec_record(&record).expect("second encoding"); - assert_eq!(first, second); - let decoded = decode_molecular_codec_record(&first).expect("decoded record"); - assert_eq!(decoded, record); - } - - #[test] - fn molecular_codec_schema_has_no_generic_payload_bag() { - let kinds = substrate_primitive_kinds(); - assert_eq!(kinds.len(), 8); - assert!(kinds.contains(&SubstratePrimitiveKind::Locus)); - assert!(kinds.contains(&SubstratePrimitiveKind::Atom)); - assert!(kinds.contains(&SubstratePrimitiveKind::Bond)); - assert!(kinds.contains(&SubstratePrimitiveKind::Reaction)); - assert!(kinds.contains(&SubstratePrimitiveKind::Witness)); - assert!(kinds.contains(&SubstratePrimitiveKind::Chassis)); - assert!(kinds.contains(&SubstratePrimitiveKind::Cassette)); - assert!(kinds.contains(&SubstratePrimitiveKind::Plasmid)); - - let fields = molecular_codec_record_field_names(); - assert_eq!( - fields, - vec![ - "codon_symbol", - "phase", - "origin_authority", - "subject", - "primitive_kind", - "primitive" - ] - ); - assert!(!fields.contains(&"family")); - assert!(!fields.contains(&"payload")); - assert!(!fields.contains(&"payload_json")); - } - - #[test] - fn molecular_codec_record_rejects_alias_header_and_kind_mismatch() { - let record = MolecularCodecRecord { - codon_symbol: "depends_on".into(), - phase: CodonPhase::DnaAuthority, - origin_authority: "GENOME_DNA_1".into(), - subject: "SUBJ".into(), - primitive_kind: SubstratePrimitiveKind::Atom, - primitive: SubstratePrimitive::Bond(SubstrateBond { - id: "B1".into(), - relation_codon: "<-".into(), - left: "A".into(), - right: "B".into(), - }), - }; - - let report = validate_molecular_codec_record(&record); - assert!(!report.valid); - assert!( - report - .failures - .iter() - .any(|failure| failure.contains("canonical codon symbol")) - ); - assert!( - report - .failures - .iter() - .any(|failure| failure.contains("primitive kind")) - ); - } - - #[test] - fn molecular_codec_record_rejects_phase_violations() { - let record = MolecularCodecRecord { - codon_symbol: "M#".into(), - phase: CodonPhase::Product, - origin_authority: "GENOME_DNA_1".into(), - subject: "SUBJ".into(), - primitive_kind: SubstratePrimitiveKind::Atom, - primitive: SubstratePrimitive::Atom(SubstrateAtom { - id: "A1".into(), - codon_symbol: "M#".into(), - lexon_symbol: None, - }), - }; - - let report = validate_molecular_codec_record(&record); - assert!(!report.valid); - assert!( - report - .failures - .iter() - .any(|failure| failure.contains("not admitted")) - ); - } - - #[test] - fn molecular_codec_record_rejects_unknown_lexon_binding() { - let record = MolecularCodecRecord { - codon_symbol: "A#".into(), - phase: CodonPhase::DnaAuthority, - origin_authority: "GENOME_DNA_1".into(), - subject: "SUBJ".into(), - primitive_kind: SubstratePrimitiveKind::Atom, - primitive: SubstratePrimitive::Atom(SubstrateAtom { - id: "A1".into(), - codon_symbol: "A#".into(), - lexon_symbol: Some("OLD_THEOREM_KIND".into()), - }), - }; - - let report = validate_molecular_codec_record(&record); - assert!(!report.valid); - assert!( - report - .failures - .iter() - .any(|failure| failure.contains("unknown atom lexon")) - ); - } - - #[test] - fn molecular_codec_record_rejects_authored_witness_truth() { - let record = MolecularCodecRecord { - codon_symbol: "W!".into(), - phase: CodonPhase::Product, - origin_authority: "GENOME_DNA_1".into(), - subject: "SUBJ".into(), - primitive_kind: SubstratePrimitiveKind::Witness, - primitive: SubstratePrimitive::Witness(SubstrateWitness { - id: "WIT_AUTHORED".into(), - subject: "SUBJ".into(), - status_codon: "|-".into(), - dependencies: vec![], - proof_route: vec![], - open_frontier: vec![], - receipt_id: "RCP_AUTHORED".into(), - derived: false, - }), - }; - - let report = validate_molecular_codec_record(&record); - assert!(!report.valid); - assert!( - report - .failures - .iter() - .any(|failure| failure.contains("must be derived")) - ); - } - - #[test] - fn substrate_witnesses_are_derived_not_authored_truth() { - let witness = derive_substrate_witness( - "SUBJ", - vec!["DEP1".into()], - vec!["ROUTE1".into()], - Vec::new(), - "RCP1", - ); - assert!(witness.derived); - assert_eq!(witness.status_codon, "|-"); - assert_eq!(witness.receipt_id, "RCP1"); - assert_eq!(witness.dependencies, vec!["DEP1"]); - } - - #[test] - fn derived_witness_serializes_as_molecular_codec_record() { - let witness = derive_substrate_witness( - "THS_CHAIN_RULE", - vec!["δ_deriv".into(), "δ_comp".into()], - vec!["↻✓".into()], - vec![], - "RCP_CHAIN", - ); - let record = witness_to_molecular_codec_record("GENOME_DNA_1", witness); - - let report = validate_molecular_codec_record(&record); - assert!(report.valid, "{:?}", report.failures); - assert_eq!(record.codon_symbol, "W!"); - assert_eq!(record.phase, CodonPhase::Product); - assert_eq!(record.primitive_kind, SubstratePrimitiveKind::Witness); - - let encoded = encode_molecular_codec_record(&record).expect("witness codec encoding"); - let decoded = decode_molecular_codec_record(&encoded).expect("witness codec decoding"); - assert_eq!(decoded, record); - } - - #[test] - fn molecular_codec_envelope_binds_header_to_record() { - let witness = derive_substrate_witness( - "THS_CHAIN_RULE", - vec!["δ_deriv".into()], - vec!["↻✓".into()], - vec![], - "RCP_CHAIN", - ); - let record = witness_to_molecular_codec_record("GENOME_DNA_1", witness); - let envelope = MolecularCodecEnvelope { - header: CodonHeader { - protocol: "l64".into(), - version: 2, - phase: CodonPhase::Product, - class_symbol: "W!".into(), - role_symbol: "|-".into(), - subject: "THS_CHAIN_RULE".into(), - }, - record, - }; - - let report = validate_molecular_codec_envelope(&envelope); - assert!(report.valid, "{:?}", report.failures); - let encoded = encode_molecular_codec_envelope(&envelope).expect("envelope encoding"); - let decoded = decode_molecular_codec_envelope(&encoded).expect("envelope decoding"); - assert_eq!(decoded, envelope); - } - - #[test] - fn molecular_codec_envelope_rejects_header_record_mismatch() { - let witness = - derive_substrate_witness("THS_CHAIN_RULE", vec![], vec!["↻✓".into()], vec![], "RCP"); - let record = witness_to_molecular_codec_record("GENOME_DNA_1", witness); - let envelope = MolecularCodecEnvelope { - header: CodonHeader { - protocol: "l64".into(), - version: 2, - phase: CodonPhase::Product, - class_symbol: "W!".into(), - role_symbol: "|-".into(), - subject: "WRONG_SUBJECT".into(), - }, - record, - }; - - let report = validate_molecular_codec_envelope(&envelope); - assert!(!report.valid); - assert!( - report - .failures - .iter() - .any(|failure| failure.contains("header subject does not match")) - ); - } - - #[test] - fn lower_chain_emits_ledger_entries_for_each_closed_phase() { - let execution = execute_lower_chain("ι ≔ σ ‖ κ").expect("lower chain"); - assert_eq!(execution.ledger_entries.len(), 4); - assert!( - execution - .ledger_entries - .iter() - .all(|entry| entry.validation_result == PhaseValidationResult::Passed) - ); - assert_eq!(execution.ledger_entries[0].phase_id, PhaseId::Tokenization); - assert_eq!( - execution.ledger_entries[1].phase_id, - PhaseId::RnaNormalization - ); - assert_eq!( - execution.ledger_entries[2].phase_id, - PhaseId::StructuralResolution - ); - assert_eq!( - execution.ledger_entries[3].phase_id, - PhaseId::CanonicalNormalization - ); - assert_eq!( - execution.ledger_entries[1].dependency_edges, - vec![execution.tokenization_receipt.id.clone()] - ); - } - - #[test] - fn lower_chain_halts_and_commits_failed_ledger_entry() { - let failure = execute_lower_chain("iei f g").expect_err("unterminated splice should halt"); - assert_eq!(failure.phase_id, PhaseId::RnaNormalization); - assert_eq!( - failure.ledger_entry.validation_result, - PhaseValidationResult::Failed - ); - assert!(!failure.ledger_entry.failure_records.is_empty()); - } -} diff --git a/l64-core/src/macro_codons.rs b/l64-core/src/macro_codons.rs deleted file mode 100644 index ae1319d..0000000 --- a/l64-core/src/macro_codons.rs +++ /dev/null @@ -1,95 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use crate::{CodonArity, CodonPhase}; - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum MacroCodonClass { - RoundTrip, - Closure, - Receipt, - Integration, - Expression, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct MacroCodonSpec { - pub symbol: String, - pub ascii_aliases: Vec, - pub class: MacroCodonClass, - pub reaction_shape: String, - pub arity: CodonArity, - pub admitted_phases: Vec, - pub witness_requirements: Vec, - pub opcode: u16, -} - -pub fn macro_codon_specs() -> Vec { - use CodonArity::*; - use MacroCodonClass::*; - vec![ - MacroCodonSpec { - symbol: "↻✓".into(), - ascii_aliases: vec!["roundtrip".into(), "roundtrip_fixed_point".into()], - class: RoundTrip, - reaction_shape: "source->dna->canonical-rna->dna fixed point".into(), - arity: Transform, - admitted_phases: vec![CodonPhase::DnaAuthority, CodonPhase::Receipt], - witness_requirements: vec![ - "canonical-id-equality".into(), - "dna-digest-stability".into(), - ], - opcode: 0x1200, - }, - MacroCodonSpec { - symbol: "□∅".into(), - ascii_aliases: vec!["closure_frontier".into()], - class: Closure, - reaction_shape: "closed frontier with explicit empty residual obligation set".into(), - arity: Variadic, - admitted_phases: vec![CodonPhase::Product, CodonPhase::Receipt], - witness_requirements: vec!["frontier-enumeration".into()], - opcode: 0x1201, - }, - MacroCodonSpec { - symbol: "πρ".into(), - ascii_aliases: vec!["view_receipt".into()], - class: Receipt, - reaction_shape: "projection/view receipt from witnessed authority".into(), - arity: Binary, - admitted_phases: vec![CodonPhase::Product, CodonPhase::Receipt], - witness_requirements: vec!["origin-dna".into(), "projection-boundary".into()], - opcode: 0x1202, - }, - MacroCodonSpec { - symbol: "⊕ρ".into(), - ascii_aliases: vec!["integration_receipt".into()], - class: Integration, - reaction_shape: "plasmid/cassette integration receipt".into(), - arity: Transform, - admitted_phases: vec![CodonPhase::DnaAuthority, CodonPhase::Receipt], - witness_requirements: vec!["pre-state".into(), "post-state".into(), "lineage".into()], - opcode: 0x1203, - }, - MacroCodonSpec { - symbol: "⇓ρ".into(), - ascii_aliases: vec!["expression_receipt".into()], - class: Expression, - reaction_shape: "witnessed authority expresses product set".into(), - arity: Transform, - admitted_phases: vec![CodonPhase::Product, CodonPhase::Receipt], - witness_requirements: vec!["origin-dna".into(), "witness-form".into()], - opcode: 0x1204, - }, - ] -} - -pub fn resolve_macro_codon_symbol_or_alias(value: &str) -> Option { - let normalized = value.trim().to_ascii_lowercase(); - macro_codon_specs().into_iter().find(|macro_codon| { - macro_codon.symbol == value - || macro_codon - .ascii_aliases - .iter() - .any(|alias| alias.eq_ignore_ascii_case(&normalized)) - }) -} diff --git a/l64-core/src/molecular.rs b/l64-core/src/molecular.rs deleted file mode 100644 index b192fec..0000000 --- a/l64-core/src/molecular.rs +++ /dev/null @@ -1,344 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use crate::{ - CodonHeader, CodonPhase, DigestRole, SubstrateWitness, codon_admitted_in_phase, - phase_admission_rule, resolve_codon_symbol_or_alias, resolve_lexon_symbol_or_alias, - role_digest_value, -}; - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub enum SubstratePrimitiveKind { - Locus, - Atom, - Bond, - Reaction, - Witness, - Chassis, - Cassette, - Plasmid, -} - -pub fn substrate_primitive_kinds() -> Vec { - vec![ - SubstratePrimitiveKind::Locus, - SubstratePrimitiveKind::Atom, - SubstratePrimitiveKind::Bond, - SubstratePrimitiveKind::Reaction, - SubstratePrimitiveKind::Witness, - SubstratePrimitiveKind::Chassis, - SubstratePrimitiveKind::Cassette, - SubstratePrimitiveKind::Plasmid, - ] -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SubstrateLocus { - pub id: String, - pub subject: String, - pub chassis_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SubstrateAtom { - pub id: String, - pub codon_symbol: String, - pub lexon_symbol: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SubstrateBond { - pub id: String, - pub relation_codon: String, - pub left: String, - pub right: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SubstrateReaction { - pub id: String, - pub process_codon: String, - pub inputs: Vec, - pub outputs: Vec, - pub receipt_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SubstrateChassis { - pub id: String, - pub policy_codons: Vec, - pub admitted_phases: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SubstrateCassette { - pub id: String, - pub locus_ids: Vec, - pub reaction_ids: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SubstratePlasmid { - pub id: String, - pub cassette_ids: Vec, - pub integration_reaction: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum SubstratePrimitive { - Locus(SubstrateLocus), - Atom(SubstrateAtom), - Bond(SubstrateBond), - Reaction(SubstrateReaction), - Witness(SubstrateWitness), - Chassis(SubstrateChassis), - Cassette(SubstrateCassette), - Plasmid(SubstratePlasmid), -} - -impl SubstratePrimitive { - pub fn kind(&self) -> SubstratePrimitiveKind { - match self { - SubstratePrimitive::Locus(_) => SubstratePrimitiveKind::Locus, - SubstratePrimitive::Atom(_) => SubstratePrimitiveKind::Atom, - SubstratePrimitive::Bond(_) => SubstratePrimitiveKind::Bond, - SubstratePrimitive::Reaction(_) => SubstratePrimitiveKind::Reaction, - SubstratePrimitive::Witness(_) => SubstratePrimitiveKind::Witness, - SubstratePrimitive::Chassis(_) => SubstratePrimitiveKind::Chassis, - SubstratePrimitive::Cassette(_) => SubstratePrimitiveKind::Cassette, - SubstratePrimitive::Plasmid(_) => SubstratePrimitiveKind::Plasmid, - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct MolecularCodecRecord { - pub codon_symbol: String, - pub phase: CodonPhase, - pub origin_authority: String, - pub subject: String, - pub primitive_kind: SubstratePrimitiveKind, - pub primitive: SubstratePrimitive, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct MolecularCodecEnvelope { - pub header: CodonHeader, - pub record: MolecularCodecRecord, -} - -pub fn molecular_codec_record_field_names() -> Vec<&'static str> { - vec![ - "codon_symbol", - "phase", - "origin_authority", - "subject", - "primitive_kind", - "primitive", - ] -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct MolecularCodecValidationReport { - pub valid: bool, - pub codec_digest: String, - pub failures: Vec, -} - -pub type MolecularCodecEnvelopeValidationReport = MolecularCodecValidationReport; - -pub fn validate_molecular_codec_record( - record: &MolecularCodecRecord, -) -> MolecularCodecValidationReport { - let mut failures = Vec::new(); - match resolve_codon_symbol_or_alias(&record.codon_symbol) { - Some(codon) => { - if codon.symbol != record.codon_symbol { - failures.push("codec record must use canonical codon symbol".into()); - } - if !codon_admitted_in_phase(&codon, record.phase) { - failures.push(format!( - "codon {} not admitted in phase {:?}", - record.codon_symbol, record.phase - )); - } - } - None => failures.push(format!("unknown codon {}", record.codon_symbol)), - } - if phase_admission_rule(record.phase).is_none() { - failures.push(format!( - "missing phase admission rule for {:?}", - record.phase - )); - } - if record.primitive.kind() != record.primitive_kind { - failures.push("primitive kind does not match primitive variant".into()); - } - validate_primitive_codons(record, &mut failures); - if record.origin_authority.trim().is_empty() { - failures.push("missing origin authority".into()); - } - if record.subject.trim().is_empty() { - failures.push("missing subject".into()); - } - - MolecularCodecValidationReport { - valid: failures.is_empty(), - codec_digest: role_digest_value(DigestRole::CodecDigest, record), - failures, - } -} - -fn validate_primitive_codons(record: &MolecularCodecRecord, failures: &mut Vec) { - match &record.primitive { - SubstratePrimitive::Atom(atom) => { - if atom.codon_symbol != record.codon_symbol { - failures.push("atom codon does not match record codon".into()); - } - if let Some(lexon) = &atom.lexon_symbol { - if resolve_lexon_symbol_or_alias(lexon).is_none() { - failures.push(format!("unknown atom lexon {lexon}")); - } - } - } - SubstratePrimitive::Bond(bond) => { - if resolve_codon_symbol_or_alias(&bond.relation_codon) - .map(|codon| codon.symbol != bond.relation_codon) - .unwrap_or(true) - { - failures.push(format!( - "bond relation codon {} is not canonical", - bond.relation_codon - )); - } - } - SubstratePrimitive::Reaction(reaction) => { - if resolve_codon_symbol_or_alias(&reaction.process_codon) - .map(|codon| codon.symbol != reaction.process_codon) - .unwrap_or(true) - { - failures.push(format!( - "reaction process codon {} is not canonical", - reaction.process_codon - )); - } - } - SubstratePrimitive::Witness(witness) => { - if !witness.derived { - failures.push("witness primitive must be derived, not authored truth".into()); - } - if resolve_codon_symbol_or_alias(&witness.status_codon).is_none() { - failures.push(format!( - "unknown witness status codon {}", - witness.status_codon - )); - } - } - SubstratePrimitive::Chassis(chassis) => { - for codon in &chassis.policy_codons { - if resolve_codon_symbol_or_alias(codon) - .map(|resolved| resolved.symbol != *codon) - .unwrap_or(true) - { - failures.push(format!("chassis policy codon {codon} is not canonical")); - } - } - } - SubstratePrimitive::Locus(_) - | SubstratePrimitive::Cassette(_) - | SubstratePrimitive::Plasmid(_) => {} - } -} - -pub fn validate_molecular_codec_envelope( - envelope: &MolecularCodecEnvelope, -) -> MolecularCodecEnvelopeValidationReport { - let mut failures = validate_molecular_codec_record(&envelope.record).failures; - let header = &envelope.header; - - if header.phase != envelope.record.phase { - failures.push("codec envelope header phase does not match record phase".into()); - } - if header.subject != envelope.record.subject { - failures.push("codec envelope header subject does not match record subject".into()); - } - validate_header_codon("class", &header.class_symbol, header.phase, &mut failures); - validate_header_codon("role", &header.role_symbol, header.phase, &mut failures); - - MolecularCodecEnvelopeValidationReport { - valid: failures.is_empty(), - codec_digest: role_digest_value(DigestRole::CodecDigest, envelope), - failures, - } -} - -fn validate_header_codon(label: &str, symbol: &str, phase: CodonPhase, failures: &mut Vec) { - match resolve_codon_symbol_or_alias(symbol) { - Some(codon) => { - if codon.symbol != symbol { - failures.push(format!( - "codec envelope header {label} codon must be canonical" - )); - } - if !codon_admitted_in_phase(&codon, phase) { - failures.push(format!( - "codec envelope header {label} codon {symbol} not admitted in phase {phase:?}" - )); - } - } - None => failures.push(format!( - "unknown codec envelope header {label} codon {symbol}" - )), - } -} - -pub fn encode_molecular_codec_record(record: &MolecularCodecRecord) -> Result, String> { - let report = validate_molecular_codec_record(record); - if !report.valid { - return Err(report.failures.join("; ")); - } - bincode::serialize(record).map_err(|err| err.to_string()) -} - -pub fn decode_molecular_codec_record(bytes: &[u8]) -> Result { - let record: MolecularCodecRecord = - bincode::deserialize(bytes).map_err(|err| err.to_string())?; - let report = validate_molecular_codec_record(&record); - if !report.valid { - return Err(report.failures.join("; ")); - } - Ok(record) -} - -pub fn encode_molecular_codec_envelope( - envelope: &MolecularCodecEnvelope, -) -> Result, String> { - let report = validate_molecular_codec_envelope(envelope); - if !report.valid { - return Err(report.failures.join("; ")); - } - bincode::serialize(envelope).map_err(|err| err.to_string()) -} - -pub fn decode_molecular_codec_envelope(bytes: &[u8]) -> Result { - let envelope: MolecularCodecEnvelope = - bincode::deserialize(bytes).map_err(|err| err.to_string())?; - let report = validate_molecular_codec_envelope(&envelope); - if !report.valid { - return Err(report.failures.join("; ")); - } - Ok(envelope) -} - -pub fn witness_to_molecular_codec_record( - origin_authority: &str, - witness: SubstrateWitness, -) -> MolecularCodecRecord { - MolecularCodecRecord { - codon_symbol: "W!".into(), - phase: CodonPhase::Product, - origin_authority: origin_authority.into(), - subject: witness.subject.clone(), - primitive_kind: SubstratePrimitiveKind::Witness, - primitive: SubstratePrimitive::Witness(witness), - } -} diff --git a/l64-core/src/witness.rs b/l64-core/src/witness.rs deleted file mode 100644 index fcc94f6..0000000 --- a/l64-core/src/witness.rs +++ /dev/null @@ -1,35 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use crate::{DigestRole, role_digest_str}; - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct SubstrateWitness { - pub id: String, - pub subject: String, - pub status_codon: String, - pub dependencies: Vec, - pub proof_route: Vec, - pub open_frontier: Vec, - pub receipt_id: String, - pub derived: bool, -} - -pub fn derive_substrate_witness( - subject: &str, - dependencies: Vec, - proof_route: Vec, - open_frontier: Vec, - receipt_id: &str, -) -> SubstrateWitness { - let digest = role_digest_str(DigestRole::WitnessId, &format!("{subject}:{receipt_id}")); - SubstrateWitness { - id: format!("WIT_{}", digest.value), - subject: subject.into(), - status_codon: "|-".into(), - dependencies, - proof_route, - open_frontier, - receipt_id: receipt_id.into(), - derived: true, - } -} diff --git a/l64-execution/Cargo.toml b/l64-execution/Cargo.toml new file mode 100644 index 0000000..6ec2c29 --- /dev/null +++ b/l64-execution/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "l64-execution" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +l64-native = { path = "../l64-native" } +l64-projection = { path = "../l64-projection" } +l64-certification = { path = "../l64-certification" } diff --git a/l64-execution/README.md b/l64-execution/README.md new file mode 100644 index 0000000..18578a6 --- /dev/null +++ b/l64-execution/README.md @@ -0,0 +1,5 @@ +# l64-execution + +Direct, non-persistent execution of current native authority. + +`execute_rna` compiles canonical `L64R1` transiently. `execute_dna` validates exact canonical `L64D`. Both derive and verify the root projection and certify every native context. Execution does not mutate authority, create reports, or persist run records. diff --git a/l64-execution/src/lib.rs b/l64-execution/src/lib.rs new file mode 100644 index 0000000..fe2331f --- /dev/null +++ b/l64-execution/src/lib.rs @@ -0,0 +1,197 @@ +#![forbid(unsafe_code)] + +use l64_certification::{ + AuthorityCertification, CertificationError, certify_graph_with_root_projection, +}; +use l64_native::{ + DnaError, Graph, RnaError, StateSymbol, compile_rna, decode_dna, dna_bytes, rna_bytes, +}; +use l64_projection::{ProjectionError, ProjectionSet}; +use std::fmt::{self, Write as _}; + +pub const EXECUTION_VERSION: u16 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExecutionSource { + Rna, + Dna, + BundleMember, +} + +impl ExecutionSource { + pub const fn as_str(self) -> &'static str { + match self { + Self::Rna => "rna", + Self::Dna => "dna", + Self::BundleMember => "bundle_member", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorityExecution { + pub source: ExecutionSource, + pub canonical_roundtrip: bool, + pub projection_verified: bool, + pub symbol: StateSymbol, + pub node_count: usize, + pub port_count: usize, + pub context_count: usize, + pub journal_len: usize, + pub projection: ProjectionSet, + pub certification: AuthorityCertification, +} + +impl AuthorityExecution { + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE EXECUTION v{EXECUTION_VERSION}"); + self.render_into(&mut out, ""); + out + } + + pub fn render_into(&self, out: &mut String, prefix: &str) { + let _ = writeln!(out, "{prefix}source={}", self.source.as_str()); + let _ = writeln!(out, "{prefix}mode=structural_authority_evaluation"); + let _ = writeln!(out, "{prefix}authority=exact_canonical_l64d"); + let _ = writeln!(out, "{prefix}authority_mutation=none"); + let _ = writeln!( + out, + "{prefix}canonical_roundtrip={}", + self.canonical_roundtrip + ); + let _ = writeln!(out, "{prefix}projection_authority=non_authoritative"); + let _ = writeln!( + out, + "{prefix}projection_verified={}", + self.projection_verified + ); + let _ = writeln!( + out, + "{prefix}certification_verdict={}", + self.certification.verdict + ); + let _ = writeln!(out, "{prefix}symbol={}", self.symbol); + let _ = writeln!(out, "{prefix}nodes={}", self.node_count); + let _ = writeln!(out, "{prefix}ports={}", self.port_count); + let _ = writeln!(out, "{prefix}contexts={}", self.context_count); + let _ = writeln!(out, "{prefix}journal={}", self.journal_len); + let _ = writeln!(out, "{prefix}root.closed={}", self.projection.report.closed); + let _ = writeln!(out, "{prefix}root.open={}", self.projection.report.open); + let _ = writeln!( + out, + "{prefix}root.invalid={}", + self.projection.report.invalid + ); + let _ = writeln!( + out, + "{prefix}root.research_candidates={}/{}", + self.projection.research.candidates.len(), + self.projection.research.total_candidates + ); + for context in &self.certification.contexts { + let _ = writeln!( + out, + "{prefix}context.{}.verdict={}", + context.context, context.verdict + ); + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ExecutionError { + Rna(RnaError), + Dna(DnaError), + NonCanonicalDna, + RoundtripMismatch, + Projection(ProjectionError), + Certification(CertificationError), +} + +impl ExecutionError { + pub const fn rna_error(&self) -> Option { + match self { + Self::Rna(error) => Some(*error), + _ => None, + } + } +} + +impl fmt::Display for ExecutionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Rna(error) => write!(f, "RNA execution failed: {error}"), + Self::Dna(error) => write!(f, "DNA execution failed: {error}"), + Self::NonCanonicalDna => f.write_str("execution requires canonical L64D authority"), + Self::RoundtripMismatch => f.write_str("RNA/DNA exact roundtrip mismatch"), + Self::Projection(error) => write!(f, "execution projection failed: {error}"), + Self::Certification(error) => write!(f, "execution certification failed: {error}"), + } + } +} + +impl std::error::Error for ExecutionError {} + +pub fn execute_rna(source: &[u8]) -> Result { + let graph = compile_rna(source).map_err(ExecutionError::Rna)?; + let canonical_rna = rna_bytes(&graph).map_err(ExecutionError::Rna)?; + let canonical_dna = dna_bytes(&graph).map_err(ExecutionError::Dna)?; + let rebuilt_graph = compile_rna(&canonical_rna).map_err(ExecutionError::Rna)?; + let rebuilt_dna = dna_bytes(&rebuilt_graph).map_err(ExecutionError::Dna)?; + if rebuilt_dna != canonical_dna { + return Err(ExecutionError::RoundtripMismatch); + } + execute_graph(&graph, ExecutionSource::Rna, true) +} + +pub fn execute_dna(bytes: &[u8]) -> Result { + let graph = decode_dna(bytes).map_err(ExecutionError::Dna)?; + let canonical_dna = dna_bytes(&graph).map_err(ExecutionError::Dna)?; + if canonical_dna != bytes { + return Err(ExecutionError::NonCanonicalDna); + } + let canonical_rna = rna_bytes(&graph).map_err(ExecutionError::Rna)?; + let rebuilt_graph = compile_rna(&canonical_rna).map_err(ExecutionError::Rna)?; + let rebuilt_dna = dna_bytes(&rebuilt_graph).map_err(ExecutionError::Dna)?; + if rebuilt_dna != bytes { + return Err(ExecutionError::RoundtripMismatch); + } + execute_graph(&graph, ExecutionSource::Dna, true) +} + +pub fn execute_canonical_graph( + graph: &Graph, + source: ExecutionSource, +) -> Result { + let dna = dna_bytes(graph).map_err(ExecutionError::Dna)?; + let decoded = decode_dna(&dna).map_err(ExecutionError::Dna)?; + let rebuilt = dna_bytes(&decoded).map_err(ExecutionError::Dna)?; + if rebuilt != dna { + return Err(ExecutionError::RoundtripMismatch); + } + execute_graph(graph, source, true) +} + +fn execute_graph( + graph: &Graph, + source: ExecutionSource, + canonical_roundtrip: bool, +) -> Result { + // Certification owns the shared fresh root derivation. Retained or externally supplied + // projections still cross `ProjectionSet::verify` before reuse. + let (certification, projection) = + certify_graph_with_root_projection(graph, 16).map_err(ExecutionError::Certification)?; + Ok(AuthorityExecution { + source, + canonical_roundtrip, + projection_verified: true, + symbol: graph.state_symbol(), + node_count: graph.node_count(), + port_count: graph.port_count(), + context_count: graph.context_count(), + journal_len: graph.journal_len(), + projection, + certification, + }) +} diff --git a/l64-execution/tests/architecture.rs b/l64-execution/tests/architecture.rs new file mode 100644 index 0000000..ef0d9d6 --- /dev/null +++ b/l64-execution/tests/architecture.rs @@ -0,0 +1,38 @@ +use std::{fs, path::Path}; + +#[test] +fn execution_is_dependency_minimal_and_nonpersistent() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap(); + for dependency in ["l64-native", "l64-projection", "l64-certification"] { + assert!(manifest.contains(dependency)); + } + for forbidden in [ + "serde", + "bincode", + "blake3", + "l64-transport", + "l64-observation", + "l64-change", + ] { + assert!( + !manifest.contains(forbidden), + "forbidden dependency {forbidden}" + ); + } + let source = fs::read_to_string(root.join("src/lib.rs")).unwrap(); + for forbidden in [ + "std::fs", + "File::", + "create_dir", + "write(", + "cache", + "registry", + "campaign", + ] { + assert!( + !source.contains(forbidden), + "forbidden execution surface {forbidden}" + ); + } +} diff --git a/l64-execution/tests/execution.rs b/l64-execution/tests/execution.rs new file mode 100644 index 0000000..d302d28 --- /dev/null +++ b/l64-execution/tests/execution.rs @@ -0,0 +1,63 @@ +use l64_certification::CertificationVerdict; +use l64_execution::{ + ExecutionError, ExecutionSource, execute_canonical_graph, execute_dna, execute_rna, +}; +use l64_native::{ + Dimension, Graph, LocusWord, Proposal, ROOT_CONTEXT, Route, dna_bytes, rna_to_dna, +}; + +const TRIANGLE: &[u8] = b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n"; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x4558454355544531)).composed(LocusWord(index)) +} + +#[test] +fn rna_and_dna_run_through_the_same_structural_carrier() { + let dna = rna_to_dna(TRIANGLE).unwrap(); + let from_rna = execute_rna(TRIANGLE).unwrap(); + let from_dna = execute_dna(&dna).unwrap(); + assert_eq!(from_rna.source, ExecutionSource::Rna); + assert_eq!(from_dna.source, ExecutionSource::Dna); + assert_eq!(from_rna.symbol, from_dna.symbol); + assert_eq!(from_rna.projection, from_dna.projection); + assert_eq!(from_rna.certification, from_dna.certification); + assert_eq!( + from_rna.certification.verdict, + CertificationVerdict::Certified + ); + assert!(from_rna.canonical_roundtrip); + assert!(from_rna.projection_verified); +} + +#[test] +fn execution_reports_open_structure_without_creating_a_campaign() { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let quantity = graph + .declare_quantity_type(route(2), scalar, Dimension::new([0; 7])) + .unwrap(); + let value = graph + .insert_value(route(3), ROOT_CONTEXT, quantity) + .unwrap(); + graph + .transact(Proposal::square_root( + route(4), + ROOT_CONTEXT, + value, + quantity, + )) + .unwrap(); + let execution = execute_canonical_graph(&graph, ExecutionSource::BundleMember).unwrap(); + assert_eq!(execution.certification.verdict, CertificationVerdict::Open); + assert!(execution.projection.report.open > 0); + assert!(execution.render_text().contains("authority_mutation=none")); +} + +#[test] +fn noncanonical_or_trailing_dna_is_rejected() { + let mut dna = + dna_bytes(&l64_native::decode_dna(&rna_to_dna(TRIANGLE).unwrap()).unwrap()).unwrap(); + dna.push(0); + assert!(matches!(execute_dna(&dna), Err(ExecutionError::Dna(_)))); +} diff --git a/l64-kernel/.gitignore b/l64-kernel/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/l64-kernel/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/l64-kernel/Cargo.toml b/l64-kernel/Cargo.toml deleted file mode 100644 index 4a390da..0000000 --- a/l64-kernel/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "l64-kernel" -version = "0.1.0" -edition = "2024" - -[dependencies] -l64-core = { path = "../l64-core" } -thiserror = { workspace = true } - -[dev-dependencies] -l64-testkit = { path = "../l64-testkit" } -serde = { workspace = true } diff --git a/l64-kernel/src/lib.rs b/l64-kernel/src/lib.rs deleted file mode 100644 index cd9e7eb..0000000 --- a/l64-kernel/src/lib.rs +++ /dev/null @@ -1,792 +0,0 @@ -use l64_core::{ - Budget, Canonicalize, CheckProofShape, ComposeBridge, EvidenceMaturity, GateVerdict, Judgment, - ObligationEvaluationMode, ObligationStatus, Promote, ProofShape, ProofShapeKind, QcObject, - RegistryLookup, ValidateJudgment, -}; -use thiserror::Error; - -#[derive(Debug, Error, PartialEq, Eq)] -pub enum KernelError { - #[error("{0}")] - Message(String), -} - -#[derive(Debug, Default)] -pub struct ConstitutionKernel; - -impl ConstitutionKernel { - pub fn validate_object( - &self, - object: &QcObject, - registry: &dyn RegistryLookup, - ) -> Result<(), KernelError> { - if object.identity.cid.trim().is_empty() { - return Err(KernelError::Message("QC-0 identity cid is empty".into())); - } - if object.structural.head.trim().is_empty() { - return Err(KernelError::Message("QC-0 structural head is empty".into())); - } - if object.constraint.regime.trim().is_empty() { - return Err(KernelError::Message( - "QC-0 constraint regime is empty".into(), - )); - } - if registry.get_regime(&object.constraint.regime).is_none() { - return Err(KernelError::Message(format!( - "unknown regime `{}`", - object.constraint.regime - ))); - } - if object.constraint.equivalence.trim().is_empty() { - return Err(KernelError::Message("QC-0 equivalence is empty".into())); - } - if object.evidence.gate_verdict == GateVerdict::Fail { - return Err(KernelError::Message( - "evidence gate is failing and object cannot validate".into(), - )); - } - if object.alias.qa_binding.trim().is_empty() { - return Err(KernelError::Message("QA-0 binding is empty".into())); - } - Ok(()) - } - - pub fn validate_regime(&self, regime: &l64_core::RegimePack) -> Result<(), KernelError> { - let required = [ - regime.ctx_law.as_str(), - regime.cut_law.as_str(), - regime.thr_law.as_str(), - regime.brc_law.as_str(), - regime.slk_law.as_str(), - regime.tol_law.as_str(), - regime.knt_law.as_str(), - regime.eq_law.as_str(), - regime.adm_law.as_str(), - ]; - if required.iter().any(|value| value.trim().is_empty()) { - return Err(KernelError::Message(format!( - "regime `{}` is missing at least one law slot", - regime.id - ))); - } - Ok(()) - } - - pub fn validate_bridge( - &self, - bridge: &l64_core::BridgeContract, - registry: &dyn RegistryLookup, - ) -> Result<(), KernelError> { - if registry.get_regime(&bridge.src).is_none() || registry.get_regime(&bridge.tgt).is_none() - { - return Err(KernelError::Message(format!( - "bridge `{}` references an unknown regime", - bridge.id - ))); - } - if bridge.id_pres.trim().is_empty() || bridge.eq_pres.trim().is_empty() { - return Err(KernelError::Message(format!( - "bridge `{}` is missing preservation clauses", - bridge.id - ))); - } - if bridge.reversibility == l64_core::ReversibilityClass::Invalid { - return Err(KernelError::Message(format!( - "bridge `{}` is constitutionally invalid", - bridge.id - ))); - } - Ok(()) - } - - pub fn validate_theorem_spec( - &self, - theorem: &l64_core::TheoremSpec, - registry: &dyn RegistryLookup, - ) -> Result<(), KernelError> { - if theorem.statement.trim().is_empty() { - return Err(KernelError::Message(format!( - "theorem `{}` is missing a statement", - theorem.id - ))); - } - if theorem.hosts.is_empty() { - return Err(KernelError::Message(format!( - "theorem `{}` has no host regimes", - theorem.id - ))); - } - if theorem - .hosts - .iter() - .any(|host| registry.get_regime(host).is_none()) - { - return Err(KernelError::Message(format!( - "theorem `{}` references an unknown host regime", - theorem.id - ))); - } - if theorem.obligations.is_empty() { - return Err(KernelError::Message(format!( - "theorem `{}` has no obligation inventory", - theorem.id - ))); - } - if theorem - .proof_shapes - .iter() - .any(|shape| registry.get_proof_shape(shape).is_none()) - { - return Err(KernelError::Message(format!( - "theorem `{}` references an unknown proof shape", - theorem.id - ))); - } - Ok(()) - } - - pub fn validate_target_profile( - &self, - target: &l64_core::TargetProfile, - ) -> Result<(), KernelError> { - if target.host_cluster.is_empty() { - return Err(KernelError::Message(format!( - "target profile `{}` has an empty host cluster", - target.id - ))); - } - if target.target_equivalence.trim().is_empty() { - return Err(KernelError::Message(format!( - "target profile `{}` is missing target equivalence", - target.id - ))); - } - if target.surface_requirement.is_some() || target.preferred_surface_target.is_some() { - return Err(KernelError::Message(format!( - "target profile `{}` uses deprecated surface-schema authority fields", - target.id - ))); - } - Ok(()) - } - - pub fn validate_route_ledger( - &self, - ledger: &l64_core::RouteLedger, - registry: &dyn RegistryLookup, - ) -> Result<(), KernelError> { - if registry.get_theorem_spec(&ledger.theorem).is_none() { - return Err(KernelError::Message(format!( - "route ledger `{}` references unknown theorem `{}`", - ledger.id, ledger.theorem - ))); - } - let bridges = ledger - .normalized_path - .iter() - .map(|id| { - registry.get_bridge(id).ok_or_else(|| { - KernelError::Message(format!( - "route ledger `{}` references unknown bridge `{id}`", - ledger.id - )) - }) - }) - .collect::, _>>()?; - self.compose_bridge_path(&bridges, Some(&ledger.budget)) - .map_err(KernelError::Message) - } - - pub fn validate_certificate( - &self, - certificate: &l64_core::Certificate, - registry: &dyn RegistryLookup, - ) -> Result<(), KernelError> { - if registry.get_theorem_spec(&certificate.theorem).is_none() { - return Err(KernelError::Message(format!( - "certificate `{}` references unknown theorem", - certificate.id - ))); - } - if registry - .get_route_ledger(&certificate.route_ledger) - .is_none() - { - return Err(KernelError::Message(format!( - "certificate `{}` references unknown route ledger", - certificate.id - ))); - } - if certificate.receipts.is_empty() { - return Err(KernelError::Message(format!( - "certificate `{}` has no receipts", - certificate.id - ))); - } - Ok(()) - } - - pub fn validate_campaign( - &self, - campaign: &l64_core::Campaign, - registry: &dyn RegistryLookup, - ) -> Result<(), KernelError> { - if registry.get_theorem_spec(&campaign.theorem).is_none() { - return Err(KernelError::Message(format!( - "campaign `{}` references unknown theorem", - campaign.id - ))); - } - if registry - .get_target_profile(&campaign.target_profile) - .is_none() - { - return Err(KernelError::Message(format!( - "campaign `{}` references unknown target profile", - campaign.id - ))); - } - if registry.get_route_ledger(&campaign.route_ledger).is_none() { - return Err(KernelError::Message(format!( - "campaign `{}` references unknown route ledger", - campaign.id - ))); - } - for obligation in &campaign.obligations { - if registry.get_obligation(obligation).is_none() { - return Err(KernelError::Message(format!( - "campaign `{}` references unknown obligation `{obligation}`", - campaign.id - ))); - } - } - Ok(()) - } - - pub fn validate_adequacy_clause( - &self, - clause: &l64_core::AdequacyClause, - registry: &dyn RegistryLookup, - ) -> Result<(), KernelError> { - if clause.description.trim().is_empty() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` is missing a description", - clause.id - ))); - } - if clause.regime_ids.is_empty() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` has no regime scope", - clause.id - ))); - } - for regime in &clause.regime_ids { - if registry.get_regime(regime).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown regime `{}`", - clause.id, regime - ))); - } - } - for theorem_id in &clause.theorem_ids { - if registry.get_theorem_spec(theorem_id).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown theorem `{}`", - clause.id, theorem_id - ))); - } - } - for bridge_id in &clause.bridge_ids { - if registry.get_bridge(bridge_id).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown bridge `{}`", - clause.id, bridge_id - ))); - } - } - for burden_pack_id in &clause.burden_pack_ids { - if registry.get_burden_pack(burden_pack_id).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown burden pack `{}`", - clause.id, burden_pack_id - ))); - } - } - for claim_packet_id in &clause.claim_packet_ids { - if registry.get_claim_packet(claim_packet_id).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown claim packet `{}`", - clause.id, claim_packet_id - ))); - } - } - for contract_id in &clause.evidence_contract_ids { - if registry.get_evidence_contract(contract_id).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown evidence contract `{}`", - clause.id, contract_id - ))); - } - } - for receipt_id in &clause.benchmark_receipt_ids { - if registry.get_benchmark_receipt(receipt_id).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown benchmark receipt `{}`", - clause.id, receipt_id - ))); - } - } - for receipt_id in &clause.challenge_receipt_ids { - if registry.get_challenge_receipt(receipt_id).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown challenge receipt `{}`", - clause.id, receipt_id - ))); - } - } - for packet_id in &clause.reproducibility_packet_ids { - if registry.get_reproducibility_packet(packet_id).is_none() { - return Err(KernelError::Message(format!( - "adequacy clause `{}` references unknown reproducibility packet `{}`", - clause.id, packet_id - ))); - } - } - if matches!(clause.kind, l64_core::AdequacyClauseKind::BridgeSoundness) - && clause.bridge_ids.is_empty() - { - return Err(KernelError::Message(format!( - "bridge soundness adequacy clause `{}` has no bridge scope", - clause.id - ))); - } - if matches!( - clause.kind, - l64_core::AdequacyClauseKind::EvidenceContractInterpretation - | l64_core::AdequacyClauseKind::BenchmarkInterpretation - | l64_core::AdequacyClauseKind::StressInterpretation - | l64_core::AdequacyClauseKind::ChallengeInterpretation - ) && clause.claim_packet_ids.is_empty() - { - return Err(KernelError::Message(format!( - "evidence adequacy clause `{}` has no claim packet scope", - clause.id - ))); - } - Ok(()) - } - - pub fn validate_obligation_status(&self, status: &ObligationStatus) -> Result<(), KernelError> { - if status.obligation_id.trim().is_empty() { - return Err(KernelError::Message( - "obligation status is missing an obligation id".into(), - )); - } - if status.detail.trim().is_empty() { - return Err(KernelError::Message(format!( - "obligation `{}` is missing explanatory detail", - status.obligation_id - ))); - } - let has_residual = status.receipts.iter().any(receipt_has_residual); - match status.evaluation_mode { - ObligationEvaluationMode::RecomputedExact => { - if status.verdict != l64_core::CertificationVerdict::Certified { - return Err(KernelError::Message(format!( - "obligation `{}` claims exact recomputation without certification", - status.obligation_id - ))); - } - if has_residual { - return Err(KernelError::Message(format!( - "obligation `{}` claims exact recomputation but still carries residual receipts", - status.obligation_id - ))); - } - } - ObligationEvaluationMode::RecomputedPartial => { - if !has_residual { - return Err(KernelError::Message(format!( - "obligation `{}` claims partial recomputation without a residual receipt", - status.obligation_id - ))); - } - } - _ => {} - } - Ok(()) - } -} - -fn receipt_has_residual(receipt: &l64_core::ObligationEvidenceReceipt) -> bool { - if receipt.subreceipts.is_empty() { - return !receipt.computed || receipt.verdict != l64_core::CertificationVerdict::Certified; - } - receipt.subreceipts.iter().any(receipt_has_residual) -} - -impl Canonicalize for ConstitutionKernel { - fn canonicalize_object( - &self, - object: &QcObject, - registry: &dyn RegistryLookup, - ) -> Result { - self.validate_object(object, registry) - .map_err(|err| err.to_string())?; - if let Some(class) = registry.find_equivalence_class(&object.id, &object.constraint.regime) - { - return registry - .get_object(&class.canonical_id) - .ok_or_else(|| format!("missing canonical object `{}`", class.canonical_id)); - } - Ok(object.clone()) - } -} - -impl Promote for ConstitutionKernel { - fn promote(&self, object: &QcObject, registry: &dyn RegistryLookup) -> Result<(), String> { - self.canonicalize_object(object, registry)?; - match object.evidence.maturity { - EvidenceMaturity::Validated | EvidenceMaturity::Certified => {} - _ => return Err("promotion requires validated or certified maturity".into()), - } - if object.evidence.gate_verdict != GateVerdict::Pass { - return Err("promotion requires a passing evidence gate".into()); - } - Ok(()) - } -} - -impl ValidateJudgment for ConstitutionKernel { - fn validate_judgment( - &self, - judgment: &Judgment, - registry: &dyn RegistryLookup, - ) -> Result<(), String> { - match judgment { - Judgment::Ctx { object } - | Judgment::Cut { object } - | Judgment::Thr { object } - | Judgment::Brc { object } - | Judgment::Knt { object } - | Judgment::Wit { object } - | Judgment::Prm { object } => { - let object = registry - .get_object(object) - .ok_or_else(|| format!("missing object `{object}`"))?; - self.validate_object(&object, registry) - .map_err(|err| err.to_string()) - } - Judgment::Slk { left, right, .. } => { - if registry.get_object(left).is_none() || registry.get_object(right).is_none() { - return Err("slack judgment references unknown object".into()); - } - Ok(()) - } - Judgment::Tol { object, .. } => { - if registry.get_object(object).is_none() { - return Err("toll judgment references unknown object".into()); - } - Ok(()) - } - Judgment::Can { object, canonical } => { - let object = registry - .get_object(object) - .ok_or_else(|| format!("missing object `{object}`"))?; - let actual = self.canonicalize_object(&object, registry)?; - if &actual.id != canonical { - return Err(format!( - "canonicalization mismatch: expected `{canonical}`, got `{}`", - actual.id - )); - } - Ok(()) - } - Judgment::Brg { bridge } => self - .validate_bridge( - ®istry - .get_bridge(bridge) - .ok_or_else(|| format!("missing bridge `{bridge}`"))?, - registry, - ) - .map_err(|err| err.to_string()), - Judgment::Path { bridges } => { - let path = bridges - .iter() - .map(|bridge_id| { - registry - .get_bridge(bridge_id) - .ok_or_else(|| format!("missing bridge `{bridge_id}`")) - }) - .collect::, _>>()?; - self.compose_bridge_path(&path, None) - } - } - } -} - -impl CheckProofShape for ConstitutionKernel { - fn check_proof_shape( - &self, - shape: &ProofShape, - _registry: &dyn RegistryLookup, - ) -> Result<(), String> { - let (min_nodes, min_edges) = match shape.kind { - ProofShapeKind::Triangle => (3, 3), - ProofShapeKind::Square => (4, 4), - ProofShapeKind::Diamond => (4, 4), - ProofShapeKind::Pentagon => (5, 5), - ProofShapeKind::Hexagon => (6, 6), - }; - if shape.nodes.len() < min_nodes { - return Err(format!("proof shape `{}` has too few nodes", shape.id)); - } - if shape.edges.len() < min_edges { - return Err(format!("proof shape `{}` has too few edges", shape.id)); - } - if shape.target_equivalence.trim().is_empty() { - return Err(format!( - "proof shape `{}` is missing target equivalence", - shape.id - )); - } - if shape.equations.is_empty() { - return Err(format!("proof shape `{}` is missing equations", shape.id)); - } - Ok(()) - } -} - -impl ComposeBridge for ConstitutionKernel { - fn compose_bridge_path( - &self, - bridges: &[l64_core::BridgeContract], - budget: Option<&Budget>, - ) -> Result<(), String> { - if bridges.is_empty() { - return Err("bridge path is empty".into()); - } - for window in bridges.windows(2) { - if window[0].tgt != window[1].src { - return Err(format!( - "bridge chain mismatch: `{}` -> `{}` does not compose into `{}`", - window[0].id, window[0].tgt, window[1].src - )); - } - } - let total_loss = bridges - .iter() - .map(|bridge| bridge.loss.len()) - .sum::(); - if let Some(budget) = budget { - if total_loss > budget.max_loss { - return Err(format!( - "bridge path exceeds loss budget: {total_loss} > {}", - budget.max_loss - )); - } - if !budget.allow_lossy_supported - && bridges.iter().any(|bridge| { - bridge.reversibility == l64_core::ReversibilityClass::LossySupported - }) - { - return Err( - "bridge path uses lossy-supported transport under a strict budget".into(), - ); - } - } - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use l64_core::{ - AliasFace, BridgeContract, ConstraintFace, EquivalenceClass, EvidenceFace, IdentityFace, - ObjectTag, PromotionGoal, ProofEdge, ProofMechanismZone, RegimePack, - RequiredProofShapeFamily, ReversibilityClass, StructuralFace, SurfaceKind, - SurfaceRequirement, TargetProfile, - }; - use l64_testkit::TestRegistryBuilder; - - fn sample_regime() -> RegimePack { - RegimePack { - id: "R_SET".into(), - ctx_law: "ctx".into(), - cut_law: "cut".into(), - thr_law: "thr".into(), - brc_law: "brc".into(), - slk_law: "slk".into(), - tol_law: "tol".into(), - knt_law: "knt".into(), - eq_law: "eq".into(), - adm_law: "adm".into(), - promoted_ops: vec!["canon".into()], - } - } - - fn sample_object(id: &str, maturity: EvidenceMaturity) -> QcObject { - QcObject { - id: id.into(), - identity: IdentityFace { - tag: ObjectTag::Ctx, - cid: id.into(), - codebook: "seed".into(), - remap: "none".into(), - lineage: "origin".into(), - }, - structural: StructuralFace { - head: "carrier".into(), - args: vec!["x".into()], - local_sections: vec!["base".into()], - morphism_hooks: vec!["identity".into()], - }, - constraint: ConstraintFace { - regime: "R_SET".into(), - contracts: vec!["total".into()], - invariants: vec!["stable".into()], - equivalence: "eq-set".into(), - admissibility: "admit".into(), - }, - evidence: EvidenceFace { - evidence_class: "Seed".into(), - traces: vec!["t".into()], - receipts: vec!["r".into()], - maturity, - gate_verdict: GateVerdict::Pass, - }, - alias: AliasFace { - aliases: vec!["ctx".into()], - profile_pack: vec!["STD".into()], - qm_binding: "reserved".into(), - qa_binding: "ctx".into(), - projection_policy: "qa-first".into(), - }, - } - } - - #[test] - fn canonicalization_collapses_equivalence_class() { - let kernel = ConstitutionKernel; - let object = sample_object("O1", EvidenceMaturity::Validated); - let canonical = sample_object("O2", EvidenceMaturity::Certified); - let registry = TestRegistryBuilder::new() - .with_object(object.clone()) - .with_object(canonical.clone()) - .with_regime(sample_regime()) - .with_equivalence_class(EquivalenceClass { - id: "EQ1".into(), - regime: "R_SET".into(), - canonical_id: "O2".into(), - members: vec!["O1".into(), "O2".into()], - }) - .build(); - - let result = kernel.canonicalize_object(&object, ®istry).unwrap(); - assert_eq!(result.id, "O2"); - } - - #[test] - fn promotion_rejects_unvalidated_object() { - let kernel = ConstitutionKernel; - let object = sample_object("O1", EvidenceMaturity::Candidate); - let registry = TestRegistryBuilder::new() - .with_object(object.clone()) - .with_regime(sample_regime()) - .build(); - - let err = kernel.promote(&object, ®istry).unwrap_err(); - assert!(err.contains("validated")); - } - - #[test] - fn target_profile_rejects_deprecated_surface_schema_authority() { - let kernel = ConstitutionKernel; - let target = TargetProfile { - id: "TGT_SURFACE_TOMBSTONE".into(), - burden_class: l64_core::BurdenClass::General, - host_cluster: vec!["R_TOP".into(), "R_CALC".into()], - target_equivalence: "eq".into(), - allowed_bridge_classes: vec![ReversibilityClass::Enriching], - loss_ceiling: 1, - rollback_ceiling: 1, - required_receipt_class: "RC".into(), - required_proof_shape_family: RequiredProofShapeFamily::Square, - promotion_goal: PromotionGoal::PromoteOperator, - primary_zone: ProofMechanismZone::PmzStructural, - surface_requirement: Some(SurfaceRequirement { - required_input: Some(SurfaceKind::Qc0), - preferred_output: None, - require_symbolic_fidelity: true, - keyboard_projection_ingress_only: true, - transform_receipts_mandatory: true, - }), - preferred_surface_target: None, - optimizer_policy: None, - policy_binding_ids: Vec::new(), - }; - - let err = kernel.validate_target_profile(&target).unwrap_err(); - assert!(err.to_string().contains("deprecated surface-schema")); - } - - #[test] - fn bridge_path_rejects_chain_mismatch() { - let kernel = ConstitutionKernel; - let left = BridgeContract { - id: "B1".into(), - src: "R_TYP".into(), - tgt: "R_SET".into(), - id_pres: "carrier".into(), - eq_pres: "eq".into(), - forget: vec![], - enrich: vec![], - loss: vec!["proof".into()], - reversibility: ReversibilityClass::Conservative, - receipts: vec![], - rollback: "allowed".into(), - }; - let right = BridgeContract { - id: "B2".into(), - src: "R_PROB".into(), - tgt: "R_LOG".into(), - id_pres: "carrier".into(), - eq_pres: "eq".into(), - forget: vec![], - enrich: vec![], - loss: vec![], - reversibility: ReversibilityClass::Conservative, - receipts: vec![], - rollback: "allowed".into(), - }; - - let err = kernel - .compose_bridge_path(&[left, right], None) - .unwrap_err(); - assert!(err.contains("does not compose")); - } - - #[test] - fn proof_shape_requires_expected_arity() { - let kernel = ConstitutionKernel; - let shape = ProofShape { - id: "P1".into(), - kind: ProofShapeKind::Triangle, - nodes: vec!["a".into(), "b".into()], - edges: vec![ProofEdge { - from: "a".into(), - to: "b".into(), - label: "f".into(), - }], - equations: vec!["f=g".into()], - target_equivalence: "eq".into(), - receipts: vec!["r".into()], - gate: GateVerdict::Pass, - }; - - let registry = TestRegistryBuilder::new().build(); - let err = kernel.check_proof_shape(&shape, ®istry).unwrap_err(); - assert!(err.contains("too few nodes")); - } -} diff --git a/l64-locus/Cargo.toml b/l64-locus/Cargo.toml deleted file mode 100644 index 5b2388f..0000000 --- a/l64-locus/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "l64-locus" -edition.workspace = true -version.workspace = true -license.workspace = true - -[dependencies] -l64-core = { path = "../l64-core" } -serde = { workspace = true } -serde_json = { workspace = true } -bincode = { workspace = true } -thiserror = { workspace = true } diff --git a/l64-locus/src/lib.rs b/l64-locus/src/lib.rs deleted file mode 100644 index 8b5b064..0000000 --- a/l64-locus/src/lib.rs +++ /dev/null @@ -1,612 +0,0 @@ -use l64_core::{ - BundleLock, CanonicalStructure, ChangeLedgerEntry, CnormReceipt, DigestRole, DnaHeaderReceipt, - DnaValidationReport, ExecutionManifest, GenomeArtifactClass, GenomeSurface, - LocusCapabilityMask, LocusDecodeMode, LocusOpcode, LocusPacket, LocusPacketHeader, - LocusPacketKind, LocusSection, NormalizedRna, RnaNormalizationReceipt, SemanticLoweringReceipt, - SsrReceipt, canonical_rna_from_structure, decode_locus_packet_with_mode, dna_header_receipt, - encode_locus_packet, ensure_cache_subdir, execute_lower_chain, locus_packet_summary, - role_digest_value, validate_dna_packet, -}; -use serde::{Deserialize, Serialize, de::DeserializeOwned}; -use std::{ - fs, - path::{Path, PathBuf}, -}; -use thiserror::Error; - -#[derive(Debug, Error)] -pub enum LocusIoError { - #[error("packet error: {0}")] - Packet(String), - #[error("io error: {0}")] - Io(#[from] std::io::Error), - #[error("json error: {0}")] - Json(#[from] serde_json::Error), - #[error("codec error: {0}")] - Codec(String), -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RnaCompilationArtifact { - pub normalized: NormalizedRna, - pub rn_receipt: RnaNormalizationReceipt, - pub ssr_receipt: SsrReceipt, - pub cnorm_receipt: CnormReceipt, - pub canonical_structure: CanonicalStructure, - pub lowering_receipt: SemanticLoweringReceipt, - pub dna_header_receipt: DnaHeaderReceipt, - pub dna_validation: DnaValidationReport, - #[serde(default)] - pub phase_ledger: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RnaDnaRoundtripReport { - pub canonical_id: String, - pub canonical_hash: String, - pub dna_bytes_equal: bool, - pub canonical_hash_equal: bool, - pub canonical_rna: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct GenomeReleaseManifest { - pub release_id: String, - pub canonical_hash: String, - pub canonical_id: String, - pub source_sequence: String, - pub canonical_genome: String, - pub claim_pages: Vec, - pub dependency_spine: String, - pub closure_map: String, - pub closure_frontier: String, - pub stress_map: String, - pub lineage: String, - pub replay_record: String, - pub view_receipts: Vec, -} - -pub fn validate_rna_source_text(input: &str) -> Result<(), LocusIoError> { - let trimmed = input.trim_start(); - if trimmed.is_empty() { - return Err(LocusIoError::Packet("RNA source is empty".into())); - } - if matches!(trimmed.as_bytes().first(), Some(b'{') | Some(b'[')) - && serde_json::from_str::(trimmed).is_ok() - { - return Err(LocusIoError::Packet( - "compile-rna accepts source RNA only; JSON/report/projection artifacts must use an explicit import or inspection command".into(), - )); - } - let report_markers = [ - "l64_release_artifact:", - "artifact_role:", - "surface_kind:", - "canonical_genome:", - "dependency_spine:", - "closure_map:", - "closure_frontier:", - "stress_map:", - "replay_record:", - "view_receipt:", - "\"artifact\"", - "\"canonical_structure\"", - "\"packet_summary\"", - "\"lineage\"", - "\"dna_validation\"", - "\"phase_ledger\"", - "\"view_receipt\"", - "\"claim_page\"", - "\"closure_map\"", - "\"stress_map\"", - "\"replay_record\"", - ]; - if report_markers.iter().any(|marker| trimmed.contains(marker)) { - return Err(LocusIoError::Packet( - "compile-rna rejected a projection/report/receipt artifact; use source RNA or canonical RNA".into(), - )); - } - Ok(()) -} - -pub fn encode_section_packet( - kind: LocusPacketKind, - opcode: LocusOpcode, - subject_id: &str, - schema_hash: &str, - payload: &T, - capabilities: LocusCapabilityMask, - authority_tier: u8, -) -> Result, LocusIoError> { - let payload_bytes = - bincode::serialize(payload).map_err(|err| LocusIoError::Codec(err.to_string()))?; - let packet = LocusPacket { - header: LocusPacketHeader { - artifact_class: GenomeArtifactClass::Gene, - surface: GenomeSurface::Dna, - kind, - version_major: 1, - version_minor: 0, - authority_tier, - capabilities, - grammar_id: "rna.v1".into(), - schema_hash: schema_hash.into(), - integrity_hash: l64_core::dna_digest_from_bytes(&payload_bytes).0, - strand_manifest: vec!["core".into()], - feature_flags: 0, - root_subject_id: subject_id.into(), - }, - sections: vec![LocusSection { - opcode, - flags: 0, - subject_id: subject_id.into(), - payload: payload_bytes, - }], - }; - encode_locus_packet(&packet).map_err(LocusIoError::Packet) -} - -pub fn decode_section_payload( - bytes: &[u8], - opcode: LocusOpcode, -) -> Result { - let packet = decode_locus_packet_with_mode(bytes, LocusDecodeMode::CurrentAuthority) - .map_err(LocusIoError::Packet)?; - let section = packet - .sections - .iter() - .find(|item| item.opcode == opcode) - .ok_or_else(|| { - LocusIoError::Packet(format!("locus packet missing section {:?}", opcode)) - })?; - bincode::deserialize(§ion.payload).map_err(|err| LocusIoError::Codec(err.to_string())) -} - -fn receipt_id(prefix: &str, parts: &[&str]) -> String { - format!( - "{prefix}_{}", - role_digest_value(DigestRole::ReceiptId, &(prefix, parts)) - ) -} - -fn source_lowering_receipt_id(subject_id: &str) -> String { - receipt_id("SLR", &["rna", subject_id]) -} - -fn dna_lowering_receipt_id(root_subject_id: &str) -> String { - receipt_id("SLR", &["dna", root_subject_id]) -} - -fn sequenced_rna_receipt_id(canonical_hash: &str) -> String { - receipt_id("RNR", &["dna-sequenced", canonical_hash]) -} - -fn sequenced_ssr_receipt_id(root_id: &str) -> String { - receipt_id("SSR_RCP", &["dna-sequenced", root_id]) -} - -fn sequenced_cnorm_receipt_id(root_id: &str) -> String { - receipt_id("CNR", &["dna-sequenced", root_id]) -} - -pub fn decode_summary( - bytes: &[u8], -) -> Result, LocusIoError> { - let packet = decode_locus_packet_with_mode(bytes, LocusDecodeMode::CurrentAuthority) - .map_err(LocusIoError::Packet)?; - Ok(locus_packet_summary(&packet)) -} - -pub fn write_section_packet( - path: &Path, - kind: LocusPacketKind, - opcode: LocusOpcode, - subject_id: &str, - schema_hash: &str, - payload: &T, - capabilities: LocusCapabilityMask, - authority_tier: u8, -) -> Result<(), LocusIoError> { - let bytes = encode_section_packet( - kind, - opcode, - subject_id, - schema_hash, - payload, - capabilities, - authority_tier, - )?; - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - fs::write(path, bytes)?; - Ok(()) -} - -pub fn manifest_cache_root() -> Result { - Ok(ensure_cache_subdir("manifests").map_err(LocusIoError::Packet)?) -} - -fn manifest_packet_path(id: &str) -> Result { - Ok(manifest_cache_root()?.join(format!("{id}.dna"))) -} - -fn bundle_lock_packet_path(id: &str) -> Result { - Ok(manifest_cache_root()?.join(format!("{id}.lock.dna"))) -} - -pub fn load_execution_manifest(id: &str) -> Result { - let packet_path = manifest_packet_path(id)?; - decode_section_payload(&fs::read(packet_path)?, LocusOpcode::CanonicalPayload) -} - -pub fn persist_execution_manifest(manifest: &ExecutionManifest) -> Result<(), LocusIoError> { - let path = manifest_packet_path(&manifest.id)?; - write_section_packet( - &path, - LocusPacketKind::CanonicalTransfer, - LocusOpcode::CanonicalPayload, - &manifest.id, - "execution_manifest.v1", - manifest, - LocusCapabilityMask::default(), - 1, - ) -} - -pub fn load_bundle_lock(id: &str) -> Result { - let packet_path = bundle_lock_packet_path(id)?; - decode_section_payload(&fs::read(packet_path)?, LocusOpcode::CanonicalPayload) -} - -pub fn persist_bundle_lock(lock: &BundleLock) -> Result<(), LocusIoError> { - let path = bundle_lock_packet_path(&lock.id)?; - write_section_packet( - &path, - LocusPacketKind::CanonicalTransfer, - LocusOpcode::CanonicalPayload, - &lock.id, - "bundle_lock.v1", - lock, - LocusCapabilityMask::default(), - 1, - ) -} - -pub fn encode_canonical_structure_to_dna_packet( - subject_id: &str, - artifact_class: GenomeArtifactClass, - strand_manifest: Vec, - canonical_structure: &CanonicalStructure, -) -> Result<(Vec, DnaHeaderReceipt, DnaValidationReport), LocusIoError> { - let packet = LocusPacket { - header: LocusPacketHeader { - artifact_class, - surface: GenomeSurface::Dna, - kind: LocusPacketKind::CanonicalTransfer, - version_major: 1, - version_minor: 0, - authority_tier: 1, - capabilities: LocusCapabilityMask::default(), - grammar_id: "rna.v1".into(), - schema_hash: "canonical_structure.v1".into(), - integrity_hash: canonical_structure.canonical_hash.clone(), - strand_manifest, - feature_flags: 0, - root_subject_id: subject_id.into(), - }, - sections: vec![LocusSection { - opcode: LocusOpcode::CanonicalPayload, - flags: 0, - subject_id: subject_id.into(), - payload: bincode::serialize(canonical_structure) - .map_err(|err| LocusIoError::Codec(err.to_string()))?, - }], - }; - let dna_validation = validate_dna_packet(&packet); - if !dna_validation.failures.is_empty() { - return Err(LocusIoError::Packet(format!( - "DNA validation failed: {}", - dna_validation.failures.join("; ") - ))); - } - let dna_header_receipt = dna_header_receipt(&packet); - let bytes = encode_locus_packet(&packet).map_err(LocusIoError::Packet)?; - Ok((bytes, dna_header_receipt, dna_validation)) -} - -pub fn decode_canonical_structure_from_dna_packet( - bytes: &[u8], -) -> Result<(LocusPacket, CanonicalStructure, DnaValidationReport), LocusIoError> { - let packet = decode_locus_packet_with_mode(bytes, LocusDecodeMode::CurrentAuthority) - .map_err(LocusIoError::Packet)?; - let dna_validation = validate_dna_packet(&packet); - if !dna_validation.failures.is_empty() { - return Err(LocusIoError::Packet(format!( - "DNA validation failed: {}", - dna_validation.failures.join("; ") - ))); - } - let section = packet - .sections - .iter() - .find(|item| item.opcode == LocusOpcode::CanonicalPayload) - .ok_or_else(|| LocusIoError::Packet("dna packet missing canonical payload".into()))?; - let canonical_structure: CanonicalStructure = bincode::deserialize(§ion.payload) - .map_err(|err| LocusIoError::Codec(err.to_string()))?; - Ok((packet, canonical_structure, dna_validation)) -} - -pub fn compile_rna_to_dna_packet( - subject_id: &str, - rna: &str, - artifact_class: GenomeArtifactClass, - strand_manifest: Vec, -) -> Result<(Vec, RnaCompilationArtifact), LocusIoError> { - validate_rna_source_text(rna)?; - let execution = execute_lower_chain(rna).map_err(|failure| { - LocusIoError::Packet( - serde_json::to_string(&failure).unwrap_or_else(|_| "lower chain failure".into()), - ) - })?; - let normalized = execution.normalized; - let rn_receipt = execution.rn_receipt; - let ssr_receipt = execution.ssr_receipt; - let canonical_structure = execution.canonical_structure; - let cnorm_receipt = execution.cnorm_receipt; - let phase_ledger = execution.ledger_entries; - let lowering_receipt = SemanticLoweringReceipt { - id: source_lowering_receipt_id(subject_id), - source_surface: GenomeSurface::Rna, - target: "canonical-structure".into(), - canonical_hash: cnorm_receipt.canonical_hash.clone(), - ephemeral_resolver_used: true, - }; - let (bytes, dna_header_receipt, dna_validation) = encode_canonical_structure_to_dna_packet( - subject_id, - artifact_class, - strand_manifest, - &canonical_structure, - )?; - Ok(( - bytes, - RnaCompilationArtifact { - normalized, - rn_receipt, - ssr_receipt, - cnorm_receipt, - canonical_structure, - lowering_receipt, - dna_header_receipt, - dna_validation, - phase_ledger, - }, - )) -} - -pub fn sequence_dna_to_canonical_rna(bytes: &[u8]) -> Result { - let (_, canonical_structure, _) = decode_canonical_structure_from_dna_packet(bytes)?; - Ok(canonical_rna_from_structure(&canonical_structure)) -} - -pub fn sequence_dna_to_rna(bytes: &[u8]) -> Result { - let (packet, canonical_structure, dna_validation) = - decode_canonical_structure_from_dna_packet(bytes)?; - let canonical_rna = canonical_rna_from_structure(&canonical_structure); - let normalized = NormalizedRna { - raw_text: canonical_rna.clone(), - normalized_text: canonical_rna.clone(), - state: l64_core::RnaState::Stabilized, - splice_regions: Vec::new(), - }; - let rn_receipt = RnaNormalizationReceipt { - id: sequenced_rna_receipt_id(&canonical_structure.canonical_hash), - token_stream_id: String::new(), - state: l64_core::RnaState::Stabilized, - normalized_text: canonical_rna, - shorthand_eliminated: true, - splice_regions: Vec::new(), - issues: Vec::new(), - }; - let ssr_receipt = SsrReceipt { - id: sequenced_ssr_receipt_id(&canonical_structure.root_id), - root_id: canonical_structure.root_id.clone(), - node_count: canonical_structure.items.len(), - transition_count: canonical_structure.items.len().saturating_sub(1), - transition_table_hash: l64_core::hash_serialized(&l64_core::ssr_transition_specs()), - ephemeral: true, - normalized_rna_id: rn_receipt.id.clone(), - }; - let cnorm_receipt = CnormReceipt { - id: sequenced_cnorm_receipt_id(&canonical_structure.root_id), - root_id: canonical_structure.root_id.clone(), - canonical_hash: canonical_structure.canonical_hash.clone(), - rule_table_hash: l64_core::hash_serialized(&l64_core::structural_equivalence_law_specs()), - idempotent: true, - erased_variations: vec!["dna-sequenced".into()], - }; - let lowering_receipt = SemanticLoweringReceipt { - id: dna_lowering_receipt_id(&packet.header.root_subject_id), - source_surface: GenomeSurface::Dna, - target: "canonical-structure".into(), - canonical_hash: cnorm_receipt.canonical_hash.clone(), - ephemeral_resolver_used: false, - }; - let dna_header_receipt = dna_header_receipt(&packet); - Ok(RnaCompilationArtifact { - normalized, - rn_receipt, - ssr_receipt, - cnorm_receipt, - canonical_structure, - lowering_receipt, - dna_header_receipt, - dna_validation, - phase_ledger: Vec::new(), - }) -} - -pub fn verify_rna_dna_roundtrip( - subject_id: &str, - rna: &str, - artifact_class: GenomeArtifactClass, - strand_manifest: Vec, -) -> Result { - let (bytes, artifact) = - compile_rna_to_dna_packet(subject_id, rna, artifact_class, strand_manifest.clone())?; - let canonical_rna = sequence_dna_to_canonical_rna(&bytes)?; - let (recompiled, reartifact) = - compile_rna_to_dna_packet(subject_id, &canonical_rna, artifact_class, strand_manifest)?; - Ok(RnaDnaRoundtripReport { - canonical_id: artifact.canonical_structure.canonical_id.0.clone(), - canonical_hash: artifact.canonical_structure.canonical_hash.clone(), - dna_bytes_equal: bytes == recompiled, - canonical_hash_equal: artifact.canonical_structure.canonical_hash - == reartifact.canonical_structure.canonical_hash, - canonical_rna, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn compile_and_sequence_rna_roundtrip() { - let (bytes, artifact) = compile_rna_to_dna_packet( - "CHAIN_RULE", - "ι ≔ σ ‖ κ", - GenomeArtifactClass::Gene, - vec!["core".into()], - ) - .expect("compile"); - assert!(!bytes.is_empty()); - assert_eq!(artifact.lowering_receipt.source_surface, GenomeSurface::Rna); - assert_eq!(artifact.phase_ledger.len(), 4); - assert_eq!( - artifact.phase_ledger[0].phase_id, - l64_core::PhaseId::Tokenization - ); - assert!(artifact.dna_header_receipt.header_truth_complete); - assert!(artifact.dna_validation.reversible); - assert!(artifact.dna_validation.canonical_payload_digest_valid); - assert!(artifact.dna_validation.failures.is_empty()); - - let sequenced = sequence_dna_to_rna(&bytes).expect("sequence"); - assert_eq!( - sequenced.canonical_structure.canonical_id, - artifact.canonical_structure.canonical_id - ); - assert_eq!( - sequenced.canonical_structure.canonical_hash, - artifact.canonical_structure.canonical_hash - ); - assert_eq!( - sequenced.lowering_receipt.source_surface, - GenomeSurface::Dna - ); - assert!(sequenced.phase_ledger.is_empty()); - - let (reencoded, _, revalidation) = encode_canonical_structure_to_dna_packet( - "CHAIN_RULE", - GenomeArtifactClass::Gene, - vec!["core".into()], - &sequenced.canonical_structure, - ) - .expect("reencode canonical structure"); - assert!(revalidation.failures.is_empty()); - assert!(revalidation.canonical_payload_digest_valid); - assert_eq!(reencoded, bytes); - - let canonical_rna = sequence_dna_to_canonical_rna(&bytes).expect("canonical rna"); - let (recompiled, recompiled_artifact) = compile_rna_to_dna_packet( - "CHAIN_RULE", - &canonical_rna, - GenomeArtifactClass::Gene, - vec!["core".into()], - ) - .expect("recompile canonical rna"); - assert_eq!(recompiled, bytes); - assert_eq!( - recompiled_artifact.canonical_structure.canonical_hash, - artifact.canonical_structure.canonical_hash - ); - - let report = verify_rna_dna_roundtrip( - "CHAIN_RULE", - "ι ≔ σ ‖ κ", - GenomeArtifactClass::Gene, - vec!["core".into()], - ) - .expect("verify roundtrip"); - assert!(report.dna_bytes_equal); - assert!(report.canonical_hash_equal); - } - - #[test] - fn sequence_rejects_dna_with_invalid_canonical_digest() { - let (bytes, _) = compile_rna_to_dna_packet( - "CHAIN_RULE", - "ι ≔ σ ‖ κ", - GenomeArtifactClass::Gene, - vec!["core".into()], - ) - .expect("compile"); - let mut packet = l64_core::decode_locus_packet(&bytes).expect("decode packet"); - packet.header.integrity_hash = "stale-digest".into(); - let corrupted = encode_locus_packet(&packet).expect("encode corrupted packet"); - let err = sequence_dna_to_rna(&corrupted).expect_err("stale digest must fail"); - assert!(err.to_string().contains("DNA validation failed")); - } - - #[test] - fn generic_section_packet_integrity_is_payload_bound() { - let left = encode_section_packet( - LocusPacketKind::CertificationEnvelope, - LocusOpcode::CanonicalPayload, - "SUBJ", - "test-schema.v1", - &vec!["left"], - LocusCapabilityMask::default(), - 1, - ) - .expect("left packet"); - let right = encode_section_packet( - LocusPacketKind::CertificationEnvelope, - LocusOpcode::CanonicalPayload, - "SUBJ", - "test-schema.v1", - &vec!["right"], - LocusCapabilityMask::default(), - 1, - ) - .expect("right packet"); - - let left_packet = l64_core::decode_locus_packet(&left).expect("left decode"); - let right_packet = l64_core::decode_locus_packet(&right).expect("right decode"); - assert_eq!( - left_packet.header.schema_hash, - right_packet.header.schema_hash - ); - assert_ne!( - left_packet.header.integrity_hash, - right_packet.header.integrity_hash - ); - assert_eq!( - left_packet.header.integrity_hash, - l64_core::dna_digest_from_bytes(&left_packet.sections[0].payload).0 - ); - } - - #[test] - fn compile_rejects_projection_report_text() { - let err = compile_rna_to_dna_packet( - "REPORT", - "{\"artifact\":{\"canonical_structure\":{}}}", - GenomeArtifactClass::Gene, - vec!["core".into()], - ) - .expect_err("report text must not compile as RNA"); - assert!(err.to_string().contains("source RNA only")); - } -} diff --git a/l64-testkit/Cargo.toml b/l64-native/Cargo.toml similarity index 61% rename from l64-testkit/Cargo.toml rename to l64-native/Cargo.toml index 9245d27..082bc27 100644 --- a/l64-testkit/Cargo.toml +++ b/l64-native/Cargo.toml @@ -1,8 +1,8 @@ [package] -name = "l64-testkit" +name = "l64-native" edition.workspace = true version.workspace = true license.workspace = true [dependencies] -l64-core = { path = "../l64-core" } +l64-symbolic = { path = "../l64-symbolic" } diff --git a/l64-native/README.md b/l64-native/README.md new file mode 100644 index 0000000..d713417 --- /dev/null +++ b/l64-native/README.md @@ -0,0 +1,50 @@ +# l64-native + +`l64-native` owns canonical `L64R1` RNA, canonical `L64D` DNA, the native graph, checked admission, proof-producing equality, context-relative closure, exact authority identity, and the canonical codec. + +## Authority boundary + +- Positive identity is exact equality of the domain-qualified canonical representation. +- The fixed-width symbolic seal is a non-authoritative fast inequality and structural-diagnosis carrier. +- RNA and DNA decoding re-execute structural, constraint, equality, context, operation, and ordering law before acceptance. +- Failed admission is atomic: authority, contexts, indexes, and journal state remain unchanged. +- Derived indexes and closure analyses are in-memory accelerators only. They do not serialize and do not participate in authority identity. + +## Native graph + +One graph carries routes, nodes, compact ports, persistent contexts, constraints, judgments, witnesses, obligations, and the transition journal. The kernel admits typed operations and deterministic evidence routes; generic value insertion cannot fabricate kernel evidence. + +The constraint core provides packed seven-axis dimensions, dimension-checked quantity operations, contradiction rejection, guarded square root, and native unresolved obligations. The equality core provides reflexivity, exact identity, symmetry, transitivity, and congruence with checked premise provenance. Incremental closure derives `Closed`, `Open`, or `Invalid` state per context without persisting a second authority database. + +## Canonical carriers + +- `L64R1`: compact canonical authored RNA with one domain and strictly increasing local slots. +- `L64D`: bounded binary DNA with a fixed 44-byte header, exact canonical payload, and symbolic state seal. +- `L64S1`: exact self-delimiting identity envelope provided by `l64-symbolic`. + +The exact fixed point is `L64R1 → L64D → L64R1 → L64D`. + +## Construction and scale + +Canonical source compilation uses private bulk construction, suppresses transient construction journaling, and derives the final state symbol once. Public graph mutation remains fully journaled. Primary routes, reverse dependencies, context-local nodes, and closure memoization are derived from canonical authority and rebuilt after decode. + +Measured scale law is enforced by `scripts/verify-native-scale.sh`; no optimization may alter canonical bytes, public mutation semantics, verdict law, or retained/external projection verification. + +## Relationships + +- `l64-projection` derives verified read-only views from `l64-native`. +- `l64-execution`, `l64-certification`, `l64-observation`, and `l64-change` consume exact native authority without becoming authority. +- `l64-transport` frames ordered DNA members without composite authority. +- `l64-cli` and the `l64` wrapper expose the product boundary. + +The historical compatibility authority island was exported and deleted. No live legacy dispatcher, registry, packet world, cache, or fallback remains. + +## Direct verification + +```bash +cargo test --locked --offline -p l64-native +./scripts/verify-native-carrier.sh +./scripts/verify-native-scale.sh +``` + +Current architectural law: [`../LOCUS64_NATIVE_CONSTITUTION.md`](../LOCUS64_NATIVE_CONSTITUTION.md). Historical correction chain: [`../LOCUS64_HISTORICAL_LAW_LEDGER.md`](../LOCUS64_HISTORICAL_LAW_LEDGER.md). diff --git a/l64-native/src/closure.rs b/l64-native/src/closure.rs new file mode 100644 index 0000000..a1d0a9a --- /dev/null +++ b/l64-native/src/closure.rs @@ -0,0 +1,63 @@ +use crate::{ContextId, NodeId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum ClosureState { + Closed, + Open, + Invalid, +} + +impl ClosureState { + pub(crate) fn combine(self, other: Self) -> Self { + self.max(other) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ClosureTransition { + node: NodeId, + before: ClosureState, + after: ClosureState, + cause: NodeId, + from_context: ContextId, + to_context: ContextId, +} + +impl ClosureTransition { + pub(crate) fn new( + node: NodeId, + before: ClosureState, + after: ClosureState, + cause: NodeId, + from_context: ContextId, + to_context: ContextId, + ) -> Self { + Self { + node, + before, + after, + cause, + from_context, + to_context, + } + } + + pub fn node(&self) -> NodeId { + self.node + } + pub fn before(&self) -> ClosureState { + self.before + } + pub fn after(&self) -> ClosureState { + self.after + } + pub fn cause(&self) -> NodeId { + self.cause + } + pub fn from_context(&self) -> ContextId { + self.from_context + } + pub fn to_context(&self) -> ContextId { + self.to_context + } +} diff --git a/l64-native/src/codec.rs b/l64-native/src/codec.rs new file mode 100644 index 0000000..c48471d --- /dev/null +++ b/l64-native/src/codec.rs @@ -0,0 +1,73 @@ +use std::{collections::BTreeMap, fmt}; + +use crate::kernel::{EVIDENCE_LOCUS, EqualityRule, JUDGMENT_LOCUS}; +use crate::{ContextDelta, Graph, LocusWord, Node, NodeId, OpCode, Port, PortRole, Route}; + +pub(crate) const CODEC_VERSION: u16 = 4; +const MAX_NODES: usize = 1 << 20; +const MAX_PORTS: usize = 1 << 22; +const MAX_CONTEXTS: usize = 1 << 20; +const MAX_ROUTES: usize = 1 << 20; +const MAX_ROUTE_WORDS: usize = 64; +const NO_NODE: NodeId = u32::MAX; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DecodeError { + Truncated, + BadMagic, + UnsupportedVersion { version: u16 }, + StructuralBound, + UnknownOpcode { opcode: u16 }, + UnknownPortRole { role: u8 }, + NonZeroPortFlags { flags: u8 }, + InvalidNode, + InvalidPortRange, + InvalidPortTarget, + InvalidPortLaw, + InvalidContext, + InvalidRoute, + InvalidAuthority, + DuplicateRoute, + TrailingBytes, + NonCanonical, +} + +impl fmt::Display for DecodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Truncated => f.write_str("canonical payload is truncated"), + Self::BadMagic => f.write_str("canonical payload magic is invalid"), + Self::UnsupportedVersion { version } => { + write!(f, "unsupported canonical codec version {version}") + } + Self::StructuralBound => f.write_str("canonical payload exceeds a structural bound"), + Self::UnknownOpcode { opcode } => write!(f, "unknown opcode {opcode}"), + Self::UnknownPortRole { role } => write!(f, "unknown port role {role}"), + Self::NonZeroPortFlags { flags } => { + write!(f, "unsupported non-zero port flags {flags}") + } + Self::InvalidNode => f.write_str("canonical payload contains an invalid node"), + Self::InvalidPortRange => { + f.write_str("canonical payload contains an invalid port range") + } + Self::InvalidPortTarget => { + f.write_str("canonical payload contains an invalid port target") + } + Self::InvalidPortLaw => f.write_str("canonical payload contains an invalid port law"), + Self::InvalidContext => f.write_str("canonical payload contains an invalid context"), + Self::InvalidRoute => f.write_str("canonical payload contains an invalid route"), + Self::InvalidAuthority => { + f.write_str("canonical payload contains invalid authority metadata") + } + Self::DuplicateRoute => f.write_str("canonical payload contains a duplicate route"), + Self::TrailingBytes => f.write_str("canonical payload has trailing bytes"), + Self::NonCanonical => f.write_str("canonical payload is not in canonical form"), + } + } +} + +impl std::error::Error for DecodeError {} + +include!("codec/io.rs"); +include!("codec/validation.rs"); +include!("codec/reader.rs"); diff --git a/l64-native/src/codec/io.rs b/l64-native/src/codec/io.rs new file mode 100644 index 0000000..5c7e697 --- /dev/null +++ b/l64-native/src/codec/io.rs @@ -0,0 +1,130 @@ +pub fn canonical_bytes(graph: &Graph) -> Vec { + let mut out = + Vec::with_capacity(22 + graph.nodes_raw().len() * 24 + graph.ports_raw().len() * 8); + out.extend_from_slice(b"L64N"); + out.extend_from_slice(&CODEC_VERSION.to_le_bytes()); + push_len(&mut out, graph.nodes_raw().len()); + push_len(&mut out, graph.ports_raw().len()); + push_len(&mut out, graph.contexts_raw().len()); + push_len(&mut out, graph.routes_raw().len()); + + for node in graph.nodes_raw() { + out.extend_from_slice(&(node.opcode() as u16).to_le_bytes()); + out.extend_from_slice(&node.context().to_le_bytes()); + out.extend_from_slice(&node.ty().unwrap_or(NO_NODE).to_le_bytes()); + out.extend_from_slice(&node.payload().to_le_bytes()); + let range = node.port_range(); + out.extend_from_slice(&(range.start as u32).to_le_bytes()); + out.extend_from_slice(&((range.end - range.start) as u16).to_le_bytes()); + } + + for port in graph.ports_raw() { + out.extend_from_slice(&port.target().to_le_bytes()); + out.push(port.role() as u8); + out.push(port.flags()); + out.extend_from_slice(&port.ordinal().to_le_bytes()); + } + + for context in graph.contexts_raw() { + out.extend_from_slice(&context.parent().to_le_bytes()); + out.extend_from_slice(&context.binding().unwrap_or(NO_NODE).to_le_bytes()); + } + + for (route, node) in graph.routes_raw() { + out.extend_from_slice(&route.domain().0.to_le_bytes()); + push_len(&mut out, route.tail().len()); + for word in route.tail() { + out.extend_from_slice(&word.0.to_le_bytes()); + } + out.extend_from_slice(&node.to_le_bytes()); + } + + out +} + +pub fn decode_canonical(bytes: &[u8]) -> Result { + let mut reader = Reader::new(bytes); + if reader.take(4)? != b"L64N" { + return Err(DecodeError::BadMagic); + } + let version = reader.u16()?; + if version != CODEC_VERSION { + return Err(DecodeError::UnsupportedVersion { version }); + } + + let node_count = reader.count(MAX_NODES)?; + let port_count = reader.count(MAX_PORTS)?; + let context_count = reader.count(MAX_CONTEXTS)?; + let route_count = reader.count(MAX_ROUTES)?; + if context_count == 0 || route_count != node_count { + return Err(DecodeError::InvalidContext); + } + + reader.require(node_count, 24)?; + let mut nodes = Vec::with_capacity(node_count); + for _ in 0..node_count { + let raw_opcode = reader.u16()?; + let opcode = OpCode::from_raw(raw_opcode) + .filter(|opcode| opcode.is_persisted_node()) + .ok_or(DecodeError::UnknownOpcode { opcode: raw_opcode })?; + let context = reader.u32()?; + let ty = reader.u32()?; + let payload = reader.u64()?; + let first_port = reader.u32()?; + let port_count = reader.u16()?; + nodes.push(Node::from_raw( + payload, context, ty, first_port, opcode, port_count, + )); + } + + reader.require(port_count, 8)?; + let mut ports = Vec::with_capacity(port_count); + for _ in 0..port_count { + let target = reader.u32()?; + let raw_role = reader.u8()?; + let role = + PortRole::from_raw(raw_role).ok_or(DecodeError::UnknownPortRole { role: raw_role })?; + let flags = reader.u8()?; + if flags != 0 { + return Err(DecodeError::NonZeroPortFlags { flags }); + } + let ordinal = reader.u16()?; + ports.push(Port::from_raw(target, role, flags, ordinal)); + } + + reader.require(context_count, 8)?; + let mut contexts = Vec::with_capacity(context_count); + for _ in 0..context_count { + contexts.push(ContextDelta::from_raw(reader.u32()?, reader.u32()?)); + } + + let mut routes = BTreeMap::new(); + for _ in 0..route_count { + let domain = LocusWord(reader.u64()?); + let tail_len = reader.count(MAX_ROUTE_WORDS)?; + reader.require(tail_len, 8)?; + let mut tail = Vec::with_capacity(tail_len); + for _ in 0..tail_len { + tail.push(LocusWord(reader.u64()?)); + } + let node = reader.u32()?; + let route = Route::from_parts(domain, tail.into_boxed_slice()); + if routes.insert(route, node).is_some() { + return Err(DecodeError::DuplicateRoute); + } + } + + if !reader.is_empty() { + return Err(DecodeError::TrailingBytes); + } + + validate_structure(&nodes, &ports, &contexts, &routes)?; + let graph = Graph::from_decoded_parts(nodes, ports, contexts, routes); + graph + .validate_decoded_authority() + .map_err(|_| DecodeError::InvalidAuthority)?; + if canonical_bytes(&graph) != bytes { + return Err(DecodeError::NonCanonical); + } + Ok(graph) +} diff --git a/l64-native/src/codec/reader.rs b/l64-native/src/codec/reader.rs new file mode 100644 index 0000000..f2127e2 --- /dev/null +++ b/l64-native/src/codec/reader.rs @@ -0,0 +1,69 @@ +fn push_len(out: &mut Vec, len: usize) { + let value = u32::try_from(len).expect("native graph section exceeds u32 length"); + out.extend_from_slice(&value.to_le_bytes()); +} + +struct Reader<'a> { + bytes: &'a [u8], + cursor: usize, +} + +impl<'a> Reader<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, cursor: 0 } + } + + fn is_empty(&self) -> bool { + self.cursor == self.bytes.len() + } + + fn take(&mut self, len: usize) -> Result<&'a [u8], DecodeError> { + let end = self.cursor.checked_add(len).ok_or(DecodeError::Truncated)?; + let value = self + .bytes + .get(self.cursor..end) + .ok_or(DecodeError::Truncated)?; + self.cursor = end; + Ok(value) + } + + fn require(&self, count: usize, width: usize) -> Result<(), DecodeError> { + let bytes = count + .checked_mul(width) + .ok_or(DecodeError::StructuralBound)?; + if self.bytes.len().saturating_sub(self.cursor) < bytes { + return Err(DecodeError::Truncated); + } + Ok(()) + } + + fn count(&mut self, maximum: usize) -> Result { + let count = self.u32()? as usize; + if count > maximum { + return Err(DecodeError::StructuralBound); + } + Ok(count) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn u16(&mut self) -> Result { + Ok(u16::from_le_bytes( + self.take(2)?.try_into().expect("fixed-width read"), + )) + } + + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes( + self.take(4)?.try_into().expect("fixed-width read"), + )) + } + + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes( + self.take(8)?.try_into().expect("fixed-width read"), + )) + } +} diff --git a/l64-native/src/codec/validation.rs b/l64-native/src/codec/validation.rs new file mode 100644 index 0000000..7cfebe9 --- /dev/null +++ b/l64-native/src/codec/validation.rs @@ -0,0 +1,264 @@ +fn validate_structure( + nodes: &[Node], + ports: &[Port], + contexts: &[ContextDelta], + routes: &BTreeMap, +) -> Result<(), DecodeError> { + let root = contexts.first().ok_or(DecodeError::InvalidContext)?; + if root.parent() != 0 || root.binding().is_some() { + return Err(DecodeError::InvalidContext); + } + for (index, context) in contexts.iter().enumerate().skip(1) { + if context.parent() as usize >= index { + return Err(DecodeError::InvalidContext); + } + let binding = context.binding().ok_or(DecodeError::InvalidContext)?; + if binding as usize >= nodes.len() { + return Err(DecodeError::InvalidContext); + } + } + + let mut port_cursor = 0usize; + for (index, node) in nodes.iter().enumerate() { + if node.context() as usize >= contexts.len() { + return Err(DecodeError::InvalidNode); + } + if let Some(ty) = node.ty() { + if ty as usize >= index || !nodes[ty as usize].opcode().is_type() { + return Err(DecodeError::InvalidNode); + } + } else if !node.opcode().is_untyped_authority() { + return Err(DecodeError::InvalidNode); + } + + let range = node.port_range(); + if range.start != port_cursor || range.end > ports.len() { + return Err(DecodeError::InvalidPortRange); + } + let node_ports = &ports[range.clone()]; + for (ordinal, port) in node_ports.iter().enumerate() { + if port.target() as usize >= index { + return Err(DecodeError::InvalidPortTarget); + } + if port.ordinal() as usize != ordinal { + return Err(DecodeError::InvalidPortLaw); + } + } + validate_port_law(node.opcode(), node_ports, node.ty().is_some())?; + validate_node_semantics(index, node, node_ports, nodes, ports)?; + port_cursor = range.end; + } + if port_cursor != ports.len() { + return Err(DecodeError::InvalidPortRange); + } + + let mut covered = vec![false; nodes.len()]; + for node in routes.values().copied() { + let slot = covered + .get_mut(node as usize) + .ok_or(DecodeError::InvalidRoute)?; + if *slot { + return Err(DecodeError::InvalidRoute); + } + *slot = true; + } + if covered.iter().any(|covered| !covered) { + return Err(DecodeError::InvalidRoute); + } + validate_evidence_routes(nodes, routes)?; + Ok(()) +} + +fn validate_node_semantics( + index: usize, + node: &Node, + node_ports: &[Port], + nodes: &[Node], + ports: &[Port], +) -> Result<(), DecodeError> { + match node.opcode() { + OpCode::Value => { + let ty = node.ty().ok_or(DecodeError::InvalidNode)?; + if matches!( + nodes[ty as usize].opcode(), + OpCode::TypeJudgment | OpCode::TypeEquality + ) { + return Err(DecodeError::InvalidNode); + } + } + OpCode::KernelWitness | OpCode::Obligation => { + let ty = node.ty().ok_or(DecodeError::InvalidNode)?; + if nodes[ty as usize].opcode() != OpCode::TypeJudgment { + return Err(DecodeError::InvalidNode); + } + if node.opcode() == OpCode::Obligation + && crate::ConstraintKind::from_payload(node.payload()).is_none() + { + return Err(DecodeError::InvalidNode); + } + } + OpCode::TypeEquality => { + if node.payload() != 0 { + return Err(DecodeError::InvalidNode); + } + } + OpCode::EqualityWitness => { + let ty = node.ty().ok_or(DecodeError::InvalidNode)?; + if nodes[ty as usize].opcode() != OpCode::TypeEquality + || node.payload() > u8::MAX as u64 + || EqualityRule::from_raw(node.payload() as u8).is_none() + { + return Err(DecodeError::InvalidNode); + } + } + OpCode::TypeQuantity => { + if crate::Dimension::from_bits(node.payload()).is_none() { + return Err(DecodeError::InvalidNode); + } + } + OpCode::Constraint => { + if crate::ConstraintKind::from_payload(node.payload()).is_none() { + return Err(DecodeError::InvalidNode); + } + } + OpCode::TypeJudgment => { + let rule = OpCode::from_raw(node.payload() as u16) + .filter(|opcode| opcode.is_executable()) + .ok_or(DecodeError::InvalidNode)?; + if node_ports.len() < 3 { + return Err(DecodeError::InvalidNode); + } + let subject = node_ports[0].target() as usize; + if subject >= index || nodes[subject].opcode() != rule { + return Err(DecodeError::InvalidNode); + } + let subject_node = &nodes[subject]; + let conclusion = node_ports.last().ok_or(DecodeError::InvalidNode)?.target(); + if subject_node.ty() != Some(conclusion) { + return Err(DecodeError::InvalidNode); + } + let subject_ports = ports + .get(subject_node.port_range()) + .ok_or(DecodeError::InvalidPortRange)?; + if subject_ports.len() != node_ports.len() - 2 + || subject_ports + .iter() + .map(Port::target) + .ne(node_ports[1..node_ports.len() - 1].iter().map(Port::target)) + { + return Err(DecodeError::InvalidNode); + } + } + _ => {} + } + Ok(()) +} + +fn validate_evidence_routes( + nodes: &[Node], + routes: &BTreeMap, +) -> Result<(), DecodeError> { + let mut attached = vec![false; nodes.len()]; + for (route, node_id) in routes { + let node = &nodes[*node_id as usize]; + if !node.opcode().is_executable() { + continue; + } + let judgment = *routes + .get(&route.composed(JUDGMENT_LOCUS)) + .ok_or(DecodeError::InvalidRoute)?; + let witness = *routes + .get(&route.composed(EVIDENCE_LOCUS)) + .ok_or(DecodeError::InvalidRoute)?; + if nodes[judgment as usize].opcode() != OpCode::TypeJudgment + || !matches!( + nodes[witness as usize].opcode(), + OpCode::KernelWitness | OpCode::Obligation + ) + || nodes[witness as usize].ty() != Some(judgment) + { + return Err(DecodeError::InvalidRoute); + } + attached[judgment as usize] = true; + attached[witness as usize] = true; + } + for (route, judgment) in routes { + if nodes[*judgment as usize].opcode() != OpCode::TypeEquality { + continue; + } + let witness = *routes + .get(&route.composed(EVIDENCE_LOCUS)) + .ok_or(DecodeError::InvalidRoute)?; + if nodes[witness as usize].opcode() != OpCode::EqualityWitness + || nodes[witness as usize].ty() != Some(*judgment) + { + return Err(DecodeError::InvalidRoute); + } + attached[*judgment as usize] = true; + attached[witness as usize] = true; + } + for (index, node) in nodes.iter().enumerate() { + if matches!( + node.opcode(), + OpCode::TypeJudgment + | OpCode::KernelWitness + | OpCode::Obligation + | OpCode::TypeEquality + | OpCode::EqualityWitness + ) && !attached[index] + { + return Err(DecodeError::InvalidRoute); + } + } + Ok(()) +} + +fn validate_port_law(opcode: OpCode, ports: &[Port], has_type: bool) -> Result<(), DecodeError> { + let valid = match opcode { + OpCode::TypeAtom => ports.is_empty() && !has_type, + OpCode::TypeMatrix => { + ports.len() == 1 && ports[0].role() == PortRole::Parameter && !has_type + } + OpCode::TypeFunction => { + ports.len() == 2 + && ports[0].role() == PortRole::Domain + && ports[1].role() == PortRole::Codomain + && !has_type + } + OpCode::TypeQuantity => { + ports.len() == 1 && ports[0].role() == PortRole::Parameter && !has_type + } + OpCode::Constraint => ports.len() == 1 && ports[0].role() == PortRole::Subject && !has_type, + OpCode::Value => ports.is_empty() && has_type, + OpCode::Compose | OpCode::MatMul | OpCode::Add | OpCode::Multiply | OpCode::Divide => { + ports.len() == 2 + && ports.iter().all(|port| port.role() == PortRole::Argument) + && has_type + } + OpCode::Sqrt => ports.len() == 1 && ports[0].role() == PortRole::Argument && has_type, + OpCode::TypeJudgment => { + ports.len() >= 3 + && ports[0].role() == PortRole::Subject + && ports[1..ports.len() - 1] + .iter() + .all(|port| port.role() == PortRole::Premise) + && ports + .last() + .is_some_and(|port| port.role() == PortRole::Conclusion) + && !has_type + } + OpCode::KernelWitness => ports.is_empty() && has_type, + OpCode::Obligation => ports.len() == 1 && ports[0].role() == PortRole::Premise && has_type, + OpCode::TypeEquality => { + ports.len() == 2 + && ports[0].role() == PortRole::Left + && ports[1].role() == PortRole::Right + && !has_type + } + OpCode::EqualityWitness => { + ports.iter().all(|port| port.role() == PortRole::Premise) && has_type + } + OpCode::ExtendContext => false, + }; + valid.then_some(()).ok_or(DecodeError::InvalidPortLaw) +} diff --git a/l64-native/src/context.rs b/l64-native/src/context.rs new file mode 100644 index 0000000..3d02fed --- /dev/null +++ b/l64-native/src/context.rs @@ -0,0 +1,22 @@ +use crate::{ContextId, NodeId}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(C)] +pub struct ContextDelta { + pub(crate) parent: ContextId, + pub(crate) binding: NodeId, +} + +impl ContextDelta { + pub(crate) fn from_raw(parent: ContextId, binding: NodeId) -> Self { + Self { parent, binding } + } + + pub fn parent(&self) -> ContextId { + self.parent + } + + pub fn binding(&self) -> Option { + (self.binding != u32::MAX).then_some(self.binding) + } +} diff --git a/l64-native/src/dimension.rs b/l64-native/src/dimension.rs new file mode 100644 index 0000000..922d2cf --- /dev/null +++ b/l64-native/src/dimension.rs @@ -0,0 +1,66 @@ +const AXIS_COUNT: usize = 7; +const USED_BITS: u32 = (AXIS_COUNT as u32) * 8; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(transparent)] +pub struct Dimension(u64); + +impl Dimension { + pub const DIMENSIONLESS: Self = Self(0); + pub const LENGTH: Self = Self(1); + pub const MASS: Self = Self(1 << 8); + pub const TIME: Self = Self(1 << 16); + + pub fn new(exponents: [i8; AXIS_COUNT]) -> Self { + let mut bits = 0_u64; + for (axis, exponent) in exponents.into_iter().enumerate() { + bits |= u64::from(exponent as u8) << (axis * 8); + } + Self(bits) + } + + pub fn exponents(self) -> [i8; AXIS_COUNT] { + let mut exponents = [0_i8; AXIS_COUNT]; + for (axis, exponent) in exponents.iter_mut().enumerate() { + *exponent = ((self.0 >> (axis * 8)) as u8) as i8; + } + exponents + } + + pub fn bits(self) -> u64 { + self.0 + } + + pub(crate) fn from_bits(bits: u64) -> Option { + (bits >> USED_BITS == 0).then_some(Self(bits)) + } + + pub fn multiply(self, other: Self) -> Option { + self.combine(other, i8::checked_add) + } + + pub fn divide(self, other: Self) -> Option { + self.combine(other, i8::checked_sub) + } + + pub fn square_root(self) -> Option { + let mut result = [0_i8; AXIS_COUNT]; + for (axis, exponent) in self.exponents().into_iter().enumerate() { + if exponent % 2 != 0 { + return None; + } + result[axis] = exponent / 2; + } + Some(Self::new(result)) + } + + fn combine(self, other: Self, operation: fn(i8, i8) -> Option) -> Option { + let left = self.exponents(); + let right = other.exponents(); + let mut result = [0_i8; AXIS_COUNT]; + for axis in 0..AXIS_COUNT { + result[axis] = operation(left[axis], right[axis])?; + } + Some(Self::new(result)) + } +} diff --git a/l64-native/src/dna.rs b/l64-native/src/dna.rs new file mode 100644 index 0000000..ad235fd --- /dev/null +++ b/l64-native/src/dna.rs @@ -0,0 +1,117 @@ +use crate::{DecodeError, Graph, SymbolicSeal, canonical_bytes, decode_canonical}; +use l64_symbolic::Composer; +use std::fmt; + +const DNA_MAGIC: &[u8; 4] = b"L64D"; +const DNA_VERSION: u16 = 2; +const DNA_FLAGS: u16 = 0; +const DNA_SYMBOL_DOMAIN: &str = "l64.native.dna.v2"; +const DNA_HEADER_BYTES: usize = 44; +pub const MAX_NATIVE_DNA_PAYLOAD_BYTES: usize = 1 << 28; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DnaError { + PayloadTooLarge, + Truncated, + BadMagic, + UnsupportedVersion { version: u16 }, + UnsupportedFlags { flags: u16 }, + TrailingBytes, + SealMismatch, + Canonical(DecodeError), +} + +impl fmt::Display for DnaError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::PayloadTooLarge => f.write_str("L64D payload exceeds the native size limit"), + Self::Truncated => f.write_str("L64D authority is truncated"), + Self::BadMagic => f.write_str("input is not L64D authority"), + Self::UnsupportedVersion { version } => write!(f, "unsupported L64D version {version}"), + Self::UnsupportedFlags { flags } => write!(f, "unsupported L64D flags {flags}"), + Self::TrailingBytes => f.write_str("L64D authority has trailing bytes"), + Self::SealMismatch => { + f.write_str("L64D symbolic seal does not match its canonical payload") + } + Self::Canonical(error) => write!(f, "invalid canonical L64D payload: {error}"), + } + } +} + +impl std::error::Error for DnaError {} + +impl From for DnaError { + fn from(value: DecodeError) -> Self { + Self::Canonical(value) + } +} + +pub fn dna_bytes(graph: &Graph) -> Result, DnaError> { + let payload = canonical_bytes(graph); + if payload.len() > MAX_NATIVE_DNA_PAYLOAD_BYTES || payload.len() > u32::MAX as usize { + return Err(DnaError::PayloadTooLarge); + } + + let mut out = Vec::with_capacity(DNA_HEADER_BYTES + payload.len()); + out.extend_from_slice(DNA_MAGIC); + out.extend_from_slice(&DNA_VERSION.to_le_bytes()); + out.extend_from_slice(&DNA_FLAGS.to_le_bytes()); + out.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + out.extend_from_slice(&dna_seal(graph, payload.len()).to_bytes()); + out.extend_from_slice(&payload); + Ok(out) +} + +pub fn decode_dna(bytes: &[u8]) -> Result { + if bytes.len() < DNA_HEADER_BYTES { + return Err(DnaError::Truncated); + } + if &bytes[..4] != DNA_MAGIC { + return Err(DnaError::BadMagic); + } + + let version = u16::from_le_bytes(bytes[4..6].try_into().expect("fixed DNA version field")); + if version != DNA_VERSION { + return Err(DnaError::UnsupportedVersion { version }); + } + let flags = u16::from_le_bytes(bytes[6..8].try_into().expect("fixed DNA flags field")); + if flags != DNA_FLAGS { + return Err(DnaError::UnsupportedFlags { flags }); + } + let payload_len = + u32::from_le_bytes(bytes[8..12].try_into().expect("fixed DNA length field")) as usize; + if payload_len > MAX_NATIVE_DNA_PAYLOAD_BYTES { + return Err(DnaError::PayloadTooLarge); + } + + let expected_len = DNA_HEADER_BYTES + .checked_add(payload_len) + .ok_or(DnaError::PayloadTooLarge)?; + if bytes.len() < expected_len { + return Err(DnaError::Truncated); + } + if bytes.len() > expected_len { + return Err(DnaError::TrailingBytes); + } + + let stored_seal = SymbolicSeal::from_bytes( + bytes[12..44] + .try_into() + .expect("fixed DNA symbolic seal field"), + ); + let payload = &bytes[DNA_HEADER_BYTES..]; + let graph = decode_canonical(payload)?; + if stored_seal != dna_seal(&graph, payload.len()) { + return Err(DnaError::SealMismatch); + } + Ok(graph) +} + +fn dna_seal(graph: &Graph, payload_len: usize) -> SymbolicSeal { + let mut composer = Composer::new(DNA_SYMBOL_DOMAIN); + composer + .u16("version", DNA_VERSION) + .u64("payload-length", payload_len as u64) + .ordered("state", &[graph.state_symbol().root]); + composer.finish() +} diff --git a/l64-native/src/graph.rs b/l64-native/src/graph.rs new file mode 100644 index 0000000..bfa7fec --- /dev/null +++ b/l64-native/src/graph.rs @@ -0,0 +1,100 @@ +use std::collections::BTreeMap; + +use crate::kernel::{ConstraintState, EqualityRule, EvidencePlan}; +use crate::{ + ClosureState, ClosureTransition, ConstraintKind, ContextDelta, Dimension, JournalEvent, + LocusWord, Obstruction, OpCode, Port, PortRole, Route, StateSymbol, SymbolicSeal, +}; + +pub type NodeId = u32; +pub type ContextId = u32; +pub type EventId = u32; + +pub const ROOT_CONTEXT: ContextId = 0; +const NO_NODE: NodeId = u32::MAX; +const META_TYPE: NodeId = u32::MAX; +const NO_EVENT: EventId = u32::MAX; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(C)] +pub struct Node { + payload: u64, + context: ContextId, + ty: NodeId, + first_port: u32, + opcode: u16, + port_count: u16, +} + +impl Node { + pub(crate) fn from_raw( + payload: u64, + context: ContextId, + ty: NodeId, + first_port: u32, + opcode: OpCode, + port_count: u16, + ) -> Self { + Self { + payload, + context, + ty, + first_port, + opcode: opcode as u16, + port_count, + } + } + + pub fn opcode(&self) -> OpCode { + OpCode::from_raw(self.opcode).expect("stored opcode is validated at insertion") + } + + pub fn context(&self) -> ContextId { + self.context + } + + pub fn ty(&self) -> Option { + (self.ty != META_TYPE).then_some(self.ty) + } + + pub fn payload(&self) -> u64 { + self.payload + } + + pub fn port_range(&self) -> core::ops::Range { + let start = self.first_port as usize; + start..start + self.port_count as usize + } +} + +#[derive(Debug, Clone, Default)] +struct DerivedIndex { + reverse: Vec>, + by_context: Vec>, + primary_route: Vec>, +} + +#[derive(Debug, Clone)] +pub struct Graph { + nodes: Vec, + ports: Vec, + contexts: Vec, + routes: BTreeMap, + journal: Vec, + symbol: StateSymbol, + derived: DerivedIndex, + track_mutations: bool, +} + +impl Default for Graph { + fn default() -> Self { + Self::new() + } +} + +include!("graph/construction.rs"); +include!("graph/typing.rs"); +include!("graph/storage.rs"); +include!("graph/context.rs"); +include!("graph/derived.rs"); +include!("graph/closure.rs"); diff --git a/l64-native/src/graph/closure.rs b/l64-native/src/graph/closure.rs new file mode 100644 index 0000000..f750057 --- /dev/null +++ b/l64-native/src/graph/closure.rs @@ -0,0 +1,202 @@ +impl Graph { + pub fn closure_state( + &self, + context: ContextId, + node: NodeId, + ) -> Result { + self.ensure_context(context)?; + self.ensure_node(node)?; + let mut memo = vec![None; self.node_count()]; + self.closure_state_inner(context, node, &mut memo) + } + + pub fn context_closure_states( + &self, + context: ContextId, + ) -> Result, Obstruction> { + let nodes = self.visible_nodes(context)?; + let mut memo = vec![None; self.node_count()]; + let mut states = Vec::with_capacity(nodes.len()); + for node in nodes { + states.push((node, self.closure_state_inner(context, node, &mut memo)?)); + } + Ok(states) + } + + pub fn context_closure(&self, context: ContextId) -> Result { + let mut state = ClosureState::Closed; + for (_, node_state) in self.context_closure_states(context)? { + state = state.combine(node_state); + if state == ClosureState::Invalid { + break; + } + } + Ok(state) + } + + pub fn global_closure(&self) -> Result { + let mut state = ClosureState::Closed; + for context in 0..self.context_count() as ContextId { + state = state.combine(self.context_closure(context)?); + if state == ClosureState::Invalid { + break; + } + } + Ok(state) + } + + pub fn closure_transitions( + &self, + from_context: ContextId, + to_context: ContextId, + ) -> Result, Obstruction> { + self.ensure_context(from_context)?; + let refinement = self.ensure_context(to_context)?; + if refinement.parent() != from_context { + return Err(Obstruction::ContextNotDirectRefinement { + parent: from_context, + child: to_context, + }); + } + let cause = refinement.binding().ok_or(Obstruction::UnknownContext { + context: to_context, + })?; + let (subject, _, _) = self.constraint_parts(cause).map_err(|_| { + Obstruction::RefinementBindingNotConstraint { + context: to_context, + binding: cause, + } + })?; + let affected = self.affected_nodes(subject)?; + let mut before_memo = vec![None; self.node_count()]; + let mut after_memo = vec![None; self.node_count()]; + let mut transitions = Vec::new(); + for node in affected { + let record = self.ensure_node(node)?; + if !self.context_visible(record.context(), from_context) { + continue; + } + let before = self.closure_state_inner(from_context, node, &mut before_memo)?; + let after = self.closure_state_inner(to_context, node, &mut after_memo)?; + if before != after { + transitions.push(ClosureTransition::new( + node, + before, + after, + cause, + from_context, + to_context, + )); + } + } + Ok(transitions) + } + + fn closure_state_inner( + &self, + context: ContextId, + node: NodeId, + memo: &mut [Option], + ) -> Result { + if let Some(state) = memo[node as usize] { + return Ok(state); + } + let record = self.ensure_node(node)?; + if !self.context_visible(record.context(), context) { + memo[node as usize] = Some(ClosureState::Invalid); + return Ok(ClosureState::Invalid); + } + + let state = match record.opcode() { + opcode if opcode.is_executable() => { + self.executable_closure_state(context, node, memo)? + } + OpCode::TypeJudgment => { + let subject = self + .ports(node) + .and_then(|ports| ports.first()) + .map(Port::target) + .ok_or(Obstruction::MalformedEvidence { node })?; + self.closure_state_inner(context, subject, memo)? + } + OpCode::KernelWitness | OpCode::Obligation => { + let judgment = record + .ty() + .ok_or(Obstruction::MalformedEvidence { node })?; + self.closure_state_inner(context, judgment, memo)? + } + OpCode::TypeEquality => self.equality_closure_state(context, node, memo)?, + OpCode::EqualityWitness => { + let judgment = record + .ty() + .ok_or(Obstruction::MalformedEquality { node })?; + self.closure_state_inner(context, judgment, memo)? + } + _ => ClosureState::Closed, + }; + memo[node as usize] = Some(state); + Ok(state) + } + + fn executable_closure_state( + &self, + context: ContextId, + node: NodeId, + memo: &mut [Option], + ) -> Result { + let record = self.ensure_node(node)?; + let ports = self + .ports(node) + .ok_or(Obstruction::UnknownNode { node })?; + let inputs = ports.iter().map(Port::target).collect::>(); + let mut state = ClosureState::Closed; + for input in &inputs { + state = state.combine(self.closure_state_inner(context, *input, memo)?); + } + if state == ClosureState::Invalid { + return Ok(state); + } + let output_type = record.ty().ok_or(Obstruction::ExpectedType { node })?; + let own = match self.validate_operation(context, record.opcode(), &inputs, output_type) { + Ok(EvidencePlan::Witness) => ClosureState::Closed, + Ok(EvidencePlan::Obligation { .. }) => ClosureState::Open, + Err(_) => ClosureState::Invalid, + }; + Ok(state.combine(own)) + } + + fn equality_closure_state( + &self, + context: ContextId, + judgment: NodeId, + memo: &mut [Option], + ) -> Result { + let (left, right) = self.equality_parts(judgment)?; + let mut state = self + .closure_state_inner(context, left, memo)? + .combine(self.closure_state_inner(context, right, memo)?); + if state == ClosureState::Invalid { + return Ok(state); + } + let witness = self + .equality_witness_for(judgment) + .ok_or(Obstruction::MalformedEquality { node: judgment })?; + let witness_node = self.ensure_node(witness)?; + let rule = EqualityRule::from_raw(witness_node.payload() as u8) + .ok_or(Obstruction::MalformedEquality { node: witness })?; + let premise_ports = self + .ports(witness) + .ok_or(Obstruction::MalformedEquality { node: witness })?; + let premises = premise_ports.iter().map(Port::target).collect::>(); + for premise in &premises { + state = state.combine(self.closure_state_inner(context, *premise, memo)?); + } + if state == ClosureState::Invalid { + return Ok(state); + } + match self.validate_equality_rule(context, left, right, rule, &premises) { + Ok(()) => Ok(state), + Err(_) => Ok(ClosureState::Invalid), + } + } +} diff --git a/l64-native/src/graph/construction.rs b/l64-native/src/graph/construction.rs new file mode 100644 index 0000000..c7525f0 --- /dev/null +++ b/l64-native/src/graph/construction.rs @@ -0,0 +1,379 @@ +impl Graph { + pub(crate) fn from_decoded_parts( + nodes: Vec, + ports: Vec, + contexts: Vec, + routes: BTreeMap, + ) -> Self { + let mut graph = Self { + nodes, + ports, + contexts, + routes, + journal: Vec::new(), + symbol: StateSymbol::ZERO, + derived: DerivedIndex::default(), + track_mutations: true, + }; + graph.rebuild_derived_index(); + graph.symbol = crate::symbol::state_symbol(&graph); + graph + } + + pub fn new() -> Self { + let mut graph = Self { + nodes: Vec::new(), + ports: Vec::new(), + contexts: vec![ContextDelta::root()], + routes: BTreeMap::new(), + journal: Vec::new(), + symbol: StateSymbol::ZERO, + derived: DerivedIndex::empty(1), + track_mutations: true, + }; + graph.symbol = crate::symbol::state_symbol(&graph); + graph + } + + pub(crate) fn new_bulk() -> Self { + Self { + nodes: Vec::new(), + ports: Vec::new(), + contexts: vec![ContextDelta::root()], + routes: BTreeMap::new(), + journal: Vec::new(), + symbol: StateSymbol::ZERO, + derived: DerivedIndex::empty(1), + track_mutations: false, + } + } + + pub(crate) fn finish_bulk(mut self) -> Self { + debug_assert!(!self.track_mutations); + self.symbol = crate::symbol::state_symbol(&self); + self.track_mutations = true; + self + } + + fn record_mutation(&mut self, operation: OpCode, subject: NodeId) -> SymbolicSeal { + if !self.track_mutations { + return SymbolicSeal::ZERO; + } + let before = self.symbol.root; + let next = crate::symbol::state_symbol(self); + let after = next.root; + self.push_event(operation, subject, before, after); + self.symbol = next; + after + } + + pub fn node(&self, id: NodeId) -> Option<&Node> { + self.nodes.get(id as usize) + } + + pub fn ports(&self, node: NodeId) -> Option<&[Port]> { + let node = self.node(node)?; + self.ports.get(node.port_range()) + } + + pub fn resolve(&self, route: &Route) -> Option { + self.routes.get(route).copied() + } + + pub fn node_count(&self) -> usize { + self.nodes.len() + } + + pub fn port_count(&self) -> usize { + self.ports.len() + } + + pub fn context_count(&self) -> usize { + self.contexts.len() + } + + pub fn context(&self, id: ContextId) -> Option<&ContextDelta> { + self.contexts.get(id as usize) + } + + pub fn journal_len(&self) -> usize { + self.journal.len() + } + + pub fn state_symbol(&self) -> StateSymbol { + self.symbol + } + + pub fn exact_state_identity(&self) -> crate::SymbolicIdentity { + crate::state_identity(self) + } + + pub fn journal(&self) -> &[JournalEvent] { + &self.journal + } + + pub fn extend_context( + &mut self, + parent: ContextId, + binding: NodeId, + ) -> Result { + self.ensure_context(parent)?; + self.ensure_node(binding)?; + self.validate_context_binding(parent, binding)?; + let id = self.contexts.len() as ContextId; + self.contexts.push(ContextDelta { parent, binding }); + self.derived.by_context.push(Vec::new()); + self.record_mutation(OpCode::ExtendContext, binding); + Ok(id) + } + + pub fn declare_atom_type( + &mut self, + route: Route, + atom_code: LocusWord, + ) -> Result { + self.insert_committed_node( + route, + ROOT_CONTEXT, + META_TYPE, + OpCode::TypeAtom, + atom_code.0, + &[], + ) + } + + pub fn declare_matrix_type( + &mut self, + route: Route, + element: NodeId, + rows: u32, + cols: u32, + ) -> Result { + self.ensure_type(element)?; + let payload = u64::from(rows) << 32 | u64::from(cols); + let port = Port::new(element, PortRole::Parameter, 0); + self.insert_committed_node( + route, + ROOT_CONTEXT, + META_TYPE, + OpCode::TypeMatrix, + payload, + &[port], + ) + } + + pub fn declare_function_type( + &mut self, + route: Route, + domain: NodeId, + codomain: NodeId, + ) -> Result { + self.ensure_type(domain)?; + self.ensure_type(codomain)?; + let ports = [ + Port::new(domain, PortRole::Domain, 0), + Port::new(codomain, PortRole::Codomain, 1), + ]; + self.insert_committed_node( + route, + ROOT_CONTEXT, + META_TYPE, + OpCode::TypeFunction, + 0, + &ports, + ) + } + + pub fn declare_quantity_type( + &mut self, + route: Route, + carrier: NodeId, + dimension: Dimension, + ) -> Result { + self.ensure_type(carrier)?; + let port = Port::new(carrier, PortRole::Parameter, 0); + self.insert_committed_node( + route, + ROOT_CONTEXT, + META_TYPE, + OpCode::TypeQuantity, + dimension.bits(), + &[port], + ) + } + + pub fn declare_constraint( + &mut self, + route: Route, + context: ContextId, + subject: NodeId, + kind: ConstraintKind, + holds: bool, + ) -> Result { + self.ensure_context(context)?; + self.ensure_node(subject)?; + let port = Port::new(subject, PortRole::Subject, 0); + self.insert_committed_node( + route, + context, + META_TYPE, + OpCode::Constraint, + kind.payload(holds), + &[port], + ) + } + + pub fn insert_value( + &mut self, + route: Route, + context: ContextId, + ty: NodeId, + ) -> Result { + self.ensure_context(context)?; + let type_node = self.ensure_type(ty)?; + if matches!(type_node.opcode(), OpCode::TypeJudgment | OpCode::TypeEquality) { + return Err(Obstruction::EvidenceOnlyType { node: ty }); + } + self.insert_committed_node(route, context, ty, OpCode::Value, 0, &[]) + } + + pub(crate) fn insert_admitted_operation( + &mut self, + routes: [Route; 3], + context: ContextId, + ty: NodeId, + opcode: OpCode, + inputs: &[NodeId], + evidence_plan: EvidencePlan, + ) -> crate::CommitResult { + let [route, judgment_route, evidence_route] = routes; + let operation = self.nodes.len() as NodeId; + let operation_first_port = self.ports.len() as u32; + self.ports.extend( + inputs + .iter() + .enumerate() + .map(|(ordinal, target)| Port::new(*target, PortRole::Argument, ordinal as u16)), + ); + self.nodes.push(Node { + payload: 0, + context, + ty, + first_port: operation_first_port, + opcode: opcode as u16, + port_count: inputs.len() as u16, + }); + + let judgment = self.nodes.len() as NodeId; + let judgment_first_port = self.ports.len() as u32; + self.ports.push(Port::new(operation, PortRole::Subject, 0)); + self.ports.extend( + inputs + .iter() + .enumerate() + .map(|(ordinal, target)| Port::new(*target, PortRole::Premise, ordinal as u16 + 1)), + ); + self.ports + .push(Port::new(ty, PortRole::Conclusion, inputs.len() as u16 + 1)); + self.nodes.push(Node { + payload: opcode as u64, + context, + ty: META_TYPE, + first_port: judgment_first_port, + opcode: OpCode::TypeJudgment as u16, + port_count: inputs.len() as u16 + 2, + }); + + let evidence = self.nodes.len() as NodeId; + let evidence_first_port = self.ports.len() as u32; + let (evidence_opcode, evidence_payload, evidence_port_count) = match evidence_plan { + EvidencePlan::Witness => (OpCode::KernelWitness, 0, 0), + EvidencePlan::Obligation { kind, subject } => { + self.ports.push(Port::new(subject, PortRole::Premise, 0)); + (OpCode::Obligation, kind.payload(true), 1) + } + }; + self.nodes.push(Node { + payload: evidence_payload, + context, + ty: judgment, + first_port: evidence_first_port, + opcode: evidence_opcode as u16, + port_count: evidence_port_count, + }); + + self.routes.insert(route.clone(), operation); + self.routes.insert(judgment_route.clone(), judgment); + self.routes.insert(evidence_route.clone(), evidence); + self.register_derived_node(operation); + self.register_derived_node(judgment); + self.register_derived_node(evidence); + self.register_derived_route(&route, operation); + self.register_derived_route(&judgment_route, judgment); + self.register_derived_route(&evidence_route, evidence); + + let after = self.record_mutation(opcode, operation); + crate::CommitResult { + node: operation, + evidence, + event: self.journal.len().saturating_sub(1) as EventId, + symbol: after, + } + } + + pub(crate) fn insert_admitted_equality( + &mut self, + routes: [Route; 2], + context: ContextId, + left: NodeId, + right: NodeId, + rule: EqualityRule, + premises: &[NodeId], + ) -> crate::CommitResult { + let [route, evidence_route] = routes; + + let judgment = self.nodes.len() as NodeId; + let judgment_first_port = self.ports.len() as u32; + self.ports.push(Port::new(left, PortRole::Left, 0)); + self.ports.push(Port::new(right, PortRole::Right, 1)); + self.nodes.push(Node { + payload: 0, + context, + ty: META_TYPE, + first_port: judgment_first_port, + opcode: OpCode::TypeEquality as u16, + port_count: 2, + }); + + let evidence = self.nodes.len() as NodeId; + let evidence_first_port = self.ports.len() as u32; + self.ports.extend( + premises + .iter() + .enumerate() + .map(|(ordinal, target)| Port::new(*target, PortRole::Premise, ordinal as u16)), + ); + self.nodes.push(Node { + payload: rule as u64, + context, + ty: judgment, + first_port: evidence_first_port, + opcode: OpCode::EqualityWitness as u16, + port_count: premises.len() as u16, + }); + + self.routes.insert(route.clone(), judgment); + self.routes.insert(evidence_route.clone(), evidence); + self.register_derived_node(judgment); + self.register_derived_node(evidence); + self.register_derived_route(&route, judgment); + self.register_derived_route(&evidence_route, evidence); + let after = self.record_mutation(OpCode::EqualityWitness, judgment); + crate::CommitResult { + node: judgment, + evidence, + event: self.journal.len().saturating_sub(1) as EventId, + symbol: after, + } + } +} diff --git a/l64-native/src/graph/context.rs b/l64-native/src/graph/context.rs new file mode 100644 index 0000000..a1821a8 --- /dev/null +++ b/l64-native/src/graph/context.rs @@ -0,0 +1,8 @@ +impl ContextDelta { + fn root() -> Self { + Self { + parent: ROOT_CONTEXT, + binding: NO_NODE, + } + } +} diff --git a/l64-native/src/graph/derived.rs b/l64-native/src/graph/derived.rs new file mode 100644 index 0000000..fea152a --- /dev/null +++ b/l64-native/src/graph/derived.rs @@ -0,0 +1,105 @@ +impl DerivedIndex { + fn empty(context_count: usize) -> Self { + Self { + reverse: Vec::new(), + by_context: vec![Vec::new(); context_count], + primary_route: Vec::new(), + } + } +} + +impl Graph { + fn rebuild_derived_index(&mut self) { + self.derived = DerivedIndex::empty(self.contexts.len()); + self.derived.reverse.resize_with(self.nodes.len(), Vec::new); + for node in 0..self.nodes.len() as NodeId { + self.register_derived_node(node); + } + let routes = self + .routes + .iter() + .map(|(route, node)| (route.clone(), *node)) + .collect::>(); + for (route, node) in routes { + self.register_derived_route(&route, node); + } + } + + fn register_derived_node(&mut self, node: NodeId) { + let record = self.nodes[node as usize]; + while self.derived.reverse.len() <= node as usize { + self.derived.reverse.push(Vec::new()); + } + while self.derived.by_context.len() <= record.context() as usize { + self.derived.by_context.push(Vec::new()); + } + self.derived.by_context[record.context() as usize].push(node); + + let mut dependencies = Vec::new(); + if let Some(ty) = record.ty() { + dependencies.push(ty); + } + dependencies.extend(self.ports[record.port_range()].iter().map(Port::target)); + dependencies.sort_unstable(); + dependencies.dedup(); + for dependency in dependencies { + self.derived.reverse[dependency as usize].push(node); + } + } + + fn register_derived_route(&mut self, route: &Route, node: NodeId) { + while self.derived.primary_route.len() <= node as usize { + self.derived.primary_route.push(None); + } + let slot = &mut self.derived.primary_route[node as usize]; + if slot.as_ref().is_none_or(|current| route < current) { + *slot = Some(route.clone()); + } + } + + pub(crate) fn derived_route_for_node(&self, node: NodeId) -> Option<&Route> { + self.derived + .primary_route + .get(node as usize) + .and_then(Option::as_ref) + } + + pub fn direct_dependents(&self, node: NodeId) -> Result<&[NodeId], Obstruction> { + self.ensure_node(node)?; + Ok(&self.derived.reverse[node as usize]) + } + + pub fn affected_nodes(&self, seed: NodeId) -> Result, Obstruction> { + self.ensure_node(seed)?; + let mut affected = std::collections::BTreeSet::from([seed]); + let mut queue = std::collections::VecDeque::from([seed]); + while let Some(current) = queue.pop_front() { + for dependent in &self.derived.reverse[current as usize] { + if affected.insert(*dependent) { + queue.push_back(*dependent); + } + } + } + Ok(affected.into_iter().collect()) + } + + pub fn visible_nodes(&self, context: ContextId) -> Result, Obstruction> { + self.ensure_context(context)?; + let mut contexts = Vec::new(); + let mut cursor = context; + loop { + contexts.push(cursor); + if cursor == ROOT_CONTEXT { + break; + } + cursor = self.ensure_context(cursor)?.parent(); + } + contexts.reverse(); + let mut nodes = Vec::new(); + for context in contexts { + nodes.extend_from_slice(&self.derived.by_context[context as usize]); + } + nodes.sort_unstable(); + Ok(nodes) + } +} diff --git a/l64-native/src/graph/storage.rs b/l64-native/src/graph/storage.rs new file mode 100644 index 0000000..f523ad3 --- /dev/null +++ b/l64-native/src/graph/storage.rs @@ -0,0 +1,126 @@ +impl Graph { + pub(crate) fn validate_context_consistency(&self) -> Result<(), Obstruction> { + for context in 1..self.contexts.len() as ContextId { + let delta = self.ensure_context(context)?; + let binding = delta + .binding() + .ok_or(Obstruction::UnknownContext { context })?; + self.validate_context_binding(delta.parent(), binding)?; + } + Ok(()) + } + + fn validate_context_binding( + &self, + parent: ContextId, + binding: NodeId, + ) -> Result<(), Obstruction> { + let node = self.ensure_node(binding)?; + if node.opcode() != OpCode::Constraint { + return Ok(()); + } + let (subject, kind, holds) = self.constraint_parts(binding)?; + let inherited = self.constraint_state(parent, subject, kind)?; + if matches!( + (inherited, holds), + (ConstraintState::Proven, false) | (ConstraintState::Refuted, true) + ) { + return Err(Obstruction::ContradictoryConstraint { subject, kind }); + } + Ok(()) + } + + pub(crate) fn ensure_node(&self, id: NodeId) -> Result<&Node, Obstruction> { + self.node(id).ok_or(Obstruction::UnknownNode { node: id }) + } + + pub(crate) fn ensure_type(&self, id: NodeId) -> Result<&Node, Obstruction> { + let node = self.ensure_node(id)?; + if !node.opcode().is_type() { + return Err(Obstruction::ExpectedType { node: id }); + } + Ok(node) + } + + pub(crate) fn ensure_context(&self, id: ContextId) -> Result<&ContextDelta, Obstruction> { + self.contexts + .get(id as usize) + .ok_or(Obstruction::UnknownContext { context: id }) + } + + fn insert_committed_node( + &mut self, + route: Route, + context: ContextId, + ty: NodeId, + opcode: OpCode, + payload: u64, + ports: &[Port], + ) -> Result { + if self.routes.contains_key(&route) { + return Err(Obstruction::RouteOccupied); + } + self.ensure_context(context)?; + for port in ports { + self.ensure_node(port.target())?; + } + if ty != META_TYPE { + self.ensure_type(ty)?; + } + + let node = self.nodes.len() as NodeId; + let first_port = self.ports.len() as u32; + self.ports.extend_from_slice(ports); + self.nodes.push(Node { + payload, + context, + ty, + first_port, + opcode: opcode as u16, + port_count: ports.len() as u16, + }); + self.routes.insert(route.clone(), node); + self.register_derived_node(node); + self.register_derived_route(&route, node); + self.record_mutation(opcode, node); + Ok(node) + } + + fn push_event( + &mut self, + operation: OpCode, + subject: NodeId, + before: SymbolicSeal, + after: SymbolicSeal, + ) { + let parent = self + .journal + .len() + .checked_sub(1) + .map(|value| value as EventId) + .unwrap_or(NO_EVENT); + self.journal.push(JournalEvent { + operation, + subject, + before, + after, + parent, + }); + } + + pub(crate) fn nodes_raw(&self) -> &[Node] { + &self.nodes + } + + pub(crate) fn ports_raw(&self) -> &[Port] { + &self.ports + } + + pub(crate) fn contexts_raw(&self) -> &[ContextDelta] { + &self.contexts + } + + pub(crate) fn routes_raw(&self) -> &BTreeMap { + &self.routes + } +} diff --git a/l64-native/src/graph/typing.rs b/l64-native/src/graph/typing.rs new file mode 100644 index 0000000..3e90405 --- /dev/null +++ b/l64-native/src/graph/typing.rs @@ -0,0 +1,126 @@ +impl Graph { + pub(crate) fn function_parts(&self, ty: NodeId) -> Result<(NodeId, NodeId), Obstruction> { + let node = self.ensure_type(ty)?; + if node.opcode() != OpCode::TypeFunction { + return Err(Obstruction::ExpectedFunctionType { node: ty }); + } + let ports = self + .ports(ty) + .ok_or(Obstruction::UnknownNode { node: ty })?; + if ports.len() != 2 { + return Err(Obstruction::MalformedType { node: ty }); + } + Ok((ports[0].target(), ports[1].target())) + } + + pub(crate) fn matrix_parts(&self, ty: NodeId) -> Result<(NodeId, u32, u32), Obstruction> { + let node = self.ensure_type(ty)?; + if node.opcode() != OpCode::TypeMatrix { + return Err(Obstruction::ExpectedMatrixType { node: ty }); + } + let ports = self + .ports(ty) + .ok_or(Obstruction::UnknownNode { node: ty })?; + if ports.len() != 1 { + return Err(Obstruction::MalformedType { node: ty }); + } + Ok(( + ports[0].target(), + (node.payload >> 32) as u32, + node.payload as u32, + )) + } + + pub(crate) fn matches_function_type( + &self, + ty: NodeId, + domain: NodeId, + codomain: NodeId, + ) -> bool { + self.function_parts(ty) == Ok((domain, codomain)) + } + + pub(crate) fn quantity_parts(&self, ty: NodeId) -> Result<(NodeId, Dimension), Obstruction> { + let node = self.ensure_type(ty)?; + if node.opcode() != OpCode::TypeQuantity { + return Err(Obstruction::ExpectedQuantityType { node: ty }); + } + let ports = self + .ports(ty) + .ok_or(Obstruction::UnknownNode { node: ty })?; + let dimension = + Dimension::from_bits(node.payload()).ok_or(Obstruction::MalformedType { node: ty })?; + if ports.len() != 1 { + return Err(Obstruction::MalformedType { node: ty }); + } + Ok((ports[0].target(), dimension)) + } + + pub(crate) fn matches_matrix_type( + &self, + ty: NodeId, + element: NodeId, + rows: u32, + cols: u32, + ) -> bool { + self.matrix_parts(ty) == Ok((element, rows, cols)) + } + + pub(crate) fn matches_quantity_type( + &self, + ty: NodeId, + carrier: NodeId, + dimension: Dimension, + ) -> bool { + self.quantity_parts(ty) == Ok((carrier, dimension)) + } + + pub(crate) fn constraint_parts( + &self, + node: NodeId, + ) -> Result<(NodeId, ConstraintKind, bool), Obstruction> { + let constraint = self.ensure_node(node)?; + if constraint.opcode() != OpCode::Constraint { + return Err(Obstruction::MalformedConstraint { node }); + } + let ports = self + .ports(node) + .ok_or(Obstruction::MalformedConstraint { node })?; + let (kind, holds) = ConstraintKind::from_payload(constraint.payload()) + .ok_or(Obstruction::MalformedConstraint { node })?; + if ports.len() != 1 || ports[0].role() != PortRole::Subject { + return Err(Obstruction::MalformedConstraint { node }); + } + Ok((ports[0].target(), kind, holds)) + } + + pub(crate) fn constraint_state( + &self, + context: ContextId, + subject: NodeId, + kind: ConstraintKind, + ) -> Result { + let mut cursor = context; + loop { + let delta = self.ensure_context(cursor)?; + if let Some(binding) = delta.binding() + && self + .node(binding) + .is_some_and(|node| node.opcode() == OpCode::Constraint) + { + let (bound_subject, bound_kind, holds) = self.constraint_parts(binding)?; + if bound_subject == subject && bound_kind == kind { + return Ok(if holds { + ConstraintState::Proven + } else { + ConstraintState::Refuted + }); + } + } + if cursor == ROOT_CONTEXT { + return Ok(ConstraintState::Unknown); + } + cursor = delta.parent(); + } + } +} diff --git a/l64-native/src/journal.rs b/l64-native/src/journal.rs new file mode 100644 index 0000000..9c10537 --- /dev/null +++ b/l64-native/src/journal.rs @@ -0,0 +1,32 @@ +use crate::{EventId, NodeId, OpCode, SymbolicSeal}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct JournalEvent { + pub(crate) operation: OpCode, + pub(crate) subject: NodeId, + pub(crate) before: SymbolicSeal, + pub(crate) after: SymbolicSeal, + pub(crate) parent: EventId, +} + +impl JournalEvent { + pub fn operation(&self) -> OpCode { + self.operation + } + + pub fn subject(&self) -> NodeId { + self.subject + } + + pub fn before(&self) -> SymbolicSeal { + self.before + } + + pub fn after(&self) -> SymbolicSeal { + self.after + } + + pub fn parent(&self) -> Option { + (self.parent != u32::MAX).then_some(self.parent) + } +} diff --git a/l64-native/src/kernel.rs b/l64-native/src/kernel.rs new file mode 100644 index 0000000..38d59e2 --- /dev/null +++ b/l64-native/src/kernel.rs @@ -0,0 +1,7 @@ +use crate::{ContextId, Dimension, Graph, LocusWord, NodeId, ROOT_CONTEXT, Route}; + +include!("kernel/types.rs"); +include!("kernel/proposal.rs"); +include!("kernel/transaction.rs"); +include!("kernel/validation.rs"); +include!("kernel/equality.rs"); diff --git a/l64-native/src/kernel/equality.rs b/l64-native/src/kernel/equality.rs new file mode 100644 index 0000000..efadfc4 --- /dev/null +++ b/l64-native/src/kernel/equality.rs @@ -0,0 +1,3 @@ +include!("equality/proof.rs"); +include!("equality/validation.rs"); +include!("equality/canonical.rs"); diff --git a/l64-native/src/kernel/equality/canonical.rs b/l64-native/src/kernel/equality/canonical.rs new file mode 100644 index 0000000..104c942 --- /dev/null +++ b/l64-native/src/kernel/equality/canonical.rs @@ -0,0 +1,125 @@ +impl Graph { + pub fn equality_path( + &self, + context: ContextId, + left: NodeId, + right: NodeId, + ) -> Result, Obstruction> { + self.ensure_context(context)?; + let left_node = self.ensure_node(left)?; + let right_node = self.ensure_node(right)?; + if !self.equality_endpoint_allowed(left_node) + || !self.equality_endpoint_allowed(right_node) + || !self.context_visible(left_node.context(), context) + || !self.context_visible(right_node.context(), context) + { + return Err(Obstruction::NoEqualityPath { left, right }); + } + if left == right { + return Ok(Vec::new()); + } + + let mut queue = std::collections::VecDeque::from([left]); + let mut parent = std::collections::BTreeMap::::new(); + parent.insert(left, (left, u32::MAX)); + while let Some(current) = queue.pop_front() { + for &judgment in self.direct_dependents(current)? { + let equality = self + .node(judgment) + .ok_or(Obstruction::UnknownNode { node: judgment })?; + if equality.opcode() != OpCode::TypeEquality + || !self.context_visible(equality.context(), context) + { + continue; + } + let (edge_left, edge_right) = self.equality_parts(judgment)?; + let next = if edge_left == current { + Some(edge_right) + } else if edge_right == current { + Some(edge_left) + } else { + None + }; + let Some(next) = next else { continue }; + if parent.contains_key(&next) { + continue; + } + parent.insert(next, (current, judgment)); + if next == right { + let mut path = Vec::new(); + let mut cursor = right; + while cursor != left { + let (previous, proof) = parent[&cursor]; + path.push(proof); + cursor = previous; + } + path.reverse(); + return Ok(path); + } + queue.push_back(next); + } + } + Err(Obstruction::NoEqualityPath { left, right }) + } + + pub fn canonical_representative( + &self, + context: ContextId, + node: NodeId, + ) -> Result { + self.ensure_context(context)?; + let subject = self.ensure_node(node)?; + if !self.equality_endpoint_allowed(subject) || !self.context_visible(subject.context(), context) + { + return Err(Obstruction::UncanonicalizableNode { node }); + } + + let mut members = std::collections::BTreeSet::from([node]); + let mut queue = std::collections::VecDeque::from([node]); + while let Some(current) = queue.pop_front() { + for &judgment in self.direct_dependents(current)? { + let equality = self + .node(judgment) + .ok_or(Obstruction::UnknownNode { node: judgment })?; + if equality.opcode() != OpCode::TypeEquality + || !self.context_visible(equality.context(), context) + { + continue; + } + let (left, right) = self.equality_parts(judgment)?; + let other = if left == current { + Some(right) + } else if right == current { + Some(left) + } else { + None + }; + if let Some(other) = other + && members.insert(other) + { + queue.push_back(other); + } + } + } + + members + .into_iter() + .filter_map(|candidate| self.route_for_node(candidate).map(|route| (route, candidate))) + .min_by(|(left, _), (right, _)| left.cmp(right)) + .map(|(_, candidate)| candidate) + .ok_or(Obstruction::UncanonicalizableNode { node }) + } + + pub fn canonical_representative_route( + &self, + context: ContextId, + node: NodeId, + ) -> Result { + let representative = self.canonical_representative(context, node)?; + self.route_for_node(representative) + .cloned() + .ok_or(Obstruction::UncanonicalizableNode { + node: representative, + }) + } +} diff --git a/l64-native/src/kernel/equality/proof.rs b/l64-native/src/kernel/equality/proof.rs new file mode 100644 index 0000000..f3ceaf1 --- /dev/null +++ b/l64-native/src/kernel/equality/proof.rs @@ -0,0 +1,158 @@ +impl Graph { + pub fn prove_reflexive_equality( + &mut self, + route: Route, + context: ContextId, + subject: NodeId, + ) -> Result { + self.prove_equality( + route, + context, + subject, + subject, + EqualityRule::Reflexive, + &[], + ) + } + + pub fn prove_structural_equality( + &mut self, + route: Route, + context: ContextId, + left: NodeId, + right: NodeId, + ) -> Result { + self.prove_equality( + route, + context, + left, + right, + EqualityRule::Structural, + &[], + ) + } + + pub fn prove_symmetric_equality( + &mut self, + route: Route, + context: ContextId, + premise: NodeId, + ) -> Result { + let (left, right) = self.equality_parts(premise)?; + self.prove_equality( + route, + context, + right, + left, + EqualityRule::Symmetry, + &[premise], + ) + } + + pub fn prove_transitive_equality( + &mut self, + route: Route, + context: ContextId, + first: NodeId, + second: NodeId, + ) -> Result { + let (left, middle) = self.equality_parts(first)?; + let (second_middle, right) = self.equality_parts(second)?; + if middle != second_middle { + return Err(Obstruction::EqualityPremiseMismatch { premise: second }); + } + self.prove_equality( + route, + context, + left, + right, + EqualityRule::Transitive, + &[first, second], + ) + } + + pub fn prove_congruent_equality( + &mut self, + route: Route, + context: ContextId, + left: NodeId, + right: NodeId, + premises: &[NodeId], + ) -> Result { + self.prove_equality( + route, + context, + left, + right, + EqualityRule::Congruence, + premises, + ) + } + + pub(crate) fn prove_equality( + &mut self, + route: Route, + context: ContextId, + left: NodeId, + right: NodeId, + rule: EqualityRule, + premises: &[NodeId], + ) -> Result { + let evidence_route = route.composed(EVIDENCE_LOCUS); + if self.resolve(&route).is_some() || self.resolve(&evidence_route).is_some() { + return Err(Obstruction::RouteOccupied); + } + self.validate_equality_rule(context, left, right, rule, premises)?; + Ok(self.insert_admitted_equality( + [route, evidence_route], + context, + left, + right, + rule, + premises, + )) + } + + pub(crate) fn equality_parts( + &self, + judgment: NodeId, + ) -> Result<(NodeId, NodeId), Obstruction> { + let node = self.ensure_node(judgment)?; + let ports = self + .ports(judgment) + .ok_or(Obstruction::MalformedEquality { node: judgment })?; + if node.opcode() != OpCode::TypeEquality + || ports.len() != 2 + || ports[0].role() != PortRole::Left + || ports[1].role() != PortRole::Right + { + return Err(Obstruction::MalformedEquality { node: judgment }); + } + Ok((ports[0].target(), ports[1].target())) + } + + pub(crate) fn equality_evidence_parts( + &self, + judgment: NodeId, + ) -> Result<(EqualityRule, Vec), Obstruction> { + let evidence = self + .equality_witness_for(judgment) + .ok_or(Obstruction::MalformedEquality { node: judgment })?; + let node = self + .node(evidence) + .ok_or(Obstruction::MalformedEquality { node: evidence })?; + let ports = self + .ports(evidence) + .ok_or(Obstruction::MalformedEquality { node: evidence })?; + let rule = EqualityRule::from_raw(node.payload() as u8) + .filter(|_| node.payload() <= u8::MAX as u64) + .ok_or(Obstruction::MalformedEquality { node: evidence })?; + if node.opcode() != OpCode::EqualityWitness + || node.ty() != Some(judgment) + || ports.iter().any(|port| port.role() != PortRole::Premise) + { + return Err(Obstruction::MalformedEquality { node: evidence }); + } + Ok((rule, ports.iter().map(Port::target).collect())) + } +} diff --git a/l64-native/src/kernel/equality/validation.rs b/l64-native/src/kernel/equality/validation.rs new file mode 100644 index 0000000..8c53496 --- /dev/null +++ b/l64-native/src/kernel/equality/validation.rs @@ -0,0 +1,288 @@ +impl Graph { + pub(crate) fn validate_equality_authority(&self) -> Result<(), Obstruction> { + let mut attached = vec![false; self.node_count()]; + for (route, judgment) in self.routes_raw() { + let node = self + .node(*judgment) + .ok_or(Obstruction::UnknownNode { node: *judgment })?; + if node.opcode() != OpCode::TypeEquality { + continue; + } + let evidence = self + .resolve(&route.composed(EVIDENCE_LOCUS)) + .ok_or(Obstruction::MalformedEquality { node: *judgment })?; + let evidence_node = self + .node(evidence) + .ok_or(Obstruction::MalformedEquality { node: evidence })?; + let evidence_ports = self + .ports(evidence) + .ok_or(Obstruction::MalformedEquality { node: evidence })?; + let rule = EqualityRule::from_raw(evidence_node.payload() as u8) + .filter(|_| evidence_node.payload() <= u8::MAX as u64) + .ok_or(Obstruction::MalformedEquality { node: evidence })?; + if evidence_node.opcode() != OpCode::EqualityWitness + || evidence_node.ty() != Some(*judgment) + || evidence_node.context() != node.context() + || evidence_ports + .iter() + .any(|port| port.role() != PortRole::Premise) + { + return Err(Obstruction::MalformedEquality { node: evidence }); + } + let premises = evidence_ports.iter().map(Port::target).collect::>(); + let (left, right) = self.equality_parts(*judgment)?; + self.validate_equality_rule(node.context(), left, right, rule, &premises)?; + attached[*judgment as usize] = true; + attached[evidence as usize] = true; + } + for (index, node) in self.nodes_raw().iter().enumerate() { + if matches!(node.opcode(), OpCode::TypeEquality | OpCode::EqualityWitness) + && !attached[index] + { + return Err(Obstruction::MalformedEquality { + node: index as NodeId, + }); + } + } + Ok(()) + } + + pub(crate) fn validate_equality_rule( + &self, + context: ContextId, + left: NodeId, + right: NodeId, + rule: EqualityRule, + premises: &[NodeId], + ) -> Result<(), Obstruction> { + self.ensure_context(context)?; + let left_node = self.ensure_node(left)?; + let right_node = self.ensure_node(right)?; + if !self.context_visible(left_node.context(), context) + || !self.context_visible(right_node.context(), context) + { + return Err(Obstruction::EqualityContextEscape { + premise: if !self.context_visible(left_node.context(), context) { + left + } else { + right + }, + context, + }); + } + if !self.equality_endpoint_allowed(left_node) + || !self.equality_endpoint_allowed(right_node) + || !self.same_equality_sort(left_node, right_node) + { + return Err(Obstruction::EqualitySortMismatch { left, right }); + } + + let premise_pairs = premises + .iter() + .map(|premise| self.checked_premise(context, *premise)) + .collect::, _>>()?; + + match rule { + EqualityRule::Reflexive => { + if left != right || !premises.is_empty() { + return Err(Obstruction::InvalidEqualityRule); + } + } + EqualityRule::Structural => { + if !premises.is_empty() || !self.structurally_equal(left, right)? { + return Err(Obstruction::InvalidEqualityRule); + } + } + EqualityRule::Symmetry => { + if premise_pairs.as_slice() != [(right, left)] { + return Err(Obstruction::InvalidEqualityRule); + } + } + EqualityRule::Transitive => { + if premise_pairs.len() != 2 + || premise_pairs[0].0 != left + || premise_pairs[0].1 != premise_pairs[1].0 + || premise_pairs[1].1 != right + { + return Err(Obstruction::InvalidEqualityRule); + } + } + EqualityRule::Congruence => { + self.validate_congruence(left, right, &premise_pairs)?; + } + } + Ok(()) + } + + fn validate_congruence( + &self, + left: NodeId, + right: NodeId, + premise_pairs: &[(NodeId, NodeId)], + ) -> Result<(), Obstruction> { + let left_node = self.ensure_node(left)?; + let right_node = self.ensure_node(right)?; + if !self.congruence_subject_allowed(left_node.opcode()) + || left_node.opcode() != right_node.opcode() + || left_node.payload() != right_node.payload() + || left_node.context() != right_node.context() + || left_node.ty() != right_node.ty() + { + return Err(Obstruction::InvalidEqualityRule); + } + let left_ports = self + .ports(left) + .ok_or(Obstruction::MalformedEquality { node: left })?; + let right_ports = self + .ports(right) + .ok_or(Obstruction::MalformedEquality { node: right })?; + if left_ports.is_empty() + || left_ports.len() != right_ports.len() + || left_ports.len() != premise_pairs.len() + { + return Err(Obstruction::InvalidEqualityRule); + } + for ((left_port, right_port), pair) in left_ports + .iter() + .zip(right_ports) + .zip(premise_pairs) + { + if left_port.role() != right_port.role() + || left_port.flags() != right_port.flags() + || left_port.ordinal() != right_port.ordinal() + || *pair != (left_port.target(), right_port.target()) + { + return Err(Obstruction::InvalidEqualityRule); + } + } + Ok(()) + } + + fn checked_premise( + &self, + context: ContextId, + premise: NodeId, + ) -> Result<(NodeId, NodeId), Obstruction> { + let node = self.ensure_node(premise)?; + if node.opcode() != OpCode::TypeEquality { + return Err(Obstruction::EqualityPremiseMismatch { premise }); + } + if !self.context_visible(node.context(), context) { + return Err(Obstruction::EqualityContextEscape { premise, context }); + } + let witness = self + .equality_witness_for(premise) + .ok_or(Obstruction::EqualityPremiseMismatch { premise })?; + let witness_node = self.ensure_node(witness)?; + if witness_node.opcode() != OpCode::EqualityWitness + || witness_node.ty() != Some(premise) + || witness_node.context() != node.context() + { + return Err(Obstruction::EqualityPremiseMismatch { premise }); + } + self.equality_parts(premise) + } + + pub fn equality_witness_for(&self, judgment: NodeId) -> Option { + let route = self.route_for_node(judgment)?; + self.resolve(&route.composed(EVIDENCE_LOCUS)) + } + + pub fn route_for_node(&self, node: NodeId) -> Option<&Route> { + self.derived_route_for_node(node) + } + + pub(crate) fn context_visible(&self, ancestor: ContextId, mut context: ContextId) -> bool { + loop { + if ancestor == context { + return true; + } + if context == ROOT_CONTEXT { + return false; + } + let Some(delta) = self.contexts_raw().get(context as usize) else { + return false; + }; + context = delta.parent(); + } + } + + fn same_equality_sort(&self, left: &crate::Node, right: &crate::Node) -> bool { + match (left.ty(), right.ty()) { + (Some(left_ty), Some(right_ty)) => left_ty == right_ty, + (None, None) => { + self.equality_endpoint_allowed(left) && self.equality_endpoint_allowed(right) + } + _ => false, + } + } + + fn equality_endpoint_allowed(&self, node: &crate::Node) -> bool { + matches!( + node.opcode(), + OpCode::TypeAtom + | OpCode::TypeMatrix + | OpCode::TypeFunction + | OpCode::TypeQuantity + | OpCode::Value + | OpCode::Compose + | OpCode::MatMul + | OpCode::Add + | OpCode::Multiply + | OpCode::Divide + | OpCode::Sqrt + ) + } + + fn congruence_subject_allowed(&self, opcode: OpCode) -> bool { + matches!( + opcode, + OpCode::TypeMatrix + | OpCode::TypeFunction + | OpCode::TypeQuantity + | OpCode::Compose + | OpCode::MatMul + | OpCode::Add + | OpCode::Multiply + | OpCode::Divide + | OpCode::Sqrt + ) + } + + fn structurally_equal(&self, left: NodeId, right: NodeId) -> Result { + let left_node = self.ensure_node(left)?; + let right_node = self.ensure_node(right)?; + if !matches!( + left_node.opcode(), + OpCode::TypeAtom + | OpCode::TypeMatrix + | OpCode::TypeFunction + | OpCode::TypeQuantity + | OpCode::Compose + | OpCode::MatMul + | OpCode::Add + | OpCode::Multiply + | OpCode::Divide + | OpCode::Sqrt + ) || left_node.opcode() != right_node.opcode() + || left_node.payload() != right_node.payload() + || left_node.context() != right_node.context() + || left_node.ty() != right_node.ty() + { + return Ok(false); + } + let left_ports = self + .ports(left) + .ok_or(Obstruction::MalformedEquality { node: left })?; + let right_ports = self + .ports(right) + .ok_or(Obstruction::MalformedEquality { node: right })?; + Ok(left_ports.len() == right_ports.len() + && left_ports.iter().zip(right_ports).all(|(left, right)| { + left.target() == right.target() + && left.role() == right.role() + && left.flags() == right.flags() + && left.ordinal() == right.ordinal() + })) + } +} diff --git a/l64-native/src/kernel/proposal.rs b/l64-native/src/kernel/proposal.rs new file mode 100644 index 0000000..ed2628d --- /dev/null +++ b/l64-native/src/kernel/proposal.rs @@ -0,0 +1,271 @@ +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Proposal { + route: Route, + context: ContextId, + opcode: OpCode, + inputs: Box<[NodeId]>, + output_type: NodeId, +} + +impl Proposal { + fn binary( + route: Route, + context: ContextId, + opcode: OpCode, + left: NodeId, + right: NodeId, + output_type: NodeId, + ) -> Self { + Self { + route, + context, + opcode, + inputs: Box::new([left, right]), + output_type, + } + } + + fn unary( + route: Route, + context: ContextId, + opcode: OpCode, + input: NodeId, + output_type: NodeId, + ) -> Self { + Self { + route, + context, + opcode, + inputs: Box::new([input]), + output_type, + } + } + + pub fn compose( + route: Route, + context: ContextId, + first: NodeId, + second: NodeId, + output_type: NodeId, + ) -> Self { + Self::binary(route, context, OpCode::Compose, first, second, output_type) + } + + pub fn matrix_multiply( + route: Route, + context: ContextId, + left: NodeId, + right: NodeId, + output_type: NodeId, + ) -> Self { + Self::binary(route, context, OpCode::MatMul, left, right, output_type) + } + + pub fn add( + route: Route, + context: ContextId, + left: NodeId, + right: NodeId, + output_type: NodeId, + ) -> Self { + Self::binary(route, context, OpCode::Add, left, right, output_type) + } + + pub fn multiply( + route: Route, + context: ContextId, + left: NodeId, + right: NodeId, + output_type: NodeId, + ) -> Self { + Self::binary(route, context, OpCode::Multiply, left, right, output_type) + } + + pub fn divide( + route: Route, + context: ContextId, + left: NodeId, + right: NodeId, + output_type: NodeId, + ) -> Self { + Self::binary(route, context, OpCode::Divide, left, right, output_type) + } + + pub fn square_root( + route: Route, + context: ContextId, + input: NodeId, + output_type: NodeId, + ) -> Self { + Self::unary(route, context, OpCode::Sqrt, input, output_type) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CommitResult { + pub node: NodeId, + pub evidence: NodeId, + pub event: u32, + pub symbol: crate::SymbolicSeal, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Obstruction { + UnknownNode { + node: NodeId, + }, + UnknownContext { + context: ContextId, + }, + RouteOccupied, + ExpectedType { + node: NodeId, + }, + ExpectedFunctionType { + node: NodeId, + }, + ExpectedMatrixType { + node: NodeId, + }, + ExpectedQuantityType { + node: NodeId, + }, + MalformedType { + node: NodeId, + }, + EvidenceOnlyType { + node: NodeId, + }, + Arity { + expected: u16, + actual: u16, + }, + FunctionBoundaryMismatch { + left: NodeId, + right: NodeId, + }, + MatrixShapeMismatch { + left_cols: u32, + right_rows: u32, + }, + MatrixElementMismatch { + left: NodeId, + right: NodeId, + }, + FunctionOutputMismatch { + output_type: NodeId, + domain: NodeId, + codomain: NodeId, + }, + MatrixOutputMismatch { + output_type: NodeId, + element: NodeId, + rows: u32, + cols: u32, + }, + QuantityCarrierMismatch { + left: NodeId, + right: NodeId, + }, + DimensionMismatch { + left: Dimension, + right: Dimension, + }, + DimensionOverflow, + NonIntegralDimensionRoot { + dimension: Dimension, + }, + GuardViolated { + subject: NodeId, + kind: ConstraintKind, + }, + QuantityOutputMismatch { + output_type: NodeId, + carrier: NodeId, + dimension: Dimension, + }, + MalformedConstraint { + node: NodeId, + }, + ContradictoryConstraint { + subject: NodeId, + kind: ConstraintKind, + }, + MalformedEvidence { + node: NodeId, + }, + EqualitySortMismatch { + left: NodeId, + right: NodeId, + }, + InvalidEqualityRule, + MalformedEquality { + node: NodeId, + }, + EqualityPremiseMismatch { + premise: NodeId, + }, + EqualityContextEscape { + premise: NodeId, + context: ContextId, + }, + UncanonicalizableNode { + node: NodeId, + }, + NoEqualityPath { + left: NodeId, + right: NodeId, + }, + ContextNotDirectRefinement { + parent: ContextId, + child: ContextId, + }, + RefinementBindingNotConstraint { + context: ContextId, + binding: NodeId, + }, +} + +impl fmt::Display for Obstruction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnknownNode { node } => write!(f, "unknown node {node}"), + Self::UnknownContext { context } => write!(f, "unknown context {context}"), + Self::RouteOccupied => f.write_str("route is already occupied"), + Self::ExpectedType { node } => write!(f, "node {node} is not a type"), + Self::ExpectedFunctionType { node } => write!(f, "node {node} is not a function type"), + Self::ExpectedMatrixType { node } => write!(f, "node {node} is not a matrix type"), + Self::ExpectedQuantityType { node } => write!(f, "node {node} is not a quantity type"), + Self::MalformedType { node } => write!(f, "node {node} has a malformed type"), + Self::EvidenceOnlyType { node } => write!(f, "node {node} is evidence-only"), + Self::Arity { expected, actual } => write!(f, "arity mismatch: expected {expected}, got {actual}"), + Self::FunctionBoundaryMismatch { left, right } => write!(f, "function boundary mismatch between nodes {left} and {right}"), + Self::MatrixShapeMismatch { left_cols, right_rows } => write!(f, "matrix shape mismatch: left columns {left_cols}, right rows {right_rows}"), + Self::MatrixElementMismatch { left, right } => write!(f, "matrix element mismatch between nodes {left} and {right}"), + Self::FunctionOutputMismatch { output_type, domain, codomain } => write!(f, "function output type {output_type} does not match domain {domain} and codomain {codomain}"), + Self::MatrixOutputMismatch { output_type, element, rows, cols } => write!(f, "matrix output type {output_type} does not match element {element} and shape {rows}x{cols}"), + Self::QuantityCarrierMismatch { left, right } => write!(f, "quantity carrier mismatch between nodes {left} and {right}"), + Self::DimensionMismatch { left, right } => write!(f, "dimension mismatch: {left:?} versus {right:?}"), + Self::DimensionOverflow => f.write_str("dimension arithmetic overflow"), + Self::NonIntegralDimensionRoot { dimension } => write!(f, "dimension {dimension:?} has no integral root"), + Self::GuardViolated { subject, kind } => write!(f, "constraint guard {kind:?} is violated by node {subject}"), + Self::QuantityOutputMismatch { output_type, carrier, dimension } => write!(f, "quantity output type {output_type} does not match carrier {carrier} and dimension {dimension:?}"), + Self::MalformedConstraint { node } => write!(f, "node {node} is a malformed constraint"), + Self::ContradictoryConstraint { subject, kind } => write!(f, "constraint {kind:?} contradicts node {subject}"), + Self::MalformedEvidence { node } => write!(f, "node {node} is malformed evidence"), + Self::EqualitySortMismatch { left, right } => write!(f, "equality sort mismatch between nodes {left} and {right}"), + Self::InvalidEqualityRule => f.write_str("equality rule is invalid"), + Self::MalformedEquality { node } => write!(f, "node {node} is a malformed equality"), + Self::EqualityPremiseMismatch { premise } => write!(f, "equality premise {premise} does not match"), + Self::EqualityContextEscape { premise, context } => write!(f, "equality premise {premise} escapes context {context}"), + Self::UncanonicalizableNode { node } => write!(f, "node {node} cannot be canonicalized"), + Self::NoEqualityPath { left, right } => write!(f, "no equality path connects nodes {left} and {right}"), + Self::ContextNotDirectRefinement { parent, child } => write!(f, "context {child} is not a direct refinement of {parent}"), + Self::RefinementBindingNotConstraint { context, binding } => write!(f, "binding {binding} in context {context} is not a constraint"), + } + } +} + +impl std::error::Error for Obstruction {} diff --git a/l64-native/src/kernel/transaction.rs b/l64-native/src/kernel/transaction.rs new file mode 100644 index 0000000..e759638 --- /dev/null +++ b/l64-native/src/kernel/transaction.rs @@ -0,0 +1,183 @@ +impl Graph { + pub fn transact(&mut self, proposal: Proposal) -> Result { + self.ensure_context(proposal.context)?; + self.ensure_type(proposal.output_type)?; + let expected = proposal + .opcode + .arity() + .expect("public proposal constructors expose executable operations only"); + if proposal.inputs.len() != expected as usize { + return Err(Obstruction::Arity { + expected, + actual: proposal.inputs.len() as u16, + }); + } + + let judgment_route = proposal.route.composed(JUDGMENT_LOCUS); + let evidence_route = proposal.route.composed(EVIDENCE_LOCUS); + if self.resolve(&proposal.route).is_some() + || self.resolve(&judgment_route).is_some() + || self.resolve(&evidence_route).is_some() + { + return Err(Obstruction::RouteOccupied); + } + + let evidence = self.validate_operation( + proposal.context, + proposal.opcode, + &proposal.inputs, + proposal.output_type, + )?; + + Ok(self.insert_admitted_operation( + [proposal.route, judgment_route, evidence_route], + proposal.context, + proposal.output_type, + proposal.opcode, + &proposal.inputs, + evidence, + )) + } + + pub(crate) fn validate_operation( + &self, + _context: ContextId, + opcode: OpCode, + inputs: &[NodeId], + output_type: NodeId, + ) -> Result { + let expected = opcode.arity().ok_or(Obstruction::Arity { + expected: 0, + actual: inputs.len() as u16, + })?; + if inputs.len() != expected as usize { + return Err(Obstruction::Arity { + expected, + actual: inputs.len() as u16, + }); + } + self.ensure_type(output_type)?; + + let left = inputs[0]; + let left_ty = self + .ensure_node(left)? + .ty() + .ok_or(Obstruction::ExpectedType { node: left })?; + let right = inputs.get(1).copied(); + let right_ty = right + .map(|node| { + self.ensure_node(node)? + .ty() + .ok_or(Obstruction::ExpectedType { node }) + }) + .transpose()?; + + match opcode { + OpCode::Compose => { + let right_ty = right_ty.expect("binary arity validated"); + let (first_domain, first_codomain) = self.function_parts(left_ty)?; + let (second_domain, second_codomain) = self.function_parts(right_ty)?; + if first_codomain != second_domain { + return Err(Obstruction::FunctionBoundaryMismatch { + left: first_codomain, + right: second_domain, + }); + } + if !self.matches_function_type(output_type, first_domain, second_codomain) { + return Err(Obstruction::FunctionOutputMismatch { + output_type, + domain: first_domain, + codomain: second_codomain, + }); + } + } + OpCode::MatMul => { + let right_ty = right_ty.expect("binary arity validated"); + let (left_element, left_rows, left_cols) = self.matrix_parts(left_ty)?; + let (right_element, right_rows, right_cols) = self.matrix_parts(right_ty)?; + if left_cols != right_rows { + return Err(Obstruction::MatrixShapeMismatch { + left_cols, + right_rows, + }); + } + if left_element != right_element { + return Err(Obstruction::MatrixElementMismatch { + left: left_element, + right: right_element, + }); + } + if !self.matches_matrix_type(output_type, left_element, left_rows, right_cols) { + return Err(Obstruction::MatrixOutputMismatch { + output_type, + element: left_element, + rows: left_rows, + cols: right_cols, + }); + } + } + OpCode::Add | OpCode::Multiply | OpCode::Divide => { + let right_ty = right_ty.expect("binary arity validated"); + let (left_carrier, left_dimension) = self.quantity_parts(left_ty)?; + let (right_carrier, right_dimension) = self.quantity_parts(right_ty)?; + if left_carrier != right_carrier { + return Err(Obstruction::QuantityCarrierMismatch { + left: left_carrier, + right: right_carrier, + }); + } + let dimension = match opcode { + OpCode::Add => { + if left_dimension != right_dimension { + return Err(Obstruction::DimensionMismatch { + left: left_dimension, + right: right_dimension, + }); + } + left_dimension + } + OpCode::Multiply => left_dimension + .multiply(right_dimension) + .ok_or(Obstruction::DimensionOverflow)?, + OpCode::Divide => left_dimension + .divide(right_dimension) + .ok_or(Obstruction::DimensionOverflow)?, + _ => unreachable!(), + }; + if !self.matches_quantity_type(output_type, left_carrier, dimension) { + return Err(Obstruction::QuantityOutputMismatch { + output_type, + carrier: left_carrier, + dimension, + }); + } + } + OpCode::Sqrt => { + let (carrier, dimension) = self.quantity_parts(left_ty)?; + let output_dimension = dimension + .square_root() + .ok_or(Obstruction::NonIntegralDimensionRoot { dimension })?; + if !self.matches_quantity_type(output_type, carrier, output_dimension) { + return Err(Obstruction::QuantityOutputMismatch { + output_type, + carrier, + dimension: output_dimension, + }); + } + return match self.constraint_state(_context, left, ConstraintKind::NonNegative)? { + ConstraintState::Proven => Ok(EvidencePlan::Witness), + ConstraintState::Refuted => Err(Obstruction::GuardViolated { + subject: left, + kind: ConstraintKind::NonNegative, + }), + ConstraintState::Unknown => Ok(EvidencePlan::Obligation { + kind: ConstraintKind::NonNegative, + subject: left, + }), + }; + } + _ => unreachable!("validated opcode is executable"), + } + Ok(EvidencePlan::Witness) + } +} diff --git a/l64-native/src/kernel/types.rs b/l64-native/src/kernel/types.rs new file mode 100644 index 0000000..c26b2af --- /dev/null +++ b/l64-native/src/kernel/types.rs @@ -0,0 +1,229 @@ +pub(crate) const JUDGMENT_LOCUS: LocusWord = LocusWord(u64::MAX - 1); +pub(crate) const EVIDENCE_LOCUS: LocusWord = LocusWord(u64::MAX); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u16)] +pub enum OpCode { + TypeAtom = 1, + TypeMatrix = 2, + TypeFunction = 3, + Value = 4, + Compose = 5, + MatMul = 6, + ExtendContext = 7, + TypeJudgment = 8, + KernelWitness = 9, + TypeQuantity = 10, + Add = 11, + Multiply = 12, + Divide = 13, + Constraint = 14, + Sqrt = 15, + Obligation = 16, + TypeEquality = 17, + EqualityWitness = 18, +} + +impl OpCode { + pub(crate) fn from_raw(value: u16) -> Option { + match value { + 1 => Some(Self::TypeAtom), + 2 => Some(Self::TypeMatrix), + 3 => Some(Self::TypeFunction), + 4 => Some(Self::Value), + 5 => Some(Self::Compose), + 6 => Some(Self::MatMul), + 7 => Some(Self::ExtendContext), + 8 => Some(Self::TypeJudgment), + 9 => Some(Self::KernelWitness), + 10 => Some(Self::TypeQuantity), + 11 => Some(Self::Add), + 12 => Some(Self::Multiply), + 13 => Some(Self::Divide), + 14 => Some(Self::Constraint), + 15 => Some(Self::Sqrt), + 16 => Some(Self::Obligation), + 17 => Some(Self::TypeEquality), + 18 => Some(Self::EqualityWitness), + _ => None, + } + } + + pub(crate) fn is_type(self) -> bool { + matches!( + self, + Self::TypeAtom + | Self::TypeMatrix + | Self::TypeFunction + | Self::TypeJudgment + | Self::TypeQuantity + | Self::TypeEquality + ) + } + + pub(crate) fn is_untyped_authority(self) -> bool { + self.is_type() || self == Self::Constraint + } + + pub(crate) fn is_persisted_node(self) -> bool { + self != Self::ExtendContext + } + + pub(crate) fn is_executable(self) -> bool { + matches!( + self, + Self::Compose | Self::MatMul | Self::Add | Self::Multiply | Self::Divide | Self::Sqrt + ) + } + + pub(crate) fn arity(self) -> Option { + match self { + Self::Compose | Self::MatMul | Self::Add | Self::Multiply | Self::Divide => Some(2), + Self::Sqrt => Some(1), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum ConstraintKind { + NonNegative = 1, +} + +impl ConstraintKind { + pub(crate) fn from_raw(value: u8) -> Option { + match value { + 1 => Some(Self::NonNegative), + _ => None, + } + } + + pub(crate) fn payload(self, holds: bool) -> u64 { + self as u64 | (u64::from(holds) << 8) + } + + pub(crate) fn from_payload(payload: u64) -> Option<(Self, bool)> { + if payload >> 9 != 0 { + return None; + } + let kind = Self::from_raw(payload as u8)?; + let truth = ((payload >> 8) & 1) != 0; + Some((kind, truth)) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ConstraintState { + Proven, + Refuted, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum EvidencePlan { + Witness, + Obligation { + kind: ConstraintKind, + subject: NodeId, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum EqualityRule { + Reflexive = 1, + Structural = 2, + Symmetry = 3, + Transitive = 4, + Congruence = 5, +} + +impl EqualityRule { + pub(crate) fn from_raw(value: u8) -> Option { + match value { + 1 => Some(Self::Reflexive), + 2 => Some(Self::Structural), + 3 => Some(Self::Symmetry), + 4 => Some(Self::Transitive), + 5 => Some(Self::Congruence), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum PortRole { + Parameter = 1, + Domain = 2, + Codomain = 3, + Argument = 4, + Subject = 5, + Premise = 6, + Conclusion = 7, + Left = 8, + Right = 9, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(C)] +pub struct Port { + target: NodeId, + role: u8, + flags: u8, + ordinal: u16, +} + +impl PortRole { + pub(crate) fn from_raw(value: u8) -> Option { + match value { + 1 => Some(Self::Parameter), + 2 => Some(Self::Domain), + 3 => Some(Self::Codomain), + 4 => Some(Self::Argument), + 5 => Some(Self::Subject), + 6 => Some(Self::Premise), + 7 => Some(Self::Conclusion), + 8 => Some(Self::Left), + 9 => Some(Self::Right), + _ => None, + } + } +} + +impl Port { + pub(crate) fn new(target: NodeId, role: PortRole, ordinal: u16) -> Self { + Self { + target, + role: role as u8, + flags: 0, + ordinal, + } + } + + pub(crate) fn from_raw(target: NodeId, role: PortRole, flags: u8, ordinal: u16) -> Self { + Self { + target, + role: role as u8, + flags, + ordinal, + } + } + + pub fn target(&self) -> NodeId { + self.target + } + + pub fn role(&self) -> PortRole { + PortRole::from_raw(self.role).expect("stored port role is validated at insertion") + } + + pub fn ordinal(&self) -> u16 { + self.ordinal + } + + pub(crate) fn flags(&self) -> u8 { + self.flags + } +} diff --git a/l64-native/src/kernel/validation.rs b/l64-native/src/kernel/validation.rs new file mode 100644 index 0000000..3837442 --- /dev/null +++ b/l64-native/src/kernel/validation.rs @@ -0,0 +1,85 @@ +impl Graph { + pub(crate) fn validate_decoded_authority(&self) -> Result<(), Obstruction> { + self.validate_context_consistency()?; + let mut attached = vec![false; self.node_count()]; + for (route, node_id) in self.routes_raw() { + let node = self + .node(*node_id) + .ok_or(Obstruction::UnknownNode { node: *node_id })?; + if !node.opcode().is_executable() { + continue; + } + let operation_ports = self + .ports(*node_id) + .ok_or(Obstruction::MalformedEvidence { node: *node_id })?; + let inputs = operation_ports.iter().map(Port::target).collect::>(); + let output_type = node + .ty() + .ok_or(Obstruction::ExpectedType { node: *node_id })?; + let plan = + self.validate_operation(node.context(), node.opcode(), &inputs, output_type)?; + + let judgment = self + .resolve(&route.composed(JUDGMENT_LOCUS)) + .ok_or(Obstruction::MalformedEvidence { node: *node_id })?; + let evidence = self + .resolve(&route.composed(EVIDENCE_LOCUS)) + .ok_or(Obstruction::MalformedEvidence { node: *node_id })?; + let judgment_node = self + .node(judgment) + .ok_or(Obstruction::MalformedEvidence { node: judgment })?; + let judgment_ports = self + .ports(judgment) + .ok_or(Obstruction::MalformedEvidence { node: judgment })?; + if judgment_node.opcode() != OpCode::TypeJudgment + || judgment_node.payload() != node.opcode() as u64 + || judgment_ports.len() != inputs.len() + 2 + || judgment_ports[0].target() != *node_id + || judgment_ports.last().map(Port::target) != Some(output_type) + || judgment_ports[1..judgment_ports.len() - 1] + .iter() + .map(Port::target) + .ne(inputs.iter().copied()) + { + return Err(Obstruction::MalformedEvidence { node: judgment }); + } + let evidence_node = self + .node(evidence) + .ok_or(Obstruction::MalformedEvidence { node: evidence })?; + let evidence_ports = self + .ports(evidence) + .ok_or(Obstruction::MalformedEvidence { node: evidence })?; + let evidence_valid = match plan { + EvidencePlan::Witness => { + evidence_node.opcode() == OpCode::KernelWitness && evidence_ports.is_empty() + } + EvidencePlan::Obligation { kind, subject } => { + evidence_node.opcode() == OpCode::Obligation + && ConstraintKind::from_payload(evidence_node.payload()) + == Some((kind, true)) + && evidence_ports.len() == 1 + && evidence_ports[0].role() == PortRole::Premise + && evidence_ports[0].target() == subject + } + }; + if !evidence_valid || evidence_node.ty() != Some(judgment) { + return Err(Obstruction::MalformedEvidence { node: evidence }); + } + attached[judgment as usize] = true; + attached[evidence as usize] = true; + } + for (index, node) in self.nodes_raw().iter().enumerate() { + if matches!( + node.opcode(), + OpCode::TypeJudgment | OpCode::KernelWitness | OpCode::Obligation + ) && !attached[index] + { + return Err(Obstruction::MalformedEvidence { + node: index as NodeId, + }); + } + } + self.validate_equality_authority()?; + Ok(()) + } +} diff --git a/l64-native/src/lib.rs b/l64-native/src/lib.rs new file mode 100644 index 0000000..88e8f57 --- /dev/null +++ b/l64-native/src/lib.rs @@ -0,0 +1,29 @@ +#![forbid(unsafe_code)] + +mod closure; +mod codec; +mod context; +mod dimension; +mod dna; +mod graph; +mod journal; +mod kernel; +mod rna; +mod route; +mod symbol; + +pub use closure::{ClosureState, ClosureTransition}; +pub use codec::{DecodeError, canonical_bytes, decode_canonical}; +pub use context::ContextDelta; +pub use dimension::Dimension; +pub use dna::{DnaError, MAX_NATIVE_DNA_PAYLOAD_BYTES, decode_dna, dna_bytes}; +pub use graph::{ContextId, EventId, Graph, Node, NodeId, ROOT_CONTEXT}; +pub use journal::JournalEvent; +pub use kernel::{CommitResult, ConstraintKind, Obstruction, OpCode, Port, PortRole, Proposal}; +pub use l64_symbolic::{SymbolicIdentity, SymbolicSeal}; +pub use rna::{ + MAX_NATIVE_RNA_BYTES, RnaError, RnaSpan, compile_rna, dna_to_rna, normalize_rna, rna_bytes, + rna_diagnostic, rna_to_dna, +}; +pub use route::{LocusWord, Route}; +pub use symbol::{STATE_SYMBOL_DOMAIN, StateSymbol, state_identity}; diff --git a/l64-native/src/rna.rs b/l64-native/src/rna.rs new file mode 100644 index 0000000..b3a7110 --- /dev/null +++ b/l64-native/src/rna.rs @@ -0,0 +1,182 @@ +use std::{collections::BTreeMap, fmt}; + +use crate::kernel::EqualityRule; +use crate::{ + ConstraintKind, ContextId, Dimension, DnaError, Graph, LocusWord, NodeId, Obstruction, OpCode, + Proposal, ROOT_CONTEXT, Route, decode_dna, dna_bytes, +}; + +const RNA_MAGIC: &[u8] = b"L64R1"; +pub const MAX_NATIVE_RNA_BYTES: usize = 1 << 24; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RnaSpan { + pub line: u32, + pub column: u32, + pub length: u32, +} + +impl RnaSpan { + pub const fn new(line: u32, column: u32, length: u32) -> Self { + Self { + line, + column, + length, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RnaError { + SourceTooLarge { actual: usize, limit: usize }, + Empty, + BadHeader { span: RnaSpan }, + InvalidArity { span: RnaSpan }, + InvalidNumber { span: RnaSpan }, + UnknownInstruction { span: RnaSpan }, + SlotOrder { span: RnaSpan, slot: u64 }, + ContextOrder { span: RnaSpan, context: u32 }, + UnknownSlot { span: RnaSpan, slot: u64 }, + UnrepresentableGraph, + Graph { span: RnaSpan, error: Obstruction }, + Dna(DnaError), +} + +impl RnaError { + pub const fn span(self) -> Option { + match self { + Self::BadHeader { span } + | Self::InvalidArity { span } + | Self::InvalidNumber { span } + | Self::UnknownInstruction { span } + | Self::SlotOrder { span, .. } + | Self::ContextOrder { span, .. } + | Self::UnknownSlot { span, .. } + | Self::Graph { span, .. } => Some(span), + Self::SourceTooLarge { .. } + | Self::Empty + | Self::UnrepresentableGraph + | Self::Dna(_) => None, + } + } +} + +impl fmt::Display for RnaError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::SourceTooLarge { actual, limit } => write!( + f, + "L64R1 source is {actual} bytes; native limit is {limit} bytes" + ), + Self::Empty => f.write_str("L64R1 source is empty"), + Self::BadHeader { span } => write!( + f, + "input is not valid L64R1 RNA at {}:{}", + span.line, span.column + ), + Self::InvalidArity { span } => write!( + f, + "invalid instruction arity at RNA {}:{}", + span.line, span.column + ), + Self::InvalidNumber { span } => { + write!(f, "invalid number at RNA {}:{}", span.line, span.column) + } + Self::UnknownInstruction { span } => write!( + f, + "unknown instruction at RNA {}:{}", + span.line, span.column + ), + Self::SlotOrder { span, slot } => write!( + f, + "slot {slot} is out of canonical order at RNA {}:{}", + span.line, span.column + ), + Self::ContextOrder { span, context } => write!( + f, + "context {context} is out of canonical order at RNA {}:{}", + span.line, span.column + ), + Self::UnknownSlot { span, slot } => write!( + f, + "RNA {}:{} references unknown slot {slot}", + span.line, span.column + ), + Self::UnrepresentableGraph => { + f.write_str("graph cannot be represented as canonical L64R1 RNA") + } + Self::Graph { span, error } => write!( + f, + "RNA graph construction failed at {}:{}: {error}", + span.line, span.column + ), + Self::Dna(error) => write!(f, "RNA/DNA conversion failed: {error}"), + } + } +} + +impl std::error::Error for RnaError {} + +impl From for RnaError { + fn from(value: DnaError) -> Self { + Self::Dna(value) + } +} + +struct RnaDiagnostic<'a> { + source: &'a [u8], + error: RnaError, +} + +pub fn rna_diagnostic(source: &[u8], error: RnaError) -> impl fmt::Display + '_ { + RnaDiagnostic { source, error } +} + +impl fmt::Display for RnaDiagnostic<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.error)?; + let Some(span) = self.error.span() else { + return Ok(()); + }; + let Some(raw_line) = self + .source + .split(|byte| *byte == b'\n') + .nth(span.line.saturating_sub(1) as usize) + else { + return Ok(()); + }; + let raw_line = raw_line.strip_suffix(b"\r").unwrap_or(raw_line); + let line_text = core::str::from_utf8(raw_line).unwrap_or(""); + let width = decimal_width(span.line); + write!(f, "\n {line:>width$} | {line_text}", line = span.line)?; + write!(f, "\n {:width$} | ", "")?; + let column = span.column.saturating_sub(1) as usize; + for byte in raw_line.iter().take(column) { + if *byte == b'\t' { + f.write_str("\t")?; + } else { + f.write_str(" ")?; + } + } + let available = raw_line.len().saturating_sub(column); + let caret_len = usize::max(1, usize::min(span.length as usize, available.max(1))); + for _ in 0..caret_len { + f.write_str("^")?; + } + Ok(()) + } +} + +const fn decimal_width(mut value: u32) -> usize { + let mut width = 1; + while value >= 10 { + value /= 10; + width += 1; + } + width +} + +include!("rna/compile.rs"); +include!("rna/sequence.rs"); +include!("rna/parse.rs"); +include!("rna/render.rs"); diff --git a/l64-native/src/rna/compile.rs b/l64-native/src/rna/compile.rs new file mode 100644 index 0000000..ddacf30 --- /dev/null +++ b/l64-native/src/rna/compile.rs @@ -0,0 +1,212 @@ +pub fn compile_rna(source: &[u8]) -> Result { + if source.len() > MAX_NATIVE_RNA_BYTES { + return Err(RnaError::SourceTooLarge { + actual: source.len(), + limit: MAX_NATIVE_RNA_BYTES, + }); + } + + let mut lines = source.split(|byte| *byte == b'\n').enumerate(); + let (header_line, header_raw) = next_nonempty(&mut lines).ok_or(RnaError::Empty)?; + let header_line_number = line_number(header_line); + let header_tokens = tokens(header_raw); + if header_tokens.len() != 2 || header_tokens[0].bytes != RNA_MAGIC { + return Err(RnaError::BadHeader { + span: line_span(header_line_number, header_raw), + }); + } + let domain_token = header_tokens[1]; + let domain = parse_u64(domain_token.bytes).ok_or(RnaError::InvalidNumber { + span: domain_token.span(header_line_number), + })?; + + let root = Route::root(LocusWord(domain)); + let mut graph = Graph::new_bulk(); + let mut slots = BTreeMap::new(); + let mut last_slot = None; + let mut instruction_count = 0usize; + + for (line_index, raw_line) in lines { + let parts = tokens(raw_line); + if parts.is_empty() { + continue; + } + let line = line_number(line_index); + let instruction = parts[0]; + let instruction_span = instruction.span(line); + + if instruction.bytes == b"h" { + if parts.len() != 4 { + return Err(RnaError::InvalidArity { + span: line_span(line, raw_line), + }); + } + let context = parse_u32_part(&parts, 1, line, raw_line)?; + if context as usize != graph.context_count() { + return Err(RnaError::ContextOrder { + span: parts[1].span(line), + context, + }); + } + let parent = parse_u32_part(&parts, 2, line, raw_line)?; + let binding = resolve_part(&slots, &parts, 3, line, raw_line)?; + let created = graph_at( + graph.extend_context(parent, binding), + instruction_span, + )?; + if created != context { + return Err(RnaError::ContextOrder { + span: parts[1].span(line), + context, + }); + } + continue; + } + + if parts.len() < 2 { + return Err(RnaError::InvalidArity { + span: line_span(line, raw_line), + }); + } + let slot = parse_part(&parts, 1, line, raw_line)?; + if let Some(previous) = last_slot + && slot <= previous + { + return Err(RnaError::SlotOrder { + span: parts[1].span(line), + slot, + }); + } + let route = root.composed(LocusWord(slot)); + + let node = match instruction.bytes { + b"a" if parts.len() == 3 => graph_at( + graph.declare_atom_type( + route, + LocusWord(parse_part(&parts, 2, line, raw_line)?), + ), + instruction_span, + )?, + b"m" if parts.len() == 5 => { + let element = resolve_part(&slots, &parts, 2, line, raw_line)?; + let rows = parse_u32_part(&parts, 3, line, raw_line)?; + let cols = parse_u32_part(&parts, 4, line, raw_line)?; + graph_at( + graph.declare_matrix_type(route, element, rows, cols), + instruction_span, + )? + } + b"f" if parts.len() == 4 => { + let domain = resolve_part(&slots, &parts, 2, line, raw_line)?; + let codomain = resolve_part(&slots, &parts, 3, line, raw_line)?; + graph_at( + graph.declare_function_type(route, domain, codomain), + instruction_span, + )? + } + b"q" if parts.len() == 10 => { + let carrier = resolve_part(&slots, &parts, 2, line, raw_line)?; + let mut exponents = [0_i8; 7]; + for (axis, exponent) in exponents.iter_mut().enumerate() { + *exponent = parse_i8_part(&parts, axis + 3, line, raw_line)?; + } + graph_at( + graph.declare_quantity_type(route, carrier, Dimension::new(exponents)), + instruction_span, + )? + } + b"v" if matches!(parts.len(), 3 | 4) => { + let ty = resolve_part(&slots, &parts, 2, line, raw_line)?; + let context = parse_optional_context(&parts, 3, line, raw_line)?; + graph_at(graph.insert_value(route, context, ty), instruction_span)? + } + b"k" if matches!(parts.len(), 5 | 6) => { + let subject = resolve_part(&slots, &parts, 2, line, raw_line)?; + let kind_raw = parse_u8_part(&parts, 3, line, raw_line)?; + let kind = ConstraintKind::from_raw(kind_raw).ok_or(RnaError::InvalidNumber { + span: parts[3].span(line), + })?; + let holds = parse_bool_part(&parts, 4, line, raw_line)?; + let context = parse_optional_context(&parts, 5, line, raw_line)?; + graph_at( + graph.declare_constraint(route, context, subject, kind, holds), + instruction_span, + )? + } + b"c" | b"x" | b"+" | b"*" | b"/" if matches!(parts.len(), 5 | 6) => { + let left = resolve_part(&slots, &parts, 2, line, raw_line)?; + let right = resolve_part(&slots, &parts, 3, line, raw_line)?; + let output = resolve_part(&slots, &parts, 4, line, raw_line)?; + let context = parse_optional_context(&parts, 5, line, raw_line)?; + let proposal = match instruction.bytes { + b"c" => Proposal::compose(route, context, left, right, output), + b"x" => Proposal::matrix_multiply(route, context, left, right, output), + b"+" => Proposal::add(route, context, left, right, output), + b"*" => Proposal::multiply(route, context, left, right, output), + b"/" => Proposal::divide(route, context, left, right, output), + _ => unreachable!(), + }; + graph_at(graph.transact(proposal), instruction_span)?.node + } + b"r" if matches!(parts.len(), 4 | 5) => { + let input = resolve_part(&slots, &parts, 2, line, raw_line)?; + let output = resolve_part(&slots, &parts, 3, line, raw_line)?; + let context = parse_optional_context(&parts, 4, line, raw_line)?; + graph_at( + graph.transact(Proposal::square_root(route, context, input, output)), + instruction_span, + )? + .node + } + b"e" if parts.len() >= 6 => { + let rule_raw = parse_u8_part(&parts, 2, line, raw_line)?; + let rule = EqualityRule::from_raw(rule_raw).ok_or(RnaError::InvalidNumber { + span: parts[2].span(line), + })?; + let left = resolve_part(&slots, &parts, 3, line, raw_line)?; + let right = resolve_part(&slots, &parts, 4, line, raw_line)?; + let context = parse_u32_part(&parts, 5, line, raw_line)?; + let premises = parts[6..] + .iter() + .map(|part| { + let slot = parse_u64(part.bytes).ok_or(RnaError::InvalidNumber { + span: part.span(line), + })?; + slots + .get(&slot) + .copied() + .ok_or(RnaError::UnknownSlot { + span: part.span(line), + slot, + }) + }) + .collect::, _>>()?; + graph_at( + graph.prove_equality(route, context, left, right, rule, &premises), + instruction_span, + )? + .node + } + b"a" | b"m" | b"f" | b"q" | b"v" | b"k" | b"c" | b"x" | b"+" | b"*" + | b"/" | b"r" | b"e" => { + return Err(RnaError::InvalidArity { + span: line_span(line, raw_line), + }); + } + _ => { + return Err(RnaError::UnknownInstruction { + span: instruction_span, + }); + } + }; + + slots.insert(slot, node); + last_slot = Some(slot); + instruction_count += 1; + } + + if instruction_count == 0 { + return Err(RnaError::Empty); + } + Ok(graph.finish_bulk()) +} diff --git a/l64-native/src/rna/parse.rs b/l64-native/src/rna/parse.rs new file mode 100644 index 0000000..d544953 --- /dev/null +++ b/l64-native/src/rna/parse.rs @@ -0,0 +1,229 @@ +#[derive(Clone, Copy)] +struct Token<'a> { + bytes: &'a [u8], + column: u32, +} + +impl Token<'_> { + fn span(self, line: u32) -> RnaSpan { + RnaSpan::new(line, self.column, self.bytes.len().max(1) as u32) + } +} + +fn require_root(context: ContextId) -> Result<(), RnaError> { + (context == ROOT_CONTEXT) + .then_some(()) + .ok_or(RnaError::UnrepresentableGraph) +} + +fn push_context(out: &mut Vec, context: ContextId) { + if context != ROOT_CONTEXT { + push_space_decimal(out, u64::from(context)); + } +} + +fn next_nonempty<'a>( + lines: &mut impl Iterator, +) -> Option<(usize, &'a [u8])> { + lines.find(|(_, line)| !trim_ascii(line).is_empty()) +} + +fn trim_ascii(mut bytes: &[u8]) -> &[u8] { + while bytes.first().is_some_and(u8::is_ascii_whitespace) { + bytes = &bytes[1..]; + } + while bytes.last().is_some_and(u8::is_ascii_whitespace) { + bytes = &bytes[..bytes.len() - 1]; + } + bytes +} + +fn tokens(line: &[u8]) -> Vec> { + let mut out = Vec::new(); + let mut index = 0usize; + while index < line.len() { + while index < line.len() && line[index].is_ascii_whitespace() { + index += 1; + } + if index == line.len() { + break; + } + let start = index; + while index < line.len() && !line[index].is_ascii_whitespace() { + index += 1; + } + out.push(Token { + bytes: &line[start..index], + column: (start + 1) as u32, + }); + } + out +} + +fn line_span(line: u32, raw_line: &[u8]) -> RnaSpan { + let first = raw_line + .iter() + .position(|byte| !byte.is_ascii_whitespace()) + .unwrap_or(0); + let last = raw_line + .iter() + .rposition(|byte| !byte.is_ascii_whitespace()) + .map(|index| index + 1) + .unwrap_or(first + 1); + RnaSpan::new(line, (first + 1) as u32, last.saturating_sub(first) as u32) +} + +fn missing_span(line: u32, raw_line: &[u8]) -> RnaSpan { + RnaSpan::new(line, raw_line.len().saturating_add(1) as u32, 1) +} + +fn part_span(parts: &[Token<'_>], index: usize, line: u32, raw_line: &[u8]) -> RnaSpan { + parts + .get(index) + .copied() + .map(|token| token.span(line)) + .unwrap_or_else(|| missing_span(line, raw_line)) +} + +fn parse_part( + parts: &[Token<'_>], + index: usize, + line: u32, + raw_line: &[u8], +) -> Result { + let token = parts.get(index).copied().ok_or(RnaError::InvalidNumber { + span: missing_span(line, raw_line), + })?; + parse_u64(token.bytes).ok_or(RnaError::InvalidNumber { + span: token.span(line), + }) +} + +fn parse_u8_part( + parts: &[Token<'_>], + index: usize, + line: u32, + raw_line: &[u8], +) -> Result { + parse_part(parts, index, line, raw_line)? + .try_into() + .map_err(|_| RnaError::InvalidNumber { + span: part_span(parts, index, line, raw_line), + }) +} + +fn parse_u32_part( + parts: &[Token<'_>], + index: usize, + line: u32, + raw_line: &[u8], +) -> Result { + parse_part(parts, index, line, raw_line)? + .try_into() + .map_err(|_| RnaError::InvalidNumber { + span: part_span(parts, index, line, raw_line), + }) +} + +fn parse_i8_part( + parts: &[Token<'_>], + index: usize, + line: u32, + raw_line: &[u8], +) -> Result { + let token = parts.get(index).copied().ok_or(RnaError::InvalidNumber { + span: missing_span(line, raw_line), + })?; + parse_i8(token.bytes).ok_or(RnaError::InvalidNumber { + span: token.span(line), + }) +} + +fn parse_bool_part( + parts: &[Token<'_>], + index: usize, + line: u32, + raw_line: &[u8], +) -> Result { + match parse_u8_part(parts, index, line, raw_line)? { + 0 => Ok(false), + 1 => Ok(true), + _ => Err(RnaError::InvalidNumber { + span: part_span(parts, index, line, raw_line), + }), + } +} + +fn parse_optional_context( + parts: &[Token<'_>], + index: usize, + line: u32, + raw_line: &[u8], +) -> Result { + if parts.len() == index { + Ok(ROOT_CONTEXT) + } else { + parse_u32_part(parts, index, line, raw_line) + } +} + +fn resolve_part( + slots: &BTreeMap, + parts: &[Token<'_>], + index: usize, + line: u32, + raw_line: &[u8], +) -> Result { + let slot = parse_part(parts, index, line, raw_line)?; + slots + .get(&slot) + .copied() + .ok_or(RnaError::UnknownSlot { + span: part_span(parts, index, line, raw_line), + slot, + }) +} + +fn graph_at(result: Result, span: RnaSpan) -> Result { + result.map_err(|error| RnaError::Graph { span, error }) +} + +fn parse_i8(bytes: &[u8]) -> Option { + let (negative, digits) = if let Some(digits) = bytes.strip_prefix(b"-") { + (true, digits) + } else if let Some(digits) = bytes.strip_prefix(b"+") { + (false, digits) + } else { + (false, bytes) + }; + let magnitude = parse_u64(digits)?; + if negative { + let magnitude: i16 = magnitude.try_into().ok()?; + i8::try_from(-magnitude).ok() + } else { + magnitude.try_into().ok() + } +} + +fn parse_u64(bytes: &[u8]) -> Option { + let (radix, digits) = if bytes.starts_with(b"0x") || bytes.starts_with(b"0X") { + (16u64, &bytes[2..]) + } else { + (10u64, bytes) + }; + if digits.is_empty() { + return None; + } + digits.iter().try_fold(0u64, |value, byte| { + let digit = match *byte { + b'0'..=b'9' => u64::from(*byte - b'0'), + b'a'..=b'f' if radix == 16 => u64::from(*byte - b'a' + 10), + b'A'..=b'F' if radix == 16 => u64::from(*byte - b'A' + 10), + _ => return None, + }; + if digit >= radix { + return None; + } + value.checked_mul(radix)?.checked_add(digit) + }) +} diff --git a/l64-native/src/rna/render.rs b/l64-native/src/rna/render.rs new file mode 100644 index 0000000..4456df7 --- /dev/null +++ b/l64-native/src/rna/render.rs @@ -0,0 +1,70 @@ +fn slot_for(slots: &BTreeMap, node: NodeId) -> Result { + slots + .get(&node) + .copied() + .ok_or(RnaError::UnrepresentableGraph) +} + +fn push_prefix(out: &mut Vec, opcode: u8, slot: u64) { + out.push(opcode); + push_space_decimal(out, slot); +} + +fn push_space_decimal(out: &mut Vec, value: u64) { + out.push(b' '); + push_decimal(out, value); +} + +fn push_space_signed(out: &mut Vec, value: i8) { + out.push(b' '); + if value < 0 { + out.push(b'-'); + push_decimal(out, u64::from(value.unsigned_abs())); + } else { + push_decimal(out, value as u64); + } +} + +fn push_space_hex(out: &mut Vec, value: u64) { + out.push(b' '); + push_hex(out, value); +} + +fn push_decimal(out: &mut Vec, mut value: u64) { + let mut buffer = [0u8; 20]; + let mut cursor = buffer.len(); + loop { + cursor -= 1; + buffer[cursor] = b'0' + (value % 10) as u8; + value /= 10; + if value == 0 { + break; + } + } + out.extend_from_slice(&buffer[cursor..]); +} + +fn push_hex(out: &mut Vec, mut value: u64) { + out.extend_from_slice(b"0x"); + if value == 0 { + out.push(b'0'); + return; + } + let mut buffer = [0u8; 16]; + let mut cursor = buffer.len(); + while value != 0 { + cursor -= 1; + let digit = (value & 0xf) as u8; + buffer[cursor] = if digit < 10 { + b'0' + digit + } else { + b'a' + digit - 10 + }; + value >>= 4; + } + out.extend_from_slice(&buffer[cursor..]); +} + +fn line_number(index: usize) -> u32 { + u32::try_from(index + 1).unwrap_or(u32::MAX) +} diff --git a/l64-native/src/rna/sequence.rs b/l64-native/src/rna/sequence.rs new file mode 100644 index 0000000..1e47ec8 --- /dev/null +++ b/l64-native/src/rna/sequence.rs @@ -0,0 +1,203 @@ +pub fn normalize_rna(source: &[u8]) -> Result, RnaError> { + rna_bytes(&compile_rna(source)?) +} + +pub fn rna_to_dna(source: &[u8]) -> Result, RnaError> { + Ok(dna_bytes(&compile_rna(source)?)?) +} + +pub fn dna_to_rna(source: &[u8]) -> Result, RnaError> { + rna_bytes(&decode_dna(source)?) +} + +pub fn rna_bytes(graph: &Graph) -> Result, RnaError> { + let mut domain = None; + let mut authored = BTreeMap::new(); + for (route, node) in graph.routes_raw() { + if route.tail().len() != 1 { + continue; + } + match domain { + Some(existing) if existing != route.domain() => { + return Err(RnaError::UnrepresentableGraph); + } + None => domain = Some(route.domain()), + _ => {} + } + if authored.insert(*node, route.tail()[0].0).is_some() { + return Err(RnaError::UnrepresentableGraph); + } + } + + let domain = domain.ok_or(RnaError::Empty)?; + let expected_authored = graph + .nodes_raw() + .iter() + .filter(|node| { + !matches!( + node.opcode(), + OpCode::TypeJudgment + | OpCode::KernelWitness + | OpCode::Obligation + | OpCode::EqualityWitness + ) + }) + .count(); + if authored.len() != expected_authored { + return Err(RnaError::UnrepresentableGraph); + } + + let mut slots = BTreeMap::new(); + let mut previous_slot = None; + for (node, slot) in &authored { + if previous_slot.is_some_and(|previous| *slot <= previous) { + return Err(RnaError::UnrepresentableGraph); + } + slots.insert(*node, *slot); + previous_slot = Some(*slot); + } + + let mut out = Vec::with_capacity(32 + authored.len() * 32 + graph.context_count() * 16); + out.extend_from_slice(RNA_MAGIC); + out.push(b' '); + push_hex(&mut out, domain.0); + out.push(b'\n'); + + let mut next_context = 1_u32; + for (node_id, slot) in authored { + emit_ready_contexts(graph, &slots, &mut out, &mut next_context, node_id)?; + emit_node(graph, &slots, &mut out, node_id, slot)?; + } + emit_ready_contexts(graph, &slots, &mut out, &mut next_context, u32::MAX)?; + if next_context as usize != graph.context_count() { + return Err(RnaError::UnrepresentableGraph); + } + + Ok(out) +} + +fn emit_ready_contexts( + graph: &Graph, + slots: &BTreeMap, + out: &mut Vec, + next_context: &mut ContextId, + before_node: NodeId, +) -> Result<(), RnaError> { + while (*next_context as usize) < graph.context_count() { + let context = &graph.contexts_raw()[*next_context as usize]; + let binding = context.binding().ok_or(RnaError::UnrepresentableGraph)?; + if binding >= before_node { + break; + } + out.push(b'h'); + push_space_decimal(out, u64::from(*next_context)); + push_space_decimal(out, u64::from(context.parent())); + push_space_decimal(out, slot_for(slots, binding)?); + out.push(b'\n'); + *next_context += 1; + } + Ok(()) +} + +fn emit_node( + graph: &Graph, + slots: &BTreeMap, + out: &mut Vec, + node_id: NodeId, + slot: u64, +) -> Result<(), RnaError> { + let node = graph.node(node_id).ok_or(RnaError::UnrepresentableGraph)?; + let ports = graph.ports(node_id).ok_or(RnaError::UnrepresentableGraph)?; + match node.opcode() { + OpCode::TypeAtom if ports.is_empty() && node.ty().is_none() => { + require_root(node.context())?; + push_prefix(out, b'a', slot); + push_space_hex(out, node.payload()); + } + OpCode::TypeMatrix if ports.len() == 1 && node.ty().is_none() => { + require_root(node.context())?; + push_prefix(out, b'm', slot); + push_space_decimal(out, slot_for(slots, ports[0].target())?); + push_space_decimal(out, node.payload() >> 32); + push_space_decimal(out, node.payload() as u32 as u64); + } + OpCode::TypeFunction if ports.len() == 2 && node.ty().is_none() => { + require_root(node.context())?; + push_prefix(out, b'f', slot); + push_space_decimal(out, slot_for(slots, ports[0].target())?); + push_space_decimal(out, slot_for(slots, ports[1].target())?); + } + OpCode::TypeQuantity if ports.len() == 1 && node.ty().is_none() => { + require_root(node.context())?; + push_prefix(out, b'q', slot); + push_space_decimal(out, slot_for(slots, ports[0].target())?); + let dimension = + Dimension::from_bits(node.payload()).ok_or(RnaError::UnrepresentableGraph)?; + for exponent in dimension.exponents() { + push_space_signed(out, exponent); + } + } + OpCode::Value if ports.is_empty() => { + push_prefix(out, b'v', slot); + push_space_decimal( + out, + slot_for(slots, node.ty().ok_or(RnaError::UnrepresentableGraph)?)?, + ); + push_context(out, node.context()); + } + OpCode::Constraint if ports.len() == 1 => { + push_prefix(out, b'k', slot); + push_space_decimal(out, slot_for(slots, ports[0].target())?); + let (kind, holds) = ConstraintKind::from_payload(node.payload()) + .ok_or(RnaError::UnrepresentableGraph)?; + push_space_decimal(out, kind as u64); + push_space_decimal(out, u64::from(holds)); + push_context(out, node.context()); + } + OpCode::Compose | OpCode::MatMul | OpCode::Add | OpCode::Multiply | OpCode::Divide + if ports.len() == 2 => + { + let opcode = match node.opcode() { + OpCode::Compose => b'c', + OpCode::MatMul => b'x', + OpCode::Add => b'+', + OpCode::Multiply => b'*', + OpCode::Divide => b'/', + _ => unreachable!(), + }; + push_prefix(out, opcode, slot); + push_space_decimal(out, slot_for(slots, ports[0].target())?); + push_space_decimal(out, slot_for(slots, ports[1].target())?); + push_space_decimal( + out, + slot_for(slots, node.ty().ok_or(RnaError::UnrepresentableGraph)?)?, + ); + push_context(out, node.context()); + } + OpCode::Sqrt if ports.len() == 1 => { + push_prefix(out, b'r', slot); + push_space_decimal(out, slot_for(slots, ports[0].target())?); + push_space_decimal( + out, + slot_for(slots, node.ty().ok_or(RnaError::UnrepresentableGraph)?)?, + ); + push_context(out, node.context()); + } + OpCode::TypeEquality if ports.len() == 2 => { + push_prefix(out, b'e', slot); + let (rule, premises) = graph + .equality_evidence_parts(node_id) + .map_err(|_| RnaError::UnrepresentableGraph)?; + push_space_decimal(out, rule as u64); + push_space_decimal(out, slot_for(slots, ports[0].target())?); + push_space_decimal(out, slot_for(slots, ports[1].target())?); + push_space_decimal(out, u64::from(node.context())); + for premise in premises { + push_space_decimal(out, slot_for(slots, premise)?); + } + } + _ => return Err(RnaError::UnrepresentableGraph), + } + out.push(b'\n'); + Ok(()) +} diff --git a/l64-native/src/route.rs b/l64-native/src/route.rs new file mode 100644 index 0000000..c8831e9 --- /dev/null +++ b/l64-native/src/route.rs @@ -0,0 +1,59 @@ +use core::cmp::Ordering; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(transparent)] +pub struct LocusWord(pub u64); + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Route { + domain: LocusWord, + tail: Box<[LocusWord]>, +} + +impl Route { + pub fn root(domain: LocusWord) -> Self { + Self { + domain, + tail: Box::new([]), + } + } + + pub fn from_parts(domain: LocusWord, tail: impl Into>) -> Self { + Self { + domain, + tail: tail.into(), + } + } + + pub fn domain(&self) -> LocusWord { + self.domain + } + + pub fn tail(&self) -> &[LocusWord] { + &self.tail + } + + pub fn composed(&self, next: LocusWord) -> Self { + let mut tail = Vec::with_capacity(self.tail.len() + 1); + tail.extend_from_slice(&self.tail); + tail.push(next); + Self { + domain: self.domain, + tail: tail.into_boxed_slice(), + } + } +} + +impl PartialOrd for Route { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Route { + fn cmp(&self, other: &Self) -> Ordering { + self.domain + .cmp(&other.domain) + .then_with(|| self.tail.as_ref().cmp(other.tail.as_ref())) + } +} diff --git a/l64-native/src/symbol.rs b/l64-native/src/symbol.rs new file mode 100644 index 0000000..c6b04e5 --- /dev/null +++ b/l64-native/src/symbol.rs @@ -0,0 +1,134 @@ +use core::fmt; + +use crate::{ContextDelta, Graph, Node, NodeId, Port, Route, canonical_bytes}; +use l64_symbolic::{Composer, SymbolicIdentity, SymbolicSeal}; + +pub const STATE_SYMBOL_DOMAIN: &str = "l64.native.state.v2"; +const NODE_DOMAIN: &str = "l64.native.node.v1"; +const PORT_DOMAIN: &str = "l64.native.port.v1"; +const CONTEXT_DOMAIN: &str = "l64.native.context.v1"; +const ROUTE_DOMAIN: &str = "l64.native.route.v1"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StateSymbol { + pub root: SymbolicSeal, + pub nodes: SymbolicSeal, + pub ports: SymbolicSeal, + pub contexts: SymbolicSeal, + pub routes: SymbolicSeal, +} + +impl StateSymbol { + pub const ZERO: Self = Self { + root: SymbolicSeal::ZERO, + nodes: SymbolicSeal::ZERO, + ports: SymbolicSeal::ZERO, + contexts: SymbolicSeal::ZERO, + routes: SymbolicSeal::ZERO, + }; + + pub fn changed_sections(self, other: Self) -> [bool; 4] { + [ + self.nodes != other.nodes, + self.ports != other.ports, + self.contexts != other.contexts, + self.routes != other.routes, + ] + } +} + +impl fmt::Display for StateSymbol { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "{} ∣ nodes={} ports={} contexts={} routes={}", + self.root.pretty(STATE_SYMBOL_DOMAIN), + self.nodes, + self.ports, + self.contexts, + self.routes + ) + } +} + +pub fn state_identity(graph: &Graph) -> SymbolicIdentity { + SymbolicIdentity::new(STATE_SYMBOL_DOMAIN, canonical_bytes(graph)) +} + +pub(crate) fn state_symbol(graph: &Graph) -> StateSymbol { + let nodes = ordered_section("nodes", graph.nodes_raw().iter().map(node_seal)); + let ports = ordered_section("ports", graph.ports_raw().iter().map(port_seal)); + let contexts = ordered_section("contexts", graph.contexts_raw().iter().map(context_seal)); + let routes = ordered_section( + "routes", + graph + .routes_raw() + .iter() + .map(|(route, node)| route_seal(route, *node)), + ); + let mut root = Composer::new(STATE_SYMBOL_DOMAIN); + root.u16("codec", crate::codec::CODEC_VERSION) + .u64("node-count", graph.nodes_raw().len() as u64) + .u64("port-count", graph.ports_raw().len() as u64) + .u64("context-count", graph.contexts_raw().len() as u64) + .u64("route-count", graph.routes_raw().len() as u64) + .ordered("sections", &[nodes, ports, contexts, routes]); + StateSymbol { + root: root.finish(), + nodes, + ports, + contexts, + routes, + } +} + +fn ordered_section(label: &str, parts: impl Iterator) -> SymbolicSeal { + let parts = parts.collect::>(); + let mut composer = Composer::new("l64.native.section.v1"); + composer.ordered(label, &parts); + composer.finish() +} + +fn node_seal(node: &Node) -> SymbolicSeal { + let range = node.port_range(); + let mut composer = Composer::new(NODE_DOMAIN); + composer + .u16("opcode", node.opcode() as u16) + .u32("context", node.context()) + .u32("type", node.ty().unwrap_or(NodeId::MAX)) + .u64("payload", node.payload()) + .u32("first-port", range.start as u32) + .u16("port-count", (range.end - range.start) as u16); + composer.finish() +} + +fn port_seal(port: &Port) -> SymbolicSeal { + let mut composer = Composer::new(PORT_DOMAIN); + composer + .u32("target", port.target()) + .u8("role", port.role() as u8) + .u8("flags", port.flags()) + .u16("ordinal", port.ordinal()); + composer.finish() +} + +fn context_seal(context: &ContextDelta) -> SymbolicSeal { + let mut composer = Composer::new(CONTEXT_DOMAIN); + composer + .u32("parent", context.parent()) + .u32("binding", context.binding().unwrap_or(NodeId::MAX)); + composer.finish() +} + +fn route_seal(route: &Route, node: NodeId) -> SymbolicSeal { + let mut tail = Vec::with_capacity(route.tail().len() * 8); + for word in route.tail() { + tail.extend_from_slice(&word.0.to_le_bytes()); + } + let mut composer = Composer::new(ROUTE_DOMAIN); + composer + .u64("domain", route.domain().0) + .field("tail", &tail) + .u32("node", node); + composer.finish() +} diff --git a/l64-native/tests/architecture.rs b/l64-native/tests/architecture.rs new file mode 100644 index 0000000..359c7d6 --- /dev/null +++ b/l64-native/tests/architecture.rs @@ -0,0 +1,73 @@ +use core::mem::size_of; +use std::{fs, path::Path}; + +use l64_native::{ClosureTransition, Dimension, Node, Port}; + +#[test] +fn compact_layout_budgets_hold() { + assert!( + size_of::() <= 32, + "Node grew to {} bytes", + size_of::() + ); + assert!( + size_of::() <= 8, + "Port grew to {} bytes", + size_of::() + ); + assert!( + size_of::() <= 24, + "ClosureTransition grew to {} bytes", + size_of::() + ); + assert!( + size_of::() <= 8, + "Dimension grew to {} bytes", + size_of::() + ); +} + +#[test] +fn native_source_rejects_coordination_heavy_dependencies() { + fn collect_rust(path: &Path, source: &mut std::string::String) { + for entry in fs::read_dir(path).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + collect_rust(&path, source); + } else if path.extension().and_then(|part| part.to_str()) == Some("rs") { + source.push_str(&fs::read_to_string(path).unwrap()); + } + } + } + + let source_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut source = std::string::String::new(); + collect_rust(&source_root, &mut source); + + let forbidden = [ + ["Str", "ing"].concat(), + ["HashMap", "<", "Str", "ing"].concat(), + ["serde", "_json"].concat(), + ["bin", "code"].concat(), + ["blake", "3"].concat(), + ["Ser", "ialize"].concat(), + ["Deser", "ialize"].concat(), + ["claim", "_packet"].concat(), + ["theorem", "_id"].concat(), + ["campaign", "_id"].concat(), + ]; + for token in forbidden { + assert!(!source.contains(&token), "forbidden native token: {token}"); + } + + let public_structs = source.matches("pub struct ").count(); + let public_enums = source.matches("pub enum ").count(); + assert!( + public_structs <= 13, + "public struct budget exceeded: {public_structs}" + ); + assert!( + public_enums <= 8, + "public enum budget exceeded: {public_enums}" + ); +} diff --git a/l64-native/tests/closure.rs b/l64-native/tests/closure.rs new file mode 100644 index 0000000..dfaa613 --- /dev/null +++ b/l64-native/tests/closure.rs @@ -0,0 +1,346 @@ +use l64_native::{ + ClosureState, ConstraintKind, Dimension, Graph, LocusWord, Obstruction, Proposal, ROOT_CONTEXT, + Route, canonical_bytes, decode_canonical, +}; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x434c4f5355524539)).composed(LocusWord(index)) +} + +struct GuardedFixture { + graph: Graph, + subject: u32, + sqrt: u32, + sqrt_evidence: u32, + downstream: u32, + independent: u32, +} + +fn guarded_fixture() -> GuardedFixture { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let dimensionless = Dimension::new([0, 0, 0, 0, 0, 0, 0]); + let quantity = graph + .declare_quantity_type(route(2), scalar, dimensionless) + .unwrap(); + let subject = graph + .insert_value(route(3), ROOT_CONTEXT, quantity) + .unwrap(); + let peer = graph + .insert_value(route(4), ROOT_CONTEXT, quantity) + .unwrap(); + let sqrt_result = graph + .transact(Proposal::square_root( + route(5), + ROOT_CONTEXT, + subject, + quantity, + )) + .unwrap(); + let downstream = graph + .transact(Proposal::multiply( + route(6), + ROOT_CONTEXT, + sqrt_result.node, + peer, + quantity, + )) + .unwrap() + .node; + + let independent_left = graph + .insert_value(route(7), ROOT_CONTEXT, quantity) + .unwrap(); + let independent_right = graph + .insert_value(route(8), ROOT_CONTEXT, quantity) + .unwrap(); + let independent = graph + .transact(Proposal::add( + route(9), + ROOT_CONTEXT, + independent_left, + independent_right, + quantity, + )) + .unwrap() + .node; + + GuardedFixture { + graph, + subject, + sqrt: sqrt_result.node, + sqrt_evidence: sqrt_result.evidence, + downstream, + independent, + } +} + +#[test] +fn reverse_incidence_is_exact_and_rebuilt_from_canonical_graph() { + let fixture = guarded_fixture(); + let affected = fixture.graph.affected_nodes(fixture.subject).unwrap(); + assert!(affected.contains(&fixture.sqrt)); + assert!(affected.contains(&fixture.sqrt_evidence)); + assert!(affected.contains(&fixture.downstream)); + assert!(!affected.contains(&fixture.independent)); + + let bytes = canonical_bytes(&fixture.graph); + let decoded = decode_canonical(&bytes).unwrap(); + assert_eq!(decoded.affected_nodes(fixture.subject).unwrap(), affected); + assert_eq!(canonical_bytes(&decoded), bytes); +} + +#[test] +fn positive_refinement_discharges_only_the_dependent_obligation_chain() { + let mut fixture = guarded_fixture(); + assert_eq!( + fixture + .graph + .closure_state(ROOT_CONTEXT, fixture.sqrt) + .unwrap(), + ClosureState::Open + ); + assert_eq!( + fixture.graph.context_closure(ROOT_CONTEXT).unwrap(), + ClosureState::Open + ); + + let cause = fixture + .graph + .declare_constraint( + route(20), + ROOT_CONTEXT, + fixture.subject, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let child = fixture.graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let transitions = fixture + .graph + .closure_transitions(ROOT_CONTEXT, child) + .unwrap(); + + assert!(transitions.iter().any(|transition| { + transition.node() == fixture.sqrt + && transition.before() == ClosureState::Open + && transition.after() == ClosureState::Closed + && transition.cause() == cause + })); + assert!(transitions.iter().any(|transition| { + transition.node() == fixture.sqrt_evidence + && transition.before() == ClosureState::Open + && transition.after() == ClosureState::Closed + })); + assert!( + !transitions + .iter() + .any(|transition| transition.node() == fixture.independent) + ); + assert_eq!( + fixture.graph.context_closure(child).unwrap(), + ClosureState::Closed + ); + assert_eq!( + fixture.graph.global_closure().unwrap(), + ClosureState::Open, + "the original open context remains valid and independently visible" + ); +} + +#[test] +fn negative_refinement_invalidates_exactly_the_reverse_reachable_subgraph() { + let mut fixture = guarded_fixture(); + let independent_before = fixture + .graph + .closure_state(ROOT_CONTEXT, fixture.independent) + .unwrap(); + let cause = fixture + .graph + .declare_constraint( + route(30), + ROOT_CONTEXT, + fixture.subject, + ConstraintKind::NonNegative, + false, + ) + .unwrap(); + let child = fixture.graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let transitions = fixture + .graph + .closure_transitions(ROOT_CONTEXT, child) + .unwrap(); + + for dependent in [fixture.sqrt, fixture.sqrt_evidence, fixture.downstream] { + assert!(transitions.iter().any(|transition| { + transition.node() == dependent && transition.after() == ClosureState::Invalid + })); + } + assert!( + !transitions + .iter() + .any(|transition| transition.node() == fixture.independent) + ); + assert_eq!( + fixture + .graph + .closure_state(child, fixture.independent) + .unwrap(), + independent_before + ); + assert_eq!( + fixture.graph.context_closure(child).unwrap(), + ClosureState::Invalid + ); + assert_eq!( + fixture.graph.global_closure().unwrap(), + ClosureState::Invalid + ); +} + +#[test] +fn equality_provenance_is_invalidated_when_its_endpoint_closure_fails() { + let mut fixture = guarded_fixture(); + let equality = fixture + .graph + .prove_reflexive_equality(route(40), ROOT_CONTEXT, fixture.sqrt) + .unwrap(); + let cause = fixture + .graph + .declare_constraint( + route(41), + ROOT_CONTEXT, + fixture.subject, + ConstraintKind::NonNegative, + false, + ) + .unwrap(); + let child = fixture.graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let transitions = fixture + .graph + .closure_transitions(ROOT_CONTEXT, child) + .unwrap(); + + assert!(transitions.iter().any(|transition| { + transition.node() == equality.node && transition.after() == ClosureState::Invalid + })); + assert!(transitions.iter().any(|transition| { + transition.node() == equality.evidence && transition.after() == ClosureState::Invalid + })); +} + +#[test] +fn closure_transition_requires_one_direct_constraint_refinement() { + let mut fixture = guarded_fixture(); + let first_binding = fixture + .graph + .declare_constraint( + route(50), + ROOT_CONTEXT, + fixture.subject, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let child = fixture + .graph + .extend_context(ROOT_CONTEXT, first_binding) + .unwrap(); + let second_subject = fixture + .graph + .insert_value( + route(51), + child, + fixture.graph.node(fixture.subject).unwrap().ty().unwrap(), + ) + .unwrap(); + let second_binding = fixture + .graph + .declare_constraint( + route(52), + child, + second_subject, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let grandchild = fixture.graph.extend_context(child, second_binding).unwrap(); + + assert_eq!( + fixture.graph.closure_transitions(ROOT_CONTEXT, grandchild), + Err(Obstruction::ContextNotDirectRefinement { + parent: ROOT_CONTEXT, + child: grandchild, + }) + ); + + let value_binding = fixture + .graph + .insert_value( + route(53), + ROOT_CONTEXT, + fixture.graph.node(fixture.subject).unwrap().ty().unwrap(), + ) + .unwrap(); + let non_constraint_child = fixture + .graph + .extend_context(ROOT_CONTEXT, value_binding) + .unwrap(); + assert_eq!( + fixture + .graph + .closure_transitions(ROOT_CONTEXT, non_constraint_child), + Err(Obstruction::RefinementBindingNotConstraint { + context: non_constraint_child, + binding: value_binding, + }) + ); +} + +#[test] +fn closure_queries_do_not_mutate_authority_or_canonical_bytes() { + let mut fixture = guarded_fixture(); + let cause = fixture + .graph + .declare_constraint( + route(60), + ROOT_CONTEXT, + fixture.subject, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let child = fixture.graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let before = canonical_bytes(&fixture.graph); + let commitment = fixture.graph.state_symbol(); + let journal = fixture.graph.journal_len(); + + let _ = fixture.graph.direct_dependents(fixture.subject).unwrap(); + let _ = fixture.graph.affected_nodes(fixture.subject).unwrap(); + let _ = fixture + .graph + .closure_transitions(ROOT_CONTEXT, child) + .unwrap(); + let _ = fixture.graph.context_closure(child).unwrap(); + let _ = fixture.graph.global_closure().unwrap(); + + assert_eq!(canonical_bytes(&fixture.graph), before); + assert_eq!(fixture.graph.state_symbol(), commitment); + assert_eq!(fixture.graph.journal_len(), journal); +} + +#[test] +fn context_closure_analysis_matches_individual_queries_exactly() { + let fixture = guarded_fixture(); + let states = fixture.graph.context_closure_states(ROOT_CONTEXT).unwrap(); + assert_eq!( + states.len(), + fixture.graph.visible_nodes(ROOT_CONTEXT).unwrap().len() + ); + for (node, state) in states { + assert_eq!( + state, + fixture.graph.closure_state(ROOT_CONTEXT, node).unwrap() + ); + } +} diff --git a/l64-native/tests/codec.rs b/l64-native/tests/codec.rs new file mode 100644 index 0000000..7bceb9c --- /dev/null +++ b/l64-native/tests/codec.rs @@ -0,0 +1,97 @@ +use l64_native::{ + DecodeError, Graph, LocusWord, Proposal, ROOT_CONTEXT, Route, canonical_bytes, decode_canonical, +}; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x4c36344e41544956)).composed(LocusWord(index)) +} + +fn representative_graph() -> Graph { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let a = graph.declare_atom_type(route(2), LocusWord(0x41)).unwrap(); + let b = graph.declare_atom_type(route(3), LocusWord(0x42)).unwrap(); + let c = graph.declare_atom_type(route(4), LocusWord(0x43)).unwrap(); + let ab = graph.declare_function_type(route(5), a, b).unwrap(); + let bc = graph.declare_function_type(route(6), b, c).unwrap(); + let ac = graph.declare_function_type(route(7), a, c).unwrap(); + let first = graph.insert_value(route(8), ROOT_CONTEXT, ab).unwrap(); + let second = graph.insert_value(route(9), ROOT_CONTEXT, bc).unwrap(); + graph + .transact(Proposal::compose( + route(10), + ROOT_CONTEXT, + first, + second, + ac, + )) + .unwrap(); + let matrix = graph.declare_matrix_type(route(11), scalar, 2, 3).unwrap(); + let value = graph.insert_value(route(12), ROOT_CONTEXT, matrix).unwrap(); + graph.extend_context(ROOT_CONTEXT, value).unwrap(); + graph +} + +#[test] +fn canonical_decode_reencode_is_exact_fixed_point() { + let graph = representative_graph(); + let bytes = canonical_bytes(&graph); + let decoded = decode_canonical(&bytes).unwrap(); + + assert_eq!(canonical_bytes(&decoded), bytes); + assert_eq!(decoded.state_symbol(), graph.state_symbol()); + assert_eq!(decoded.node_count(), graph.node_count()); + assert_eq!(decoded.port_count(), graph.port_count()); + assert_eq!(decoded.context_count(), graph.context_count()); + assert_eq!(decoded.journal_len(), 0); + for index in 1..=12 { + assert_eq!(decoded.resolve(&route(index)), graph.resolve(&route(index))); + } +} + +#[test] +fn decoder_rejects_truncation_and_trailing_bytes() { + let bytes = canonical_bytes(&representative_graph()); + assert_eq!( + decode_canonical(&bytes[..bytes.len() - 1]).unwrap_err(), + DecodeError::Truncated + ); + + let mut trailing = bytes; + trailing.push(0); + assert_eq!( + decode_canonical(&trailing).unwrap_err(), + DecodeError::TrailingBytes + ); +} + +#[test] +fn decoder_rejects_unknown_node_opcode() { + let mut bytes = canonical_bytes(&representative_graph()); + let first_node_opcode = 22; + bytes[first_node_opcode..first_node_opcode + 2].copy_from_slice(&u16::MAX.to_le_bytes()); + assert_eq!( + decode_canonical(&bytes).unwrap_err(), + DecodeError::UnknownOpcode { opcode: u16::MAX } + ); +} + +#[test] +fn decoder_rejects_noncanonical_route_order() { + let graph = representative_graph(); + let mut bytes = canonical_bytes(&graph); + let routes_offset = + 22 + graph.node_count() * 24 + graph.port_count() * 8 + graph.context_count() * 8; + let first_route_len = 8 + 4 + 8 + 4; + let first = bytes[routes_offset..routes_offset + first_route_len].to_vec(); + let second = + bytes[routes_offset + first_route_len..routes_offset + 2 * first_route_len].to_vec(); + bytes[routes_offset..routes_offset + first_route_len].copy_from_slice(&second); + bytes[routes_offset + first_route_len..routes_offset + 2 * first_route_len] + .copy_from_slice(&first); + + assert_eq!( + decode_canonical(&bytes).unwrap_err(), + DecodeError::NonCanonical + ); +} diff --git a/l64-native/tests/constraints.rs b/l64-native/tests/constraints.rs new file mode 100644 index 0000000..65a0d4a --- /dev/null +++ b/l64-native/tests/constraints.rs @@ -0,0 +1,328 @@ +use l64_native::{ + ConstraintKind, DecodeError, Dimension, Graph, LocusWord, Obstruction, OpCode, Proposal, + ROOT_CONTEXT, Route, canonical_bytes, decode_canonical, +}; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x434f4e5354524149)).composed(LocusWord(index)) +} + +fn quantity_fixture() -> (Graph, u32, u32, u32, u32, u32) { + let mut graph = Graph::new(); + let real = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let length = graph + .declare_quantity_type(route(2), real, Dimension::LENGTH) + .unwrap(); + let time = graph + .declare_quantity_type(route(3), real, Dimension::TIME) + .unwrap(); + let speed = graph + .declare_quantity_type( + route(4), + real, + Dimension::LENGTH.divide(Dimension::TIME).unwrap(), + ) + .unwrap(); + let area = graph + .declare_quantity_type( + route(5), + real, + Dimension::LENGTH.multiply(Dimension::LENGTH).unwrap(), + ) + .unwrap(); + (graph, real, length, time, speed, area) +} + +#[test] +fn dimension_vector_composes_without_schema_objects() { + let velocity = Dimension::LENGTH.divide(Dimension::TIME).unwrap(); + let acceleration = velocity.divide(Dimension::TIME).unwrap(); + assert_eq!(velocity.exponents(), [1, 0, -1, 0, 0, 0, 0]); + assert_eq!(acceleration.exponents(), [1, 0, -2, 0, 0, 0, 0]); + assert_eq!(Dimension::LENGTH.square_root(), None); + assert_eq!( + Dimension::LENGTH + .multiply(Dimension::LENGTH) + .unwrap() + .square_root(), + Some(Dimension::LENGTH) + ); +} + +#[test] +fn incompatible_addition_rejects_without_mutation() { + let (mut graph, _, length, time, _, _) = quantity_fixture(); + let left = graph.insert_value(route(10), ROOT_CONTEXT, length).unwrap(); + let right = graph.insert_value(route(11), ROOT_CONTEXT, time).unwrap(); + let before = canonical_bytes(&graph); + + let result = graph.transact(Proposal::add(route(12), ROOT_CONTEXT, left, right, length)); + + assert_eq!( + result, + Err(Obstruction::DimensionMismatch { + left: Dimension::LENGTH, + right: Dimension::TIME, + }) + ); + assert_eq!(canonical_bytes(&graph), before); + assert!(graph.resolve(&route(12)).is_none()); +} + +#[test] +fn multiplication_and_division_validate_derived_dimensions() { + let (mut graph, _, length, time, speed, area) = quantity_fixture(); + let left = graph.insert_value(route(20), ROOT_CONTEXT, length).unwrap(); + let right = graph.insert_value(route(21), ROOT_CONTEXT, length).unwrap(); + let duration = graph.insert_value(route(22), ROOT_CONTEXT, time).unwrap(); + + let product = graph + .transact(Proposal::multiply( + route(23), + ROOT_CONTEXT, + left, + right, + area, + )) + .unwrap(); + let quotient = graph + .transact(Proposal::divide( + route(24), + ROOT_CONTEXT, + left, + duration, + speed, + )) + .unwrap(); + + assert_eq!( + graph.node(product.evidence).unwrap().opcode(), + OpCode::KernelWitness + ); + assert_eq!( + graph.node(quotient.evidence).unwrap().opcode(), + OpCode::KernelWitness + ); + let bytes = canonical_bytes(&graph); + let decoded = decode_canonical(&bytes).unwrap(); + assert_eq!(canonical_bytes(&decoded), bytes); +} + +#[test] +fn decoder_rechecks_operation_law_instead_of_trusting_witness_shape() { + let (mut graph, _, length, time, speed, area) = quantity_fixture(); + let left = graph.insert_value(route(30), ROOT_CONTEXT, length).unwrap(); + let duration = graph.insert_value(route(31), ROOT_CONTEXT, time).unwrap(); + let committed = graph + .transact(Proposal::divide( + route(32), + ROOT_CONTEXT, + left, + duration, + speed, + )) + .unwrap(); + let mut bytes = canonical_bytes(&graph); + let node_record = 22 + committed.node as usize * 24; + bytes[node_record + 6..node_record + 10].copy_from_slice(&area.to_le_bytes()); + let judgment = committed.node + 1; + let conclusion_port = graph.node(judgment).unwrap().port_range().end - 1; + let port_section = 22 + graph.node_count() * 24; + let conclusion_record = port_section + conclusion_port * 8; + bytes[conclusion_record..conclusion_record + 4].copy_from_slice(&area.to_le_bytes()); + + assert_eq!( + decode_canonical(&bytes).unwrap_err(), + DecodeError::InvalidAuthority + ); +} + +#[test] +fn contradictory_context_is_rejected_before_context_mutation() { + let (mut graph, _, length, _, _, _) = quantity_fixture(); + let value = graph.insert_value(route(40), ROOT_CONTEXT, length).unwrap(); + let nonnegative = graph + .declare_constraint( + route(41), + ROOT_CONTEXT, + value, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let positive_context = graph.extend_context(ROOT_CONTEXT, nonnegative).unwrap(); + let negative = graph + .declare_constraint( + route(42), + ROOT_CONTEXT, + value, + ConstraintKind::NonNegative, + false, + ) + .unwrap(); + let before = canonical_bytes(&graph); + let before_journal = graph.journal_len(); + + assert_eq!( + graph.extend_context(positive_context, negative), + Err(Obstruction::ContradictoryConstraint { + subject: value, + kind: ConstraintKind::NonNegative, + }) + ); + assert_eq!(canonical_bytes(&graph), before); + assert_eq!(graph.journal_len(), before_journal); +} + +#[test] +fn decoder_rejects_a_serialized_contradictory_context() { + let (mut graph, _, length, _, _, _) = quantity_fixture(); + let value = graph.insert_value(route(50), ROOT_CONTEXT, length).unwrap(); + let first = graph + .declare_constraint( + route(51), + ROOT_CONTEXT, + value, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let first_context = graph.extend_context(ROOT_CONTEXT, first).unwrap(); + let second = graph + .declare_constraint( + route(52), + first_context, + value, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + graph.extend_context(first_context, second).unwrap(); + + let valid = canonical_bytes(&graph); + let decoded = decode_canonical(&valid).unwrap(); + assert_eq!(canonical_bytes(&decoded), valid); + + let mut contradictory = valid; + let second_record = 22 + second as usize * 24; + contradictory[second_record + 10..second_record + 18].copy_from_slice(&1_u64.to_le_bytes()); + assert_eq!( + decode_canonical(&contradictory).unwrap_err(), + DecodeError::InvalidAuthority + ); +} + +fn square_root_fixture() -> (Graph, u32, u32, u32) { + let mut graph = Graph::new(); + let real = graph.declare_atom_type(route(60), LocusWord(0x52)).unwrap(); + let length = graph + .declare_quantity_type(route(61), real, Dimension::LENGTH) + .unwrap(); + let area = graph + .declare_quantity_type( + route(62), + real, + Dimension::LENGTH.multiply(Dimension::LENGTH).unwrap(), + ) + .unwrap(); + let value = graph.insert_value(route(63), ROOT_CONTEXT, area).unwrap(); + (graph, value, length, area) +} + +#[test] +fn unresolved_square_root_guard_is_preserved_as_obligation() { + let (mut graph, value, length, _) = square_root_fixture(); + let committed = graph + .transact(Proposal::square_root( + route(64), + ROOT_CONTEXT, + value, + length, + )) + .unwrap(); + + let evidence = graph.node(committed.evidence).unwrap(); + assert_eq!(evidence.opcode(), OpCode::Obligation); + assert_eq!(graph.ports(committed.evidence).unwrap()[0].target(), value); + let bytes = canonical_bytes(&graph); + let decoded = decode_canonical(&bytes).unwrap(); + assert_eq!(canonical_bytes(&decoded), bytes); +} + +#[test] +fn discharged_square_root_guard_produces_kernel_witness() { + let (mut graph, value, length, _) = square_root_fixture(); + let condition = graph + .declare_constraint( + route(65), + ROOT_CONTEXT, + value, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let context = graph.extend_context(ROOT_CONTEXT, condition).unwrap(); + let committed = graph + .transact(Proposal::square_root(route(66), context, value, length)) + .unwrap(); + + assert_eq!( + graph.node(committed.evidence).unwrap().opcode(), + OpCode::KernelWitness + ); +} + +#[test] +fn refuted_square_root_guard_rejects_without_mutation() { + let (mut graph, value, length, _) = square_root_fixture(); + let condition = graph + .declare_constraint( + route(67), + ROOT_CONTEXT, + value, + ConstraintKind::NonNegative, + false, + ) + .unwrap(); + let context = graph.extend_context(ROOT_CONTEXT, condition).unwrap(); + let before = canonical_bytes(&graph); + let before_journal = graph.journal_len(); + + assert_eq!( + graph.transact(Proposal::square_root(route(68), context, value, length)), + Err(Obstruction::GuardViolated { + subject: value, + kind: ConstraintKind::NonNegative, + }) + ); + assert_eq!(canonical_bytes(&graph), before); + assert_eq!(graph.journal_len(), before_journal); +} + +#[test] +fn decoder_refuses_a_forged_witness_for_an_unresolved_guard() { + let (mut graph, value, length, _) = square_root_fixture(); + let committed = graph + .transact(Proposal::square_root( + route(69), + ROOT_CONTEXT, + value, + length, + )) + .unwrap(); + let mut bytes = canonical_bytes(&graph); + let node_count = graph.node_count(); + let port_count = graph.port_count(); + let evidence_record = 22 + committed.evidence as usize * 24; + bytes[evidence_record..evidence_record + 2] + .copy_from_slice(&(OpCode::KernelWitness as u16).to_le_bytes()); + bytes[evidence_record + 22..evidence_record + 24].copy_from_slice(&0_u16.to_le_bytes()); + bytes[10..14].copy_from_slice(&((port_count - 1) as u32).to_le_bytes()); + let last_port = 22 + node_count * 24 + (port_count - 1) * 8; + bytes.drain(last_port..last_port + 8); + + assert_eq!( + decode_canonical(&bytes).unwrap_err(), + DecodeError::InvalidAuthority + ); +} diff --git a/l64-native/tests/dna.rs b/l64-native/tests/dna.rs new file mode 100644 index 0000000..91944f3 --- /dev/null +++ b/l64-native/tests/dna.rs @@ -0,0 +1,96 @@ +use l64_native::{ + DnaError, Graph, LocusWord, Proposal, ROOT_CONTEXT, Route, decode_dna, dna_bytes, +}; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x4c36344e41544956)).composed(LocusWord(index)) +} + +fn proven_graph() -> Graph { + let mut graph = Graph::new(); + let a = graph.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + let b = graph.declare_atom_type(route(2), LocusWord(0x42)).unwrap(); + let c = graph.declare_atom_type(route(3), LocusWord(0x43)).unwrap(); + let ab = graph.declare_function_type(route(4), a, b).unwrap(); + let bc = graph.declare_function_type(route(5), b, c).unwrap(); + let ac = graph.declare_function_type(route(6), a, c).unwrap(); + let first = graph.insert_value(route(7), ROOT_CONTEXT, ab).unwrap(); + let second = graph.insert_value(route(8), ROOT_CONTEXT, bc).unwrap(); + graph + .transact(Proposal::compose(route(9), ROOT_CONTEXT, first, second, ac)) + .unwrap(); + graph +} + +#[test] +fn native_dna_roundtrip_is_exact_fixed_point() { + let graph = proven_graph(); + let dna = dna_bytes(&graph).unwrap(); + let decoded = decode_dna(&dna).unwrap(); + + assert_eq!(dna_bytes(&decoded).unwrap(), dna); + assert_eq!(decoded.state_symbol(), graph.state_symbol()); + assert_eq!(decoded.journal_len(), 0); + assert!(!dna.windows(b"claim".len()).any(|window| window == b"claim")); + assert!( + !dna.windows(b"theorem".len()) + .any(|window| window == b"theorem") + ); +} + +#[test] +fn native_dna_rejects_header_seal_tampering() { + let mut dna = dna_bytes(&proven_graph()).unwrap(); + dna[12] ^= 1; + assert_eq!(decode_dna(&dna).unwrap_err(), DnaError::SealMismatch); +} + +#[test] +fn native_dna_rejects_valid_alternate_payload_under_stale_seal() { + let mut left = Graph::new(); + left.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + let mut right = Graph::new(); + right.declare_atom_type(route(1), LocusWord(0x42)).unwrap(); + + let mut dna = dna_bytes(&left).unwrap(); + let right_dna = dna_bytes(&right).unwrap(); + assert_eq!(dna.len(), right_dna.len()); + dna[44..].copy_from_slice(&right_dna[44..]); + assert_eq!(decode_dna(&dna).unwrap_err(), DnaError::SealMismatch); +} + +#[test] +fn native_dna_rejects_unknown_header_state() { + let original = dna_bytes(&proven_graph()).unwrap(); + + for unsupported in [1_u16, 3_u16] { + let mut version = original.clone(); + version[4..6].copy_from_slice(&unsupported.to_le_bytes()); + assert_eq!( + decode_dna(&version).unwrap_err(), + DnaError::UnsupportedVersion { + version: unsupported, + } + ); + } + + let mut flags = original; + flags[6..8].copy_from_slice(&1u16.to_le_bytes()); + assert_eq!( + decode_dna(&flags).unwrap_err(), + DnaError::UnsupportedFlags { flags: 1 } + ); +} + +#[test] +fn native_dna_rejects_length_mismatch() { + let dna = dna_bytes(&proven_graph()).unwrap(); + assert_eq!( + decode_dna(&dna[..dna.len() - 1]).unwrap_err(), + DnaError::Truncated + ); + + let mut trailing = dna; + trailing.push(0); + assert_eq!(decode_dna(&trailing).unwrap_err(), DnaError::TrailingBytes); +} diff --git a/l64-native/tests/equality.rs b/l64-native/tests/equality.rs new file mode 100644 index 0000000..58f9f77 --- /dev/null +++ b/l64-native/tests/equality.rs @@ -0,0 +1,273 @@ +use l64_native::{ + ConstraintKind, DecodeError, Dimension, Graph, LocusWord, OpCode, ROOT_CONTEXT, Route, + canonical_bytes, decode_canonical, dna_to_rna, rna_to_dna, +}; + +fn route(slot: u64) -> Route { + Route::root(LocusWord(0x4551)).composed(LocusWord(slot)) +} + +#[test] +fn primitive_equality_is_a_judgment_with_checked_witness() { + let mut graph = Graph::new(); + let left = graph.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + let right = graph.declare_atom_type(route(2), LocusWord(0x41)).unwrap(); + + let structural = graph + .prove_structural_equality(route(3), ROOT_CONTEXT, left, right) + .unwrap(); + assert_eq!( + graph.node(structural.node).unwrap().opcode(), + OpCode::TypeEquality + ); + assert_eq!( + graph.node(structural.evidence).unwrap().opcode(), + OpCode::EqualityWitness + ); + assert_eq!( + graph.node(structural.evidence).unwrap().ty(), + Some(structural.node) + ); + + let reflexive = graph + .prove_reflexive_equality(route(4), ROOT_CONTEXT, left) + .unwrap(); + assert_eq!( + graph.node(reflexive.node).unwrap().opcode(), + OpCode::TypeEquality + ); + + let bytes = canonical_bytes(&graph); + let decoded = decode_canonical(&bytes).unwrap(); + assert_eq!(canonical_bytes(&decoded), bytes); +} + +#[test] +fn symmetry_transitivity_and_route_canonicalization_follow_proof_paths() { + let mut graph = Graph::new(); + let left = graph.declare_atom_type(route(10), LocusWord(0x41)).unwrap(); + let right = graph.declare_atom_type(route(20), LocusWord(0x41)).unwrap(); + let forward = graph + .prove_structural_equality(route(30), ROOT_CONTEXT, left, right) + .unwrap(); + let backward = graph + .prove_symmetric_equality(route(40), ROOT_CONTEXT, forward.node) + .unwrap(); + graph + .prove_transitive_equality(route(50), ROOT_CONTEXT, forward.node, backward.node) + .unwrap(); + + assert_eq!( + graph.canonical_representative(ROOT_CONTEXT, right).unwrap(), + left + ); + assert_eq!( + graph + .canonical_representative_route(ROOT_CONTEXT, right) + .unwrap(), + route(10) + ); +} + +#[test] +fn congruence_lifts_checked_argument_equalities() { + let mut graph = Graph::new(); + let carrier_left = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let carrier_right = graph.declare_atom_type(route(2), LocusWord(0x52)).unwrap(); + let carrier_eq = graph + .prove_structural_equality(route(3), ROOT_CONTEXT, carrier_left, carrier_right) + .unwrap(); + + let dimension = Dimension::new([1, 0, 0, 0, 0, 0, 0]); + let quantity_left = graph + .declare_quantity_type(route(4), carrier_left, dimension) + .unwrap(); + let quantity_right = graph + .declare_quantity_type(route(5), carrier_right, dimension) + .unwrap(); + let quantity_eq = graph + .prove_congruent_equality( + route(6), + ROOT_CONTEXT, + quantity_left, + quantity_right, + &[carrier_eq.node], + ) + .unwrap(); + + let function_left = graph + .declare_function_type(route(7), quantity_left, quantity_left) + .unwrap(); + let function_right = graph + .declare_function_type(route(8), quantity_right, quantity_right) + .unwrap(); + graph + .prove_congruent_equality( + route(9), + ROOT_CONTEXT, + function_left, + function_right, + &[quantity_eq.node, quantity_eq.node], + ) + .unwrap(); + + assert_eq!( + graph + .canonical_representative(ROOT_CONTEXT, function_right) + .unwrap(), + function_left + ); +} + +#[test] +fn child_context_equality_does_not_escape_to_parent() { + let mut graph = Graph::new(); + let carrier = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let quantity = graph + .declare_quantity_type(route(2), carrier, Dimension::new([0, 0, 0, 0, 0, 0, 0])) + .unwrap(); + let value = graph + .insert_value(route(3), ROOT_CONTEXT, quantity) + .unwrap(); + let guard = graph + .declare_constraint( + route(4), + ROOT_CONTEXT, + value, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let child = graph.extend_context(ROOT_CONTEXT, guard).unwrap(); + + let left = graph.declare_atom_type(route(5), LocusWord(0x41)).unwrap(); + let right = graph.declare_atom_type(route(6), LocusWord(0x41)).unwrap(); + graph + .prove_structural_equality(route(7), child, left, right) + .unwrap(); + + assert_eq!( + graph.canonical_representative(ROOT_CONTEXT, right).unwrap(), + right + ); + assert_eq!(graph.canonical_representative(child, right).unwrap(), left); +} + +#[test] +fn forged_equality_rule_is_rejected_during_decode() { + let mut graph = Graph::new(); + let left = graph.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + let right = graph.declare_atom_type(route(2), LocusWord(0x41)).unwrap(); + let proof = graph + .prove_structural_equality(route(3), ROOT_CONTEXT, left, right) + .unwrap(); + let mut bytes = canonical_bytes(&graph); + + const HEADER_BYTES: usize = 22; + const NODE_BYTES: usize = 24; + const PAYLOAD_OFFSET: usize = 10; + let offset = HEADER_BYTES + proof.evidence as usize * NODE_BYTES + PAYLOAD_OFFSET; + bytes[offset..offset + 8].copy_from_slice(&1_u64.to_le_bytes()); + + assert!(matches!( + decode_canonical(&bytes), + Err(DecodeError::InvalidAuthority) + )); +} + +#[test] +fn equality_path_exposes_deterministic_checked_provenance() { + let mut graph = Graph::new(); + let first = graph.declare_atom_type(route(10), LocusWord(0x41)).unwrap(); + let second = graph.declare_atom_type(route(20), LocusWord(0x41)).unwrap(); + let third = graph.declare_atom_type(route(30), LocusWord(0x41)).unwrap(); + let first_proof = graph + .prove_structural_equality(route(40), ROOT_CONTEXT, first, second) + .unwrap(); + let second_proof = graph + .prove_structural_equality(route(50), ROOT_CONTEXT, second, third) + .unwrap(); + + assert_eq!( + graph.equality_path(ROOT_CONTEXT, first, third).unwrap(), + vec![first_proof.node, second_proof.node] + ); +} + +#[test] +fn invalid_merges_are_rejected_before_state_mutation() { + let mut graph = Graph::new(); + let left = graph.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + let right = graph.declare_atom_type(route(2), LocusWord(0x42)).unwrap(); + let before = ( + graph.node_count(), + graph.port_count(), + graph.journal_len(), + graph.state_symbol(), + ); + + assert!(matches!( + graph.prove_structural_equality(route(3), ROOT_CONTEXT, left, right), + Err(l64_native::Obstruction::InvalidEqualityRule) + )); + assert_eq!( + ( + graph.node_count(), + graph.port_count(), + graph.journal_len(), + graph.state_symbol(), + ), + before + ); +} + +#[test] +fn forged_congruence_premise_path_is_rejected_during_decode() { + let mut graph = Graph::new(); + let carrier_left = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let carrier_right = graph.declare_atom_type(route(2), LocusWord(0x52)).unwrap(); + let carrier_eq = graph + .prove_structural_equality(route(3), ROOT_CONTEXT, carrier_left, carrier_right) + .unwrap(); + let dimension = Dimension::new([1, 0, 0, 0, 0, 0, 0]); + let quantity_left = graph + .declare_quantity_type(route(4), carrier_left, dimension) + .unwrap(); + let quantity_right = graph + .declare_quantity_type(route(5), carrier_right, dimension) + .unwrap(); + let proof = graph + .prove_congruent_equality( + route(6), + ROOT_CONTEXT, + quantity_left, + quantity_right, + &[carrier_eq.node], + ) + .unwrap(); + let evidence = graph.node(proof.evidence).unwrap(); + let premise_port = evidence.port_range().start; + let mut bytes = canonical_bytes(&graph); + + const HEADER_BYTES: usize = 22; + const NODE_BYTES: usize = 24; + const PORT_BYTES: usize = 8; + let port_base = HEADER_BYTES + graph.node_count() * NODE_BYTES; + let target_offset = port_base + premise_port * PORT_BYTES; + bytes[target_offset..target_offset + 4].copy_from_slice(&carrier_left.to_le_bytes()); + + assert!(matches!( + decode_canonical(&bytes), + Err(DecodeError::InvalidAuthority) + )); +} + +#[test] +fn equality_proofs_reach_exact_rna_dna_fixed_point() { + let source = b"L64R1 0x4551\na 1 0x41\na 2 0x41\ne 3 2 1 2 0\ne 4 3 2 1 0 3\ne 5 4 1 1 0 3 4\n"; + let dna = rna_to_dna(source).unwrap(); + let canonical_rna = dna_to_rna(&dna).unwrap(); + let rebuilt = rna_to_dna(&canonical_rna).unwrap(); + assert_eq!(rebuilt, dna); + assert!(canonical_rna.windows(2).any(|window| window == b"e ")); +} diff --git a/l64-native/tests/rna.rs b/l64-native/tests/rna.rs new file mode 100644 index 0000000..6335ef7 --- /dev/null +++ b/l64-native/tests/rna.rs @@ -0,0 +1,150 @@ +use l64_native::{ + ConstraintKind, Dimension, Obstruction, RnaError, RnaSpan, compile_rna, decode_dna, dna_bytes, + dna_to_rna, normalize_rna, rna_diagnostic, rna_to_dna, +}; + +const CANONICAL_COMPOSE: &[u8] = b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n"; + +#[test] +fn native_rna_compiles_and_reaches_exact_dna_fixed_point() { + let graph = compile_rna(CANONICAL_COMPOSE).unwrap(); + assert_eq!(graph.node_count(), 11); + assert_eq!( + graph.journal_len(), + 0, + "canonical source compilation is bulk construction" + ); + + let exact_dna = dna_bytes(&graph).unwrap(); + let decoded = decode_dna(&exact_dna).unwrap(); + assert_eq!(decoded.state_symbol(), graph.state_symbol()); + + let dna = rna_to_dna(CANONICAL_COMPOSE).unwrap(); + let sequenced = dna_to_rna(&dna).unwrap(); + assert_eq!(sequenced, CANONICAL_COMPOSE); + assert_eq!(rna_to_dna(&sequenced).unwrap(), dna); +} + +#[test] +fn native_rna_normalization_removes_surface_variation() { + let source = b"\n L64R1 0X4C36344E41544956\n a 1 0X41\n a 2 0x42\n a 3 0x43\n f 4 1 2\n f 5 2 3\n f 6 1 3\n v 7 4\n v 8 5\n c 9 7 8 6\n\n"; + assert_eq!(normalize_rna(source).unwrap(), CANONICAL_COMPOSE); +} + +#[test] +fn invalid_matrix_source_refuses_before_dna_exists() { + let source = b"L64R1 0x4c36344e41544956\na 1 0x52\nm 2 1 2 3\nm 3 1 4 2\nm 4 1 2 2\nv 5 2\nv 6 3\nx 7 5 6 4\n"; + assert_eq!( + rna_to_dna(source), + Err(RnaError::Graph { + span: RnaSpan::new(8, 1, 1), + error: Obstruction::MatrixShapeMismatch { + left_cols: 3, + right_rows: 4, + }, + }) + ); +} + +#[test] +fn native_rna_rejects_unknown_and_non_topological_slots() { + let unknown = b"L64R1 0x1\na 1 0x41\nf 2 1 9\n"; + assert_eq!( + compile_rna(unknown).unwrap_err(), + RnaError::UnknownSlot { + span: RnaSpan::new(3, 7, 1), + slot: 9, + } + ); + + let unordered = b"L64R1 0x1\na 2 0x41\na 1 0x42\n"; + assert_eq!( + compile_rna(unordered).unwrap_err(), + RnaError::SlotOrder { + span: RnaSpan::new(3, 3, 1), + slot: 1, + } + ); +} + +#[test] +fn native_rna_rejects_record_like_or_named_instructions() { + let source = b"L64R1 0x1\nclaim 1 2\n"; + assert_eq!( + compile_rna(source).unwrap_err(), + RnaError::UnknownInstruction { + span: RnaSpan::new(2, 1, 5), + } + ); +} + +const CONSTRAINT_RNA: &[u8] = b"L64R1 0x434f4e5354524149\na 1 0x52\nq 2 1 1 0 0 0 0 0 0\nq 3 1 2 0 0 0 0 0 0\nv 4 3\nr 5 4 2\nk 6 4 1 1\nh 1 0 6\nr 7 4 2 1\n"; + +#[test] +fn constraints_contexts_and_obligations_reach_exact_rna_dna_fixed_point() { + let graph = compile_rna(CONSTRAINT_RNA).unwrap(); + assert_eq!(graph.context_count(), 2); + let dna = rna_to_dna(CONSTRAINT_RNA).unwrap(); + let sequenced = dna_to_rna(&dna).unwrap(); + assert_eq!(sequenced, CONSTRAINT_RNA); + assert_eq!(rna_to_dna(&sequenced).unwrap(), dna); + assert!(!sequenced.windows(2).any(|window| window == b"{:")); +} + +#[test] +fn rna_preserves_unknown_guard_and_refuses_refuted_guard() { + let refuted = b"L64R1 0x434f4e5354524149\na 1 0x52\nq 2 1 1 0 0 0 0 0 0\nq 3 1 2 0 0 0 0 0 0\nv 4 3\nk 5 4 1 0\nh 1 0 5\nr 6 4 2 1\n"; + assert_eq!( + rna_to_dna(refuted), + Err(RnaError::Graph { + span: RnaSpan::new(8, 1, 1), + error: Obstruction::GuardViolated { + subject: 3, + kind: ConstraintKind::NonNegative, + }, + }) + ); +} + +#[test] +fn rna_rejects_dimensionally_invalid_addition() { + let source = b"L64R1 0x434f4e5354524149\na 1 0x52\nq 2 1 1 0 0 0 0 0 0\nq 3 1 0 0 1 0 0 0 0\nv 4 2\nv 5 3\n+ 6 4 5 2\n"; + assert_eq!( + rna_to_dna(source), + Err(RnaError::Graph { + span: RnaSpan::new(7, 1, 1), + error: Obstruction::DimensionMismatch { + left: Dimension::LENGTH, + right: Dimension::TIME, + }, + }) + ); +} + +#[test] +fn rna_rejects_nonsequential_context_ids() { + let source = b"L64R1 0x1\na 1 0x52\nq 2 1 0 0 0 0 0 0 0\nv 3 2\nk 4 3 1 1\nh 2 0 4\n"; + assert_eq!( + compile_rna(source).unwrap_err(), + RnaError::ContextOrder { + span: RnaSpan::new(6, 3, 1), + context: 2, + } + ); +} + +#[test] +fn rna_diagnostic_renders_exact_token_span() { + let source = b"L64R1 0x1\na nope 0x41\n"; + let error = compile_rna(source).unwrap_err(); + assert_eq!( + error, + RnaError::InvalidNumber { + span: RnaSpan::new(2, 3, 4), + } + ); + let diagnostic = format!("{}", rna_diagnostic(source, error)); + assert!(diagnostic.contains("invalid number at RNA 2:3")); + assert!(diagnostic.contains("2 | a nope 0x41")); + assert!(diagnostic.contains("| ^^^^")); +} diff --git a/l64-native/tests/symbol.rs b/l64-native/tests/symbol.rs new file mode 100644 index 0000000..39480d5 --- /dev/null +++ b/l64-native/tests/symbol.rs @@ -0,0 +1,65 @@ +use l64_native::{Graph, LocusWord, ROOT_CONTEXT, Route, canonical_bytes, decode_canonical}; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x53594d424f4c4943)).composed(LocusWord(index)) +} + +#[test] +fn exact_state_identity_is_canonical_byte_identity() { + let mut left = Graph::new(); + left.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + + let mut right = Graph::new(); + right.declare_atom_type(route(1), LocusWord(0x42)).unwrap(); + + let left_identity = left.exact_state_identity(); + let right_identity = right.exact_state_identity(); + assert!(left_identity.verify_exact("l64.native.state.v2", &canonical_bytes(&left))); + assert_ne!(left_identity, right_identity); + assert_ne!(left_identity.seal(), right_identity.seal()); +} + +#[test] +fn state_symbol_localizes_structural_change_classes() { + let mut graph = Graph::new(); + let empty = graph.state_symbol(); + + let atom = graph.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + let after_atom = graph.state_symbol(); + assert_eq!( + empty.changed_sections(after_atom), + [true, false, false, true] + ); + + graph.declare_function_type(route(2), atom, atom).unwrap(); + let after_function = graph.state_symbol(); + assert_eq!( + after_atom.changed_sections(after_function), + [true, true, false, true] + ); + + graph.extend_context(ROOT_CONTEXT, atom).unwrap(); + let after_context = graph.state_symbol(); + assert_eq!( + after_function.changed_sections(after_context), + [false, false, true, false] + ); +} + +#[test] +fn symbolic_and_exact_identity_survive_canonical_fixed_point() { + let mut graph = Graph::new(); + let atom = graph.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + graph.declare_function_type(route(2), atom, atom).unwrap(); + graph.extend_context(ROOT_CONTEXT, atom).unwrap(); + + let bytes = canonical_bytes(&graph); + let decoded = decode_canonical(&bytes).unwrap(); + assert_eq!(decoded.state_symbol(), graph.state_symbol()); + assert_eq!(decoded.exact_state_identity(), graph.exact_state_identity()); + assert!( + decoded + .exact_state_identity() + .verify_exact("l64.native.state.v2", &bytes) + ); +} diff --git a/l64-native/tests/workloads.rs b/l64-native/tests/workloads.rs new file mode 100644 index 0000000..0510a5f --- /dev/null +++ b/l64-native/tests/workloads.rs @@ -0,0 +1,111 @@ +use l64_native::{Graph, LocusWord, Obstruction, OpCode, Proposal, ROOT_CONTEXT, Route}; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x4c36344e41544956)).composed(LocusWord(index)) +} + +#[test] +fn valid_typed_function_composition_commits() { + let mut graph = Graph::new(); + let a = graph.declare_atom_type(route(1), LocusWord(0x41)).unwrap(); + let b = graph.declare_atom_type(route(2), LocusWord(0x42)).unwrap(); + let c = graph.declare_atom_type(route(3), LocusWord(0x43)).unwrap(); + let ab = graph.declare_function_type(route(4), a, b).unwrap(); + let bc = graph.declare_function_type(route(5), b, c).unwrap(); + let ac = graph.declare_function_type(route(6), a, c).unwrap(); + let first = graph.insert_value(route(7), ROOT_CONTEXT, ab).unwrap(); + let second = graph.insert_value(route(8), ROOT_CONTEXT, bc).unwrap(); + let before = graph.state_symbol(); + let before_nodes = graph.node_count(); + + let committed = graph + .transact(Proposal::compose(route(9), ROOT_CONTEXT, first, second, ac)) + .unwrap(); + + assert_eq!(graph.node_count(), before_nodes + 3); + assert_ne!(graph.state_symbol(), before); + assert_eq!(graph.node(committed.node).unwrap().ty(), Some(ac)); + assert_eq!(graph.ports(committed.node).unwrap().len(), 2); + let evidence = graph.node(committed.evidence).unwrap(); + assert_eq!(evidence.opcode(), OpCode::KernelWitness); + let judgment = evidence.ty().unwrap(); + assert_eq!(graph.node(judgment).unwrap().opcode(), OpCode::TypeJudgment); + assert_eq!(graph.ports(judgment).unwrap().len(), 4); + assert_eq!(graph.journal().last().unwrap().after(), committed.symbol); +} + +#[test] +fn invalid_matrix_shape_rejects_without_mutation() { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(11), LocusWord(0x52)).unwrap(); + let left_ty = graph.declare_matrix_type(route(12), scalar, 2, 3).unwrap(); + let right_ty = graph.declare_matrix_type(route(13), scalar, 4, 2).unwrap(); + let output_ty = graph.declare_matrix_type(route(14), scalar, 2, 2).unwrap(); + let left = graph + .insert_value(route(15), ROOT_CONTEXT, left_ty) + .unwrap(); + let right = graph + .insert_value(route(16), ROOT_CONTEXT, right_ty) + .unwrap(); + + let before_commitment = graph.state_symbol(); + let before_nodes = graph.node_count(); + let before_ports = graph.port_count(); + let before_contexts = graph.context_count(); + let before_journal = graph.journal_len(); + + let result = graph.transact(Proposal::matrix_multiply( + route(17), + ROOT_CONTEXT, + left, + right, + output_ty, + )); + + assert_eq!( + result, + Err(Obstruction::MatrixShapeMismatch { + left_cols: 3, + right_rows: 4, + }) + ); + assert_eq!(graph.state_symbol(), before_commitment); + assert_eq!(graph.node_count(), before_nodes); + assert_eq!(graph.port_count(), before_ports); + assert_eq!(graph.context_count(), before_contexts); + assert_eq!(graph.journal_len(), before_journal); + assert!(graph.resolve(&route(17)).is_none()); +} + +#[test] +fn kernel_judgment_cannot_be_forged_through_value_insertion() { + let mut graph = Graph::new(); + let a = graph.declare_atom_type(route(31), LocusWord(0x41)).unwrap(); + let b = graph.declare_atom_type(route(32), LocusWord(0x42)).unwrap(); + let c = graph.declare_atom_type(route(33), LocusWord(0x43)).unwrap(); + let ab = graph.declare_function_type(route(34), a, b).unwrap(); + let bc = graph.declare_function_type(route(35), b, c).unwrap(); + let ac = graph.declare_function_type(route(36), a, c).unwrap(); + let first = graph.insert_value(route(37), ROOT_CONTEXT, ab).unwrap(); + let second = graph.insert_value(route(38), ROOT_CONTEXT, bc).unwrap(); + let committed = graph + .transact(Proposal::compose( + route(39), + ROOT_CONTEXT, + first, + second, + ac, + )) + .unwrap(); + let judgment = graph.node(committed.evidence).unwrap().ty().unwrap(); + let before = graph.state_symbol(); + let before_nodes = graph.node_count(); + + assert_eq!( + graph.insert_value(route(40), ROOT_CONTEXT, judgment), + Err(Obstruction::EvidenceOnlyType { node: judgment }) + ); + assert_eq!(graph.state_symbol(), before); + assert_eq!(graph.node_count(), before_nodes); + assert!(graph.resolve(&route(40)).is_none()); +} diff --git a/l64-observation/Cargo.toml b/l64-observation/Cargo.toml new file mode 100644 index 0000000..937f34e --- /dev/null +++ b/l64-observation/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "l64-observation" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +l64-native = { path = "../l64-native" } +l64-projection = { path = "../l64-projection" } +l64-transport = { path = "../l64-transport" } +l64-certification = { path = "../l64-certification" } diff --git a/l64-observation/README.md b/l64-observation/README.md new file mode 100644 index 0000000..abd38e0 --- /dev/null +++ b/l64-observation/README.md @@ -0,0 +1,11 @@ +# l64-observation + +`l64-observation` is the read-only current-path observation carrier for exact native authority. + +It binds three already-existing contacts for every native context: + +- direct structural certification from `l64-certification`, +- verified replay projection from `l64-projection`, +- verified closure/opcode report projection from `l64-projection`. + +The carrier does not persist reports, create campaigns, resolve policies, manage caches, or issue a second authority. A native bundle remains an ordered transport of independently observed `L64D` members and receives no composite authority, verdict, or observation. diff --git a/l64-observation/src/lib.rs b/l64-observation/src/lib.rs new file mode 100644 index 0000000..aa11e36 --- /dev/null +++ b/l64-observation/src/lib.rs @@ -0,0 +1,266 @@ +#![forbid(unsafe_code)] + +use l64_certification::{ + AuthorityCertification, CertificationError, ContextCertification, certify_graph, +}; +use l64_native::{ContextId, DnaError, Graph, OpCode, Route, decode_dna, dna_bytes}; +use l64_projection::{ProjectionError, ReplayView, ReportView}; +use l64_transport::{BundleError, decode_bundle}; +use std::fmt::{self, Write as _}; + +pub const OBSERVATION_VERSION: u16 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ObservationSurface { + Replay, + Report, +} + +impl fmt::Display for ObservationSurface { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Replay => "replay", + Self::Report => "report", + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ContextObservation { + pub certification: ContextCertification, + pub replay: ReplayView, + pub report: ReportView, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorityObservation { + pub certification: AuthorityCertification, + pub contexts: Vec, +} + +impl AuthorityObservation { + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE OBSERVATION v{OBSERVATION_VERSION}"); + self.render_into(&mut out, ""); + out + } + + pub fn render_into(&self, out: &mut String, prefix: &str) { + render_authority(out, self, prefix); + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BundleObservation { + pub members: Vec, +} + +impl BundleObservation { + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE BUNDLE OBSERVATION v{OBSERVATION_VERSION}"); + let _ = writeln!(out, "transport=canonical_l64b"); + let _ = writeln!(out, "transport_verified=true"); + let _ = writeln!(out, "members={}", self.members.len()); + let _ = writeln!(out, "composite_authority=none"); + let _ = writeln!(out, "composite_verdict=none"); + let _ = writeln!(out, "composite_observation=none"); + for (index, member) in self.members.iter().enumerate() { + member.render_into(&mut out, &format!("member.{index}.")); + } + out + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ObservationError { + Dna(DnaError), + NonCanonicalDna, + Certification(CertificationError), + Projection { + context: ContextId, + surface: ObservationSurface, + error: ProjectionError, + }, + Bundle(BundleError), +} + +impl fmt::Display for ObservationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Dna(error) => write!(f, "DNA observation failed: {error}"), + Self::NonCanonicalDna => f.write_str("observation requires canonical L64D authority"), + Self::Certification(error) => write!(f, "observation certification failed: {error}"), + Self::Projection { + context, + surface, + error, + } => write!( + f, + "{surface} projection failed in context {context}: {error}" + ), + Self::Bundle(error) => write!(f, "bundle observation failed: {error}"), + } + } +} + +impl std::error::Error for ObservationError {} + +pub fn observe_dna(bytes: &[u8]) -> Result { + let graph = decode_dna(bytes).map_err(ObservationError::Dna)?; + let canonical = dna_bytes(&graph).map_err(ObservationError::Dna)?; + if canonical != bytes { + return Err(ObservationError::NonCanonicalDna); + } + observe_canonical_graph(&graph) +} + +pub fn observe_bundle(bytes: &[u8]) -> Result { + let bundle = decode_bundle(bytes).map_err(ObservationError::Bundle)?; + let mut members = Vec::with_capacity(bundle.len()); + for member in bundle.members() { + members.push(observe_canonical_graph(member.graph())?); + } + Ok(BundleObservation { members }) +} + +pub fn observe_canonical_graph(graph: &Graph) -> Result { + let certification = certify_graph(graph).map_err(ObservationError::Certification)?; + let mut contexts = Vec::with_capacity(graph.context_count()); + for context in 0..graph.context_count() as ContextId { + let replay = + ReplayView::derive(graph, context).map_err(|error| ObservationError::Projection { + context, + surface: ObservationSurface::Replay, + error, + })?; + replay + .verify(graph) + .map_err(|error| ObservationError::Projection { + context, + surface: ObservationSurface::Replay, + error, + })?; + + let report = + ReportView::derive(graph, context).map_err(|error| ObservationError::Projection { + context, + surface: ObservationSurface::Report, + error, + })?; + report + .verify(graph) + .map_err(|error| ObservationError::Projection { + context, + surface: ObservationSurface::Report, + error, + })?; + + let context_certification = certification.contexts[context as usize].clone(); + contexts.push(ContextObservation { + certification: context_certification, + replay, + report, + }); + } + Ok(AuthorityObservation { + certification, + contexts, + }) +} + +fn render_authority(out: &mut String, observation: &AuthorityObservation, prefix: &str) { + let authority = &observation.certification; + let _ = writeln!(out, "{prefix}scope=native_certification_replay_observation"); + let _ = writeln!(out, "{prefix}authority=exact_canonical_l64d"); + let _ = writeln!(out, "{prefix}canonical_dna={}", authority.canonical_dna); + let _ = writeln!(out, "{prefix}projection_authority=non_authoritative"); + let _ = writeln!(out, "{prefix}symbol={}", authority.symbol); + let _ = writeln!(out, "{prefix}nodes={}", authority.node_count); + let _ = writeln!(out, "{prefix}contexts={}", authority.context_count); + let _ = writeln!(out, "{prefix}journal={}", authority.journal_len); + let _ = writeln!(out, "{prefix}verdict={}", authority.verdict); + + for context in &observation.contexts { + let id = context.certification.context; + let context_prefix = format!("{prefix}context.{id}."); + let _ = writeln!( + out, + "{context_prefix}certification_projection_verified={}", + context.certification.projection_verified + ); + let _ = writeln!(out, "{context_prefix}replay_projection_verified=true"); + let _ = writeln!(out, "{context_prefix}report_projection_verified=true"); + let _ = writeln!( + out, + "{context_prefix}verdict={}", + context.certification.verdict + ); + let _ = writeln!(out, "{context_prefix}closed={}", context.report.closed); + let _ = writeln!(out, "{context_prefix}open={}", context.report.open); + let _ = writeln!(out, "{context_prefix}invalid={}", context.report.invalid); + let _ = writeln!( + out, + "{context_prefix}obligation_routes={}", + context.report.obligation_routes.len() + ); + let _ = writeln!( + out, + "{context_prefix}invalid_routes={}", + context.report.invalid_routes.len() + ); + for count in &context.report.opcode_counts { + let _ = writeln!( + out, + "{context_prefix}opcode.{}.count={}", + opcode_number(count.opcode), + count.count + ); + } + let _ = writeln!( + out, + "{context_prefix}replay_steps={}", + context.replay.steps.len() + ); + for (ordinal, step) in context.replay.steps.iter().enumerate() { + let step_prefix = format!("{context_prefix}replay.{ordinal}."); + let _ = writeln!(out, "{step_prefix}event={}", step.event); + let _ = writeln!( + out, + "{step_prefix}operation={}", + opcode_number(step.operation) + ); + let _ = writeln!(out, "{step_prefix}subject_node={}", step.subject.node); + let _ = writeln!( + out, + "{step_prefix}subject_context={}", + step.subject.declared_context + ); + let _ = writeln!( + out, + "{step_prefix}subject_route={}", + render_route(&step.subject.route) + ); + let _ = writeln!(out, "{step_prefix}before={}", step.before); + let _ = writeln!(out, "{step_prefix}after={}", step.after); + let parent = step + .parent + .map(|value| value.to_string()) + .unwrap_or_else(|| "none".to_string()); + let _ = writeln!(out, "{step_prefix}parent={parent}"); + } + } +} + +fn opcode_number(opcode: OpCode) -> u16 { + opcode as u16 +} + +fn render_route(route: &Route) -> String { + let mut out = format!("{:016x}", route.domain().0); + for word in route.tail() { + let _ = write!(out, "/{:016x}", word.0); + } + out +} diff --git a/l64-observation/tests/architecture.rs b/l64-observation/tests/architecture.rs new file mode 100644 index 0000000..dc04840 --- /dev/null +++ b/l64-observation/tests/architecture.rs @@ -0,0 +1,57 @@ +use std::{fs, path::Path}; + +#[test] +fn observation_depends_only_on_current_native_carriers() { + let manifest = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml")) + .expect("read observation manifest"); + let dependency_block = manifest + .split_once("[dependencies]") + .map(|(_, tail)| tail) + .expect("dependency block"); + let dependencies = dependency_block + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .collect::>(); + assert_eq!( + dependencies, + vec![ + "l64-native = { path = \"../l64-native\" }", + "l64-projection = { path = \"../l64-projection\" }", + "l64-transport = { path = \"../l64-transport\" }", + "l64-certification = { path = \"../l64-certification\" }", + ] + ); +} + +#[test] +fn observation_source_contains_no_schema_forest() { + let source = fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("lib.rs"), + ) + .expect("read observation source"); + for forbidden in [ + "serde", + "bincode", + "HashMap", + "std::fs", + "thread", + "Mutex", + "RwLock", + "cache", + "Registry", + "BundleWorld", + "Policy", + "Campaign", + "Receipt", + "digest", + "blake3", + ] { + assert!( + !source.contains(forbidden), + "native observation source contains forbidden token {forbidden}" + ); + } +} diff --git a/l64-observation/tests/observation.rs b/l64-observation/tests/observation.rs new file mode 100644 index 0000000..5e83053 --- /dev/null +++ b/l64-observation/tests/observation.rs @@ -0,0 +1,122 @@ +use l64_certification::CertificationVerdict; +use l64_native::{ + ConstraintKind, Dimension, Graph, LocusWord, Proposal, ROOT_CONTEXT, Route, dna_bytes, + rna_to_dna, +}; +use l64_observation::{ObservationError, observe_bundle, observe_dna}; +use l64_transport::bundle_bytes; + +const CERTIFIED_RNA: &[u8] = b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n"; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x4f42534552564531)).composed(LocusWord(index)) +} + +fn open_graph() -> (Graph, u32) { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let quantity = graph + .declare_quantity_type(route(2), scalar, Dimension::new([0, 0, 0, 0, 0, 0, 0])) + .unwrap(); + let subject = graph + .insert_value(route(3), ROOT_CONTEXT, quantity) + .unwrap(); + graph + .transact(Proposal::square_root( + route(4), + ROOT_CONTEXT, + subject, + quantity, + )) + .unwrap(); + (graph, subject) +} + +#[test] +fn canonical_authority_observation_binds_verified_native_surfaces() { + let dna = rna_to_dna(CERTIFIED_RNA).unwrap(); + let observation = observe_dna(&dna).unwrap(); + assert_eq!( + observation.certification.verdict, + CertificationVerdict::Certified + ); + assert_eq!(observation.contexts.len(), 1); + let root = &observation.contexts[0]; + assert!(root.certification.projection_verified); + assert_eq!( + root.replay.steps.len(), + observation.certification.journal_len + ); + assert_eq!(root.report.invalid, 0); + let rendered = observation.render_text(); + assert!(rendered.contains("authority=exact_canonical_l64d")); + assert!(rendered.contains("projection_authority=non_authoritative")); + assert!(rendered.contains("replay_projection_verified=true")); + assert!(rendered.contains("report_projection_verified=true")); +} + +#[test] +fn open_burden_is_observed_without_becoming_a_campaign() { + let (graph, _) = open_graph(); + let observation = observe_dna(&dna_bytes(&graph).unwrap()).unwrap(); + assert_eq!( + observation.certification.verdict, + CertificationVerdict::Open + ); + assert_eq!(observation.contexts[0].certification.burdens.open, 1); + assert!(observation.contexts[0].report.open >= 1); +} + +#[test] +fn invalid_child_context_remains_visible_in_report_and_certification() { + let (mut graph, subject) = open_graph(); + let cause = graph + .declare_constraint( + route(5), + ROOT_CONTEXT, + subject, + ConstraintKind::NonNegative, + false, + ) + .unwrap(); + let child = graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let observation = observe_dna(&dna_bytes(&graph).unwrap()).unwrap(); + assert_eq!( + observation.certification.verdict, + CertificationVerdict::Invalid + ); + let child = &observation.contexts[child as usize]; + assert_eq!(child.certification.verdict, CertificationVerdict::Invalid); + assert!(child.report.invalid > 0); + assert!(!child.report.invalid_routes.is_empty()); +} + +#[test] +fn bundle_members_are_observed_independently() { + let certified = rna_to_dna(CERTIFIED_RNA).unwrap(); + let (open, _) = open_graph(); + let open = dna_bytes(&open).unwrap(); + let bundle = bundle_bytes(&[&certified, &open]).unwrap(); + let observation = observe_bundle(&bundle).unwrap(); + assert_eq!(observation.members.len(), 2); + assert_eq!( + observation.members[0].certification.verdict, + CertificationVerdict::Certified + ); + assert_eq!( + observation.members[1].certification.verdict, + CertificationVerdict::Open + ); + let rendered = observation.render_text(); + assert!(rendered.contains("composite_authority=none")); + assert!(rendered.contains("composite_verdict=none")); + assert!(rendered.contains("composite_observation=none")); + assert!(!rendered.contains("bundle_verdict=")); +} + +#[test] +fn trailing_dna_bytes_are_rejected() { + let mut dna = rna_to_dna(CERTIFIED_RNA).unwrap(); + dna.push(0); + assert!(matches!(observe_dna(&dna), Err(ObservationError::Dna(_)))); +} diff --git a/l64-observe/Cargo.toml b/l64-observe/Cargo.toml deleted file mode 100644 index 92abedc..0000000 --- a/l64-observe/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "l64-observe" -version.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -anyhow.workspace = true -serde.workspace = true -serde_json.workspace = true -bincode.workspace = true -l64-core = { path = "../l64-core" } -l64-locus = { path = "../l64-locus" } -l64-bundle = { path = "../l64-bundle" } -l64-cert = { path = "../l64-cert" } -l64-atlas = { path = "../l64-atlas" } -l64-policy = { path = "../l64-policy" } diff --git a/l64-observe/src/lib.rs b/l64-observe/src/lib.rs deleted file mode 100644 index cdd1cf7..0000000 --- a/l64-observe/src/lib.rs +++ /dev/null @@ -1,2729 +0,0 @@ -use anyhow::{Result, anyhow}; -use l64_atlas::CompiledAtlas; -use l64_bundle::{BundleWorld, load_bundle_world}; -use l64_cert::{ - CertificationOptions, certify_derived_campaign_with_options, - certify_derived_theorem_with_options, replay_report, -}; -use l64_core::{ - BundleLock, CertificationReport, DriftReport, ExecutionEvent, ExecutionEventKind, - ExecutionManifest, ExecutionScheduleHash, ExecutionScope, ExplanationObject, ImpactPrediction, - LocusCapabilityMask, LocusOpcode, LocusPacketKind, ObligationDrift, ObligationStatus, - ObservationEdge, ObservationGraph, ObservationNode, ObservationNodeKind, ObservationRecord, - OrderingReceipt, ParallelizationPolicy, PlanExecutionRecord, PolicyResolution, - PredictionAssessment, PredictionAssessmentOutcome, PredictionClass, RecomputationPlan, - RecomputationStep, RecomputationStepKind, ReconciliationRecord, RegistryLookup, ReplayStatus, - ReuseTrustClass, RiskClassification, RouteExplanation, ScheduledStepStatus, - SchedulerDecisionReceipt, SchedulerPolicy, SemanticDiff, SemanticDiffClass, - StepExecutionOutcome, TheoremDrift, resolve_cache_root, runtime_root_report, -}; -use l64_locus::{decode_section_payload, write_section_packet}; -use l64_policy::resolve_policy_graph; -use serde::{Deserialize, Serialize, de::DeserializeOwned}; -use std::{ - collections::{BTreeMap, BTreeSet, HashMap}, - fs, - path::PathBuf, - sync::mpsc, - thread, -}; - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObservationArtifact { - pub record: ObservationRecord, - pub graph: ObservationGraph, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ObserveRunResult { - pub artifact: ObservationArtifact, - pub persisted_path: String, -} - -fn receipt_count(receipts: &[l64_core::ObligationEvidenceReceipt]) -> usize { - receipts - .iter() - .map(|receipt| 1 + receipt_count(&receipt.subreceipts)) - .sum() -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum PredictionTarget { - ProposedBundle { - bundle_id: String, - policy_resolution: Option, - theorem_ids: Vec, - campaign_ids: Vec, - route_candidate_ids: Vec, - dependency_ids: Vec, - }, - PolicyOverride { - policy_id: String, - kind: String, - notes: Vec, - }, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct PredictionRecord { - pub prediction: ImpactPrediction, - pub target: PredictionTarget, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ExecutePlanOptions { - pub dry_run: bool, - pub no_cache: bool, - pub strict: bool, - pub force_parallel: bool, - pub force_parallel_obligations: bool, - pub force_serialized: bool, - pub max_workers: Option, - pub max_obligation_workers: Option, - pub strict_determinism: bool, -} - -impl Default for ExecutePlanOptions { - fn default() -> Self { - Self { - dry_run: false, - no_cache: false, - strict: false, - force_parallel: false, - force_parallel_obligations: false, - force_serialized: false, - max_workers: None, - max_obligation_workers: None, - strict_determinism: true, - } - } -} - -#[derive(Debug, Clone)] -struct ExecutedTaskBatch { - reports: Vec, - lane_records: Vec, - schedule_hash: ExecutionScheduleHash, - coherence_receipts: Vec, - ordering_receipt: OrderingReceipt, - explanation: Vec, -} - -impl ExecutedTaskBatch { - fn empty() -> Self { - Self { - reports: Vec::new(), - lane_records: Vec::new(), - schedule_hash: ExecutionScheduleHash { - id: "SCHH_EMPTY".into(), - hash: "empty".into(), - }, - coherence_receipts: Vec::new(), - ordering_receipt: OrderingReceipt { - id: "ORD_EMPTY".into(), - ordered_step_ids: Vec::new(), - notes: vec!["no execution steps".into()], - }, - explanation: Vec::new(), - } - } -} - -fn cache_root() -> Result { - let root = PathBuf::from( - resolve_cache_root() - .map_err(anyhow::Error::msg)? - .absolute_path, - ) - .join("observe"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn observations_root() -> Result { - let root = cache_root()?.join("observations"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn diffs_root() -> Result { - let root = cache_root()?.join("diffs"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn predictions_root() -> Result { - let root = cache_root()?.join("predictions"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn plans_root() -> Result { - let root = cache_root()?.join("plans"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn explanations_root() -> Result { - let root = cache_root()?.join("explanations"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn assessments_root() -> Result { - let root = cache_root()?.join("assessments"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn executions_root() -> Result { - let root = cache_root()?.join("executions"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn reconciliations_root() -> Result { - let root = cache_root()?.join("reconciliations"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn dna_store_path(root: &PathBuf, id: &str) -> PathBuf { - root.join(format!("{id}.dna")) -} - -fn persist_store_payload( - root: PathBuf, - id: &str, - kind: LocusPacketKind, - opcode: LocusOpcode, - schema_hash: &str, - payload: &T, - capabilities: LocusCapabilityMask, -) -> Result { - let path = dna_store_path(&root, id); - write_section_packet( - &path, - kind, - opcode, - id, - schema_hash, - payload, - capabilities, - 1, - ) - .map_err(anyhow::Error::msg)?; - Ok(path) -} - -fn load_store_payload( - root: PathBuf, - id: &str, - opcode: LocusOpcode, -) -> Result { - let dna_path = dna_store_path(&root, id); - decode_section_payload(&fs::read(dna_path)?, opcode).map_err(anyhow::Error::msg) -} - -pub fn observe_report( - report: &CertificationReport, - manifest: Option<&ExecutionManifest>, - lock: Option<&BundleLock>, -) -> Result { - let report_id = report_id(report); - let record_id = format!("OBS_{report_id}"); - let graph_id = format!("OBG_{report_id}"); - let mut nodes = Vec::new(); - let mut edges = Vec::new(); - let mut events = Vec::new(); - let mut choices = Vec::new(); - let mut obligation_traces = Vec::new(); - let mut route_events = Vec::new(); - let mut cache_events = Vec::new(); - - nodes.push(ObservationNode { - id: format!("OBN_{report_id}_REPORT"), - kind: ObservationNodeKind::Report, - ref_id: report_id.clone(), - label: format!("report {}", report.theorem_id), - attributes: btreemap([("verdict", format!("{:?}", report.verdict))]), - }); - nodes.push(ObservationNode { - id: format!("OBN_{report_id}_THEOREM"), - kind: ObservationNodeKind::Theorem, - ref_id: report.theorem_id.clone(), - label: report.theorem_id.clone(), - attributes: BTreeMap::new(), - }); - edges.push(edge( - &format!("OBN_{report_id}_THEOREM"), - &format!("OBN_{report_id}_REPORT"), - "reported-as", - )); - - if let Some(campaign_id) = &report.campaign_id { - nodes.push(ObservationNode { - id: format!("OBN_{report_id}_CAMPAIGN"), - kind: ObservationNodeKind::Campaign, - ref_id: campaign_id.clone(), - label: campaign_id.clone(), - attributes: BTreeMap::new(), - }); - edges.push(edge( - &format!("OBN_{report_id}_CAMPAIGN"), - &format!("OBN_{report_id}_REPORT"), - "certified-as", - )); - } - - if let Some(policy_resolution) = &report.policy_resolution { - nodes.push(ObservationNode { - id: format!("OBN_{report_id}_POLICY"), - kind: ObservationNodeKind::PolicyResolution, - ref_id: policy_resolution.id.clone(), - label: policy_resolution.id.clone(), - attributes: btreemap([ - ("scope", format!("{:?}", policy_resolution.scope)), - ("verdict", format!("{:?}", policy_resolution.verdict)), - ]), - }); - edges.push(edge( - &format!("OBN_{report_id}_POLICY"), - &format!("OBN_{report_id}_REPORT"), - "governs", - )); - for policy_id in &policy_resolution.applied_policy_ids { - let node_id = format!("OBN_{report_id}_APPLIED_{policy_id}"); - nodes.push(ObservationNode { - id: node_id.clone(), - kind: ObservationNodeKind::PolicyObject, - ref_id: policy_id.clone(), - label: policy_id.clone(), - attributes: BTreeMap::new(), - }); - edges.push(edge( - &node_id, - &format!("OBN_{report_id}_POLICY"), - "applied-by", - )); - } - } - - if let Some(winner) = &report.selected_atlas_cell { - nodes.push(ObservationNode { - id: format!("OBN_{report_id}_ROUTE"), - kind: ObservationNodeKind::RouteWinner, - ref_id: winner.clone(), - label: winner.clone(), - attributes: btreemap([("path", report.selected_path.join("->"))]), - }); - edges.push(edge( - &format!("OBN_{report_id}_ROUTE"), - &format!("OBN_{report_id}_REPORT"), - "selected-for", - )); - events.push(ExecutionEvent { - id: format!("EVT_{report_id}_ROUTE"), - kind: ExecutionEventKind::RouteSelected, - summary: format!("selected route winner {winner}"), - related_ids: vec![winner.clone(), report_id.clone()], - }); - } - - if let Some(explanation) = &report.route_explanation { - route_events.push(route_trace(report, explanation)); - choices.push(mk_choice(report, explanation)); - } - - for obligation in &report.obligations { - let node_id = format!("OBN_{report_id}_OBL_{}", obligation.obligation_id); - nodes.push(ObservationNode { - id: node_id.clone(), - kind: ObservationNodeKind::Obligation, - ref_id: obligation.obligation_id.clone(), - label: obligation.obligation_id.clone(), - attributes: btreemap([ - ("verdict", format!("{:?}", obligation.verdict)), - ("mode", format!("{:?}", obligation.evaluation_mode)), - ( - "receipt_count", - receipt_count(&obligation.receipts).to_string(), - ), - ]), - }); - edges.push(edge( - &node_id, - &format!("OBN_{report_id}_REPORT"), - "evaluated-for", - )); - obligation_traces.push(mk_obligation_trace(report, obligation)); - events.push(ExecutionEvent { - id: format!("EVT_{report_id}_OBL_{}", obligation.obligation_id), - kind: ExecutionEventKind::ObligationEvaluated, - summary: format!( - "obligation {} {:?} {:?}", - obligation.obligation_id, obligation.verdict, obligation.evaluation_mode - ), - related_ids: vec![report_id.clone(), obligation.obligation_id.clone()], - }); - } - - if let Some(envelope) = &report.execution_envelope { - if let Some(bundle_id) = &envelope.bundle_id { - nodes.push(ObservationNode { - id: format!("OBN_{report_id}_BUNDLE"), - kind: ObservationNodeKind::Bundle, - ref_id: bundle_id.clone(), - label: bundle_id.clone(), - attributes: btreemap([("bundle_hash", envelope.bundle_hash.clone())]), - }); - edges.push(edge( - &format!("OBN_{report_id}_BUNDLE"), - &format!("OBN_{report_id}_REPORT"), - "executed-as", - )); - } - cache_events.push(l64_core::CacheReplayEvent { - id: format!("CCE_{report_id}"), - report_id: report_id.clone(), - replay_status: envelope.replay_status.clone(), - reason: format!("report replay status {:?}", envelope.replay_status), - }); - events.push(ExecutionEvent { - id: format!("EVT_{report_id}_CACHE"), - kind: match envelope.replay_status { - ReplayStatus::Fresh => ExecutionEventKind::CacheMiss, - ReplayStatus::CacheHit => ExecutionEventKind::CacheHit, - ReplayStatus::ReplayOnly => ExecutionEventKind::ReplayRun, - ReplayStatus::Invalidated => ExecutionEventKind::ReplayRun, - }, - summary: format!("replay status {:?}", envelope.replay_status), - related_ids: vec![report_id.clone()], - }); - } - - if let Some(manifest) = manifest { - nodes.push(ObservationNode { - id: format!("OBN_{report_id}_MANIFEST"), - kind: ObservationNodeKind::Manifest, - ref_id: manifest.id.clone(), - label: manifest.id.clone(), - attributes: btreemap([ - ("bundle_id", manifest.bundle_id.clone()), - ("policy_hash", manifest.policy_manifest.policy_hash.clone()), - ]), - }); - edges.push(edge( - &format!("OBN_{report_id}_MANIFEST"), - &format!("OBN_{report_id}_REPORT"), - "materializes", - )); - } - - if let Some(lock) = lock { - nodes.push(ObservationNode { - id: format!("OBN_{report_id}_LOCK"), - kind: ObservationNodeKind::Lock, - ref_id: lock.id.clone(), - label: lock.id.clone(), - attributes: btreemap([("manifest_id", lock.manifest_id.clone())]), - }); - edges.push(edge( - &format!("OBN_{report_id}_LOCK"), - &format!("OBN_{report_id}_REPORT"), - "locks", - )); - } - - let graph = ObservationGraph { - id: graph_id.clone(), - record_id: record_id.clone(), - nodes, - edges, - choices, - obligation_traces, - route_events, - cache_events, - }; - let record = ObservationRecord { - id: record_id.clone(), - report_id: report_id.clone(), - theorem_id: report.theorem_id.clone(), - campaign_id: report.campaign_id.clone(), - bundle_id: report - .execution_envelope - .as_ref() - .and_then(|item| item.bundle_id.clone()), - manifest_id: manifest.map(|item| item.id.clone()), - lock_id: lock.map(|item| item.id.clone()), - graph_id, - events, - }; - let artifact = ObservationArtifact { record, graph }; - let path = persist_store_payload( - observations_root()?, - &record_id, - LocusPacketKind::CanonicalTransfer, - LocusOpcode::Forensic, - "observe_artifact.v1", - &artifact, - LocusCapabilityMask { - has_forensic: true, - ..Default::default() - }, - )?; - Ok(ObserveRunResult { - artifact, - persisted_path: path.display().to_string(), - }) -} - -pub fn load_observation(id: &str) -> Result { - load_store_payload(observations_root()?, id, LocusOpcode::Forensic) -} - -pub fn compare_reports( - left: &CertificationReport, - right: &CertificationReport, -) -> Result { - let diff = semantic_diff_between_reports(left, right); - persist_diff(&diff)?; - Ok(diff) -} - -pub fn compare_manifests( - left: &ExecutionManifest, - right: &ExecutionManifest, -) -> Result { - let mut summary = Vec::new(); - let mut changed_policies = Vec::new(); - let mut changed_routes = Vec::new(); - let mut changed_deps = Vec::new(); - if left.policy_manifest.policy_hash != right.policy_manifest.policy_hash { - summary.push("policy graph changed".into()); - changed_policies.extend(right.policy_manifest.policy_ids.clone()); - } - if left.route_winner_ids != right.route_winner_ids { - summary.push("route winners changed".into()); - changed_routes.extend(symmetric_diff( - &left.route_winner_ids, - &right.route_winner_ids, - )); - } - if left.dependency_graph != right.dependency_graph { - summary.push("bundle dependency graph changed".into()); - changed_deps.extend(diff_dependencies( - &left.dependency_graph, - &right.dependency_graph, - )); - } - let diff = SemanticDiff { - id: format!("DIF_{}", stable_id(&(left.id.clone() + &right.id))), - left_id: left.id.clone(), - right_id: right.id.clone(), - class: classify( - !changed_policies.is_empty(), - !changed_routes.is_empty(), - false, - false, - !changed_deps.is_empty(), - ), - summary: if summary.is_empty() { - vec!["no semantic manifest drift".into()] - } else { - summary - }, - theorem_drifts: Vec::new(), - changed_policy_ids: changed_policies, - changed_route_ids: changed_routes, - changed_dependency_ids: changed_deps, - }; - persist_diff(&diff)?; - Ok(diff) -} - -pub fn compare_locks( - left_lock: &BundleLock, - left_manifest: &ExecutionManifest, - right_lock: &BundleLock, - right_manifest: &ExecutionManifest, -) -> Result { - let mut diff = compare_manifests(left_manifest, right_manifest)?; - diff.left_id = left_lock.id.clone(); - diff.right_id = right_lock.id.clone(); - if left_lock.report_ids != right_lock.report_ids { - diff.summary.push("locked report set changed".into()); - } - persist_diff(&diff)?; - Ok(diff) -} - -pub fn compare_report_manifest( - report: &CertificationReport, - manifest: &ExecutionManifest, -) -> Result { - let report_id = report_id(report); - let route_change = report - .selected_atlas_cell - .as_ref() - .map(|winner| !manifest.route_winner_ids.contains(winner)) - .unwrap_or(false); - let policy_change = report - .execution_envelope - .as_ref() - .map(|item| item.policy_hash != manifest.policy_manifest.policy_hash) - .unwrap_or(true); - let diff = SemanticDiff { - id: format!("DIF_{}", stable_id(&(report_id.clone() + &manifest.id))), - left_id: report_id, - right_id: manifest.id.clone(), - class: classify(policy_change, route_change, false, false, false), - summary: { - let mut summary = Vec::new(); - if policy_change { - summary.push("report policy provenance differs from manifest".into()); - } - if route_change { - summary.push("report route winner not present in manifest".into()); - } - if summary.is_empty() { - summary.push("report matches manifest semantically".into()); - } - summary - }, - theorem_drifts: Vec::new(), - changed_policy_ids: manifest.policy_manifest.policy_ids.clone(), - changed_route_ids: if route_change { - manifest.route_winner_ids.clone() - } else { - Vec::new() - }, - changed_dependency_ids: Vec::new(), - }; - persist_diff(&diff)?; - Ok(diff) -} - -pub fn compare_bundle_worlds(left: &BundleWorld, right: &BundleWorld) -> Result { - let mut summary = Vec::new(); - let changed_dependencies = - diff_dependencies(&left.manifest.dependencies, &right.manifest.dependencies); - let changed_policies = symmetric_diff( - &left - .overlay - .local - .policy_objects - .iter() - .map(|item| item.id.clone()) - .collect::>(), - &right - .overlay - .local - .policy_objects - .iter() - .map(|item| item.id.clone()) - .collect::>(), - ); - let local_semantics_changed = left.overlay.local != right.overlay.local; - if local_semantics_changed { - summary.push("bundle-local semantic payload changed".into()); - } - if !changed_policies.is_empty() { - summary.push("bundle-local policy objects changed".into()); - } - if !changed_dependencies.is_empty() { - summary.push("bundle dependency graph changed".into()); - } - let diff = SemanticDiff { - id: format!( - "DIF_{}", - stable_id(&(left.manifest.id.clone() + &right.manifest.id)) - ), - left_id: left.manifest.id.clone(), - right_id: right.manifest.id.clone(), - class: if !local_semantics_changed { - SemanticDiffClass::NoSemanticChange - } else { - classify( - !changed_policies.is_empty(), - false, - false, - false, - !changed_dependencies.is_empty(), - ) - }, - summary: if summary.is_empty() { - vec!["surface-only or filename-only change lowered to identical semantic bundle".into()] - } else { - summary - }, - theorem_drifts: Vec::new(), - changed_policy_ids: changed_policies, - changed_route_ids: Vec::new(), - changed_dependency_ids: changed_dependencies, - }; - persist_diff(&diff)?; - Ok(diff) -} - -pub fn explain_drift(diff: &SemanticDiff) -> Result { - let mut details = diff.summary.clone(); - for theorem in &diff.theorem_drifts { - if theorem.route_before != theorem.route_after { - details.push(format!( - "theorem {} changed route from {:?} to {:?}", - theorem.theorem_id, theorem.route_before, theorem.route_after - )); - } - for obligation in &theorem.obligation_drifts { - details.push(format!( - "obligation {} drifted from {:?}/{:?} to {:?}/{:?}: {}", - obligation.obligation_id, - obligation.verdict_before, - obligation.mode_before, - obligation.verdict_after, - obligation.mode_after, - obligation.meaning - )); - } - } - let explanation = ExplanationObject { - id: format!("EXC_{}", stable_id(&diff.id)), - title: format!("constitutional drift for {}", diff.id), - details, - related_ids: vec![diff.left_id.clone(), diff.right_id.clone(), diff.id.clone()], - }; - persist_store_payload( - explanations_root()?, - &explanation.id, - LocusPacketKind::CanonicalTransfer, - LocusOpcode::Forensic, - "explanation_object.v1", - &explanation, - LocusCapabilityMask { - has_forensic: true, - ..Default::default() - }, - )?; - Ok(explanation) -} - -pub fn drift_report(diff: &SemanticDiff) -> Result { - let report = DriftReport { - id: format!("DRF_{}", stable_id(&diff.id)), - diff_id: diff.id.clone(), - summary: diff.summary.clone(), - theorem_drifts: diff.theorem_drifts.clone(), - }; - persist_store_payload( - explanations_root()?, - &format!("{}.drift", report.id), - LocusPacketKind::CanonicalTransfer, - LocusOpcode::Forensic, - "drift_report.v1", - &report, - LocusCapabilityMask { - has_forensic: true, - ..Default::default() - }, - )?; - Ok(report) -} - -pub fn predict_from_bundle_change( - baseline_report: &CertificationReport, - baseline_bundle: Option<&BundleWorld>, - proposed_bundle: &BundleWorld, - proposed_resolution: Option<&PolicyResolution>, -) -> Result { - let mut reasons = Vec::new(); - let mut class = PredictionClass::InconclusivePrediction; - let mut confidence = RiskClassification::Unknown; - - if let Some(base_bundle) = baseline_bundle { - let bundle_diff = compare_bundle_worlds(base_bundle, proposed_bundle)?; - match bundle_diff.class { - SemanticDiffClass::NoSemanticChange => { - class = PredictionClass::NoImpactPredicted; - confidence = RiskClassification::Exact; - reasons.push("proposed bundle lowers to the same semantic overlay world".into()); - } - SemanticDiffClass::PolicyOnly => { - if let Some(resolution) = proposed_resolution { - let base = baseline_report.policy_resolution.as_ref(); - if let Some(base) = base { - if base.replay_cache != resolution.replay_cache - && base.optimizer == resolution.optimizer - && base.evaluator == resolution.evaluator - { - class = PredictionClass::ReplayOnlyImpact; - confidence = RiskClassification::Strong; - reasons.push("replay/cache policy changed without route or evaluator policy changes".into()); - } else if base.optimizer != resolution.optimizer { - class = PredictionClass::RouteWinnerChangeLikely; - confidence = RiskClassification::Strong; - reasons.push("optimizer backend or active axes changed".into()); - } else if base.evaluator != resolution.evaluator { - class = classify_evaluator_prediction( - baseline_report, - resolution, - &mut reasons, - ); - confidence = RiskClassification::Strong; - } else { - class = PredictionClass::ReportHashChangeLikely; - confidence = RiskClassification::Moderate; - reasons.push("policy provenance changed without obvious route or obligation trigger".into()); - } - } - } - } - SemanticDiffClass::BundleDependencyOnly => { - class = PredictionClass::RouteWinnerChangeLikely; - confidence = RiskClassification::Moderate; - reasons.push( - "bundle dependency graph changed, so route winners may need re-selection" - .into(), - ); - } - _ => { - class = PredictionClass::CertificationVerdictChangeLikely; - confidence = RiskClassification::Moderate; - reasons.extend(bundle_diff.summary); - } - } - } - - if let Some(resolution) = proposed_resolution { - if let Some(base) = &baseline_report.policy_resolution { - if base.optimizer != resolution.optimizer { - class = PredictionClass::RouteWinnerChangeLikely; - confidence = RiskClassification::Strong; - reasons.push("policy graph changes route ranking rules".into()); - } - if base.evaluator != resolution.evaluator { - class = classify_evaluator_prediction(baseline_report, resolution, &mut reasons); - confidence = RiskClassification::Strong; - } - if base.replay_cache != resolution.replay_cache - && matches!(class, PredictionClass::NoImpactPredicted) - { - class = PredictionClass::ReplayOnlyImpact; - confidence = RiskClassification::Strong; - reasons.push("replay/cache reuse rules changed".into()); - } - } - } - - let prediction = ImpactPrediction { - id: format!( - "PRD_{}", - stable_id(&(report_id(baseline_report) + &proposed_bundle.manifest.id)) - ), - baseline_id: report_id(baseline_report), - proposed_id: proposed_bundle.manifest.id.clone(), - class, - confidence, - reasons, - affected_theorems: vec![baseline_report.theorem_id.clone()], - affected_reports: vec![report_id(baseline_report)], - }; - let record = PredictionRecord { - prediction, - target: PredictionTarget::ProposedBundle { - bundle_id: proposed_bundle.manifest.id.clone(), - policy_resolution: proposed_resolution.cloned(), - theorem_ids: proposed_bundle - .overlay - .local - .theorem_specs - .iter() - .map(|item| item.id.clone()) - .collect(), - campaign_ids: proposed_bundle - .overlay - .local - .campaigns - .iter() - .map(|item| item.id.clone()) - .collect(), - route_candidate_ids: proposed_bundle - .overlay - .local - .atlas_cells - .iter() - .map(|item| item.id.clone()) - .collect(), - dependency_ids: proposed_bundle - .manifest - .dependencies - .iter() - .map(|item| item.id.clone()) - .collect(), - }, - }; - persist_prediction(&record)?; - Ok(record) -} - -pub fn predict_from_policy_override( - baseline_report: &CertificationReport, - policy_id: &str, - kind: &str, - notes: Vec, -) -> Result { - let mut reasons = vec![format!( - "proposed policy override {policy_id} of kind {kind}" - )]; - let (class, confidence) = match kind { - "Optimizer" => ( - PredictionClass::RouteWinnerChangeLikely, - RiskClassification::Strong, - ), - "Evaluator" => ( - if baseline_report.obligations.iter().any(|item| { - matches!( - item.evaluation_mode, - l64_core::ObligationEvaluationMode::Unsupported - | l64_core::ObligationEvaluationMode::RecomputedApproximate - | l64_core::ObligationEvaluationMode::RecomputedPartial - ) - }) { - PredictionClass::ObligationOutcomeChangeLikely - } else { - PredictionClass::ReportHashChangeLikely - }, - RiskClassification::Strong, - ), - "ReplayCache" => ( - PredictionClass::ReplayOnlyImpact, - RiskClassification::Strong, - ), - _ => ( - PredictionClass::InconclusivePrediction, - RiskClassification::Unknown, - ), - }; - reasons.extend(notes.clone()); - let record = PredictionRecord { - prediction: ImpactPrediction { - id: format!( - "PRD_{}", - stable_id(&(report_id(baseline_report) + policy_id)) - ), - baseline_id: report_id(baseline_report), - proposed_id: policy_id.to_string(), - class, - confidence, - reasons, - affected_theorems: vec![baseline_report.theorem_id.clone()], - affected_reports: vec![report_id(baseline_report)], - }, - target: PredictionTarget::PolicyOverride { - policy_id: policy_id.to_string(), - kind: kind.to_string(), - notes, - }, - }; - persist_prediction(&record)?; - Ok(record) -} - -pub fn load_prediction(id: &str) -> Result { - load_store_payload(predictions_root()?, id, LocusOpcode::Frontier) -} - -pub fn load_diff(id: &str) -> Result { - load_store_payload(diffs_root()?, id, LocusOpcode::Coverage) -} - -pub fn load_plan(id: &str) -> Result { - load_store_payload(plans_root()?, id, LocusOpcode::Proposal) -} - -pub fn load_execution(id: &str) -> Result { - load_store_payload(executions_root()?, id, LocusOpcode::ReceiptTable) -} - -pub fn load_reconciliation(id: &str) -> Result { - load_store_payload(reconciliations_root()?, id, LocusOpcode::Coverage) -} - -pub fn plan_recompute_from_prediction(record: &PredictionRecord) -> Result { - let mut steps = Vec::new(); - let mut reusable_artifacts = Vec::new(); - let mut invalidated_artifacts = Vec::new(); - match record.prediction.class { - PredictionClass::NoImpactPredicted => { - reusable_artifacts.extend(record.prediction.affected_reports.clone()); - steps.push(step( - "Reuse", - RecomputationStepKind::Reuse, - &record.prediction.baseline_id, - "semantic bundle unchanged", - )); - } - PredictionClass::ReplayOnlyImpact => { - reusable_artifacts.extend(record.prediction.affected_reports.clone()); - steps.push(step( - "Replay", - RecomputationStepKind::Replay, - &record.prediction.baseline_id, - "policy change affects replay/cache path only", - )); - } - PredictionClass::ReportHashChangeLikely => { - reusable_artifacts.push(record.prediction.baseline_id.clone()); - steps.push(step( - "ReExport", - RecomputationStepKind::ReExportReport, - &record.prediction.baseline_id, - "report provenance likely changes without deeper semantic drift", - )); - } - PredictionClass::RouteWinnerChangeLikely => { - invalidated_artifacts.push(record.prediction.baseline_id.clone()); - steps.push(step( - "ReRoute", - RecomputationStepKind::ReRoute, - &record.prediction.proposed_id, - "route ranking or atlas dependencies changed", - )); - steps.push(step( - "ReCert", - RecomputationStepKind::ReCertifyTheorem, - &record.prediction.baseline_id, - "route winner may drift", - )); - steps.push(step( - "ReManifest", - RecomputationStepKind::RebuildManifestLock, - &record.prediction.proposed_id, - "route winner hash participates in manifests and locks", - )); - } - PredictionClass::ObligationOutcomeChangeLikely => { - invalidated_artifacts.push(record.prediction.baseline_id.clone()); - steps.push(step( - "ReEval", - RecomputationStepKind::ReEvaluateObligation, - &record.prediction.baseline_id, - "evaluator policy may change obligation outcome", - )); - steps.push(step( - "ReCert", - RecomputationStepKind::ReCertifyTheorem, - &record.prediction.baseline_id, - "verdict may drift after obligation replay", - )); - } - PredictionClass::CertificationVerdictChangeLikely => { - invalidated_artifacts.push(record.prediction.baseline_id.clone()); - steps.push(step( - "ReRoute", - RecomputationStepKind::ReRoute, - &record.prediction.proposed_id, - "mixed structural drift", - )); - steps.push(step( - "ReEval", - RecomputationStepKind::ReEvaluateObligation, - &record.prediction.baseline_id, - "mixed structural drift", - )); - steps.push(step( - "ReRun", - RecomputationStepKind::ReRunCampaign, - &record.prediction.baseline_id, - "campaign report may change", - )); - steps.push(step( - "ReManifest", - RecomputationStepKind::RebuildManifestLock, - &record.prediction.proposed_id, - "report and route hashes changed", - )); - } - PredictionClass::BundleConflictRisk | PredictionClass::InconclusivePrediction => { - steps.push(step( - "ReRun", - RecomputationStepKind::ReRunCampaign, - &record.prediction.proposed_id, - "structural uncertainty prevents a smaller lawful reuse set", - )); - } - } - let plan = RecomputationPlan { - id: format!("RCP_{}", stable_id(&record.prediction.id)), - prediction_id: Some(record.prediction.id.clone()), - diff_id: None, - reusable_artifacts, - invalidated_artifacts, - steps, - explanation: record.prediction.reasons.clone(), - }; - persist_store_payload( - plans_root()?, - &plan.id, - LocusPacketKind::FrontierEnvelope, - LocusOpcode::Proposal, - "recompute_plan.v1", - &plan, - LocusCapabilityMask { - has_frontier: true, - ..Default::default() - }, - )?; - Ok(plan) -} - -pub fn plan_recompute_from_diff(diff: &SemanticDiff) -> Result { - let prediction = PredictionRecord { - prediction: ImpactPrediction { - id: format!("PRD_{}", stable_id(&diff.id)), - baseline_id: diff.left_id.clone(), - proposed_id: diff.right_id.clone(), - class: map_diff_to_prediction(&diff.class), - confidence: RiskClassification::Moderate, - reasons: diff.summary.clone(), - affected_theorems: diff - .theorem_drifts - .iter() - .map(|item| item.theorem_id.clone()) - .collect(), - affected_reports: vec![diff.left_id.clone()], - }, - target: PredictionTarget::PolicyOverride { - policy_id: "derived-from-diff".into(), - kind: format!("{:?}", diff.class), - notes: diff.summary.clone(), - }, - }; - let mut plan = plan_recompute_from_prediction(&prediction)?; - plan.diff_id = Some(diff.id.clone()); - persist_store_payload( - plans_root()?, - &plan.id, - LocusPacketKind::FrontierEnvelope, - LocusOpcode::Proposal, - "recompute_plan.v1", - &plan, - LocusCapabilityMask { - has_frontier: true, - ..Default::default() - }, - )?; - Ok(plan) -} - -pub fn assess_prediction( - record: &PredictionRecord, - actual_report: &CertificationReport, -) -> Result { - let baseline = replay_report(&record.prediction.baseline_id) - .map_err(|_| anyhow!("baseline report not available for assessment"))?; - let actual_diff = semantic_diff_between_reports(&baseline, actual_report); - persist_diff(&actual_diff)?; - let predicted = severity(&record.prediction.class); - let actual = severity(&map_diff_to_prediction(&actual_diff.class)); - let outcome = if matches!( - record.prediction.class, - PredictionClass::InconclusivePrediction - ) { - PredictionAssessmentOutcome::PredictionUncheckable - } else if predicted == actual { - PredictionAssessmentOutcome::PredictionConfirmed - } else if predicted < actual { - PredictionAssessmentOutcome::PredictionUnderestimated - } else { - PredictionAssessmentOutcome::PredictionOverestimated - }; - let assessment = PredictionAssessment { - id: format!( - "RSK_{}", - stable_id(&(record.prediction.id.clone() + &actual_diff.id)) - ), - prediction_id: record.prediction.id.clone(), - actual_diff_id: actual_diff.id.clone(), - outcome, - notes: actual_diff.summary.clone(), - }; - persist_store_payload( - assessments_root()?, - &assessment.id, - LocusPacketKind::FrontierEnvelope, - LocusOpcode::Coverage, - "prediction_assessment.v1", - &assessment, - LocusCapabilityMask { - has_frontier: true, - ..Default::default() - }, - )?; - Ok(assessment) -} - -pub fn execute_plan( - plan: &RecomputationPlan, - options: &ExecutePlanOptions, -) -> Result { - let prediction = plan - .prediction_id - .as_ref() - .map(|id| load_prediction(id)) - .transpose()?; - let root_resolution = runtime_root_report(&[]).map_err(anyhow::Error::msg)?; - let scheduler_policy = scheduler_policy_for(prediction.as_ref(), options); - let execution_scope = ExecutionScope { - id: format!( - "SCP_{}", - stable_id(&(plan.id.clone() + &scheduler_policy.id)) - ), - cache_namespace: l64_core::CacheNamespace { - id: root_resolution - .cache_root - .namespace - .clone() - .unwrap_or_else(|| "default".into()), - root: root_resolution.cache_root.absolute_path.clone(), - }, - }; - let mut outcomes = Vec::new(); - let mut resulting_reports = Vec::new(); - let mut resulting_report_ids = Vec::new(); - let mut manifest_ids = Vec::new(); - let lock_ids = Vec::new(); - let mut rerun_artifacts = Vec::new(); - let reused_artifacts = plan.reusable_artifacts.clone(); - let mut coherence_receipts = Vec::new(); - let mut obligation_plans = Vec::new(); - let mut obligation_lanes = Vec::new(); - let mut obligation_ordering_receipts = Vec::new(); - let mut obligation_merge_receipts = Vec::new(); - let mut replay_legality_checks = Vec::new(); - let mut replay_barrier_receipts = Vec::new(); - let mut replay_merge_receipts = Vec::new(); - let mut replay_divergence_records = Vec::new(); - let mut obligation_cache_shards = Vec::new(); - let mut obligation_write_sets = Vec::new(); - let mut obligation_collision_reports = Vec::new(); - let mut obligation_namespace_receipts = Vec::new(); - - let needs_rerun = plan.steps.iter().any(|step| { - matches!( - step.kind, - RecomputationStepKind::ReEvaluateObligation - | RecomputationStepKind::ReRoute - | RecomputationStepKind::ReCertifyTheorem - | RecomputationStepKind::ReRunCampaign - | RecomputationStepKind::RebuildManifestLock - ) - }); - - let execution_result = if options.dry_run { - ExecutedTaskBatch::empty() - } else if let Some(prediction) = prediction.as_ref() { - if needs_rerun || !scheduler_policy.replay_allowed { - run_prediction_target(prediction, &scheduler_policy, options)? - } else { - let baseline = replay_report(&prediction.prediction.baseline_id) - .map_err(|err| anyhow!("unable to replay baseline report: {err}"))?; - ExecutedTaskBatch { - reports: vec![baseline], - lane_records: vec![l64_core::LaneExecutionRecord { - lane_id: "LAN_0".into(), - step_ids: plan.steps.iter().map(|item| item.id.clone()).collect(), - task_ids: vec![prediction.prediction.baseline_id.clone()], - serialized_reason: Some("replay/cache policy allowed direct reuse".into()), - }], - coherence_receipts: Vec::new(), - schedule_hash: ExecutionScheduleHash { - id: format!("SCHH_{}", stable_id(&plan.id)), - hash: stable_id(&(plan.id.clone() + "|replay")), - }, - ordering_receipt: OrderingReceipt { - id: format!("ORD_{}", stable_id(&plan.id)), - ordered_step_ids: plan.steps.iter().map(|item| item.id.clone()).collect(), - notes: vec!["serialized replay ordering".into()], - }, - explanation: vec!["scheduler reused cached baseline report".into()], - } - } - } else { - ExecutedTaskBatch::empty() - }; - let execution_reports = execution_result.reports.clone(); - - if !execution_result.coherence_receipts.is_empty() { - coherence_receipts.extend(execution_result.coherence_receipts.clone()); - } - rerun_artifacts.extend(execution_reports.iter().map(report_id)); - for report in &execution_reports { - if let Some(plan) = &report.obligation_plan { - obligation_plans.push(plan.clone()); - } - obligation_lanes.extend(report.obligation_lanes.clone()); - if let Some(receipt) = &report.obligation_ordering_receipt { - obligation_ordering_receipts.push(receipt.clone()); - } - if let Some(receipt) = &report.obligation_merge_receipt { - obligation_merge_receipts.push(receipt.clone()); - } - replay_legality_checks.extend(report.replay_legality_checks.clone()); - replay_barrier_receipts.extend(report.replay_barrier_receipts.clone()); - if let Some(receipt) = &report.replay_merge_receipt { - replay_merge_receipts.push(receipt.clone()); - } - replay_divergence_records.extend(report.replay_divergence_records.clone()); - obligation_cache_shards.extend(report.obligation_cache_shards.clone()); - obligation_write_sets.extend(report.obligation_write_sets.clone()); - obligation_collision_reports.extend(report.obligation_collision_reports.clone()); - if let Some(receipt) = &report.obligation_namespace_receipt { - obligation_namespace_receipts.push(receipt.clone()); - } - } - - let manifest = if options.dry_run { - None - } else { - prediction.as_ref().and_then(|record| { - build_execution_manifest_for_prediction( - record, - &execution_reports, - plan, - &scheduler_policy, - &execution_scope, - &execution_result.lane_records, - &execution_result.schedule_hash, - &execution_result.ordering_receipt, - &coherence_receipts, - &obligation_plans, - &obligation_lanes, - &obligation_ordering_receipts, - &obligation_merge_receipts, - &replay_legality_checks, - &replay_barrier_receipts, - &replay_merge_receipts, - &replay_divergence_records, - &obligation_cache_shards, - &obligation_write_sets, - &obligation_collision_reports, - &obligation_namespace_receipts, - ) - .ok() - }) - }; - if let Some(manifest) = &manifest { - persist_execution_manifest(manifest)?; - manifest_ids.push(manifest.id.clone()); - } - - let reconciliation = if options.dry_run { - None - } else if let (Some(prediction), Some(report)) = - (prediction.as_ref(), execution_reports.first()) - { - let assessment = assess_prediction(prediction, report)?; - let reconciliation = ReconciliationRecord { - id: format!("REC_{}", stable_id(&(plan.id.clone() + &assessment.id))), - prediction_id: prediction.prediction.id.clone(), - plan_id: plan.id.clone(), - execution_id: format!("RUN_{}", stable_id(&plan.id)), - assessment: assessment.clone(), - notes: assessment.notes.clone(), - }; - persist_reconciliation(&reconciliation)?; - Some(reconciliation) - } else { - None - }; - - for step in &plan.steps { - let (status, produced, reasons) = if options.dry_run { - ( - ScheduledStepStatus::DryRun, - Vec::new(), - vec!["dry-run requested".into()], - ) - } else { - match step.kind { - RecomputationStepKind::Reuse => ( - ScheduledStepStatus::Reused, - vec![step.target_id.clone()], - vec!["semantic identity preserved; scheduler reused baseline artifact".into()], - ), - RecomputationStepKind::Replay - if scheduler_policy.replay_allowed && !needs_rerun => - { - ( - ScheduledStepStatus::Replayed, - vec![step.target_id.clone()], - vec!["replay/cache policy allowed reuse of cached report".into()], - ) - } - RecomputationStepKind::RebuildManifestLock => ( - ScheduledStepStatus::Executed, - manifest - .as_ref() - .map(|item| vec![item.id.clone()]) - .unwrap_or_default(), - vec!["manifest rebuilt to reflect executed plan and reconciliation".into()], - ), - RecomputationStepKind::ReExportReport => ( - ScheduledStepStatus::Executed, - execution_reports.iter().map(report_id).collect(), - vec!["report provenance refreshed after certification lanes completed".into()], - ), - _ => ( - ScheduledStepStatus::Executed, - execution_reports.iter().map(report_id).collect(), - vec!["scheduler executed plan step against bundle-local target".into()], - ), - } - }; - let receipt = SchedulerDecisionReceipt { - id: format!("SDR_{}", stable_id(&(plan.id.clone() + &step.id))), - step_id: step.id.clone(), - policy_resolution_id: prediction - .as_ref() - .and_then(|item| prediction_policy_resolution(item)) - .map(|item| item.id.clone()), - decision: format!("{status:?}"), - reasons, - }; - outcomes.push(StepExecutionOutcome { - step_id: step.id.clone(), - kind: step.kind.clone(), - status, - produced_artifact_ids: produced, - receipt, - }); - } - - for mut report in execution_reports { - if let Some(envelope) = &mut report.execution_envelope { - envelope.executed_plan_id = Some(plan.id.clone()); - envelope.reconciliation_id = reconciliation.as_ref().map(|item| item.id.clone()); - if let Some(manifest) = &manifest { - envelope.manifest_id = Some(manifest.id.clone()); - } - } - if let Some(reconciliation) = &reconciliation { - report.reconciliation_summary = reconciliation.notes.clone(); - } - resulting_report_ids.push(report_id(&report)); - resulting_reports.push(report); - } - - let record = PlanExecutionRecord { - id: format!( - "RUN_{}", - stable_id(&(plan.id.clone() + &scheduler_policy.id)) - ), - plan_id: plan.id.clone(), - prediction_id: plan.prediction_id.clone(), - scheduler_policy, - root_resolution, - execution_scope: Some(execution_scope), - lane_records: execution_result.lane_records, - schedule_hash: Some(execution_result.schedule_hash), - coherence_receipts, - ordering_receipt: Some(execution_result.ordering_receipt), - obligation_plans, - obligation_lanes, - obligation_ordering_receipts, - obligation_merge_receipts, - replay_legality_checks, - replay_barrier_receipts, - replay_merge_receipts, - replay_divergence_records, - obligation_cache_shards, - obligation_write_sets, - obligation_collision_reports, - obligation_namespace_receipts, - outcomes, - reused_artifacts, - rerun_artifacts, - resulting_report_ids, - resulting_reports, - manifest_ids, - lock_ids, - explanation: execution_result - .explanation - .into_iter() - .chain(plan.explanation.clone()) - .collect(), - }; - persist_execution(&record)?; - Ok(record) -} - -pub fn reconcile_prediction_to_report( - prediction: &PredictionRecord, - actual_report: &CertificationReport, -) -> Result { - let assessment = assess_prediction(prediction, actual_report)?; - let record = ReconciliationRecord { - id: format!( - "REC_{}", - stable_id(&(prediction.prediction.id.clone() + &assessment.id)) - ), - prediction_id: prediction.prediction.id.clone(), - plan_id: "direct".into(), - execution_id: actual_report - .execution_envelope - .as_ref() - .and_then(|item| item.executed_plan_id.clone()) - .unwrap_or_else(|| report_id(actual_report)), - assessment: assessment.clone(), - notes: assessment.notes.clone(), - }; - persist_reconciliation(&record)?; - Ok(record) -} - -pub fn compare_executions( - left: &PlanExecutionRecord, - right: &PlanExecutionRecord, -) -> Result { - let mut summary = Vec::new(); - let mut changed_routes = Vec::new(); - let mut changed_policies = Vec::new(); - if left.scheduler_policy != right.scheduler_policy { - summary.push("scheduler policy changed".into()); - changed_policies.push(left.scheduler_policy.id.clone()); - changed_policies.push(right.scheduler_policy.id.clone()); - } - if left.obligation_lanes != right.obligation_lanes - || left.obligation_plans != right.obligation_plans - { - summary.push("obligation execution schedule changed".into()); - } - if left.resulting_report_ids != right.resulting_report_ids { - summary.push("resulting report set changed".into()); - } - for (l, r) in left - .resulting_reports - .iter() - .zip(right.resulting_reports.iter()) - { - let nested = semantic_diff_between_reports(l, r); - if nested.class != SemanticDiffClass::NoSemanticChange { - summary.extend(nested.summary.clone()); - changed_routes.extend(nested.changed_route_ids.clone()); - changed_policies.extend(nested.changed_policy_ids.clone()); - } - } - let diff = SemanticDiff { - id: format!("DIF_{}", stable_id(&(left.id.clone() + &right.id))), - left_id: left.id.clone(), - right_id: right.id.clone(), - class: classify( - !changed_policies.is_empty(), - !changed_routes.is_empty(), - false, - false, - false, - ), - summary: if summary.is_empty() { - vec!["no semantic execution drift".into()] - } else { - summary - }, - theorem_drifts: Vec::new(), - changed_policy_ids: changed_policies, - changed_route_ids: changed_routes, - changed_dependency_ids: Vec::new(), - }; - persist_diff(&diff)?; - Ok(diff) -} - -fn semantic_diff_between_reports( - left: &CertificationReport, - right: &CertificationReport, -) -> SemanticDiff { - let mut summary = Vec::new(); - let mut changed_policies = Vec::new(); - let mut changed_routes = Vec::new(); - let mut theorem_drifts = Vec::new(); - let mut obligations_changed = false; - let mut replay_changed = false; - - if left.policy_resolution != right.policy_resolution { - summary.push("policy resolution changed".into()); - changed_policies = symmetric_diff( - &left - .policy_resolution - .as_ref() - .map(|item| item.applied_policy_ids.clone()) - .unwrap_or_default(), - &right - .policy_resolution - .as_ref() - .map(|item| item.applied_policy_ids.clone()) - .unwrap_or_default(), - ); - } - if left.selected_atlas_cell != right.selected_atlas_cell - || left.selected_path != right.selected_path - { - summary.push("route winner changed".into()); - if let Some(left_id) = &left.selected_atlas_cell { - changed_routes.push(left_id.clone()); - } - if let Some(right_id) = &right.selected_atlas_cell { - changed_routes.push(right_id.clone()); - } - } - let obligation_drifts = diff_obligations(&left.obligations, &right.obligations); - if !obligation_drifts.is_empty() { - obligations_changed = true; - summary.push("obligation outcomes changed".into()); - } - if left - .execution_envelope - .as_ref() - .map(|item| &item.replay_status) - != right - .execution_envelope - .as_ref() - .map(|item| &item.replay_status) - { - replay_changed = true; - summary.push("replay/cache behavior changed".into()); - } - if left.verdict != right.verdict { - summary.push(format!( - "certification verdict changed from {:?} to {:?}", - left.verdict, right.verdict - )); - } - theorem_drifts.push(TheoremDrift { - theorem_id: left.theorem_id.clone(), - verdict_before: Some(left.verdict.clone()), - verdict_after: Some(right.verdict.clone()), - route_before: left.selected_atlas_cell.clone(), - route_after: right.selected_atlas_cell.clone(), - obligation_drifts, - summary: summary.clone(), - }); - SemanticDiff { - id: format!("DIF_{}", stable_id(&(report_id(left) + &report_id(right)))), - left_id: report_id(left), - right_id: report_id(right), - class: classify( - !changed_policies.is_empty(), - !changed_routes.is_empty(), - obligations_changed, - replay_changed, - false, - ), - summary: if summary.is_empty() { - vec!["no semantic report drift".into()] - } else { - summary - }, - theorem_drifts, - changed_policy_ids: changed_policies, - changed_route_ids: changed_routes, - changed_dependency_ids: Vec::new(), - } -} - -fn diff_obligations(left: &[ObligationStatus], right: &[ObligationStatus]) -> Vec { - let left_map = left - .iter() - .map(|item| (item.obligation_id.clone(), item)) - .collect::>(); - let right_map = right - .iter() - .map(|item| (item.obligation_id.clone(), item)) - .collect::>(); - let mut ids = left_map.keys().cloned().collect::>(); - ids.extend(right_map.keys().cloned()); - ids.into_iter() - .filter_map(|id| { - let before = left_map.get(&id).copied(); - let after = right_map.get(&id).copied(); - if before == after { - return None; - } - Some(ObligationDrift { - obligation_id: id, - verdict_before: before.map(|item| item.verdict.clone()), - verdict_after: after.map(|item| item.verdict.clone()), - mode_before: before.map(|item| item.evaluation_mode.clone()), - mode_after: after.map(|item| item.evaluation_mode.clone()), - meaning: format!( - "obligation drift from {:?}/{:?}/receipts={} to {:?}/{:?}/receipts={}", - before.map(|item| item.verdict.clone()), - before.map(|item| item.evaluation_mode.clone()), - before - .map(|item| receipt_count(&item.receipts)) - .unwrap_or_default(), - after.map(|item| item.verdict.clone()), - after.map(|item| item.evaluation_mode.clone()), - after - .map(|item| receipt_count(&item.receipts)) - .unwrap_or_default() - ), - }) - }) - .collect() -} - -fn classify( - policy_changed: bool, - route_changed: bool, - obligation_changed: bool, - replay_changed: bool, - dependency_changed: bool, -) -> SemanticDiffClass { - let count = usize::from(policy_changed) - + usize::from(route_changed) - + usize::from(obligation_changed) - + usize::from(replay_changed) - + usize::from(dependency_changed); - match ( - count, - policy_changed, - route_changed, - obligation_changed, - replay_changed, - dependency_changed, - ) { - (0, ..) => SemanticDiffClass::NoSemanticChange, - (1, true, false, false, false, false) => SemanticDiffClass::PolicyOnly, - (1, false, true, false, false, false) => SemanticDiffClass::RouteOnly, - (1, false, false, true, false, false) => SemanticDiffClass::ObligationOnly, - (1, false, false, false, true, false) => SemanticDiffClass::ReplayOnly, - (1, false, false, false, false, true) => SemanticDiffClass::BundleDependencyOnly, - _ => SemanticDiffClass::Mixed, - } -} - -fn classify_evaluator_prediction( - baseline_report: &CertificationReport, - resolution: &PolicyResolution, - reasons: &mut Vec, -) -> PredictionClass { - if resolution.evaluator.unsupported_mode == l64_core::UnsupportedHandlingMode::StrictFail - && baseline_report.obligations.iter().any(|item| { - matches!( - item.evaluation_mode, - l64_core::ObligationEvaluationMode::Unsupported - | l64_core::ObligationEvaluationMode::RecomputedApproximate - | l64_core::ObligationEvaluationMode::RecomputedPartial - ) - }) - { - reasons.push( - "stricter evaluator policy can flip unsupported or approximate obligations".into(), - ); - PredictionClass::ObligationOutcomeChangeLikely - } else { - reasons.push( - "evaluator provenance changed without an obvious strictness-triggered flip".into(), - ); - PredictionClass::ReportHashChangeLikely - } -} - -fn map_diff_to_prediction(class: &SemanticDiffClass) -> PredictionClass { - match class { - SemanticDiffClass::NoSemanticChange => PredictionClass::NoImpactPredicted, - SemanticDiffClass::PolicyOnly => PredictionClass::ReportHashChangeLikely, - SemanticDiffClass::RouteOnly => PredictionClass::RouteWinnerChangeLikely, - SemanticDiffClass::ObligationOnly => PredictionClass::ObligationOutcomeChangeLikely, - SemanticDiffClass::ReplayOnly => PredictionClass::ReplayOnlyImpact, - SemanticDiffClass::SurfaceOnly => PredictionClass::ReportHashChangeLikely, - SemanticDiffClass::BundleDependencyOnly => PredictionClass::RouteWinnerChangeLikely, - SemanticDiffClass::Mixed => PredictionClass::CertificationVerdictChangeLikely, - SemanticDiffClass::Inconclusive => PredictionClass::InconclusivePrediction, - } -} - -fn severity(class: &PredictionClass) -> usize { - match class { - PredictionClass::NoImpactPredicted => 0, - PredictionClass::ReplayOnlyImpact => 1, - PredictionClass::ReportHashChangeLikely => 2, - PredictionClass::RouteWinnerChangeLikely => 3, - PredictionClass::ObligationOutcomeChangeLikely => 4, - PredictionClass::CertificationVerdictChangeLikely => 5, - PredictionClass::BundleConflictRisk => 6, - PredictionClass::InconclusivePrediction => 7, - } -} - -fn persist_diff(diff: &SemanticDiff) -> Result<()> { - persist_store_payload( - diffs_root()?, - &diff.id, - LocusPacketKind::FrontierEnvelope, - LocusOpcode::Coverage, - "semantic_diff.v1", - diff, - LocusCapabilityMask { - has_frontier: true, - ..Default::default() - }, - )?; - Ok(()) -} - -fn persist_execution(record: &PlanExecutionRecord) -> Result<()> { - persist_store_payload( - executions_root()?, - &record.id, - LocusPacketKind::FrontierEnvelope, - LocusOpcode::ReceiptTable, - "plan_execution.v1", - record, - LocusCapabilityMask { - has_frontier: true, - ..Default::default() - }, - )?; - Ok(()) -} - -fn persist_reconciliation(record: &ReconciliationRecord) -> Result<()> { - persist_store_payload( - reconciliations_root()?, - &record.id, - LocusPacketKind::FrontierEnvelope, - LocusOpcode::Coverage, - "reconciliation_record.v1", - record, - LocusCapabilityMask { - has_frontier: true, - ..Default::default() - }, - )?; - Ok(()) -} - -fn persist_execution_manifest(manifest: &ExecutionManifest) -> Result<()> { - let root = PathBuf::from( - resolve_cache_root() - .map_err(anyhow::Error::msg)? - .absolute_path, - ) - .join("manifests"); - fs::create_dir_all(&root)?; - persist_store_payload( - root, - &manifest.id, - LocusPacketKind::CanonicalTransfer, - LocusOpcode::CanonicalPayload, - "execution_manifest.v1", - manifest, - LocusCapabilityMask::default(), - )?; - Ok(()) -} - -fn persist_prediction(record: &PredictionRecord) -> Result<()> { - persist_store_payload( - predictions_root()?, - &record.prediction.id, - LocusPacketKind::FrontierEnvelope, - LocusOpcode::Frontier, - "prediction_record.v1", - record, - LocusCapabilityMask { - has_frontier: true, - ..Default::default() - }, - )?; - Ok(()) -} - -fn route_trace( - report: &CertificationReport, - explanation: &RouteExplanation, -) -> l64_core::RouteTraceEvent { - l64_core::RouteTraceEvent { - id: format!("RTE_{}", report_id(report)), - theorem_id: report.theorem_id.clone(), - winner_id: explanation.winner_atlas_cell_id.clone(), - optimizer_backend: explanation.optimizer_backend.clone(), - axes: explanation.axes_used.clone(), - explanation: explanation.explanation.clone(), - } -} - -fn mk_choice( - report: &CertificationReport, - explanation: &RouteExplanation, -) -> l64_core::ChoiceRecord { - l64_core::ChoiceRecord { - id: format!("CHC_{}", report_id(report)), - choice_kind: "route-winner".into(), - selected_id: explanation - .winner_atlas_cell_id - .clone() - .unwrap_or_else(|| "none".into()), - alternatives: explanation.dominated_candidates.clone(), - reasons: explanation.explanation.clone(), - } -} - -fn mk_obligation_trace( - report: &CertificationReport, - obligation: &ObligationStatus, -) -> l64_core::ObligationTraceRecord { - l64_core::ObligationTraceRecord { - id: format!("OTR_{}_{}", report_id(report), obligation.obligation_id), - theorem_id: report.theorem_id.clone(), - obligation_id: obligation.obligation_id.clone(), - verdict: obligation.verdict.clone(), - evaluation_mode: obligation.evaluation_mode.clone(), - detail: obligation.detail.clone(), - receipts: obligation.receipts.clone(), - } -} - -fn edge(from: &str, to: &str, relation: &str) -> ObservationEdge { - ObservationEdge { - id: format!("OBE_{}", stable_id(&(from.to_string() + to + relation))), - from: from.to_string(), - to: to.to_string(), - relation: relation.to_string(), - } -} - -fn step( - label: &str, - kind: RecomputationStepKind, - target_id: &str, - reason: &str, -) -> RecomputationStep { - RecomputationStep { - id: format!( - "{}_{:}", - label, - stable_id(&(target_id.to_string() + reason)) - ), - kind, - target_id: target_id.to_string(), - reason: reason.to_string(), - } -} - -fn diff_dependencies( - left: &[l64_core::BundleDependency], - right: &[l64_core::BundleDependency], -) -> Vec { - let left_set = left - .iter() - .map(|item| item.id.clone()) - .collect::>(); - let right_set = right - .iter() - .map(|item| item.id.clone()) - .collect::>(); - left_set.symmetric_difference(&right_set).cloned().collect() -} - -fn symmetric_diff(left: &[String], right: &[String]) -> Vec { - let left_set = left.iter().cloned().collect::>(); - let right_set = right.iter().cloned().collect::>(); - left_set.symmetric_difference(&right_set).cloned().collect() -} - -fn btreemap( - items: [(impl Into, impl Into); N], -) -> BTreeMap { - items - .into_iter() - .map(|(key, value)| (key.into(), value.into())) - .collect() -} - -fn stable_id(input: &str) -> String { - let mut hash: u64 = 0xcbf29ce484222325; - for byte in input.as_bytes() { - hash ^= u64::from(*byte); - hash = hash.wrapping_mul(0x100000001b3); - } - format!("{hash:x}") -} - -fn prediction_policy_resolution(record: &PredictionRecord) -> Option<&PolicyResolution> { - match &record.target { - PredictionTarget::ProposedBundle { - policy_resolution, .. - } => policy_resolution.as_ref(), - PredictionTarget::PolicyOverride { .. } => None, - } -} - -fn scheduler_policy_for( - prediction: Option<&PredictionRecord>, - options: &ExecutePlanOptions, -) -> SchedulerPolicy { - let mut scheduler_config = prediction - .and_then(prediction_policy_resolution) - .map(|resolution| resolution.scheduler.clone()) - .unwrap_or(l64_core::SchedulerPolicyConfig { - parallelization: ParallelizationPolicy::Serialize, - max_workers: 1, - allow_parallel_replay: false, - allow_parallel_certification: true, - allow_parallel_exports: true, - deterministic_ordering: true, - allow_parallel_obligations: false, - max_obligation_workers: 1, - allow_parallel_obligation_replay: false, - serialize_canonicalization_sensitive: true, - }); - if options.force_parallel { - scheduler_config.parallelization = ParallelizationPolicy::ParallelIndependent; - } - if options.force_parallel_obligations { - scheduler_config.allow_parallel_obligations = true; - if scheduler_config.max_obligation_workers <= 1 { - scheduler_config.max_obligation_workers = options.max_workers.unwrap_or(2).max(2); - } - } - if options.force_serialized { - scheduler_config.parallelization = ParallelizationPolicy::Serialize; - scheduler_config.allow_parallel_obligations = false; - } - if let Some(max_workers) = options.max_workers { - scheduler_config.max_workers = max_workers.max(1); - } else if scheduler_config.parallelization == ParallelizationPolicy::ParallelIndependent - && scheduler_config.max_workers == 1 - { - scheduler_config.max_workers = thread::available_parallelism() - .map(|v| v.get()) - .unwrap_or(2) - .max(2); - } - if let Some(max_workers) = options.max_obligation_workers { - scheduler_config.max_obligation_workers = max_workers.max(1); - } else if scheduler_config.allow_parallel_obligations - && scheduler_config.max_obligation_workers == 1 - { - scheduler_config.max_obligation_workers = scheduler_config.max_workers.max(2); - } - if options.strict_determinism { - scheduler_config.deterministic_ordering = true; - } - let (replay_allowed, strict_unsupported, reuse_trust) = prediction - .and_then(prediction_policy_resolution) - .map(|resolution| { - ( - resolution.replay_cache.replay_allowed, - matches!( - resolution.evaluator.unsupported_mode, - l64_core::UnsupportedHandlingMode::StrictFail - ), - match resolution.replay_cache.trust_class { - l64_core::ReplayTrustClass::ExactPolicyOnly => ReuseTrustClass::ExactOnly, - l64_core::ReplayTrustClass::AllowSurfaceOnlyChanges => { - ReuseTrustClass::SurfaceStable - } - l64_core::ReplayTrustClass::AllowApproximateReuse => { - ReuseTrustClass::ApproximateAllowed - } - }, - ) - }) - .unwrap_or((true, options.strict, ReuseTrustClass::ExactOnly)); - SchedulerPolicy { - id: format!( - "SCH_{}", - stable_id( - prediction - .map(|item| item.prediction.id.as_str()) - .unwrap_or("default-scheduler") - ) - ), - replay_allowed, - strict_recomputation: options.strict, - strict_unsupported, - parallelization: scheduler_config.parallelization, - max_workers: scheduler_config.max_workers.max(1), - allow_parallel_replay: scheduler_config.allow_parallel_replay, - allow_parallel_certification: scheduler_config.allow_parallel_certification, - allow_parallel_exports: scheduler_config.allow_parallel_exports, - deterministic_ordering: scheduler_config.deterministic_ordering, - allow_parallel_obligations: scheduler_config.allow_parallel_obligations, - max_obligation_workers: scheduler_config.max_obligation_workers, - allow_parallel_obligation_replay: scheduler_config.allow_parallel_obligation_replay, - serialize_canonicalization_sensitive: scheduler_config.serialize_canonicalization_sensitive, - reuse_trust, - notes: vec!["scheduler derived from resolved replay/evaluator/scheduler policy".into()], - } -} - -fn build_execution_manifest_for_prediction( - record: &PredictionRecord, - reports: &[CertificationReport], - plan: &RecomputationPlan, - scheduler_policy: &SchedulerPolicy, - execution_scope: &ExecutionScope, - lane_records: &[l64_core::LaneExecutionRecord], - schedule_hash: &ExecutionScheduleHash, - ordering_receipt: &OrderingReceipt, - coherence_receipts: &[l64_core::ConcurrencyCoherenceReceipt], - obligation_plans: &[l64_core::ObligationPlan], - obligation_lanes: &[l64_core::ObligationLaneRecord], - obligation_ordering_receipts: &[l64_core::ObligationOrderingReceipt], - obligation_merge_receipts: &[l64_core::ObligationMergeReceipt], - replay_legality_checks: &[l64_core::ReplayLegalityCheck], - replay_barrier_receipts: &[l64_core::ReplayBarrierReceipt], - replay_merge_receipts: &[l64_core::ReplayMergeReceipt], - replay_divergence_records: &[l64_core::ReplayDivergenceRecord], - obligation_cache_shards: &[l64_core::ObligationCacheShard], - obligation_write_sets: &[l64_core::ObligationWriteSet], - obligation_collision_reports: &[l64_core::ObligationCollisionReport], - obligation_namespace_receipts: &[l64_core::ObligationNamespaceReceipt], -) -> Result { - let bundle_id = match &record.target { - PredictionTarget::ProposedBundle { bundle_id, .. } => bundle_id.clone(), - PredictionTarget::PolicyOverride { .. } => reports - .first() - .and_then(|item| item.execution_envelope.as_ref()) - .and_then(|item| item.bundle_id.clone()) - .ok_or_else(|| anyhow!("policy override execution needs a bundle-backed report"))?, - }; - let world = load_bundle_world(&bundle_id)?; - let resolution = match &record.target { - PredictionTarget::ProposedBundle { - policy_resolution, .. - } => policy_resolution.clone().unwrap_or( - resolve_policy_graph( - &world.overlay, - Some(&world.manifest.id), - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .campaigns - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.as_str()), - scheduler_policy.strict_recomputation, - reports - .first() - .and_then(|item| item.route_explanation.as_ref()) - .map(|item| item.optimizer_policy.clone()) - .unwrap_or(l64_core::OptimizerPolicy::Conservative), - ) - .map_err(anyhow::Error::msg)? - .resolution, - ), - PredictionTarget::PolicyOverride { .. } => { - resolve_policy_graph( - &world.overlay, - Some(&world.manifest.id), - world - .overlay - .local - .theorem_specs - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .campaigns - .first() - .map(|item| item.id.as_str()), - world - .overlay - .local - .target_profiles - .first() - .map(|item| item.id.as_str()), - scheduler_policy.strict_recomputation, - reports - .first() - .and_then(|item| item.route_explanation.as_ref()) - .map(|item| item.optimizer_policy.clone()) - .unwrap_or(l64_core::OptimizerPolicy::Conservative), - ) - .map_err(anyhow::Error::msg)? - .resolution - } - }; - let bundle_hash = reports - .first() - .and_then(|item| item.execution_envelope.as_ref()) - .map(|item| item.bundle_hash.clone()) - .unwrap_or_else(|| stable_id(&world.manifest.id)); - let mut manifest = l64_policy::build_execution_manifest( - &world.manifest.id, - &bundle_hash, - world.manifest.dependencies.clone(), - &resolution, - reports - .iter() - .filter_map(|item| item.selected_atlas_cell.clone()) - .collect(), - vec!["l64-cert-obl-v2".into()], - vec!["v7-surfaces".into()], - reports.iter().map(report_id).collect(), - ); - manifest.executed_plan_hash = Some(stable_id(&serde_json::to_string(plan)?)); - manifest.executed_steps = plan - .steps - .iter() - .map(|step| StepExecutionOutcome { - step_id: step.id.clone(), - kind: step.kind.clone(), - status: ScheduledStepStatus::Executed, - produced_artifact_ids: Vec::new(), - receipt: SchedulerDecisionReceipt { - id: format!("SDR_{}", stable_id(&(manifest.id.clone() + &step.id))), - step_id: step.id.clone(), - policy_resolution_id: Some(resolution.id.clone()), - decision: "manifest-captured".into(), - reasons: vec![step.reason.clone()], - }, - }) - .collect(); - manifest.reused_artifacts = plan.reusable_artifacts.clone(); - manifest.rerun_artifacts = plan.invalidated_artifacts.clone(); - manifest.reconciliation_summary = Vec::new(); - manifest.root_resolution = Some(runtime_root_report(&[]).map_err(anyhow::Error::msg)?); - manifest.scheduler_policy = Some(scheduler_policy.clone()); - manifest.execution_scope = Some(execution_scope.clone()); - manifest.lane_records = lane_records.to_vec(); - manifest.schedule_hash = Some(schedule_hash.clone()); - manifest.coherence_receipts = coherence_receipts.to_vec(); - manifest.ordering_receipt = Some(ordering_receipt.clone()); - manifest.obligation_plans = obligation_plans.to_vec(); - manifest.obligation_lanes = obligation_lanes.to_vec(); - manifest.obligation_ordering_receipts = obligation_ordering_receipts.to_vec(); - manifest.obligation_merge_receipts = obligation_merge_receipts.to_vec(); - manifest.replay_legality_checks = replay_legality_checks.to_vec(); - manifest.replay_barrier_receipts = replay_barrier_receipts.to_vec(); - manifest.replay_merge_receipts = replay_merge_receipts.to_vec(); - manifest.replay_divergence_records = replay_divergence_records.to_vec(); - manifest.obligation_cache_shards = obligation_cache_shards.to_vec(); - manifest.obligation_write_sets = obligation_write_sets.to_vec(); - manifest.obligation_collision_reports = obligation_collision_reports.to_vec(); - manifest.obligation_namespace_receipts = obligation_namespace_receipts.to_vec(); - Ok(manifest) -} - -fn run_prediction_target( - record: &PredictionRecord, - scheduler_policy: &SchedulerPolicy, - options: &ExecutePlanOptions, -) -> Result { - let (world, options) = match &record.target { - PredictionTarget::ProposedBundle { - bundle_id, - policy_resolution, - .. - } => { - let world = load_bundle_world(bundle_id)?; - let optimizer = policy_resolution - .as_ref() - .map(|item| item.optimizer.optimizer_policy.clone()) - .unwrap_or(l64_core::OptimizerPolicy::Conservative); - let options = CertificationOptions { - optimizer_policy: optimizer, - bundle_hash: stable_id(&serde_json::to_string(&world.manifest)?), - policy_hash: stable_id( - &policy_resolution - .as_ref() - .map(|item| serde_json::to_string(item).unwrap_or_default()) - .unwrap_or_default(), - ), - bundle_id: Some(world.manifest.id.clone()), - evaluator_policy: None, - cache_policy: None, - no_cache: options.no_cache, - replay_only: false, - strict_derived: options.strict, - strict_policy: scheduler_policy.strict_recomputation, - force_parallel_obligations: scheduler_policy.allow_parallel_obligations - || options.force_parallel_obligations, - max_obligation_workers: Some(scheduler_policy.max_obligation_workers), - }; - (world, options) - } - PredictionTarget::PolicyOverride { - policy_id, kind, .. - } => { - let baseline = replay_report(&record.prediction.baseline_id).map_err(|err| { - anyhow!("unable to load baseline report for policy execution: {err}") - })?; - let bundle_id = baseline - .execution_envelope - .as_ref() - .and_then(|item| item.bundle_id.clone()) - .ok_or_else(|| anyhow!("baseline report is not bundle-backed"))?; - let world = load_bundle_world(&bundle_id)?; - let policy = world.overlay.get_policy_object(policy_id).ok_or_else(|| { - anyhow!("policy `{policy_id}` not present in overlay or seed registry") - })?; - let mut options = CertificationOptions { - optimizer_policy: baseline - .route_explanation - .as_ref() - .map(|item| item.optimizer_policy.clone()) - .unwrap_or(l64_core::OptimizerPolicy::Conservative), - bundle_hash: stable_id(&serde_json::to_string(&world.manifest)?), - policy_hash: stable_id(&(policy_id.clone() + kind)), - bundle_id: Some(world.manifest.id.clone()), - evaluator_policy: None, - cache_policy: None, - no_cache: options.no_cache, - replay_only: false, - strict_derived: options.strict, - strict_policy: scheduler_policy.strict_recomputation, - force_parallel_obligations: scheduler_policy.allow_parallel_obligations - || options.force_parallel_obligations, - max_obligation_workers: Some(scheduler_policy.max_obligation_workers), - }; - match kind.as_str() { - "Optimizer" => { - if let Some(config) = &policy.optimizer { - options.optimizer_policy = config.optimizer_policy.clone(); - } - } - "Evaluator" => options.evaluator_policy = Some(policy.id.clone()), - "ReplayCache" => options.cache_policy = Some(policy.id.clone()), - _ => {} - } - (world, options) - } - }; - - let tasks = execution_tasks(&world)?; - if tasks.is_empty() { - return Ok(ExecutedTaskBatch::empty()); - } - let can_parallelize = scheduler_policy.parallelization - == ParallelizationPolicy::ParallelIndependent - && scheduler_policy.max_workers > 1 - && tasks.len() > 1 - && scheduler_policy.allow_parallel_certification - && (!options.replay_only || scheduler_policy.allow_parallel_replay); - - if !can_parallelize { - let mut reports = Vec::new(); - for task in &tasks { - reports.push(run_task(&world, &options, task, false)?); - } - return Ok(ExecutedTaskBatch { - reports, - lane_records: vec![l64_core::LaneExecutionRecord { - lane_id: "LAN_0".into(), - step_ids: tasks.iter().map(|task| task.task_id()).collect(), - task_ids: tasks.iter().map(|task| task.task_id()).collect(), - serialized_reason: Some(serialization_reason(scheduler_policy, &tasks)), - }], - schedule_hash: ExecutionScheduleHash { - id: format!("SCHH_{}", stable_id(&world.manifest.id)), - hash: stable_id(&(world.manifest.id.clone() + "|serial")), - }, - coherence_receipts: Vec::new(), - ordering_receipt: OrderingReceipt { - id: format!( - "ORD_{}", - stable_id(&(world.manifest.id.clone() + "|serial")) - ), - ordered_step_ids: tasks.iter().map(|task| task.task_id()).collect(), - notes: vec![ - "serialized certification due to scheduler policy or dependency limits".into(), - ], - }, - explanation: vec![serialization_reason(scheduler_policy, &tasks)], - }); - } - - let worker_count = scheduler_policy.max_workers.min(tasks.len()).max(1); - let lane_records = assign_lanes(&tasks, worker_count); - let (tx, rx) = mpsc::channel(); - thread::scope(|scope| { - for (index, task) in tasks.iter().cloned().enumerate() { - let tx = tx.clone(); - let world = world.clone(); - let mut lane_options = options.clone(); - lane_options.no_cache = true; - scope.spawn(move || { - let result = run_task(&world, &lane_options, &task, true); - let _ = tx.send((index, task, result)); - }); - } - }); - drop(tx); - let mut ordered = Vec::new(); - for item in rx { - ordered.push(item); - } - ordered.sort_by_key(|(index, _, _)| *index); - let mut reports = Vec::new(); - for (_, _, result) in ordered { - reports.push(result?); - } - let schedule_hash = ExecutionScheduleHash { - id: format!( - "SCHH_{}", - stable_id(&(world.manifest.id.clone() + "|parallel")) - ), - hash: stable_id( - &lane_records - .iter() - .map(|lane| format!("{}:{}", lane.lane_id, lane.task_ids.join(","))) - .collect::>() - .join("|"), - ), - }; - let coherence = l64_core::ConcurrencyCoherenceReceipt { - id: format!("COH_{}", stable_id(&(world.manifest.id.clone() + &schedule_hash.hash))), - namespace_id: resolve_cache_root() - .map_err(anyhow::Error::msg)? - .namespace - .unwrap_or_else(|| "default".into()), - merged_artifact_ids: reports.iter().map(report_id).collect(), - notes: vec![ - "parallel worker lanes ran with isolated no-cache certification and merged deterministically".into(), - ], - }; - Ok(ExecutedTaskBatch { - reports, - lane_records, - schedule_hash, - coherence_receipts: vec![coherence], - ordering_receipt: OrderingReceipt { - id: format!( - "ORD_{}", - stable_id(&(world.manifest.id.clone() + "|parallel")) - ), - ordered_step_ids: tasks.iter().map(|task| task.task_id()).collect(), - notes: vec!["deterministic task ordering preserved across parallel lanes".into()], - }, - explanation: vec!["independent certification tasks executed in parallel lanes".into()], - }) -} - -fn report_id(report: &CertificationReport) -> String { - format!( - "REPORT_{}_{}", - report.theorem_id, - report - .campaign_id - .clone() - .unwrap_or_else(|| "THEOREM".into()) - ) -} - -#[derive(Debug, Clone)] -enum ExecutionTask { - Campaign { - campaign_id: String, - }, - Theorem { - theorem_id: String, - target_profile_id: String, - }, -} - -impl ExecutionTask { - fn task_id(&self) -> String { - match self { - Self::Campaign { campaign_id } => campaign_id.clone(), - Self::Theorem { - theorem_id, - target_profile_id, - } => format!("{theorem_id}@{target_profile_id}"), - } - } -} - -fn execution_tasks(world: &BundleWorld) -> Result> { - if world.overlay.local.campaigns.is_empty() { - let target = world - .overlay - .local - .target_profiles - .first() - .ok_or_else(|| anyhow!("bundle theorem execution requires a target profile"))?; - let mut tasks = world - .overlay - .local - .theorem_specs - .iter() - .map(|item| ExecutionTask::Theorem { - theorem_id: item.id.clone(), - target_profile_id: target.id.clone(), - }) - .collect::>(); - tasks.sort_by_key(|task| task.task_id()); - Ok(tasks) - } else { - let mut tasks = world - .overlay - .local - .campaigns - .iter() - .map(|item| ExecutionTask::Campaign { - campaign_id: item.id.clone(), - }) - .collect::>(); - tasks.sort_by_key(|task| task.task_id()); - Ok(tasks) - } -} - -fn run_task( - world: &BundleWorld, - options: &CertificationOptions, - task: &ExecutionTask, - parallel_lane: bool, -) -> Result { - let atlas = CompiledAtlas::compile(&world.overlay).map_err(anyhow::Error::msg)?; - let mut report = match task { - ExecutionTask::Campaign { campaign_id } => { - certify_derived_campaign_with_options(&world.overlay, &atlas, campaign_id, options) - .map_err(anyhow::Error::msg)? - } - ExecutionTask::Theorem { - theorem_id, - target_profile_id, - } => certify_derived_theorem_with_options( - &world.overlay, - &atlas, - theorem_id, - target_profile_id, - None, - options, - ) - .map_err(anyhow::Error::msg)?, - }; - if parallel_lane { - report - .diagnostics - .push("certification computed in parallel lane with isolated cache writes".into()); - } - Ok(report) -} - -fn serialization_reason(scheduler_policy: &SchedulerPolicy, tasks: &[ExecutionTask]) -> String { - if scheduler_policy.parallelization == ParallelizationPolicy::Serialize { - "scheduler policy requires serialized execution".into() - } else if scheduler_policy.max_workers <= 1 { - "max worker policy reduced execution to a single lane".into() - } else if tasks.len() <= 1 { - "only one certification task is available".into() - } else if !scheduler_policy.allow_parallel_certification { - "scheduler policy forbids parallel certification".into() - } else if !scheduler_policy.allow_parallel_replay { - "replay or strict certification settings block parallel reuse".into() - } else { - "lane barriers forced serialization".into() - } -} - -fn assign_lanes( - tasks: &[ExecutionTask], - worker_count: usize, -) -> Vec { - let mut lanes = (0..worker_count) - .map(|index| l64_core::LaneExecutionRecord { - lane_id: format!("LAN_{index}"), - step_ids: Vec::new(), - task_ids: Vec::new(), - serialized_reason: None, - }) - .collect::>(); - for (index, task) in tasks.iter().enumerate() { - let lane_index = index % worker_count; - lanes[lane_index].task_ids.push(task.task_id()); - lanes[lane_index].step_ids.push(task.task_id()); - } - lanes -} - -#[cfg(test)] -mod tests { - use super::*; - use l64_core::{ - CertificationCandidate, CertificationVerdict, DeterministicExecutionEnvelope, - EvaluatorPolicyConfig, EvidencePreference, OptimizerBackend, OptimizerPolicy, - OptimizerPolicyConfig, PolicyResolution, PolicyScope, PolicyTrace, PolicyVerdict, - ReplayCachePolicyConfig, ReplayTrustClass, ReportPolicyConfig, RouteExplanation, - RouteScoreVector, UnsupportedHandlingMode, - }; - - fn sample_report(id: &str, winner: &str) -> CertificationReport { - CertificationReport { - theorem_id: id.into(), - campaign_id: Some(format!("CPG_{id}")), - target_profile_id: "TGT".into(), - verdict: CertificationVerdict::Benchmarked, - selected_atlas_cell: Some(winner.into()), - selected_path: vec!["B1".into()], - route_class_id: None, - certificate_id: None, - candidates: vec![CertificationCandidate { - atlas_cell_id: winner.into(), - path: vec!["B1".into()], - loss_count: 0, - proof_shapes: vec!["PS".into()], - route_class_id: None, - score: vec![0], - route_score: Some(RouteScoreVector { - lawfulness: 0, - identity_preservation: 0, - loss_compliance: 0, - rollback_viability: 0, - proof_shape_satisfiability: 0, - bundle_resolution: 0, - surface_transition_penalty: 0, - execution_cost: 0, - derived_obligation_depth: 0, - maturity_confidence: 0, - symbolic_fidelity: 0, - receipt_completeness: 0, - }), - }], - obligations: vec![], - reasons: vec![], - diagnostics: vec![], - deficiencies: vec![], - adequacy_records: vec![], - checker_receipts: vec![], - burden_pack_ids: vec![], - claim_packet_ids: vec![], - evidence_contract_ids: vec![], - benchmark_receipt_ids: vec![], - challenge_receipt_ids: vec![], - reproducibility_packet_ids: vec![], - promotion_artifact_ids: vec![], - reused_artifact_ids: vec![], - default_selected_artifact_ids: vec![], - payoff_receipt_ids: vec![], - policy_resolution: Some(PolicyResolution { - id: "MPR".into(), - scope: PolicyScope::Global, - applied_policy_ids: vec!["MOP_OPT".into()], - conflicts: vec![], - trace: PolicyTrace { - id: "MPT".into(), - steps: vec!["resolved".into()], - }, - optimizer: OptimizerPolicyConfig { - optimizer_policy: OptimizerPolicy::Conservative, - backend: OptimizerBackend::Lexicographic, - active_axes: vec![l64_core::OptimizationAxis::Lawfulness], - route_explanation_verbosity: "standard".into(), - symbolic_fidelity_preferred: false, - tie_break_rules: vec![], - }, - evaluator: EvaluatorPolicyConfig { - evidence_preference: EvidencePreference::RecomputeIfSupported, - allow_approximation: true, - unsupported_mode: UnsupportedHandlingMode::Permit, - require_symbolic_fidelity_route: false, - prefer_comp_replay: true, - }, - replay_cache: ReplayCachePolicyConfig { - replay_allowed: true, - exact_policy_match_required: true, - survive_surface_only_changes: false, - reuse_approximate_results: true, - optimizer_change_invalidates: true, - surface_pack_change_invalidates: true, - trust_class: ReplayTrustClass::ExactPolicyOnly, - }, - report: ReportPolicyConfig { - export_surfaces: Vec::new(), - include_policy_trace: true, - include_route_explanation: true, - include_obligation_logs: true, - }, - scheduler: l64_core::SchedulerPolicyConfig { - parallelization: l64_core::ParallelizationPolicy::Serialize, - max_workers: 1, - allow_parallel_replay: false, - allow_parallel_certification: true, - allow_parallel_exports: true, - deterministic_ordering: true, - allow_parallel_obligations: false, - max_obligation_workers: 1, - allow_parallel_obligation_replay: false, - serialize_canonicalization_sensitive: true, - }, - verdict: PolicyVerdict::Applied, - }), - route_explanation: Some(RouteExplanation { - optimizer_policy: OptimizerPolicy::Conservative, - optimizer_backend: OptimizerBackend::Lexicographic, - policy_resolution_id: Some("MPR".into()), - winner_atlas_cell_id: Some(winner.into()), - winner_score: None, - dominated_candidates: vec!["A2".into()], - rejected_candidates: vec![], - axes_used: vec![l64_core::OptimizationAxis::Lawfulness], - explanation: vec!["test route".into()], - }), - execution_envelope: Some(DeterministicExecutionEnvelope { - bundle_hash: "bundle".into(), - bundle_id: Some("BND_TEST".into()), - policy_hash: "policy".into(), - policy_resolution_id: Some("MPR".into()), - manifest_id: Some("EXM".into()), - lock_id: Some("BLK".into()), - route_winner_hash: "winner".into(), - obligation_replay_keys: vec![], - report_hash: "report".into(), - replay_status: ReplayStatus::Fresh, - executed_plan_id: None, - reconciliation_id: None, - }), - reconciliation_summary: Vec::new(), - obligation_plan: None, - obligation_lanes: Vec::new(), - obligation_ordering_receipt: None, - obligation_merge_receipt: None, - replay_legality_checks: Vec::new(), - replay_barrier_receipts: Vec::new(), - replay_merge_receipt: None, - replay_divergence_records: Vec::new(), - obligation_cache_shards: Vec::new(), - reuse_legality_receipts: Vec::new(), - reuse_decision_receipts: Vec::new(), - residual_verification_receipts: Vec::new(), - obligation_write_sets: Vec::new(), - obligation_collision_reports: Vec::new(), - obligation_namespace_receipt: None, - } - } - - #[test] - fn report_diff_detects_route_change() { - let left = sample_report("THS_A", "A1"); - let right = sample_report("THS_A", "A2"); - let diff = compare_reports(&left, &right).unwrap(); - assert_eq!(diff.class, SemanticDiffClass::RouteOnly); - } - - #[test] - fn observation_artifact_is_populated() { - let report = sample_report("THS_A", "A1"); - let observed = observe_report(&report, None, None).unwrap(); - assert!(!observed.artifact.graph.nodes.is_empty()); - assert!(!observed.artifact.record.events.is_empty()); - } -} diff --git a/l64-policy/Cargo.toml b/l64-policy/Cargo.toml deleted file mode 100644 index d668e7c..0000000 --- a/l64-policy/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "l64-policy" -edition.workspace = true -version.workspace = true -license.workspace = true - -[dependencies] -l64-core = { path = "../l64-core" } -serde = { workspace = true } -serde_json = { workspace = true } -thiserror = { workspace = true } diff --git a/l64-policy/src/lib.rs b/l64-policy/src/lib.rs deleted file mode 100644 index 80e079f..0000000 --- a/l64-policy/src/lib.rs +++ /dev/null @@ -1,677 +0,0 @@ -use l64_core::{ - BundleDependency, EvaluatorPolicyConfig, EvidencePreference, ExecutionManifest, - MechanizationPolicyObject, OptimizationAxis, OptimizerBackend, OptimizerPolicy, - OptimizerPolicyConfig, PolicyBinding, PolicyConflict, PolicyResolution, PolicyScope, - PolicyTrace, PolicyVerdict, RegistryLookup, ReplayCachePolicyConfig, ReplayLockManifest, - ReplayTrustClass, ReportPolicyConfig, SchedulerPolicyConfig, UnsupportedHandlingMode, -}; -use serde::{Deserialize, Serialize}; -use thiserror::Error; - -#[derive(Debug, Error)] -pub enum PolicyError { - #[error("illegal policy conflict: {0}")] - Conflict(String), -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ResolvedPolicyGraph { - pub resolution: PolicyResolution, - pub optimizer_backend: OptimizerBackend, -} - -pub fn resolve_policy_graph( - registry: &impl RegistryLookup, - bundle_id: Option<&str>, - theorem_id: Option<&str>, - campaign_id: Option<&str>, - target_profile_id: Option<&str>, - strict: bool, - fallback_optimizer: OptimizerPolicy, -) -> Result { - let mut candidates = builtin_policies(); - candidates.extend(registry.policy_objects()); - let bindings = registry.policy_bindings(); - - let scope = if let Some(id) = campaign_id { - PolicyScope::Campaign(id.to_string()) - } else if let Some(id) = theorem_id { - PolicyScope::Theorem(id.to_string()) - } else if let Some(id) = target_profile_id { - PolicyScope::TargetProfile(id.to_string()) - } else if let Some(id) = bundle_id { - PolicyScope::Bundle(id.to_string()) - } else { - PolicyScope::Global - }; - - let applicable = applicable_policies( - &candidates, - &bindings, - bundle_id, - theorem_id, - campaign_id, - target_profile_id, - ); - let mut trace_steps = vec!["resolved built-in policy baseline".to_string()]; - let mut conflicts = Vec::new(); - - let mut optimizer = default_optimizer(fallback_optimizer); - let mut evaluator = default_evaluator(); - let mut replay_cache = default_replay_cache(); - let mut report = default_report(); - let mut scheduler = default_scheduler(); - let mut applied_policy_ids = Vec::new(); - - for policy in applicable { - applied_policy_ids.push(policy.id.clone()); - trace_steps.push(format!("applied {:?} policy {}", policy.kind, policy.id)); - if let Some(config) = &policy.optimizer { - if policy.kind != l64_core::PolicyKind::Optimizer && strict { - conflicts.push(conflict_for( - &policy, - "optimizer config on non-optimizer policy", - )); - continue; - } - optimizer = config.clone(); - } - if let Some(config) = &policy.evaluator { - if policy.kind != l64_core::PolicyKind::Evaluator && strict { - conflicts.push(conflict_for( - &policy, - "evaluator config on non-evaluator policy", - )); - continue; - } - evaluator = config.clone(); - } - if let Some(config) = &policy.replay_cache { - if policy.kind != l64_core::PolicyKind::ReplayCache && strict { - conflicts.push(conflict_for(&policy, "replay config on non-replay policy")); - continue; - } - replay_cache = config.clone(); - } - if let Some(config) = &policy.report { - if policy.kind != l64_core::PolicyKind::ReportExport && strict { - conflicts.push(conflict_for(&policy, "report config on non-report policy")); - continue; - } - report = config.clone(); - } - if let Some(config) = &policy.scheduler { - scheduler = config.clone(); - } - } - - if strict { - ensure_scope_conflicts(&mut conflicts, &applied_policy_ids, &candidates, &scope); - } - if strict && conflicts.iter().any(|item| item.illegal) { - return Err(PolicyError::Conflict( - conflicts - .iter() - .map(|item| item.message.clone()) - .collect::>() - .join("; "), - )); - } - - let resolution = PolicyResolution { - id: format!("MPR_{}", simple_id(&applied_policy_ids.join("|"))), - scope, - applied_policy_ids, - conflicts: conflicts.clone(), - trace: PolicyTrace { - id: format!("MPT_{}", simple_id(&trace_steps.join("|"))), - steps: trace_steps, - }, - optimizer: optimizer.clone(), - evaluator, - replay_cache, - report, - scheduler, - verdict: if conflicts.is_empty() { - PolicyVerdict::Applied - } else { - PolicyVerdict::Conflict - }, - }; - - Ok(ResolvedPolicyGraph { - optimizer_backend: optimizer.backend.clone(), - resolution, - }) -} - -pub fn build_execution_manifest( - bundle_id: &str, - bundle_hash: &str, - dependencies: Vec, - resolution: &PolicyResolution, - route_winner_ids: Vec, - evaluator_versions: Vec, - pack_versions: Vec, - report_ids: Vec, -) -> ExecutionManifest { - ExecutionManifest { - id: format!("EXM_{}", simple_id(&(bundle_id.to_string() + bundle_hash))), - bundle_id: bundle_id.to_string(), - bundle_hash: bundle_hash.to_string(), - dependency_graph: dependencies, - policy_manifest: l64_core::PolicyManifest { - id: format!("PMF_{}", simple_id(&resolution.id)), - resolution_id: resolution.id.clone(), - policy_ids: resolution.applied_policy_ids.clone(), - policy_hash: simple_id(&serde_json::to_string(resolution).unwrap_or_default()), - }, - route_winner_ids, - evaluator_versions, - pack_versions, - report_ids, - executed_plan_hash: None, - executed_steps: Vec::new(), - reused_artifacts: Vec::new(), - rerun_artifacts: Vec::new(), - reconciliation_summary: Vec::new(), - root_resolution: None, - scheduler_policy: None, - execution_scope: None, - lane_records: Vec::new(), - schedule_hash: None, - coherence_receipts: Vec::new(), - ordering_receipt: None, - obligation_plans: Vec::new(), - obligation_lanes: Vec::new(), - obligation_ordering_receipts: Vec::new(), - obligation_merge_receipts: Vec::new(), - replay_legality_checks: Vec::new(), - replay_barrier_receipts: Vec::new(), - replay_merge_receipts: Vec::new(), - replay_divergence_records: Vec::new(), - obligation_cache_shards: Vec::new(), - obligation_write_sets: Vec::new(), - obligation_collision_reports: Vec::new(), - obligation_namespace_receipts: Vec::new(), - } -} - -pub fn build_replay_lock_manifest( - report_id: &str, - report_hash: &str, - route_winner_hash: &str, - policy_hash: &str, - bundle_hash: &str, -) -> ReplayLockManifest { - ReplayLockManifest { - id: format!("RLM_{}", simple_id(&(report_id.to_string() + report_hash))), - report_id: report_id.to_string(), - report_hash: report_hash.to_string(), - route_winner_hash: route_winner_hash.to_string(), - policy_hash: policy_hash.to_string(), - bundle_hash: bundle_hash.to_string(), - } -} - -fn applicable_policies<'a>( - candidates: &'a [MechanizationPolicyObject], - bindings: &[PolicyBinding], - bundle_id: Option<&str>, - theorem_id: Option<&str>, - campaign_id: Option<&str>, - target_profile_id: Option<&str>, -) -> Vec<&'a MechanizationPolicyObject> { - let mut scored = candidates - .iter() - .filter_map(|policy| { - let direct = match &policy.scope { - PolicyScope::Global => Some(0_u32), - PolicyScope::Bundle(id) if bundle_id == Some(id.as_str()) => Some(30), - PolicyScope::Theorem(id) if theorem_id == Some(id.as_str()) => Some(40), - PolicyScope::Campaign(id) if campaign_id == Some(id.as_str()) => Some(50), - PolicyScope::TargetProfile(id) if target_profile_id == Some(id.as_str()) => { - Some(60) - } - _ => None, - }; - let binding_bonus = bindings - .iter() - .filter(|binding| binding.policy_id == policy.id) - .filter(|binding| match &binding.scope { - PolicyScope::Global => true, - PolicyScope::Bundle(id) => bundle_id == Some(id.as_str()), - PolicyScope::Theorem(id) => theorem_id == Some(id.as_str()), - PolicyScope::Campaign(id) => campaign_id == Some(id.as_str()), - PolicyScope::TargetProfile(id) => target_profile_id == Some(id.as_str()), - }) - .map(|binding| binding.priority) - .max() - .unwrap_or_default(); - direct.map(|score| (score + binding_bonus, policy)) - }) - .collect::>(); - scored.sort_by(|left, right| { - left.0 - .cmp(&right.0) - .then_with(|| left.1.id.cmp(&right.1.id)) - }); - scored.into_iter().map(|(_, policy)| policy).collect() -} - -fn ensure_scope_conflicts( - conflicts: &mut Vec, - applied_ids: &[String], - candidates: &[MechanizationPolicyObject], - scope: &PolicyScope, -) { - let same_scope = candidates - .iter() - .filter(|item| &item.scope == scope) - .collect::>(); - for window in same_scope.windows(2) { - if let [left, right] = window { - if left.kind == right.kind - && applied_ids.contains(&left.id) - && applied_ids.contains(&right.id) - { - conflicts.push(PolicyConflict { - id: format!("MPC_{}", simple_id(&(left.id.clone() + &right.id))), - kind: left.kind.clone(), - left_policy_id: left.id.clone(), - right_policy_id: right.id.clone(), - message: format!("same-scope {:?} policies both applied", left.kind), - illegal: true, - }); - } - } - } -} - -fn conflict_for(policy: &MechanizationPolicyObject, message: &str) -> PolicyConflict { - PolicyConflict { - id: format!("MPC_{}", simple_id(&(policy.id.clone() + message))), - kind: policy.kind.clone(), - left_policy_id: policy.id.clone(), - right_policy_id: policy.extends.clone().unwrap_or_default(), - message: message.to_string(), - illegal: true, - } -} - -fn default_optimizer(policy: OptimizerPolicy) -> OptimizerPolicyConfig { - OptimizerPolicyConfig { - optimizer_policy: policy.clone(), - backend: OptimizerBackend::Lexicographic, - active_axes: vec![ - OptimizationAxis::Lawfulness, - OptimizationAxis::IdentityPreservation, - OptimizationAxis::LossCompliance, - OptimizationAxis::RollbackViability, - OptimizationAxis::ProofShapeSatisfiability, - OptimizationAxis::BundleResolution, - OptimizationAxis::SurfaceTransitionPenalty, - OptimizationAxis::ExecutionCost, - OptimizationAxis::DerivedObligationDepth, - OptimizationAxis::MaturityConfidence, - OptimizationAxis::SymbolicFidelity, - OptimizationAxis::ReceiptCompleteness, - ], - route_explanation_verbosity: "standard".into(), - symbolic_fidelity_preferred: matches!(policy, OptimizerPolicy::SymbolicFidelityFirst), - tie_break_rules: vec!["shorter-path".into(), "lower-loss".into()], - } -} - -fn default_evaluator() -> EvaluatorPolicyConfig { - EvaluatorPolicyConfig { - evidence_preference: EvidencePreference::RecomputeIfSupported, - allow_approximation: true, - unsupported_mode: UnsupportedHandlingMode::Permit, - require_symbolic_fidelity_route: false, - prefer_comp_replay: true, - } -} - -fn default_replay_cache() -> ReplayCachePolicyConfig { - ReplayCachePolicyConfig { - replay_allowed: true, - exact_policy_match_required: true, - survive_surface_only_changes: false, - reuse_approximate_results: true, - optimizer_change_invalidates: true, - surface_pack_change_invalidates: true, - trust_class: ReplayTrustClass::ExactPolicyOnly, - } -} - -fn default_report() -> ReportPolicyConfig { - ReportPolicyConfig { - export_surfaces: Vec::new(), - include_policy_trace: true, - include_route_explanation: true, - include_obligation_logs: true, - } -} - -fn default_scheduler() -> SchedulerPolicyConfig { - SchedulerPolicyConfig { - parallelization: l64_core::ParallelizationPolicy::Serialize, - max_workers: 1, - allow_parallel_replay: false, - allow_parallel_certification: true, - allow_parallel_exports: true, - deterministic_ordering: true, - allow_parallel_obligations: false, - max_obligation_workers: 1, - allow_parallel_obligation_replay: false, - serialize_canonicalization_sensitive: true, - } -} - -fn builtin_policies() -> Vec { - vec![ - MechanizationPolicyObject { - id: "MOP_GLOBAL_DEFAULT".into(), - kind: l64_core::PolicyKind::Optimizer, - scope: PolicyScope::Global, - extends: None, - optimizer: Some(default_optimizer(OptimizerPolicy::Conservative)), - evaluator: None, - replay_cache: None, - report: None, - scheduler: None, - canonicalizer_mode: Some("canonical-default".into()), - merge_policy: None, - notes: vec!["seed global optimizer baseline".into()], - }, - MechanizationPolicyObject { - id: "MOP_GLOBAL_EVAL".into(), - kind: l64_core::PolicyKind::Evaluator, - scope: PolicyScope::Global, - extends: None, - optimizer: None, - evaluator: Some(default_evaluator()), - replay_cache: None, - report: None, - scheduler: None, - canonicalizer_mode: None, - merge_policy: None, - notes: vec!["seed global evaluator baseline".into()], - }, - MechanizationPolicyObject { - id: "MOP_GLOBAL_REPLAY".into(), - kind: l64_core::PolicyKind::ReplayCache, - scope: PolicyScope::Global, - extends: None, - optimizer: None, - evaluator: None, - replay_cache: Some(default_replay_cache()), - report: None, - scheduler: None, - canonicalizer_mode: None, - merge_policy: None, - notes: vec!["seed global replay baseline".into()], - }, - MechanizationPolicyObject { - id: "MOP_GLOBAL_REPORT".into(), - kind: l64_core::PolicyKind::ReportExport, - scope: PolicyScope::Global, - extends: None, - optimizer: None, - evaluator: None, - replay_cache: None, - report: Some(default_report()), - scheduler: Some(default_scheduler()), - canonicalizer_mode: None, - merge_policy: None, - notes: vec!["seed global report baseline".into()], - }, - ] -} - -fn simple_id(input: &str) -> String { - let mut hash: u64 = 1469598103934665603; - for byte in input.as_bytes() { - hash ^= u64::from(*byte); - hash = hash.wrapping_mul(1099511628211); - } - format!("{hash:x}") -} - -#[cfg(test)] -mod tests { - use super::*; - use l64_core::RegistryLookup; - - #[derive(Default)] - struct EmptyRegistry { - policies: Vec, - bindings: Vec, - } - impl RegistryLookup for EmptyRegistry { - fn get_object(&self, _: &str) -> Option { - None - } - fn get_regime(&self, _: &str) -> Option { - None - } - fn get_bridge(&self, _: &str) -> Option { - None - } - fn get_proof_shape(&self, _: &str) -> Option { - None - } - fn get_atlas_cell(&self, _: &str) -> Option { - None - } - fn get_mechanization_package(&self, _: &str) -> Option { - None - } - fn get_theorem_spec(&self, _: &str) -> Option { - None - } - fn get_obligation(&self, _: &str) -> Option { - None - } - fn get_target_profile(&self, _: &str) -> Option { - None - } - fn get_route_ledger(&self, _: &str) -> Option { - None - } - fn get_certificate(&self, _: &str) -> Option { - None - } - fn get_campaign(&self, _: &str) -> Option { - None - } - fn get_campaign_portfolio(&self, _: &str) -> Option { - None - } - fn get_route_class(&self, _: &str) -> Option { - None - } - fn get_atlas_deficiency(&self, _: &str) -> Option { - None - } - fn atlas_deficiencies(&self) -> Vec { - Vec::new() - } - fn get_adequacy_clause(&self, _: &str) -> Option { - None - } - fn adequacy_clauses(&self) -> Vec { - Vec::new() - } - fn get_codebook_pack(&self, _: &str) -> Option { - None - } - fn get_glyph_pack(&self, _: &str) -> Option { - None - } - fn get_combo_pack(&self, _: &str) -> Option { - None - } - fn get_projection_policy(&self, _: &str) -> Option { - None - } - fn get_alias_expansion_policy(&self, _: &str) -> Option { - None - } - fn get_surface_deficiency(&self, _: &str) -> Option { - None - } - fn get_policy_object(&self, _: &str) -> Option { - None - } - fn policy_objects(&self) -> Vec { - self.policies.clone() - } - fn policy_bindings(&self) -> Vec { - self.bindings.clone() - } - fn find_equivalence_class(&self, _: &str, _: &str) -> Option { - None - } - fn atlas_cells(&self) -> Vec { - Vec::new() - } - } - - #[test] - fn resolves_builtin_policy_graph() { - let resolved = resolve_policy_graph( - &EmptyRegistry::default(), - Some("BND_LOCAL"), - None, - None, - None, - false, - OptimizerPolicy::Conservative, - ) - .unwrap(); - assert_eq!(resolved.resolution.verdict, PolicyVerdict::Applied); - assert!(!resolved.resolution.applied_policy_ids.is_empty()); - } - - #[test] - fn evaluator_authority_is_named_and_scoped() { - let mut evaluator = default_evaluator(); - evaluator.allow_approximation = false; - evaluator.unsupported_mode = UnsupportedHandlingMode::StrictFail; - let registry = EmptyRegistry { - policies: vec![MechanizationPolicyObject { - id: "MOP_THS_LOCAL_EVAL".into(), - kind: l64_core::PolicyKind::Evaluator, - scope: PolicyScope::Theorem("THS_LOCAL".into()), - extends: None, - optimizer: None, - evaluator: Some(evaluator), - replay_cache: None, - report: None, - scheduler: None, - canonicalizer_mode: None, - merge_policy: None, - notes: vec!["theorem-scoped evaluator".into()], - }], - bindings: Vec::new(), - }; - - let resolved = resolve_policy_graph( - ®istry, - Some("BND_LOCAL"), - Some("THS_LOCAL"), - None, - None, - true, - OptimizerPolicy::Conservative, - ) - .unwrap(); - - assert_eq!( - resolved.resolution.scope, - PolicyScope::Theorem("THS_LOCAL".into()) - ); - assert!( - resolved - .resolution - .applied_policy_ids - .iter() - .any(|id| id == "MOP_THS_LOCAL_EVAL") - ); - assert!(!resolved.resolution.evaluator.allow_approximation); - assert_eq!( - resolved.resolution.evaluator.unsupported_mode, - UnsupportedHandlingMode::StrictFail - ); - } - - #[test] - fn policy_precedence_receipt_is_stable_across_registry_order() { - let evaluator_policy = MechanizationPolicyObject { - id: "MOP_A_EVAL".into(), - kind: l64_core::PolicyKind::Evaluator, - scope: PolicyScope::Theorem("THS_LOCAL".into()), - extends: None, - optimizer: None, - evaluator: Some(default_evaluator()), - replay_cache: None, - report: None, - scheduler: None, - canonicalizer_mode: None, - merge_policy: None, - notes: Vec::new(), - }; - let replay_policy = MechanizationPolicyObject { - id: "MOP_B_REPLAY".into(), - kind: l64_core::PolicyKind::ReplayCache, - scope: PolicyScope::Theorem("THS_LOCAL".into()), - extends: None, - optimizer: None, - evaluator: None, - replay_cache: Some(default_replay_cache()), - report: None, - scheduler: None, - canonicalizer_mode: None, - merge_policy: None, - notes: Vec::new(), - }; - let left_registry = EmptyRegistry { - policies: vec![replay_policy.clone(), evaluator_policy.clone()], - bindings: Vec::new(), - }; - let right_registry = EmptyRegistry { - policies: vec![evaluator_policy, replay_policy], - bindings: Vec::new(), - }; - - let left = resolve_policy_graph( - &left_registry, - Some("BND_LOCAL"), - Some("THS_LOCAL"), - None, - None, - true, - OptimizerPolicy::Conservative, - ) - .unwrap(); - let right = resolve_policy_graph( - &right_registry, - Some("BND_LOCAL"), - Some("THS_LOCAL"), - None, - None, - true, - OptimizerPolicy::Conservative, - ) - .unwrap(); - - assert_eq!(left.resolution.id, right.resolution.id); - assert_eq!( - left.resolution.applied_policy_ids, - right.resolution.applied_policy_ids - ); - assert_eq!(left.resolution.trace.steps, right.resolution.trace.steps); - } -} diff --git a/l64-command/Cargo.toml b/l64-projection/Cargo.toml similarity index 54% rename from l64-command/Cargo.toml rename to l64-projection/Cargo.toml index 18ac287..c3edf3f 100644 --- a/l64-command/Cargo.toml +++ b/l64-projection/Cargo.toml @@ -1,9 +1,8 @@ [package] -name = "l64-command" +name = "l64-projection" edition.workspace = true version.workspace = true license.workspace = true [dependencies] -clap = { workspace = true } -l64-core = { path = "../l64-core" } +l64-native = { path = "../l64-native" } diff --git a/l64-projection/README.md b/l64-projection/README.md new file mode 100644 index 0000000..9df38b6 --- /dev/null +++ b/l64-projection/README.md @@ -0,0 +1,15 @@ +# l64-projection + +`l64-projection` derives read-only upper views from `l64-native::Graph` authority. + +It provides five coordinated views over one native state and context: + +- atlas candidates from executable operation and equality nodes; +- certification burdens from context-relative closure and native evidence; +- replay steps from the native journal; +- deterministic aggregate reporting; +- ranked research candidates from open and invalid reverse-reachable structure. + +Every projection carries its native composed state symbol, context, structural counts, journal length, and projection version. Verification rebuilds the complete view from the graph and requires exact equality. The crate has no storage, registry, cache, import, promotion, serialization, independent hashing, or alternate graph dependency. It reuses the symbolic identity carried by native authority. + +Projection records are expendable. Native authority remains canonical. diff --git a/l64-projection/examples/native_projection.rs b/l64-projection/examples/native_projection.rs new file mode 100644 index 0000000..f3c593d --- /dev/null +++ b/l64-projection/examples/native_projection.rs @@ -0,0 +1,29 @@ +use l64_native::{Dimension, Graph, LocusWord, Proposal, ROOT_CONTEXT, Route}; +use l64_projection::ProjectionSet; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x50524f4a45435431)).composed(LocusWord(index)) +} + +fn main() { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let quantity = graph + .declare_quantity_type(route(2), scalar, Dimension::new([0, 0, 0, 0, 0, 0, 0])) + .unwrap(); + let value = graph + .insert_value(route(3), ROOT_CONTEXT, quantity) + .unwrap(); + graph + .transact(Proposal::square_root( + route(4), + ROOT_CONTEXT, + value, + quantity, + )) + .unwrap(); + + let projection = ProjectionSet::derive(&graph, ROOT_CONTEXT, 8).unwrap(); + projection.verify(&graph).unwrap(); + print!("{}", projection.render_text()); +} diff --git a/l64-projection/src/analysis.rs b/l64-projection/src/analysis.rs new file mode 100644 index 0000000..18235d7 --- /dev/null +++ b/l64-projection/src/analysis.rs @@ -0,0 +1,37 @@ +use crate::{ProjectionError, ProjectionSource}; +use l64_native::{ClosureState, ContextId, Graph, NodeId}; + +pub(crate) struct ContextAnalysis { + pub source: ProjectionSource, + nodes: Vec, + closures: Vec>, +} + +impl ContextAnalysis { + pub fn derive(graph: &Graph, context: ContextId) -> Result { + let source = ProjectionSource::capture(graph, context)?; + let states = graph.context_closure_states(context)?; + let mut nodes = Vec::with_capacity(states.len()); + let mut closures = vec![None; graph.node_count()]; + for (node, state) in states { + nodes.push(node); + closures[node as usize] = Some(state); + } + Ok(Self { + source, + nodes, + closures, + }) + } + + pub fn nodes(&self) -> &[NodeId] { + &self.nodes + } + + pub fn closure(&self, node: NodeId) -> Result { + self.closures + .get(node as usize) + .and_then(|state| *state) + .ok_or(ProjectionError::UnknownNode(node)) + } +} diff --git a/l64-projection/src/atlas.rs b/l64-projection/src/atlas.rs new file mode 100644 index 0000000..c463294 --- /dev/null +++ b/l64-projection/src/atlas.rs @@ -0,0 +1,112 @@ +use crate::{ + ContextAnalysis, EvidenceRef, PortRef, ProjectionError, ProjectionSource, SourceRef, + closure_rank, evidence_ref, source_ref, +}; +use l64_native::{ClosureState, ContextId, Graph, OpCode, Route}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum AtlasCandidateKind { + Operation, + Equality, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AtlasCandidate { + pub kind: AtlasCandidateKind, + pub source: SourceRef, + pub opcode: OpCode, + pub closure: ClosureState, + pub output_type: Option, + pub ports: Vec, + pub direct_dependents: Vec, + pub canonical_route: Option, + pub evidence: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AtlasView { + pub source: ProjectionSource, + pub candidates: Vec, +} + +impl AtlasView { + pub fn derive(graph: &Graph, context: ContextId) -> Result { + let analysis = ContextAnalysis::derive(graph, context)?; + Self::derive_analyzed(graph, &analysis) + } + + pub(crate) fn derive_analyzed( + graph: &Graph, + analysis: &ContextAnalysis, + ) -> Result { + let context = analysis.source.context; + let mut candidates = Vec::new(); + for &node in analysis.nodes() { + let record = graph.node(node).ok_or(ProjectionError::UnknownNode(node))?; + let kind = match record.opcode() { + OpCode::Compose + | OpCode::MatMul + | OpCode::Add + | OpCode::Multiply + | OpCode::Divide + | OpCode::Sqrt => AtlasCandidateKind::Operation, + OpCode::TypeEquality => AtlasCandidateKind::Equality, + _ => continue, + }; + let source = source_ref(graph, node)?; + let output_type = record.ty().map(|id| source_ref(graph, id)).transpose()?; + let ports = graph + .ports(node) + .ok_or(ProjectionError::UnknownNode(node))? + .iter() + .map(|port| { + Ok(PortRef { + role: port.role(), + ordinal: port.ordinal(), + target: source_ref(graph, port.target())?, + }) + }) + .collect::, ProjectionError>>()?; + let mut direct_dependents = graph + .direct_dependents(node)? + .iter() + .copied() + .map(|id| source_ref(graph, id)) + .collect::, ProjectionError>>()?; + direct_dependents.sort(); + let canonical_route = graph.canonical_representative_route(context, node).ok(); + let evidence = evidence_ref(graph, node, |id| analysis.closure(id))?; + candidates.push(AtlasCandidate { + kind, + source, + opcode: record.opcode(), + closure: analysis.closure(node)?, + output_type, + ports, + direct_dependents, + canonical_route, + evidence, + }); + } + candidates.sort_by(|left, right| { + closure_rank(left.closure) + .cmp(&closure_rank(right.closure)) + .then_with(|| left.kind.cmp(&right.kind)) + .then_with(|| left.source.route.cmp(&right.source.route)) + }); + Ok(Self { + source: analysis.source.clone(), + candidates, + }) + } + + pub fn verify(&self, graph: &Graph) -> Result<(), ProjectionError> { + self.source.verify(graph)?; + let rebuilt = Self::derive(graph, self.source.context)?; + if &rebuilt == self { + Ok(()) + } else { + Err(ProjectionError::ProjectionMismatch) + } + } +} diff --git a/l64-projection/src/certification.rs b/l64-projection/src/certification.rs new file mode 100644 index 0000000..4cc7629 --- /dev/null +++ b/l64-projection/src/certification.rs @@ -0,0 +1,97 @@ +use crate::{AtlasView, ContextAnalysis, ProjectionError, ProjectionSource, SourceRef}; +use l64_native::{ClosureState, ContextId, Graph, OpCode}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum BurdenState { + Discharged, + Open, + Invalid, + MissingEvidence, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CertificationBurden { + pub subject: SourceRef, + pub closure: ClosureState, + pub state: BurdenState, + pub judgment: Option, + pub evidence: Option, + pub evidence_opcode: Option, + pub dependencies: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CertificationView { + pub source: ProjectionSource, + pub burdens: Vec, +} + +impl CertificationView { + pub fn derive(graph: &Graph, context: ContextId) -> Result { + let analysis = ContextAnalysis::derive(graph, context)?; + let atlas = AtlasView::derive_analyzed(graph, &analysis)?; + Ok(Self::from_atlas(&atlas)) + } + + pub(crate) fn from_atlas(atlas: &AtlasView) -> Self { + let mut burdens = Vec::with_capacity(atlas.candidates.len()); + for candidate in &atlas.candidates { + let closure = candidate.closure; + let (judgment, evidence, evidence_opcode) = candidate + .evidence + .as_ref() + .map(|item| { + ( + item.judgment.clone(), + Some(item.evidence.clone()), + Some(item.opcode), + ) + }) + .unwrap_or((None, None, None)); + let state = match (closure, evidence_opcode) { + (ClosureState::Invalid, _) => BurdenState::Invalid, + (ClosureState::Open, _) => BurdenState::Open, + (ClosureState::Closed, Some(_)) => BurdenState::Discharged, + (ClosureState::Closed, None) => BurdenState::MissingEvidence, + }; + let mut dependencies = candidate + .ports + .iter() + .map(|port| port.target.clone()) + .collect::>(); + if let Some(output_type) = &candidate.output_type { + dependencies.push(output_type.clone()); + } + dependencies.sort(); + dependencies.dedup(); + burdens.push(CertificationBurden { + subject: candidate.source.clone(), + closure, + state, + judgment, + evidence, + evidence_opcode, + dependencies, + }); + } + burdens.sort_by(|left, right| { + left.state + .cmp(&right.state) + .then_with(|| left.subject.route.cmp(&right.subject.route)) + }); + Self { + source: atlas.source.clone(), + burdens, + } + } + + pub fn verify(&self, graph: &Graph) -> Result<(), ProjectionError> { + self.source.verify(graph)?; + let rebuilt = Self::derive(graph, self.source.context)?; + if &rebuilt == self { + Ok(()) + } else { + Err(ProjectionError::ProjectionMismatch) + } + } +} diff --git a/l64-projection/src/lib.rs b/l64-projection/src/lib.rs new file mode 100644 index 0000000..7431afa --- /dev/null +++ b/l64-projection/src/lib.rs @@ -0,0 +1,25 @@ +#![forbid(unsafe_code)] + +mod analysis; +mod atlas; +mod certification; +mod order; +mod replay; +mod report; +mod research; +mod set; +mod source; + +pub use atlas::{AtlasCandidate, AtlasCandidateKind, AtlasView}; +pub use certification::{BurdenState, CertificationBurden, CertificationView}; +pub use replay::{ReplayStep, ReplayView}; +pub use report::{OpcodeCount, ReportView}; +pub use research::{ResearchCandidate, ResearchView}; +pub use set::ProjectionSet; +pub use source::{EvidenceRef, PortRef, ProjectionError, ProjectionSource, SourceRef}; + +pub const PROJECTION_VERSION: u16 = 1; + +pub(crate) use analysis::ContextAnalysis; +pub(crate) use order::closure_rank; +pub(crate) use source::{evidence_ref, source_ref}; diff --git a/l64-projection/src/order.rs b/l64-projection/src/order.rs new file mode 100644 index 0000000..15bf0f8 --- /dev/null +++ b/l64-projection/src/order.rs @@ -0,0 +1,9 @@ +use l64_native::ClosureState; + +pub(crate) fn closure_rank(state: ClosureState) -> u8 { + match state { + ClosureState::Invalid => 0, + ClosureState::Open => 1, + ClosureState::Closed => 2, + } +} diff --git a/l64-projection/src/replay.rs b/l64-projection/src/replay.rs new file mode 100644 index 0000000..136aa97 --- /dev/null +++ b/l64-projection/src/replay.rs @@ -0,0 +1,60 @@ +use crate::{ContextAnalysis, ProjectionError, ProjectionSource, SourceRef, source_ref}; +use l64_native::{ContextId, Graph, OpCode, SymbolicSeal}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReplayStep { + pub event: u32, + pub operation: OpCode, + pub subject: SourceRef, + pub before: SymbolicSeal, + pub after: SymbolicSeal, + pub parent: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReplayView { + pub source: ProjectionSource, + pub steps: Vec, +} + +impl ReplayView { + pub fn derive(graph: &Graph, context: ContextId) -> Result { + let analysis = ContextAnalysis::derive(graph, context)?; + Self::derive_analyzed(graph, &analysis) + } + + pub(crate) fn derive_analyzed( + graph: &Graph, + analysis: &ContextAnalysis, + ) -> Result { + let visible = analysis.nodes(); + let mut steps = Vec::new(); + for (event, item) in graph.journal().iter().enumerate() { + if visible.binary_search(&item.subject()).is_err() { + continue; + } + steps.push(ReplayStep { + event: event as u32, + operation: item.operation(), + subject: source_ref(graph, item.subject())?, + before: item.before(), + after: item.after(), + parent: item.parent(), + }); + } + Ok(Self { + source: analysis.source.clone(), + steps, + }) + } + + pub fn verify(&self, graph: &Graph) -> Result<(), ProjectionError> { + self.source.verify(graph)?; + let rebuilt = Self::derive(graph, self.source.context)?; + if &rebuilt == self { + Ok(()) + } else { + Err(ProjectionError::ProjectionMismatch) + } + } +} diff --git a/l64-projection/src/report.rs b/l64-projection/src/report.rs new file mode 100644 index 0000000..80bb5f2 --- /dev/null +++ b/l64-projection/src/report.rs @@ -0,0 +1,82 @@ +use crate::{ContextAnalysis, ProjectionError, ProjectionSource, source_ref}; +use l64_native::{ClosureState, ContextId, Graph, OpCode, Route}; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OpcodeCount { + pub opcode: OpCode, + pub count: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReportView { + pub source: ProjectionSource, + pub closed: usize, + pub open: usize, + pub invalid: usize, + pub opcode_counts: Vec, + pub obligation_routes: Vec, + pub invalid_routes: Vec, +} + +impl ReportView { + pub fn derive(graph: &Graph, context: ContextId) -> Result { + let analysis = ContextAnalysis::derive(graph, context)?; + Self::derive_analyzed(graph, &analysis) + } + + pub(crate) fn derive_analyzed( + graph: &Graph, + analysis: &ContextAnalysis, + ) -> Result { + let mut closed = 0; + let mut open = 0; + let mut invalid = 0; + let mut counts = BTreeMap::::new(); + let mut obligation_routes = Vec::new(); + let mut invalid_routes = Vec::new(); + for &node in analysis.nodes() { + let record = graph.node(node).ok_or(ProjectionError::UnknownNode(node))?; + match analysis.closure(node)? { + ClosureState::Closed => closed += 1, + ClosureState::Open => open += 1, + ClosureState::Invalid => { + invalid += 1; + invalid_routes.push(source_ref(graph, node)?.route); + } + } + let entry = counts + .entry(record.opcode() as u16) + .or_insert((record.opcode(), 0)); + entry.1 += 1; + if record.opcode() == OpCode::Obligation { + obligation_routes.push(source_ref(graph, node)?.route); + } + } + obligation_routes.sort(); + invalid_routes.sort(); + let opcode_counts = counts + .into_values() + .map(|(opcode, count)| OpcodeCount { opcode, count }) + .collect(); + Ok(Self { + source: analysis.source.clone(), + closed, + open, + invalid, + opcode_counts, + obligation_routes, + invalid_routes, + }) + } + + pub fn verify(&self, graph: &Graph) -> Result<(), ProjectionError> { + self.source.verify(graph)?; + let rebuilt = Self::derive(graph, self.source.context)?; + if &rebuilt == self { + Ok(()) + } else { + Err(ProjectionError::ProjectionMismatch) + } + } +} diff --git a/l64-projection/src/research.rs b/l64-projection/src/research.rs new file mode 100644 index 0000000..986e77d --- /dev/null +++ b/l64-projection/src/research.rs @@ -0,0 +1,100 @@ +use crate::{ + ContextAnalysis, ProjectionError, ProjectionSource, SourceRef, closure_rank, evidence_ref, + source_ref, +}; +use l64_native::{ClosureState, ContextId, Graph, OpCode, Route}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResearchCandidate { + pub source: SourceRef, + pub opcode: OpCode, + pub closure: ClosureState, + pub direct_dependents: usize, + pub affected_nodes: usize, + pub canonical_route: Option, + pub evidence: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResearchView { + pub source: ProjectionSource, + pub total_candidates: usize, + pub limit: usize, + pub candidates: Vec, +} + +impl ResearchView { + pub fn derive( + graph: &Graph, + context: ContextId, + limit: usize, + ) -> Result { + let analysis = ContextAnalysis::derive(graph, context)?; + Self::derive_analyzed(graph, &analysis, limit) + } + + pub(crate) fn derive_analyzed( + graph: &Graph, + analysis: &ContextAnalysis, + limit: usize, + ) -> Result { + let context = analysis.source.context; + let mut candidates = Vec::new(); + for &node in analysis.nodes() { + let record = graph.node(node).ok_or(ProjectionError::UnknownNode(node))?; + let closure = analysis.closure(node)?; + let direct_dependents = graph.direct_dependents(node)?.len(); + let candidate_opcode = matches!( + record.opcode(), + OpCode::Compose + | OpCode::MatMul + | OpCode::Add + | OpCode::Multiply + | OpCode::Divide + | OpCode::Sqrt + | OpCode::TypeEquality + ); + if closure == ClosureState::Closed && !(candidate_opcode && direct_dependents > 0) { + continue; + } + let affected_nodes = graph.affected_nodes(node)?.len(); + candidates.push(ResearchCandidate { + source: source_ref(graph, node)?, + opcode: record.opcode(), + closure, + direct_dependents, + affected_nodes, + canonical_route: graph.canonical_representative_route(context, node).ok(), + evidence: evidence_ref(graph, node, |id| analysis.closure(id))? + .map(|item| item.evidence), + }); + } + candidates.sort_by(|left, right| { + closure_rank(left.closure) + .cmp(&closure_rank(right.closure)) + .then_with(|| right.affected_nodes.cmp(&left.affected_nodes)) + .then_with(|| right.direct_dependents.cmp(&left.direct_dependents)) + .then_with(|| left.source.route.cmp(&right.source.route)) + }); + let total_candidates = candidates.len(); + if limit < candidates.len() { + candidates.truncate(limit); + } + Ok(Self { + source: analysis.source.clone(), + total_candidates, + limit, + candidates, + }) + } + + pub fn verify(&self, graph: &Graph) -> Result<(), ProjectionError> { + self.source.verify(graph)?; + let rebuilt = Self::derive(graph, self.source.context, self.limit)?; + if &rebuilt == self { + Ok(()) + } else { + Err(ProjectionError::ProjectionMismatch) + } + } +} diff --git a/l64-projection/src/set.rs b/l64-projection/src/set.rs new file mode 100644 index 0000000..a57878a --- /dev/null +++ b/l64-projection/src/set.rs @@ -0,0 +1,102 @@ +use crate::{ + AtlasView, CertificationView, ContextAnalysis, ProjectionError, ProjectionSource, ReplayView, + ReportView, ResearchView, +}; +use l64_native::{ContextId, Graph, Route}; +use std::fmt::Write as _; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProjectionSet { + pub source: ProjectionSource, + pub atlas: AtlasView, + pub certification: CertificationView, + pub replay: ReplayView, + pub report: ReportView, + pub research: ResearchView, +} + +impl ProjectionSet { + pub fn derive( + graph: &Graph, + context: ContextId, + research_limit: usize, + ) -> Result { + let analysis = ContextAnalysis::derive(graph, context)?; + let atlas = AtlasView::derive_analyzed(graph, &analysis)?; + Ok(Self { + source: analysis.source.clone(), + certification: CertificationView::from_atlas(&atlas), + replay: ReplayView::derive_analyzed(graph, &analysis)?, + report: ReportView::derive_analyzed(graph, &analysis)?, + research: ResearchView::derive_analyzed(graph, &analysis, research_limit)?, + atlas, + }) + } + + pub fn verify(&self, graph: &Graph) -> Result<(), ProjectionError> { + self.source.verify(graph)?; + let rebuilt = Self::derive(graph, self.source.context, self.research.limit)?; + if &rebuilt == self { + Ok(()) + } else { + Err(ProjectionError::ProjectionMismatch) + } + } + + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE PROJECTION v{}", self.source.version); + let _ = writeln!(out, "context={}", self.source.context); + let _ = writeln!(out, "symbol={}", self.source.symbol); + let _ = writeln!(out, "nodes={}", self.source.node_count); + let _ = writeln!(out, "contexts={}", self.source.context_count); + let _ = writeln!(out, "journal={}", self.source.journal_len); + let _ = writeln!(out, "atlas_candidates={}", self.atlas.candidates.len()); + let _ = writeln!( + out, + "certification_burdens={}", + self.certification.burdens.len() + ); + let _ = writeln!(out, "replay_steps={}", self.replay.steps.len()); + let _ = writeln!(out, "closed={}", self.report.closed); + let _ = writeln!(out, "open={}", self.report.open); + let _ = writeln!(out, "invalid={}", self.report.invalid); + let _ = writeln!( + out, + "research_candidates={}/{}", + self.research.candidates.len(), + self.research.total_candidates + ); + for candidate in &self.research.candidates { + let _ = writeln!( + out, + "research route={} opcode={:?} closure={:?} affected={} dependents={}", + format_route(&candidate.source.route), + candidate.opcode, + candidate.closure, + candidate.affected_nodes, + candidate.direct_dependents + ); + } + out + } +} +fn format_route(route: &Route) -> String { + let mut out = format!("{:016x}", route.domain().0); + for word in route.tail() { + let _ = write!(out, "/{:016x}", word.0); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use l64_native::LocusWord; + + #[test] + fn route_format_is_numeric_and_stable() { + let route = Route::root(LocusWord(0x12)).composed(LocusWord(0x34)); + assert_eq!(format_route(&route), "0000000000000012/0000000000000034"); + } +} diff --git a/l64-projection/src/source.rs b/l64-projection/src/source.rs new file mode 100644 index 0000000..d0854b2 --- /dev/null +++ b/l64-projection/src/source.rs @@ -0,0 +1,194 @@ +use crate::PROJECTION_VERSION; +use l64_native::{ + ClosureState, ContextId, Graph, NodeId, Obstruction, OpCode, PortRole, Route, StateSymbol, +}; +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProjectionError { + UnknownContext(ContextId), + UnknownNode(NodeId), + MissingRoute(NodeId), + Native(Obstruction), + VersionMismatch { expected: u16, actual: u16 }, + SourceMismatch, + ProjectionMismatch, +} + +impl fmt::Display for ProjectionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnknownContext(context) => write!(f, "unknown projection context {context}"), + Self::UnknownNode(node) => write!(f, "projection references unknown node {node}"), + Self::MissingRoute(node) => write!(f, "projection node {node} has no route"), + Self::Native(error) => write!(f, "native projection derivation failed: {error}"), + Self::VersionMismatch { expected, actual } => write!( + f, + "projection version mismatch: expected {expected}, got {actual}" + ), + Self::SourceMismatch => f.write_str("projection source does not match authority"), + Self::ProjectionMismatch => f.write_str("projection content does not match authority"), + } + } +} + +impl std::error::Error for ProjectionError {} + +impl From for ProjectionError { + fn from(value: Obstruction) -> Self { + Self::Native(value) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProjectionSource { + pub symbol: StateSymbol, + pub context: ContextId, + pub node_count: usize, + pub context_count: usize, + pub journal_len: usize, + pub version: u16, +} + +impl ProjectionSource { + pub fn capture(graph: &Graph, context: ContextId) -> Result { + graph + .context(context) + .ok_or(ProjectionError::UnknownContext(context))?; + Ok(Self { + symbol: graph.state_symbol(), + context, + node_count: graph.node_count(), + context_count: graph.context_count(), + journal_len: graph.journal_len(), + version: PROJECTION_VERSION, + }) + } + + pub fn verify(&self, graph: &Graph) -> Result<(), ProjectionError> { + if self.version != PROJECTION_VERSION { + return Err(ProjectionError::VersionMismatch { + expected: PROJECTION_VERSION, + actual: self.version, + }); + } + graph + .context(self.context) + .ok_or(ProjectionError::UnknownContext(self.context))?; + if self.symbol != graph.state_symbol() + || self.node_count != graph.node_count() + || self.context_count != graph.context_count() + || self.journal_len != graph.journal_len() + { + return Err(ProjectionError::SourceMismatch); + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct SourceRef { + pub node: NodeId, + pub route: Route, + pub declared_context: ContextId, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PortRef { + pub role: PortRole, + pub ordinal: u16, + pub target: SourceRef, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EvidenceRef { + pub judgment: Option, + pub evidence: SourceRef, + pub opcode: OpCode, + pub closure: ClosureState, +} + +pub(crate) fn source_ref(graph: &Graph, node: NodeId) -> Result { + let record = graph.node(node).ok_or(ProjectionError::UnknownNode(node))?; + let route = graph + .route_for_node(node) + .cloned() + .ok_or(ProjectionError::MissingRoute(node))?; + Ok(SourceRef { + node, + route, + declared_context: record.context(), + }) +} + +pub(crate) fn evidence_ref( + graph: &Graph, + subject: NodeId, + closure: impl Fn(NodeId) -> Result, +) -> Result, ProjectionError> { + let subject_node = graph + .node(subject) + .ok_or(ProjectionError::UnknownNode(subject))?; + if subject_node.opcode() == OpCode::TypeEquality { + let Some(evidence) = graph.equality_witness_for(subject) else { + return Ok(None); + }; + let evidence_node = graph + .node(evidence) + .ok_or(ProjectionError::UnknownNode(evidence))?; + return Ok(Some(EvidenceRef { + judgment: Some(source_ref(graph, subject)?), + evidence: source_ref(graph, evidence)?, + opcode: evidence_node.opcode(), + closure: closure(evidence)?, + })); + } + + let mut judgments = graph + .direct_dependents(subject)? + .iter() + .copied() + .filter(|candidate| { + let Some(node) = graph.node(*candidate) else { + return false; + }; + if node.opcode() != OpCode::TypeJudgment { + return false; + } + graph + .ports(*candidate) + .and_then(|ports| ports.first()) + .map(|port| port.role() == PortRole::Subject && port.target() == subject) + .unwrap_or(false) + }) + .collect::>(); + judgments.sort_by_key(|node| graph.route_for_node(*node).cloned()); + let Some(judgment) = judgments.first().copied() else { + return Ok(None); + }; + let mut evidence = graph + .direct_dependents(judgment)? + .iter() + .copied() + .filter(|candidate| { + let Some(node) = graph.node(*candidate) else { + return false; + }; + node.ty() == Some(judgment) + && matches!(node.opcode(), OpCode::KernelWitness | OpCode::Obligation) + }) + .collect::>(); + evidence.sort_by_key(|node| graph.route_for_node(*node).cloned()); + let Some(evidence) = evidence.first().copied() else { + return Ok(None); + }; + let evidence_node = graph + .node(evidence) + .ok_or(ProjectionError::UnknownNode(evidence))?; + Ok(Some(EvidenceRef { + judgment: Some(source_ref(graph, judgment)?), + evidence: source_ref(graph, evidence)?, + opcode: evidence_node.opcode(), + closure: closure(evidence)?, + })) +} diff --git a/l64-projection/tests/architecture.rs b/l64-projection/tests/architecture.rs new file mode 100644 index 0000000..711fa56 --- /dev/null +++ b/l64-projection/tests/architecture.rs @@ -0,0 +1,54 @@ +use std::{fs, path::Path}; + +#[test] +fn projection_crate_depends_only_on_native_authority() { + let manifest = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml")) + .expect("read projection manifest"); + let dependency_block = manifest + .split_once("[dependencies]") + .map(|(_, tail)| tail) + .expect("dependency block"); + let dependencies = dependency_block + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .collect::>(); + assert_eq!( + dependencies, + vec!["l64-native = { path = \"../l64-native\" }"] + ); +} + +#[test] +fn projection_source_contains_no_parallel_authority_machinery() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut source = String::new(); + for entry in fs::read_dir(root).expect("read source directory") { + let path = entry.expect("source entry").path(); + if path.extension().and_then(|value| value.to_str()) == Some("rs") { + source.push_str(&fs::read_to_string(path).expect("read source file")); + } + } + for forbidden in [ + "std::fs", + "File::", + "OpenOptions", + "serde", + "bincode", + "blake3", + "HashMap", + "Mutex", + "RwLock", + "thread::", + "spawn(", + "Registry", + "persist_", + "import_", + "promote_", + ] { + assert!( + !source.contains(forbidden), + "projection source contains forbidden authority token {forbidden}" + ); + } +} diff --git a/l64-projection/tests/projection.rs b/l64-projection/tests/projection.rs new file mode 100644 index 0000000..8233cdc --- /dev/null +++ b/l64-projection/tests/projection.rs @@ -0,0 +1,259 @@ +use l64_native::{ + ClosureState, ConstraintKind, Dimension, Graph, LocusWord, OpCode, Proposal, ROOT_CONTEXT, + Route, canonical_bytes, decode_canonical, +}; +use l64_projection::{BurdenState, ProjectionError, ProjectionSet}; + +fn route(index: u64) -> Route { + Route::root(LocusWord(0x50524f4a45435431)).composed(LocusWord(index)) +} + +struct Fixture { + graph: Graph, + subject: u32, + sqrt: u32, + downstream: u32, + independent: u32, +} + +fn fixture() -> Fixture { + let mut graph = Graph::new(); + let scalar = graph.declare_atom_type(route(1), LocusWord(0x52)).unwrap(); + let quantity = graph + .declare_quantity_type(route(2), scalar, Dimension::new([0, 0, 0, 0, 0, 0, 0])) + .unwrap(); + let subject = graph + .insert_value(route(3), ROOT_CONTEXT, quantity) + .unwrap(); + let peer = graph + .insert_value(route(4), ROOT_CONTEXT, quantity) + .unwrap(); + let sqrt = graph + .transact(Proposal::square_root( + route(5), + ROOT_CONTEXT, + subject, + quantity, + )) + .unwrap() + .node; + let downstream = graph + .transact(Proposal::multiply( + route(6), + ROOT_CONTEXT, + sqrt, + peer, + quantity, + )) + .unwrap() + .node; + let left = graph + .insert_value(route(7), ROOT_CONTEXT, quantity) + .unwrap(); + let right = graph + .insert_value(route(8), ROOT_CONTEXT, quantity) + .unwrap(); + let independent = graph + .transact(Proposal::add(route(9), ROOT_CONTEXT, left, right, quantity)) + .unwrap() + .node; + graph + .prove_reflexive_equality(route(10), ROOT_CONTEXT, independent) + .unwrap(); + Fixture { + graph, + subject, + sqrt, + downstream, + independent, + } +} + +#[test] +fn all_upper_views_are_derived_without_mutating_native_authority() { + let fixture = fixture(); + let before = canonical_bytes(&fixture.graph); + let commitment = fixture.graph.state_symbol(); + let counts = ( + fixture.graph.node_count(), + fixture.graph.port_count(), + fixture.graph.context_count(), + fixture.graph.journal_len(), + ); + + let projection = ProjectionSet::derive(&fixture.graph, ROOT_CONTEXT, 16).unwrap(); + projection.verify(&fixture.graph).unwrap(); + + assert_eq!(canonical_bytes(&fixture.graph), before); + assert_eq!(fixture.graph.state_symbol(), commitment); + assert_eq!( + ( + fixture.graph.node_count(), + fixture.graph.port_count(), + fixture.graph.context_count(), + fixture.graph.journal_len(), + ), + counts + ); + assert!( + projection + .atlas + .candidates + .iter() + .any(|item| item.source.node == fixture.sqrt && item.closure == ClosureState::Open) + ); + assert!( + projection + .certification + .burdens + .iter() + .any(|item| item.subject.node == fixture.sqrt && item.state == BurdenState::Open) + ); + assert!(!projection.replay.steps.is_empty()); + assert!(projection.report.open > 0); + assert!( + projection + .research + .candidates + .iter() + .any(|item| item.source.node == fixture.sqrt) + ); +} + +#[test] +fn regeneration_and_rendering_are_deterministic() { + let fixture = fixture(); + let first = ProjectionSet::derive(&fixture.graph, ROOT_CONTEXT, 8).unwrap(); + let second = ProjectionSet::derive(&fixture.graph, ROOT_CONTEXT, 8).unwrap(); + assert_eq!(first, second); + assert_eq!(first.render_text(), second.render_text()); +} + +#[test] +fn every_projection_reference_resolves_to_native_authority() { + let fixture = fixture(); + let projection = ProjectionSet::derive(&fixture.graph, ROOT_CONTEXT, 32).unwrap(); + for candidate in &projection.atlas.candidates { + assert_eq!( + fixture.graph.resolve(&candidate.source.route), + Some(candidate.source.node) + ); + for port in &candidate.ports { + assert_eq!( + fixture.graph.resolve(&port.target.route), + Some(port.target.node) + ); + } + for dependent in &candidate.direct_dependents { + assert_eq!( + fixture.graph.resolve(&dependent.route), + Some(dependent.node) + ); + } + if let Some(evidence) = &candidate.evidence { + assert_eq!( + fixture.graph.resolve(&evidence.evidence.route), + Some(evidence.evidence.node) + ); + if let Some(judgment) = &evidence.judgment { + assert_eq!(fixture.graph.resolve(&judgment.route), Some(judgment.node)); + } + } + } +} + +#[test] +fn stale_and_forged_projections_are_rejected() { + let mut fixture = fixture(); + let projection = ProjectionSet::derive(&fixture.graph, ROOT_CONTEXT, 8).unwrap(); + + let mut forged = projection.clone(); + forged.report.closed = forged.report.closed.saturating_add(1); + assert_eq!( + forged.verify(&fixture.graph), + Err(ProjectionError::ProjectionMismatch) + ); + + fixture + .graph + .declare_atom_type(route(100), LocusWord(0x99)) + .unwrap(); + assert_eq!( + projection.verify(&fixture.graph), + Err(ProjectionError::SourceMismatch) + ); +} + +#[test] +fn context_specific_views_preserve_open_closed_and_invalid_divergence() { + let mut positive = fixture(); + let cause = positive + .graph + .declare_constraint( + route(20), + ROOT_CONTEXT, + positive.subject, + ConstraintKind::NonNegative, + true, + ) + .unwrap(); + let child = positive.graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let root = ProjectionSet::derive(&positive.graph, ROOT_CONTEXT, 16).unwrap(); + let refined = ProjectionSet::derive(&positive.graph, child, 16).unwrap(); + let root_sqrt = root + .certification + .burdens + .iter() + .find(|item| item.subject.node == positive.sqrt) + .unwrap(); + let child_sqrt = refined + .certification + .burdens + .iter() + .find(|item| item.subject.node == positive.sqrt) + .unwrap(); + assert_eq!(root_sqrt.state, BurdenState::Open); + assert_eq!(child_sqrt.state, BurdenState::Discharged); + assert_eq!(child_sqrt.evidence_opcode, Some(OpCode::Obligation)); + assert_eq!(child_sqrt.closure, ClosureState::Closed); + assert_eq!(root.source.context, ROOT_CONTEXT); + assert_eq!(refined.source.context, child); + + let mut negative = fixture(); + let cause = negative + .graph + .declare_constraint( + route(30), + ROOT_CONTEXT, + negative.subject, + ConstraintKind::NonNegative, + false, + ) + .unwrap(); + let child = negative.graph.extend_context(ROOT_CONTEXT, cause).unwrap(); + let invalid = ProjectionSet::derive(&negative.graph, child, 16).unwrap(); + assert!( + invalid.certification.burdens.iter().any(|item| { + item.subject.node == negative.sqrt && item.state == BurdenState::Invalid + }) + ); + assert!(invalid.certification.burdens.iter().any(|item| { + item.subject.node == negative.downstream && item.state == BurdenState::Invalid + })); + assert!(!invalid.certification.burdens.iter().any(|item| { + item.subject.node == negative.independent && item.state == BurdenState::Invalid + })); +} + +#[test] +fn replay_projection_is_bound_to_the_actual_runtime_journal() { + let fixture = fixture(); + let projection = ProjectionSet::derive(&fixture.graph, ROOT_CONTEXT, 8).unwrap(); + let decoded = decode_canonical(&canonical_bytes(&fixture.graph)).unwrap(); + assert_eq!(decoded.state_symbol(), fixture.graph.state_symbol()); + assert_eq!(decoded.journal_len(), 0); + assert_eq!( + projection.verify(&decoded), + Err(ProjectionError::SourceMismatch) + ); +} diff --git a/l64-registry/.gitignore b/l64-registry/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/l64-registry/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/l64-registry/Cargo.toml b/l64-registry/Cargo.toml deleted file mode 100644 index 4d86e46..0000000 --- a/l64-registry/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "l64-registry" -version = "0.1.0" -edition = "2024" - -[dependencies] -l64-core = { path = "../l64-core" } -serde_json = { workspace = true } -thiserror = { workspace = true } diff --git a/l64-registry/data/seed.v1.json b/l64-registry/data/seed.v1.json deleted file mode 100644 index 350df2d..0000000 --- a/l64-registry/data/seed.v1.json +++ /dev/null @@ -1,1136 +0,0 @@ -{ - "version": "seed.v1", - "objects": [ - { - "id": "OBJ_CTX_SET", - "identity": { "tag": "CTX", "cid": "OBJ_CTX_SET", "codebook": "GEN1", "remap": "none", "lineage": "seed" }, - "structural": { "head": "carrier", "args": ["set"], "local_sections": ["base"], "morphism_hooks": ["identity"] }, - "constraint": { "regime": "R_SET", "contracts": ["carrier-total"], "invariants": ["extensional-stable"], "equivalence": "eq-set", "admissibility": "admit-basic" }, - "evidence": { "evidence_class": "Seed", "traces": ["T_set"], "receipts": ["RC_set"], "maturity": "Validated", "gate_verdict": "Pass" }, - "alias": { "aliases": ["ctx_set"], "profile_pack": ["STD"], "qm_binding": "reserved", "qa_binding": "ctx_set", "projection_policy": "qa-first" } - }, - { - "id": "OBJ_CTX_SET_CANON", - "identity": { "tag": "CTX", "cid": "OBJ_CTX_SET_CANON", "codebook": "GEN1", "remap": "canon", "lineage": "seed" }, - "structural": { "head": "carrier", "args": ["set"], "local_sections": ["base"], "morphism_hooks": ["identity"] }, - "constraint": { "regime": "R_SET", "contracts": ["carrier-total"], "invariants": ["extensional-stable"], "equivalence": "eq-set", "admissibility": "admit-basic" }, - "evidence": { "evidence_class": "Seed", "traces": ["T_set"], "receipts": ["RC_set", "RC_canon"], "maturity": "Certified", "gate_verdict": "Pass" }, - "alias": { "aliases": ["ctx_set_canon"], "profile_pack": ["STD"], "qm_binding": "reserved", "qa_binding": "ctx_set_canon", "projection_policy": "qa-first" } - }, - { - "id": "OPR_PROMOTED_OPR_CHAIN1", - "identity": { "tag": "OPR", "cid": "OPR_PROMOTED_OPR_CHAIN1", "codebook": "QC0_CORE", "remap": "none", "lineage": "seed-promoted:THS_CHAIN_RULE" }, - "structural": { "head": "operator", "args": ["THS_CHAIN_RULE", "CPG_CHAIN_RULE"], "local_sections": ["first-order derivative composition"], "morphism_hooks": ["B_TOP_TO_CALC"] }, - "constraint": { "regime": "R_CALC", "contracts": ["chain-rule", "first-order", "default-promoted"], "invariants": ["jet-compose", "reduction-exact"], "equivalence": "first-order jet equivalence", "admissibility": "default-promoted on the derivative-local witness extraction burden" }, - "evidence": { "evidence_class": "SeedPromotion", "traces": ["THS_CHAIN_RULE", "CPG_CHAIN_RULE"], "receipts": ["CRT_CHAIN_RULE", "TRL_CHAIN_RULE"], "maturity": "Certified", "gate_verdict": "Pass" }, - "alias": { "aliases": ["OPR.Chain1"], "profile_pack": ["STD", "chain-rule", "default-promoted"], "qm_binding": "THS·ChainRule", "qa_binding": "OPR.Chain1", "projection_policy": "canonical-authored" } - } - ], - "regimes": [ - { "id": "R_SET", "ctx_law": "carrier context formation", "cut_law": "subset distinction", "thr_law": "function preservation", "brc_law": "subset localization", "slk_law": "extensional slack", "tol_law": "finite size toll", "knt_law": "obstruction by contradiction", "eq_law": "extensional equality", "adm_law": "basic admissibility", "promoted_ops": ["canon_set", "quotient_set"] }, - { "id": "R_LOG", "ctx_law": "judgment context", "cut_law": "formula distinction", "thr_law": "derivation preservation", "brc_law": "local theory frame", "slk_law": "proof irrelevance slack", "tol_law": "proof burden toll", "knt_law": "inconsistency witness", "eq_law": "logical equivalence", "adm_law": "derivable admissibility", "promoted_ops": ["normalize_proof"] }, - { "id": "R_TYP", "ctx_law": "typing context", "cut_law": "type distinction", "thr_law": "typed morphism", "brc_law": "dependent frame", "slk_law": "proof-relevant slack", "tol_law": "term complexity toll", "knt_law": "type mismatch witness", "eq_law": "definitional equality", "adm_law": "well-typed admissibility", "promoted_ops": ["lift_typ"] }, - { "id": "R_ALG", "ctx_law": "algebra carrier context", "cut_law": "substructure distinction", "thr_law": "homomorphism law", "brc_law": "local algebra frame", "slk_law": "isomorphism slack", "tol_law": "generator toll", "knt_law": "obstruction ideal", "eq_law": "algebraic equivalence", "adm_law": "axiom-preserving admissibility", "promoted_ops": ["lift_alg"] }, - { "id": "R_TOP", "ctx_law": "space context", "cut_law": "open-set distinction", "thr_law": "continuous thread", "brc_law": "local chart frame", "slk_law": "homotopy slack", "tol_law": "cover complexity toll", "knt_law": "obstruction cocycle", "eq_law": "homeomorphic equivalence", "adm_law": "local-global admissibility", "promoted_ops": ["localize_top"] }, - { "id": "R_CALC", "ctx_law": "smooth context", "cut_law": "derivative distinction", "thr_law": "smooth map law", "brc_law": "chart localization", "slk_law": "jet slack", "tol_law": "order toll", "knt_law": "non-smooth witness", "eq_law": "jet equivalence", "adm_law": "smooth admissibility", "promoted_ops": ["ref_1", "ref_r", "OPR_PROMOTED_OPR_CHAIN1"] }, - { "id": "R_PROB", "ctx_law": "sample context", "cut_law": "event distinction", "thr_law": "measure-preserving thread", "brc_law": "sigma-localization", "slk_law": "distribution slack", "tol_law": "entropy toll", "knt_law": "non-measurable witness", "eq_law": "almost-sure equivalence", "adm_law": "measurable admissibility", "promoted_ops": ["measprob_mu", "norm_mu"] }, - { "id": "R_COMP", "ctx_law": "machine context", "cut_law": "state distinction", "thr_law": "execution thread", "brc_law": "local machine frame", "slk_law": "observational slack", "tol_law": "cost toll", "knt_law": "deadlock witness", "eq_law": "observational equivalence", "adm_law": "safe execution admissibility", "promoted_ops": ["exec", "cert_phi"] }, - { "id": "R_MECH", "ctx_law": "parse context", "cut_law": "syntax distinction", "thr_law": "canonical transport", "brc_law": "registry localization", "slk_law": "canon slack", "tol_law": "runtime toll", "knt_law": "parse obstruction", "eq_law": "canonical equivalence", "adm_law": "pass-only admissibility", "promoted_ops": ["parse", "canon", "select", "check"] } - ], - "bridges": [ - { "id": "B_TYPE_TO_SET", "src": "R_TYP", "tgt": "R_SET", "id_pres": "carrier identity preserved", "eq_pres": "extensional carrier equality", "forget": ["proof relevance"], "enrich": [], "loss": ["proof terms"], "reversibility": "Conservative", "receipts": ["Rig"], "rollback": "requires witness" }, - { "id": "B_TYPE_TO_ALG", "src": "R_TYP", "tgt": "R_ALG", "id_pres": "typed algebra carrier preserved", "eq_pres": "structure-preserving equality", "forget": [], "enrich": ["algebraic operations"], "loss": [], "reversibility": "Enriching", "receipts": ["Lift^Typ->Alg"], "rollback": "allowed" }, - { "id": "B_TOP_TO_CALC", "src": "R_TOP", "tgt": "R_CALC", "id_pres": "local chart identity preserved", "eq_pres": "smooth equivalence", "forget": [], "enrich": ["derivative witness"], "loss": [], "reversibility": "Enriching", "receipts": ["Ref_1"], "rollback": "allowed" }, - { "id": "B_TOP_TO_PROB", "src": "R_TOP", "tgt": "R_PROB", "id_pres": "measurable carrier preserved", "eq_pres": "measure-compatible equivalence", "forget": ["differential payload"], "enrich": ["normalization"], "loss": ["smooth structure"], "reversibility": "LossySupported", "receipts": ["MeasProb_mu"], "rollback": "partial" }, - { "id": "B_PROB_TO_LOG", "src": "R_PROB", "tgt": "R_LOG", "id_pres": "judgment object preserved", "eq_pres": "probabilistic theorem equivalence", "forget": ["sampling detail"], "enrich": ["logical theorem"], "loss": ["execution trace"], "reversibility": "Conservative", "receipts": ["ProbJudg_phi"], "rollback": "allowed" }, - { "id": "B_PROB_TO_COMP", "src": "R_PROB", "tgt": "R_COMP", "id_pres": "stateful carrier preserved", "eq_pres": "simulation equivalence", "forget": [], "enrich": ["algorithmic realization"], "loss": [], "reversibility": "Enriching", "receipts": ["Exec"], "rollback": "allowed" }, - { "id": "B_COMP_TO_LOG", "src": "R_COMP", "tgt": "R_LOG", "id_pres": "witness identity preserved", "eq_pres": "certified property equivalence", "forget": ["runtime detail"], "enrich": ["logical certificate"], "loss": ["cost profile"], "reversibility": "Conservative", "receipts": ["Cert_phi"], "rollback": "allowed" } - ], - "proof_shapes": [ - { "id": "PS_TRIANGLE_CERT", "kind": "Triangle", "nodes": ["prob", "comp", "log"], "edges": [{ "from": "prob", "to": "comp", "label": "Exec" }, { "from": "comp", "to": "log", "label": "Cert_phi" }, { "from": "prob", "to": "log", "label": "ProbJudg_phi" }], "equations": ["Cert_phi o Exec = ProbJudg_phi"], "target_equivalence": "logical-certification", "receipts": ["RC_triangle"], "gate": "Pass" }, - { "id": "PS_SQUARE_TOPO", "kind": "Square", "nodes": ["top", "calc", "prob", "logic"], "edges": [{ "from": "top", "to": "calc", "label": "Ref_1" }, { "from": "top", "to": "prob", "label": "MeasProb_mu" }, { "from": "calc", "to": "logic", "label": "local-proof" }, { "from": "prob", "to": "logic", "label": "ProbJudg_phi" }], "equations": ["local-proof o Ref_1 ~= ProbJudg_phi o MeasProb_mu"], "target_equivalence": "bridge-check", "receipts": ["RC_square"], "gate": "Pass" } - ], - "atlas_cells": [ - { "id": "A_TYPE_TO_SET", "source_regime": "R_TYP", "target_regime": "R_SET", "burden_class": "ExtensionalCarrierReasoning", "proof_target": "extensional carrier reasoning", "candidate_paths": [["B_TYPE_TO_SET"]], "normalized_winner": ["B_TYPE_TO_SET"], "winner_state": "SeedWinner", "loss_profile": { "items": ["proof terms"] }, "proof_shapes_checked": ["PS_TRIANGLE_CERT"], "recipe_maturity": "Seeded", "failure_signatures": [{ "code": "TYPE_SET_EXT", "message": "proof relevance queried without extensional witness" }], "side_conditions": ["proof relevance not queried"] }, - { "id": "A_TYPE_TO_ALG", "source_regime": "R_TYP", "target_regime": "R_ALG", "burden_class": "ProofRelevantAlgebra", "proof_target": "proof relevant algebra", "candidate_paths": [["B_TYPE_TO_ALG"]], "normalized_winner": ["B_TYPE_TO_ALG"], "winner_state": "SeedWinner", "loss_profile": { "items": [] }, "proof_shapes_checked": ["PS_TRIANGLE_CERT"], "recipe_maturity": "Seeded", "failure_signatures": [{ "code": "TYPE_ALG_EXT", "message": "extensional collapse invalidates proof-relevant payload" }], "side_conditions": ["extensionality certified when indirect path is used"] }, - { "id": "A_TOP_TO_CALC", "source_regime": "R_TOP", "target_regime": "R_CALC", "burden_class": "DerivativeLocalWitnessExtraction", "proof_target": "derivative witness extraction", "candidate_paths": [["B_TOP_TO_CALC"]], "normalized_winner": ["B_TOP_TO_CALC"], "winner_state": "SeedWinner", "loss_profile": { "items": [] }, "proof_shapes_checked": ["PS_SQUARE_TOPO"], "recipe_maturity": "Seeded", "failure_signatures": [{ "code": "TOP_CALC_SMOOTH", "message": "missing smoothability witness" }], "side_conditions": ["smoothability admissible"] }, - { "id": "A_TOP_TO_PROB", "source_regime": "R_TOP", "target_regime": "R_PROB", "burden_class": "MeasurableNormalizedBranching", "proof_target": "measurable normalized branching law", "candidate_paths": [["B_TOP_TO_PROB"]], "normalized_winner": ["B_TOP_TO_PROB"], "winner_state": "SeedWinner", "loss_profile": { "items": ["smooth structure"] }, "proof_shapes_checked": ["PS_SQUARE_TOPO"], "recipe_maturity": "Seeded", "failure_signatures": [{ "code": "TOP_PROB_MEAS", "message": "missing measurable normalization witness" }], "side_conditions": ["differential payload not required"] }, - { "id": "A_PROB_TO_LOG", "source_regime": "R_PROB", "target_regime": "R_LOG", "burden_class": "ProbabilisticJudgment", "proof_target": "direct theorem in probabilistic judgment class", "candidate_paths": [["B_PROB_TO_LOG"], ["B_PROB_TO_COMP", "B_COMP_TO_LOG"]], "normalized_winner": ["B_PROB_TO_LOG"], "winner_state": "SeedWinner", "loss_profile": { "items": ["execution trace"] }, "proof_shapes_checked": ["PS_TRIANGLE_CERT"], "recipe_maturity": "Stable", "failure_signatures": [{ "code": "PROB_LOG_CERT", "message": "certification route required for executable witness" }], "side_conditions": ["algorithmic certification not required"] }, - { "id": "A_PROB_TO_COMP", "source_regime": "R_PROB", "target_regime": "R_COMP", "burden_class": "SimulationExecutableInference", "proof_target": "simulation executable inference", "candidate_paths": [["B_PROB_TO_COMP"]], "normalized_winner": ["B_PROB_TO_COMP"], "winner_state": "SeedWinner", "loss_profile": { "items": [] }, "proof_shapes_checked": ["PS_TRIANGLE_CERT"], "recipe_maturity": "Stable", "failure_signatures": [{ "code": "PROB_COMP_EXEC", "message": "missing executable realization witness" }], "side_conditions": ["simulation witness required"] }, - { "id": "A_COMP_TO_LOG", "source_regime": "R_COMP", "target_regime": "R_LOG", "burden_class": "CertifiedPropertyWitness", "proof_target": "certified property witness", "candidate_paths": [["B_COMP_TO_LOG"]], "normalized_winner": ["B_COMP_TO_LOG"], "winner_state": "SeedWinner", "loss_profile": { "items": ["cost profile"] }, "proof_shapes_checked": ["PS_TRIANGLE_CERT"], "recipe_maturity": "Stable", "failure_signatures": [{ "code": "COMP_LOG_CERT", "message": "missing logical certification witness" }], "side_conditions": ["property witness available"] } - ], - "mechanization_packages": [ - { "id": "MEC_MECH0", "parser": { "id": "PRS_QA0", "supported_surfaces": ["QA-0"] }, "canonicalizer": { "id": "CNZ_SEED", "regime_scope": ["R_SET", "R_LOG", "R_TYP", "R_ALG", "R_TOP", "R_CALC", "R_PROB", "R_COMP", "R_MECH"] }, "registry": { "id": "RGY_SEED", "domains": ["objects", "regimes", "bridges", "proof_shapes", "atlas_cells", "mechanization_packages"] }, "selector": { "id": "SEL_ATLAS", "burden_axes": ["fit", "stability", "compressibility", "transportability", "proof-yield"] }, "checker": { "id": "CHK_COMMUTE", "proof_shapes": ["Square", "Triangle", "Diamond", "Pentagon", "Hexagon"] } } - ], - "equivalence_classes": [ - { "id": "EQ_SET_CANON", "regime": "R_SET", "canonical_id": "OBJ_CTX_SET_CANON", "members": ["OBJ_CTX_SET", "OBJ_CTX_SET_CANON"] } - ], - "theorem_specs": [ - { - "id": "THS_CHAIN_RULE", - "statement": "DER(g∘f,x) ≈1 DER(g,f(x))∘DER(f,x)", - "hosts": ["R_TOP", "R_CALC"], - "bridges": ["B_TOP_TO_CALC"], - "operators": ["OPR.Chain1"], - "target_equivalence": "first-order jet equivalence", - "obligations": ["OblEq", "OblAdm", "OblLoc", "OblRed"], - "primary_zone": "PmzStructural", - "verdict": "Benchmarked", - "proof_shapes": ["PS_SQUARE_TOPO"] - }, - { - "id": "THS_CHAIN_RULE_RECIPE", - "statement": "reuse Chain₁ as the default first-order derivative-composition recipe on the same local cluster", - "hosts": ["R_TOP", "R_CALC"], - "bridges": ["B_TOP_TO_CALC"], - "operators": ["OPR.Chain1"], - "target_equivalence": "first-order jet equivalence", - "obligations": ["OblEq", "OblRed"], - "primary_zone": "PmzReduction", - "verdict": "Benchmarked", - "proof_shapes": ["PS_SQUARE_TOPO"] - }, - { - "id": "THS_CHAIN_RULE_TRANSPORT", - "statement": "reuse Chain₁ to certify chart-local derivative transport on the active first-order cluster", - "hosts": ["R_TOP", "R_CALC"], - "bridges": ["B_TOP_TO_CALC"], - "operators": [], - "target_equivalence": "first-order jet equivalence", - "obligations": ["OblLoc", "OblEq", "OblRed"], - "primary_zone": "PmzStructural", - "verdict": "Benchmarked", - "proof_shapes": ["PS_SQUARE_TOPO"] - }, - { - "id": "THS_BAYES_BRACE", - "statement": "normalized measurable bracing preserves conditional branch adequacy on the active top-to-prob route", - "hosts": ["R_TOP", "R_PROB"], - "bridges": ["B_TOP_TO_PROB"], - "operators": ["OPR.BayesBrace1"], - "target_equivalence": "measure-compatible conditioning transport", - "obligations": ["OblLoc", "OblTol", "OblAde"], - "primary_zone": "PmzStructural", - "verdict": "Benchmarked", - "proof_shapes": ["PS_SQUARE_TOPO"] - }, - { - "id": "THS_CH_NORM", - "statement": "normalization witnesses in R_TYP survive extensional carrier collapse along the active type-to-set route", - "hosts": ["R_TYP", "R_SET"], - "bridges": ["B_TYPE_TO_SET"], - "operators": ["OPR.CHNorm1"], - "target_equivalence": "extensional carrier equality under normalization", - "obligations": ["OblAde", "OblRed", "OblEq"], - "primary_zone": "PmzStructural", - "verdict": "Benchmarked", - "proof_shapes": ["PS_TRIANGLE_CERT"] - }, - { - "id": "THS_EXEC_INFER", - "statement": "normalized probabilistic branching admits executable realization on the active prob-to-comp route", - "hosts": ["R_PROB", "R_COMP"], - "bridges": ["B_PROB_TO_COMP"], - "operators": ["OPR.ExecInfer1"], - "target_equivalence": "simulation executable inference", - "obligations": ["OblAde", "OblTol", "OblRed"], - "primary_zone": "PmzOperational", - "verdict": "Benchmarked", - "proof_shapes": ["PS_TRIANGLE_CERT"] - }, - { - "id": "THS_PROB_JUDG", - "statement": "normalized probabilistic judgment transports lawfully into the active logic shell", - "hosts": ["R_PROB", "R_LOG"], - "bridges": ["B_PROB_TO_LOG"], - "operators": ["OPR.ProbJudg1"], - "target_equivalence": "probabilistic theorem equivalence", - "obligations": ["OblAde", "OblTol"], - "primary_zone": "PmzStructural", - "verdict": "Benchmarked", - "proof_shapes": ["PS_TRIANGLE_CERT"] - }, - { - "id": "THS_CERT_PROP", - "statement": "certified computational property witnesses transport lawfully into the active logic shell", - "hosts": ["R_COMP", "R_LOG"], - "bridges": ["B_COMP_TO_LOG"], - "operators": ["OPR.CertProp1"], - "target_equivalence": "certified property equivalence", - "obligations": ["OblRed", "OblObs", "OblTol"], - "primary_zone": "PmzOperational", - "verdict": "Benchmarked", - "proof_shapes": ["PS_TRIANGLE_CERT"] - }, - { - "id": "THS_CH_INH", - "statement": "proof-relevant inherited algebra structure survives the active type-to-alg route only if typed inhabitance remains exact", - "hosts": ["R_TYP", "R_ALG"], - "bridges": ["B_TYPE_TO_ALG"], - "operators": ["OPR.CHInh1"], - "target_equivalence": "structure-preserving algebra equality", - "obligations": ["OblAde", "OblAdm", "OblEq"], - "primary_zone": "PmzStructural", - "verdict": "Benchmarked", - "proof_shapes": ["PS_TRIANGLE_CERT"] - } - ], - "obligations": [ - { "id": "OBL_CHAIN_EQ", "kind": "OblEq", "description": "first-order slack equivalence preserved under composition", "status": "Benchmarked" }, - { "id": "OBL_CHAIN_ADM", "kind": "OblAdm", "description": "both derivatives admitted in R_CALC", "status": "Benchmarked" }, - { "id": "OBL_CHAIN_LOC", "kind": "OblLoc", "description": "same brace-localization at x", "status": "Benchmarked" }, - { "id": "OBL_CHAIN_RED", "kind": "OblRed", "description": "reduction of remainder terms preserves first-order equivalence", "status": "RouteFound" }, - { "id": "OBL_BAYES_LOC", "kind": "OblLoc", "description": "measurable brace remains locally chart-compatible on the source topological carrier", "status": "Benchmarked" }, - { "id": "OBL_BAYES_TOL", "kind": "OblTol", "description": "conditioning and normalization toll remain lawful on the active probabilistic carrier", "status": "Benchmarked" }, - { "id": "OBL_BAYES_ADE", "kind": "OblAde", "description": "pushforward and branch adequacy survive measurable normalization on the selected route", "status": "Benchmarked" }, - { "id": "OBL_CH_ADE", "kind": "OblAde", "description": "typed witness remains inhabited under the active carrier collapse", "status": "Benchmarked" }, - { "id": "OBL_CH_RED", "kind": "OblRed", "description": "type normalization corresponds to extensional carrier reduction on the selected route", "status": "Benchmarked" }, - { "id": "OBL_CH_EQ", "kind": "OblEq", "description": "carrier-level extensional equality survives normalization collapse", "status": "Benchmarked" }, - { "id": "OBL_EXEC_ADE", "kind": "OblAde", "description": "probabilistic branching remains executable under pushforward realization", "status": "Benchmarked" }, - { "id": "OBL_EXEC_TOL", "kind": "OblTol", "description": "probabilistic normalization toll remains lawful before executable realization", "status": "Benchmarked" }, - { "id": "OBL_EXEC_RED", "kind": "OblRed", "description": "executable realization reaches normal form on the selected route", "status": "Benchmarked" }, - { "id": "OBL_JDG_ADE", "kind": "OblAde", "description": "probabilistic judgment remains adequate under logical transport", "status": "Benchmarked" }, - { "id": "OBL_JDG_TOL", "kind": "OblTol", "description": "normalization and conditioning toll remain lawful on the judgment route", "status": "Benchmarked" }, - { "id": "OBL_CERT_RED", "kind": "OblRed", "description": "computational property witness reaches certified normal form", "status": "Benchmarked" }, - { "id": "OBL_CERT_OBS", "kind": "OblObs", "description": "computational property witness remains observationally stable", "status": "Benchmarked" }, - { "id": "OBL_CERT_TOL", "kind": "OblTol", "description": "computational cost toll remains lawful under logical certification", "status": "Benchmarked" }, - { "id": "OBL_CHI_ADE", "kind": "OblAde", "description": "typed inherited witness remains inhabited on the active algebra route", "status": "Benchmarked" }, - { "id": "OBL_CHI_ADM", "kind": "OblAdm", "description": "algebraic closure and associativity hold on the inherited carrier", "status": "Benchmarked" }, - { "id": "OBL_CHI_EQ", "kind": "OblEq", "description": "structure-preserving equality survives inherited algebra transport", "status": "Benchmarked" } - ], - "target_profiles": [ - { - "id": "TGT_CHAIN_RULE", - "burden_class": "DerivativeLocalWitnessExtraction", - "host_cluster": ["R_TOP", "R_CALC"], - "target_equivalence": "first-order jet equivalence", - "allowed_bridge_classes": ["Enriching", "Conservative"], - "loss_ceiling": 1, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "MixedBattery", - "promotion_goal": "PromoteOperator", - "primary_zone": "PmzStructural" - }, - { - "id": "TGT_CHAIN_RULE_RECIPE", - "burden_class": "DerivativeLocalWitnessExtraction", - "host_cluster": ["R_TOP", "R_CALC"], - "target_equivalence": "first-order jet equivalence", - "allowed_bridge_classes": ["Enriching", "Conservative"], - "loss_ceiling": 1, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "MixedBattery", - "promotion_goal": "PromoteOperator", - "primary_zone": "PmzReduction" - }, - { - "id": "TGT_CHAIN_RULE_TRANSPORT", - "burden_class": "DerivativeLocalWitnessExtraction", - "host_cluster": ["R_TOP", "R_CALC"], - "target_equivalence": "first-order jet equivalence", - "allowed_bridge_classes": ["Enriching", "Conservative"], - "loss_ceiling": 1, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "MixedBattery", - "promotion_goal": "PromoteRouteClass", - "primary_zone": "PmzStructural" - }, - { - "id": "TGT_BAYES_BRACE", - "burden_class": "MeasurableNormalizedBranching", - "host_cluster": ["R_TOP", "R_PROB"], - "target_equivalence": "measure-compatible conditioning transport", - "allowed_bridge_classes": ["LossySupported", "Conservative"], - "loss_ceiling": 1, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "Square", - "promotion_goal": "OpenBlocked", - "primary_zone": "PmzStructural" - }, - { - "id": "TGT_CH_NORM", - "burden_class": "ExtensionalCarrierReasoning", - "host_cluster": ["R_TYP", "R_SET"], - "target_equivalence": "extensional carrier equality under normalization", - "allowed_bridge_classes": ["Conservative"], - "loss_ceiling": 1, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "Triangle", - "promotion_goal": "OpenBlocked", - "primary_zone": "PmzStructural" - }, - { - "id": "TGT_EXEC_INFER", - "burden_class": "SimulationExecutableInference", - "host_cluster": ["R_PROB", "R_COMP"], - "target_equivalence": "simulation executable inference", - "allowed_bridge_classes": ["Enriching"], - "loss_ceiling": 0, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "Triangle", - "promotion_goal": "OpenBlocked", - "primary_zone": "PmzOperational" - }, - { - "id": "TGT_PROB_JUDG", - "burden_class": "ProbabilisticJudgment", - "host_cluster": ["R_PROB", "R_LOG"], - "target_equivalence": "probabilistic theorem equivalence", - "allowed_bridge_classes": ["Conservative"], - "loss_ceiling": 1, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "Triangle", - "promotion_goal": "OpenBlocked", - "primary_zone": "PmzStructural" - }, - { - "id": "TGT_CERT_PROP", - "burden_class": "CertifiedPropertyWitness", - "host_cluster": ["R_COMP", "R_LOG"], - "target_equivalence": "certified property equivalence", - "allowed_bridge_classes": ["Conservative"], - "loss_ceiling": 1, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "Triangle", - "promotion_goal": "OpenBlocked", - "primary_zone": "PmzOperational" - }, - { - "id": "TGT_CH_INH", - "burden_class": "ProofRelevantAlgebra", - "host_cluster": ["R_TYP", "R_ALG"], - "target_equivalence": "structure-preserving algebra equality", - "allowed_bridge_classes": ["Enriching"], - "loss_ceiling": 0, - "rollback_ceiling": 1, - "required_receipt_class": "RC_ths", - "required_proof_shape_family": "Triangle", - "promotion_goal": "OpenBlocked", - "primary_zone": "PmzStructural" - } - ], - "route_ledgers": [ - { - "id": "TRL_CHAIN_RULE", - "theorem": "THS_CHAIN_RULE", - "paths": [["B_TOP_TO_CALC"]], - "budget": { "max_loss": 1, "allow_lossy_supported": false, "require_proof": true }, - "losses": [], - "receipts": ["Ref_1", "Can", "Red"], - "normalized_path": ["B_TOP_TO_CALC"] - }, - { - "id": "TRL_CHAIN_RULE_RECIPE", - "theorem": "THS_CHAIN_RULE_RECIPE", - "paths": [["B_TOP_TO_CALC"]], - "budget": { "max_loss": 1, "allow_lossy_supported": false, "require_proof": true }, - "losses": [], - "receipts": ["Ref_1", "Can", "Red"], - "normalized_path": ["B_TOP_TO_CALC"] - }, - { - "id": "TRL_CHAIN_RULE_TRANSPORT", - "theorem": "THS_CHAIN_RULE_TRANSPORT", - "paths": [["B_TOP_TO_CALC"]], - "budget": { "max_loss": 1, "allow_lossy_supported": false, "require_proof": true }, - "losses": [], - "receipts": ["Ref_1", "Can", "Red"], - "normalized_path": ["B_TOP_TO_CALC"] - }, - { - "id": "TRL_BAYES_BRACE", - "theorem": "THS_BAYES_BRACE", - "paths": [["B_TOP_TO_PROB"]], - "budget": { "max_loss": 1, "allow_lossy_supported": true, "require_proof": true }, - "losses": ["smooth structure"], - "receipts": ["MeasProb_mu", "Norm", "Push"], - "normalized_path": ["B_TOP_TO_PROB"] - }, - { - "id": "TRL_CH_NORM", - "theorem": "THS_CH_NORM", - "paths": [["B_TYPE_TO_SET"]], - "budget": { "max_loss": 1, "allow_lossy_supported": false, "require_proof": true }, - "losses": ["proof terms"], - "receipts": ["Rig", "Norm"], - "normalized_path": ["B_TYPE_TO_SET"] - }, - { - "id": "TRL_EXEC_INFER", - "theorem": "THS_EXEC_INFER", - "paths": [["B_PROB_TO_COMP"]], - "budget": { "max_loss": 0, "allow_lossy_supported": false, "require_proof": true }, - "losses": [], - "receipts": ["Exec"], - "normalized_path": ["B_PROB_TO_COMP"] - }, - { - "id": "TRL_PROB_JUDG", - "theorem": "THS_PROB_JUDG", - "paths": [["B_PROB_TO_LOG"]], - "budget": { "max_loss": 1, "allow_lossy_supported": false, "require_proof": true }, - "losses": ["execution trace"], - "receipts": ["ProbJudg_phi"], - "normalized_path": ["B_PROB_TO_LOG"] - }, - { - "id": "TRL_CERT_PROP", - "theorem": "THS_CERT_PROP", - "paths": [["B_COMP_TO_LOG"]], - "budget": { "max_loss": 1, "allow_lossy_supported": false, "require_proof": true }, - "losses": ["cost profile"], - "receipts": ["Cert_phi"], - "normalized_path": ["B_COMP_TO_LOG"] - }, - { - "id": "TRL_CH_INH", - "theorem": "THS_CH_INH", - "paths": [["B_TYPE_TO_ALG"]], - "budget": { "max_loss": 0, "allow_lossy_supported": false, "require_proof": true }, - "losses": [], - "receipts": ["Lift^Typ->Alg"], - "normalized_path": ["B_TYPE_TO_ALG"] - } - ], - "certificates": [ - { - "id": "CRT_CHAIN_RULE", - "theorem": "THS_CHAIN_RULE", - "route_ledger": "TRL_CHAIN_RULE", - "proof_shapes": ["PS_SQUARE_TOPO"], - "receipts": ["RC_ths", "TR_chain", "BENCH"], - "verdict": "Benchmarked" - }, - { - "id": "CRT_CHAIN_RULE_RECIPE", - "theorem": "THS_CHAIN_RULE_RECIPE", - "route_ledger": "TRL_CHAIN_RULE_RECIPE", - "proof_shapes": ["PS_SQUARE_TOPO"], - "receipts": ["RC_ths", "TR_chain", "RECIPE"], - "verdict": "Benchmarked" - }, - { - "id": "CRT_CHAIN_RULE_TRANSPORT", - "theorem": "THS_CHAIN_RULE_TRANSPORT", - "route_ledger": "TRL_CHAIN_RULE_TRANSPORT", - "proof_shapes": ["PS_SQUARE_TOPO"], - "receipts": ["RC_ths", "TR_chain", "TRANSPORT"], - "verdict": "Benchmarked" - }, - { - "id": "CRT_BAYES_BRACE", - "theorem": "THS_BAYES_BRACE", - "route_ledger": "TRL_BAYES_BRACE", - "proof_shapes": ["PS_SQUARE_TOPO"], - "receipts": ["RC_ths", "TR_bayes", "MEAS"], - "verdict": "Benchmarked" - }, - { - "id": "CRT_CH_NORM", - "theorem": "THS_CH_NORM", - "route_ledger": "TRL_CH_NORM", - "proof_shapes": ["PS_TRIANGLE_CERT"], - "receipts": ["RC_ths", "TR_ch", "NORM"], - "verdict": "Benchmarked" - }, - { - "id": "CRT_EXEC_INFER", - "theorem": "THS_EXEC_INFER", - "route_ledger": "TRL_EXEC_INFER", - "proof_shapes": ["PS_TRIANGLE_CERT"], - "receipts": ["RC_ths", "TR_exec", "EXEC"], - "verdict": "Benchmarked" - }, - { - "id": "CRT_PROB_JUDG", - "theorem": "THS_PROB_JUDG", - "route_ledger": "TRL_PROB_JUDG", - "proof_shapes": ["PS_TRIANGLE_CERT"], - "receipts": ["RC_ths", "TR_prob", "JUDG"], - "verdict": "Benchmarked" - }, - { - "id": "CRT_CERT_PROP", - "theorem": "THS_CERT_PROP", - "route_ledger": "TRL_CERT_PROP", - "proof_shapes": ["PS_TRIANGLE_CERT"], - "receipts": ["RC_ths", "TR_cert", "PROP"], - "verdict": "Benchmarked" - }, - { - "id": "CRT_CH_INH", - "theorem": "THS_CH_INH", - "route_ledger": "TRL_CH_INH", - "proof_shapes": ["PS_TRIANGLE_CERT"], - "receipts": ["RC_ths", "TR_ch", "INH"], - "verdict": "Benchmarked" - } - ], - "campaigns": [ - { - "id": "CPG_CHAIN_RULE", - "theorem": "THS_CHAIN_RULE", - "target_profile": "TGT_CHAIN_RULE", - "route_ledger": "TRL_CHAIN_RULE", - "obligations": ["OBL_CHAIN_EQ", "OBL_CHAIN_ADM", "OBL_CHAIN_LOC", "OBL_CHAIN_RED"], - "certificates": ["CRT_CHAIN_RULE"], - "dependencies": [], - "campaign_class": "COperator", - "verdict": "Benchmarked", - "payoff": ["OPR.Chain1", "ATL.RouteClass.Chain"] - }, - { - "id": "CPG_CHAIN_RULE_RECIPE", - "theorem": "THS_CHAIN_RULE_RECIPE", - "target_profile": "TGT_CHAIN_RULE_RECIPE", - "route_ledger": "TRL_CHAIN_RULE_RECIPE", - "obligations": ["OBL_CHAIN_EQ", "OBL_CHAIN_RED"], - "certificates": ["CRT_CHAIN_RULE_RECIPE"], - "dependencies": ["CPG_CHAIN_RULE"], - "campaign_class": "COperator", - "verdict": "Benchmarked", - "payoff": ["OPR.Chain1", "Recipe.Chain1"] - }, - { - "id": "CPG_CHAIN_RULE_TRANSPORT", - "theorem": "THS_CHAIN_RULE_TRANSPORT", - "target_profile": "TGT_CHAIN_RULE_TRANSPORT", - "route_ledger": "TRL_CHAIN_RULE_TRANSPORT", - "obligations": ["OBL_CHAIN_LOC", "OBL_CHAIN_EQ", "OBL_CHAIN_RED"], - "certificates": ["CRT_CHAIN_RULE_TRANSPORT"], - "dependencies": ["CPG_CHAIN_RULE"], - "campaign_class": "CBridge", - "verdict": "Benchmarked", - "payoff": ["OPR.Chain1", "ATL.RouteClass.ChainTransport"] - }, - { - "id": "CPG_BAYES_BRACE", - "theorem": "THS_BAYES_BRACE", - "target_profile": "TGT_BAYES_BRACE", - "route_ledger": "TRL_BAYES_BRACE", - "obligations": ["OBL_BAYES_LOC", "OBL_BAYES_TOL", "OBL_BAYES_ADE"], - "certificates": ["CRT_BAYES_BRACE"], - "dependencies": [], - "campaign_class": "CBridge", - "verdict": "Benchmarked", - "payoff": ["ATL.RouteClass.BayesBrace", "Recipe.BayesBrace"] - }, - { - "id": "CPG_CH_NORM", - "theorem": "THS_CH_NORM", - "target_profile": "TGT_CH_NORM", - "route_ledger": "TRL_CH_NORM", - "obligations": ["OBL_CH_ADE", "OBL_CH_RED", "OBL_CH_EQ"], - "certificates": ["CRT_CH_NORM"], - "dependencies": [], - "campaign_class": "CBasic", - "verdict": "Benchmarked", - "payoff": ["ATL.RouteClass.CHNorm", "Recipe.CHNorm"] - }, - { - "id": "CPG_EXEC_INFER", - "theorem": "THS_EXEC_INFER", - "target_profile": "TGT_EXEC_INFER", - "route_ledger": "TRL_EXEC_INFER", - "obligations": ["OBL_EXEC_ADE", "OBL_EXEC_TOL", "OBL_EXEC_RED"], - "certificates": ["CRT_EXEC_INFER"], - "dependencies": [], - "campaign_class": "CBasic", - "verdict": "Benchmarked", - "payoff": ["ATL.RouteClass.ExecInfer", "Recipe.ExecInfer"] - }, - { - "id": "CPG_PROB_JUDG", - "theorem": "THS_PROB_JUDG", - "target_profile": "TGT_PROB_JUDG", - "route_ledger": "TRL_PROB_JUDG", - "obligations": ["OBL_JDG_ADE", "OBL_JDG_TOL"], - "certificates": ["CRT_PROB_JUDG"], - "dependencies": [], - "campaign_class": "CBasic", - "verdict": "Benchmarked", - "payoff": ["ATL.RouteClass.ProbJudg", "Recipe.ProbJudg"] - }, - { - "id": "CPG_CERT_PROP", - "theorem": "THS_CERT_PROP", - "target_profile": "TGT_CERT_PROP", - "route_ledger": "TRL_CERT_PROP", - "obligations": ["OBL_CERT_RED", "OBL_CERT_OBS", "OBL_CERT_TOL"], - "certificates": ["CRT_CERT_PROP"], - "dependencies": [], - "campaign_class": "CBasic", - "verdict": "Benchmarked", - "payoff": ["ATL.RouteClass.CertProp", "Recipe.CertProp"] - }, - { - "id": "CPG_CH_INH", - "theorem": "THS_CH_INH", - "target_profile": "TGT_CH_INH", - "route_ledger": "TRL_CH_INH", - "obligations": ["OBL_CHI_ADE", "OBL_CHI_ADM", "OBL_CHI_EQ"], - "certificates": ["CRT_CH_INH"], - "dependencies": [], - "campaign_class": "CBasic", - "verdict": "Benchmarked", - "payoff": ["ATL.RouteClass.CHInh", "Recipe.CHInh"] - } - ], - "campaign_portfolios": [ - { "id": "CMPA_FLAGSHIP", "campaigns": ["CPG_CHAIN_RULE", "CPG_CHAIN_RULE_RECIPE", "CPG_CHAIN_RULE_TRANSPORT", "CPG_BAYES_BRACE", "CPG_CH_NORM", "CPG_EXEC_INFER", "CPG_PROB_JUDG", "CPG_CERT_PROP", "CPG_CH_INH"], "normalized": true } - ], - "route_classes": [ - { - "id": "RTC_CHAIN_RULE", - "theorem": "THS_CHAIN_RULE", - "target_profile": "TGT_CHAIN_RULE", - "equivalent_paths": [["B_TOP_TO_CALC"]], - "canonical_path": ["B_TOP_TO_CALC"], - "verdict": "Benchmarked" - }, - { - "id": "RTC_CHAIN_RULE_RECIPE", - "theorem": "THS_CHAIN_RULE_RECIPE", - "target_profile": "TGT_CHAIN_RULE_RECIPE", - "equivalent_paths": [["B_TOP_TO_CALC"]], - "canonical_path": ["B_TOP_TO_CALC"], - "verdict": "Benchmarked" - }, - { - "id": "RTC_CHAIN_RULE_TRANSPORT", - "theorem": "THS_CHAIN_RULE_TRANSPORT", - "target_profile": "TGT_CHAIN_RULE_TRANSPORT", - "equivalent_paths": [["B_TOP_TO_CALC"]], - "canonical_path": ["B_TOP_TO_CALC"], - "verdict": "Benchmarked" - }, - { - "id": "RTC_BAYES_BRACE", - "theorem": "THS_BAYES_BRACE", - "target_profile": "TGT_BAYES_BRACE", - "equivalent_paths": [["B_TOP_TO_PROB"]], - "canonical_path": ["B_TOP_TO_PROB"], - "verdict": "Benchmarked" - }, - { - "id": "RTC_CH_NORM", - "theorem": "THS_CH_NORM", - "target_profile": "TGT_CH_NORM", - "equivalent_paths": [["B_TYPE_TO_SET"]], - "canonical_path": ["B_TYPE_TO_SET"], - "verdict": "Benchmarked" - }, - { - "id": "RTC_EXEC_INFER", - "theorem": "THS_EXEC_INFER", - "target_profile": "TGT_EXEC_INFER", - "equivalent_paths": [["B_PROB_TO_COMP"]], - "canonical_path": ["B_PROB_TO_COMP"], - "verdict": "Benchmarked" - }, - { - "id": "RTC_PROB_JUDG", - "theorem": "THS_PROB_JUDG", - "target_profile": "TGT_PROB_JUDG", - "equivalent_paths": [["B_PROB_TO_LOG"]], - "canonical_path": ["B_PROB_TO_LOG"], - "verdict": "Benchmarked" - }, - { - "id": "RTC_CERT_PROP", - "theorem": "THS_CERT_PROP", - "target_profile": "TGT_CERT_PROP", - "equivalent_paths": [["B_COMP_TO_LOG"]], - "canonical_path": ["B_COMP_TO_LOG"], - "verdict": "Benchmarked" - }, - { - "id": "RTC_CH_INH", - "theorem": "THS_CH_INH", - "target_profile": "TGT_CH_INH", - "equivalent_paths": [["B_TYPE_TO_ALG"]], - "canonical_path": ["B_TYPE_TO_ALG"], - "verdict": "Benchmarked" - } - ], - "atlas_deficiencies": [ - { - "id": "DGN_CHAIN_RULE_ADEQUACY", - "class": "DNoAdequacy", - "atlas_cell": "A_TOP_TO_CALC", - "theorem": "THS_CHAIN_RULE", - "message": "semantic adequacy remains scaffolded rather than discharged" - } - ], - "adequacy_clauses": [ - { - "id": "ADQ_CHAIN_CALC_OBJECT", - "kind": "ObjectInterpretation", - "regime_ids": ["R_CALC"], - "bridge_ids": [], - "theorem_ids": ["THS_CHAIN_RULE", "THS_CHAIN_RULE_RECIPE", "THS_CHAIN_RULE_TRANSPORT"], - "description": "first-order derivative witnesses must be executable as lawful local calculus objects", - "blocking": true - }, - { - "id": "ADQ_CHAIN_TOP_THREAD", - "kind": "ThreadInterpretation", - "regime_ids": ["R_TOP"], - "bridge_ids": [], - "theorem_ids": ["THS_CHAIN_RULE", "THS_CHAIN_RULE_RECIPE", "THS_CHAIN_RULE_TRANSPORT"], - "description": "topological/local thread transport must remain continuous and overlap-compatible", - "blocking": true - }, - { - "id": "ADQ_CHAIN_CALC_EQ", - "kind": "EquivalenceInterpretation", - "regime_ids": ["R_CALC"], - "bridge_ids": [], - "theorem_ids": ["THS_CHAIN_RULE", "THS_CHAIN_RULE_RECIPE", "THS_CHAIN_RULE_TRANSPORT"], - "description": "first-order jet equivalence must be executable on the selected burden", - "blocking": true - }, - { - "id": "ADQ_CHAIN_CALC_TOLL", - "kind": "TollInterpretation", - "regime_ids": ["R_CALC"], - "bridge_ids": [], - "theorem_ids": ["THS_CHAIN_RULE", "THS_CHAIN_RULE_RECIPE", "THS_CHAIN_RULE_TRANSPORT"], - "description": "first-order remainder toll must reduce lawfully on the selected burden", - "blocking": true - }, - { - "id": "ADQ_CHAIN_TOP_KNOT", - "kind": "KnotInterpretation", - "regime_ids": ["R_TOP"], - "bridge_ids": [], - "theorem_ids": ["THS_CHAIN_RULE", "THS_CHAIN_RULE_RECIPE", "THS_CHAIN_RULE_TRANSPORT"], - "description": "no local obstruction knot may remain on the selected chart-local transport", - "blocking": true - }, - { - "id": "ADQ_CHAIN_TOP_CALC_BRIDGE", - "kind": "BridgeSoundness", - "regime_ids": ["R_TOP", "R_CALC"], - "bridge_ids": ["B_TOP_TO_CALC"], - "theorem_ids": ["THS_CHAIN_RULE", "THS_CHAIN_RULE_RECIPE", "THS_CHAIN_RULE_TRANSPORT"], - "description": "the promoted top-to-calc bridge must carry Ref_1 soundness on the selected route", - "blocking": true - }, - { - "id": "ADQ_BAYES_PROB_OBJECT", - "kind": "ObjectInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_BAYES_BRACE"], - "description": "probabilistic branch objects must remain normalized and pushforward-stable on the active route", - "blocking": true - }, - { - "id": "ADQ_BAYES_TOP_THREAD", - "kind": "ThreadInterpretation", - "regime_ids": ["R_TOP"], - "bridge_ids": [], - "theorem_ids": ["THS_BAYES_BRACE"], - "description": "topological threading into the probabilistic brace must remain continuous and overlap-compatible", - "blocking": true - }, - { - "id": "ADQ_BAYES_PROB_EQ", - "kind": "EquivalenceInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_BAYES_BRACE"], - "description": "measure-compatible conditioning transport must remain adequate on the selected burden", - "blocking": true - }, - { - "id": "ADQ_BAYES_PROB_TOLL", - "kind": "TollInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_BAYES_BRACE"], - "description": "conditioning and normalization toll must reduce lawfully on the selected burden", - "blocking": true - }, - { - "id": "ADQ_BAYES_TOP_KNOT", - "kind": "KnotInterpretation", - "regime_ids": ["R_TOP"], - "bridge_ids": [], - "theorem_ids": ["THS_BAYES_BRACE"], - "description": "no topological obstruction knot may remain on the measurable brace shell", - "blocking": true - }, - { - "id": "ADQ_BAYES_TOP_PROB_BRIDGE", - "kind": "BridgeSoundness", - "regime_ids": ["R_TOP", "R_PROB"], - "bridge_ids": ["B_TOP_TO_PROB"], - "theorem_ids": ["THS_BAYES_BRACE"], - "description": "the top-to-prob bridge must carry measurable normalization soundness on the selected route", - "blocking": true - }, - { - "id": "ADQ_CH_TYP_OBJECT", - "kind": "ObjectInterpretation", - "regime_ids": ["R_TYP"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_NORM"], - "description": "typed normalization objects must remain inhabited on the active type-to-set route", - "blocking": true - }, - { - "id": "ADQ_CH_TYP_THREAD", - "kind": "ThreadInterpretation", - "regime_ids": ["R_TYP"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_NORM"], - "description": "typed normalization threads must remain lawful under carrier collapse", - "blocking": true - }, - { - "id": "ADQ_CH_SET_EQ", - "kind": "EquivalenceInterpretation", - "regime_ids": ["R_SET"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_NORM"], - "description": "extensional carrier equality must remain adequate after normalization collapse", - "blocking": true - }, - { - "id": "ADQ_CH_TYP_TOLL", - "kind": "TollInterpretation", - "regime_ids": ["R_TYP"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_NORM"], - "description": "normalization toll must reduce lawfully before extensional carrier collapse", - "blocking": true - }, - { - "id": "ADQ_CH_TYP_KNOT", - "kind": "KnotInterpretation", - "regime_ids": ["R_TYP"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_NORM"], - "description": "no type-level obstruction knot may remain on the active normalization witness", - "blocking": true - }, - { - "id": "ADQ_CH_TYP_SET_BRIDGE", - "kind": "BridgeSoundness", - "regime_ids": ["R_TYP", "R_SET"], - "bridge_ids": ["B_TYPE_TO_SET"], - "theorem_ids": ["THS_CH_NORM"], - "description": "the type-to-set bridge must carry Rig soundness on the selected normalization route", - "blocking": true - }, - { - "id": "ADQ_EXEC_PROB_OBJECT", - "kind": "ObjectInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_EXEC_INFER"], - "description": "probabilistic executable branching objects must remain normalized and pushforward-stable", - "blocking": true - }, - { - "id": "ADQ_EXEC_PROB_THREAD", - "kind": "ThreadInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_EXEC_INFER"], - "description": "probabilistic branching threads must remain lawful before executable realization", - "blocking": true - }, - { - "id": "ADQ_EXEC_COMP_EQ", - "kind": "EquivalenceInterpretation", - "regime_ids": ["R_COMP"], - "bridge_ids": [], - "theorem_ids": ["THS_EXEC_INFER"], - "description": "executable realization must remain adequate under simulation transport", - "blocking": true - }, - { - "id": "ADQ_EXEC_COMP_TOLL", - "kind": "TollInterpretation", - "regime_ids": ["R_PROB", "R_COMP"], - "bridge_ids": [], - "theorem_ids": ["THS_EXEC_INFER"], - "description": "branching and execution toll must remain lawful on the selected realization route", - "blocking": true - }, - { - "id": "ADQ_EXEC_COMP_KNOT", - "kind": "KnotInterpretation", - "regime_ids": ["R_COMP"], - "bridge_ids": [], - "theorem_ids": ["THS_EXEC_INFER"], - "description": "no executable obstruction knot may remain after simulation realization", - "blocking": true - }, - { - "id": "ADQ_EXEC_PROB_COMP_BRIDGE", - "kind": "BridgeSoundness", - "regime_ids": ["R_PROB", "R_COMP"], - "bridge_ids": ["B_PROB_TO_COMP"], - "theorem_ids": ["THS_EXEC_INFER"], - "description": "the prob-to-comp bridge must carry Exec soundness on the selected route", - "blocking": true - }, - { - "id": "ADQ_JDG_PROB_OBJECT", - "kind": "ObjectInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_PROB_JUDG"], - "description": "probabilistic judgment objects must remain normalized on the selected logical route", - "blocking": true - }, - { - "id": "ADQ_JDG_PROB_THREAD", - "kind": "ThreadInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_PROB_JUDG"], - "description": "probabilistic judgment threads must remain lawful under logical transport", - "blocking": true - }, - { - "id": "ADQ_JDG_LOG_EQ", - "kind": "EquivalenceInterpretation", - "regime_ids": ["R_LOG"], - "bridge_ids": [], - "theorem_ids": ["THS_PROB_JUDG"], - "description": "probabilistic theorem equivalence must remain adequate on the selected logic shell", - "blocking": true - }, - { - "id": "ADQ_JDG_PROB_TOLL", - "kind": "TollInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_PROB_JUDG"], - "description": "normalization and conditioning toll must remain lawful on the selected judgment route", - "blocking": true - }, - { - "id": "ADQ_JDG_PROB_KNOT", - "kind": "KnotInterpretation", - "regime_ids": ["R_PROB"], - "bridge_ids": [], - "theorem_ids": ["THS_PROB_JUDG"], - "description": "no probabilistic obstruction knot may remain on the active judgment route", - "blocking": true - }, - { - "id": "ADQ_JDG_PROB_LOG_BRIDGE", - "kind": "BridgeSoundness", - "regime_ids": ["R_PROB", "R_LOG"], - "bridge_ids": ["B_PROB_TO_LOG"], - "theorem_ids": ["THS_PROB_JUDG"], - "description": "the prob-to-log bridge must carry ProbJudg_phi soundness on the selected route", - "blocking": true - }, - { - "id": "ADQ_CERT_COMP_OBJECT", - "kind": "ObjectInterpretation", - "regime_ids": ["R_COMP"], - "bridge_ids": [], - "theorem_ids": ["THS_CERT_PROP"], - "description": "computational property witnesses must remain executable objects on the selected route", - "blocking": true - }, - { - "id": "ADQ_CERT_COMP_THREAD", - "kind": "ThreadInterpretation", - "regime_ids": ["R_COMP"], - "bridge_ids": [], - "theorem_ids": ["THS_CERT_PROP"], - "description": "computational execution threads must remain replayable on the selected route", - "blocking": true - }, - { - "id": "ADQ_CERT_LOG_EQ", - "kind": "EquivalenceInterpretation", - "regime_ids": ["R_LOG"], - "bridge_ids": [], - "theorem_ids": ["THS_CERT_PROP"], - "description": "certified property equivalence must remain adequate on the selected logic shell", - "blocking": true - }, - { - "id": "ADQ_CERT_COMP_TOLL", - "kind": "TollInterpretation", - "regime_ids": ["R_COMP"], - "bridge_ids": [], - "theorem_ids": ["THS_CERT_PROP"], - "description": "computational cost toll must remain lawful under certification transport", - "blocking": true - }, - { - "id": "ADQ_CERT_COMP_KNOT", - "kind": "KnotInterpretation", - "regime_ids": ["R_COMP"], - "bridge_ids": [], - "theorem_ids": ["THS_CERT_PROP"], - "description": "no executable obstruction knot may remain on the certified property witness", - "blocking": true - }, - { - "id": "ADQ_CERT_COMP_LOG_BRIDGE", - "kind": "BridgeSoundness", - "regime_ids": ["R_COMP", "R_LOG"], - "bridge_ids": ["B_COMP_TO_LOG"], - "theorem_ids": ["THS_CERT_PROP"], - "description": "the comp-to-log bridge must carry Cert_phi soundness on the selected route", - "blocking": true - }, - { - "id": "ADQ_CHI_TYP_OBJECT", - "kind": "ObjectInterpretation", - "regime_ids": ["R_TYP"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_INH"], - "description": "typed inherited objects must remain inhabited before algebraic enrichment", - "blocking": true - }, - { - "id": "ADQ_CHI_TYP_THREAD", - "kind": "ThreadInterpretation", - "regime_ids": ["R_TYP"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_INH"], - "description": "typed inherited threads must remain lawful before algebraic enrichment", - "blocking": true - }, - { - "id": "ADQ_CHI_ALG_EQ", - "kind": "EquivalenceInterpretation", - "regime_ids": ["R_ALG"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_INH"], - "description": "structure-preserving algebra equality must remain adequate on the selected route", - "blocking": true - }, - { - "id": "ADQ_CHI_TYP_TOLL", - "kind": "TollInterpretation", - "regime_ids": ["R_TYP"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_INH"], - "description": "typed inhabitance toll must remain lawful before algebraic enrichment", - "blocking": true - }, - { - "id": "ADQ_CHI_TYP_KNOT", - "kind": "KnotInterpretation", - "regime_ids": ["R_TYP"], - "bridge_ids": [], - "theorem_ids": ["THS_CH_INH"], - "description": "no type-side obstruction knot may remain before algebraic enrichment", - "blocking": true - }, - { - "id": "ADQ_CHI_TYP_ALG_BRIDGE", - "kind": "BridgeSoundness", - "regime_ids": ["R_TYP", "R_ALG"], - "bridge_ids": ["B_TYPE_TO_ALG"], - "theorem_ids": ["THS_CH_INH"], - "description": "the type-to-alg bridge must carry Lift^Typ->Alg soundness on the selected route", - "blocking": true - } - ], - "codebook_packs": [ - { - "id": "CB_CORE", - "version": "1", - "symbols": ["CTX","CUT","THR","BRC","SLK","TOL","KNT","WIT","CAN","PRM"] - } - ], - "glyph_packs": [ - { - "id": "GLYPH_PACK_A", - "version": "1", - "pack": "PackA", - "delimiters": { - "identity_open": "⟦", - "identity_close": "⟧", - "struct_open": "⟨", - "struct_close": "⟩", - "constraint_open": "〔", - "constraint_close": "〕", - "evidence_open": "⦃", - "evidence_close": "⦄", - "alias_open": "⟪", - "alias_close": "⟫" - }, - "operators": { - "maps_to": "↦", - "approx": "≈", - "compose": "∘" - } - } - ], - "combo_packs": [ - { - "id": "COMBO_PACK_A", - "version": "1", - "pack": "PackA", - "combos": { - "id_open": "⟦", - "id_close": "⟧", - "st_open": "⟨", - "st_close": "⟩", - "ct_open": "〔", - "ct_close": "〕", - "ev_open": "⦃", - "ev_close": "⦄", - "al_open": "⟪", - "al_close": "⟫", - "maps_to": "↦", - "approx": "≈", - "compose": "∘", - "nl": "\n" - } - } - ], - "projection_policies": [ - { - "id": "PROJ_QC0_CORE", - "kind": "StrictAuthority", - "allow_qa0_downgrade": false - }, - { - "id": "PROJ_QM0_A", - "kind": "CanonicalAuthored", - "allow_qa0_downgrade": true - }, - { - "id": "PROJ_QA0_A", - "kind": "DebugMirrorOnly", - "allow_qa0_downgrade": true - } - ], - "alias_expansion_policies": [ - { - "id": "ALIAS_STRICT", - "kind": "ForbidImplicit", - "allowed_aliases": [] - }, - { - "id": "ALIAS_DECLARED", - "kind": "ExpandAndReceipt", - "allowed_aliases": ["ctx_set","ctx_set_canon"] - } - ] -} diff --git a/l64-registry/src/lib.rs b/l64-registry/src/lib.rs deleted file mode 100644 index f333615..0000000 --- a/l64-registry/src/lib.rs +++ /dev/null @@ -1,388 +0,0 @@ -use l64_core::{ - AdequacyClause, AliasExpansionPolicy, ArtifactOrigin, AtlasCell, AtlasDeficiency, - BenchmarkReceipt, BridgeContract, BurdenPack, Campaign, CampaignPortfolio, Certificate, - ChallengeReceipt, ClaimPacket, CodebookPack, ComboPack, EquivalenceClass, EvidenceContract, - GlyphPack, MechanizationPackage, MechanizationPolicyObject, Obligation, PolicyBinding, - ProjectionPolicy, ProofShape, QcObject, RegimePack, RegistryBundle, RegistryLookup, - ReproducibilityPacket, RouteClass, RouteLedger, SurfaceDeficiency, TargetProfile, TheoremSpec, -}; -use std::collections::HashMap; -use thiserror::Error; - -const SEED_DATA: &str = include_str!("../data/seed.v1.json"); - -#[derive(Debug, Error)] -pub enum RegistryError { - #[error("invalid registry seed: {0}")] - InvalidSeed(String), -} - -#[derive(Debug, Clone)] -pub struct SeedRegistry { - bundle: RegistryBundle, - object_index: HashMap, - regime_index: HashMap, - bridge_index: HashMap, - proof_shape_index: HashMap, - atlas_cell_index: HashMap, - mechanization_index: HashMap, - theorem_index: HashMap, - obligation_index: HashMap, - target_profile_index: HashMap, - route_ledger_index: HashMap, - certificate_index: HashMap, - campaign_index: HashMap, - portfolio_index: HashMap, - route_class_index: HashMap, - atlas_deficiency_index: HashMap, - adequacy_clause_index: HashMap, - burden_pack_index: HashMap, - claim_packet_index: HashMap, - evidence_contract_index: HashMap, - benchmark_receipt_index: HashMap, - challenge_receipt_index: HashMap, - reproducibility_packet_index: HashMap, - codebook_pack_index: HashMap, - glyph_pack_index: HashMap, - combo_pack_index: HashMap, - projection_policy_index: HashMap, - alias_policy_index: HashMap, - surface_deficiency_index: HashMap, - policy_object_index: HashMap, -} - -impl SeedRegistry { - pub fn load() -> Result { - let bundle: RegistryBundle = serde_json::from_str(SEED_DATA) - .map_err(|err| RegistryError::InvalidSeed(err.to_string()))?; - Ok(Self { - object_index: build_index(&bundle.objects, |item| item.id.as_str()), - regime_index: build_index(&bundle.regimes, |item| item.id.as_str()), - bridge_index: build_index(&bundle.bridges, |item| item.id.as_str()), - proof_shape_index: build_index(&bundle.proof_shapes, |item| item.id.as_str()), - atlas_cell_index: build_index(&bundle.atlas_cells, |item| item.id.as_str()), - mechanization_index: build_index(&bundle.mechanization_packages, |item| { - item.id.as_str() - }), - theorem_index: build_index(&bundle.theorem_specs, |item| item.id.as_str()), - obligation_index: build_index(&bundle.obligations, |item| item.id.as_str()), - target_profile_index: build_index(&bundle.target_profiles, |item| item.id.as_str()), - route_ledger_index: build_index(&bundle.route_ledgers, |item| item.id.as_str()), - certificate_index: build_index(&bundle.certificates, |item| item.id.as_str()), - campaign_index: build_index(&bundle.campaigns, |item| item.id.as_str()), - portfolio_index: build_index(&bundle.campaign_portfolios, |item| item.id.as_str()), - route_class_index: build_index(&bundle.route_classes, |item| item.id.as_str()), - atlas_deficiency_index: build_index(&bundle.atlas_deficiencies, |item| { - item.id.as_str() - }), - adequacy_clause_index: build_index(&bundle.adequacy_clauses, |item| item.id.as_str()), - burden_pack_index: build_index(&bundle.burden_packs, |item| item.id.as_str()), - claim_packet_index: build_index(&bundle.claim_packets, |item| item.id.as_str()), - evidence_contract_index: build_index(&bundle.evidence_contracts, |item| { - item.id.as_str() - }), - benchmark_receipt_index: build_index(&bundle.benchmark_receipts, |item| { - item.id.as_str() - }), - challenge_receipt_index: build_index(&bundle.challenge_receipts, |item| { - item.id.as_str() - }), - reproducibility_packet_index: build_index(&bundle.reproducibility_packets, |item| { - item.id.as_str() - }), - codebook_pack_index: build_index(&bundle.codebook_packs, |item| item.id.as_str()), - glyph_pack_index: build_index(&bundle.glyph_packs, |item| item.id.as_str()), - combo_pack_index: build_index(&bundle.combo_packs, |item| item.id.as_str()), - projection_policy_index: build_index(&bundle.projection_policies, |item| { - item.id.as_str() - }), - alias_policy_index: build_index(&bundle.alias_expansion_policies, |item| { - item.id.as_str() - }), - surface_deficiency_index: build_index(&bundle.surface_deficiencies, |item| { - item.id.as_str() - }), - policy_object_index: build_index(&bundle.policy_objects, |item| item.id.as_str()), - bundle, - }) - } - - pub fn bundle(&self) -> &RegistryBundle { - &self.bundle - } -} - -impl RegistryLookup for SeedRegistry { - fn get_object(&self, id: &str) -> Option { - self.object_index - .get(id) - .and_then(|index| self.bundle.objects.get(*index)) - .cloned() - } - fn get_object_origin(&self, id: &str) -> ArtifactOrigin { - if self.object_index.contains_key(id) { - ArtifactOrigin::Seed - } else { - ArtifactOrigin::Unknown - } - } - - fn get_regime(&self, id: &str) -> Option { - self.regime_index - .get(id) - .and_then(|index| self.bundle.regimes.get(*index)) - .cloned() - } - - fn get_bridge(&self, id: &str) -> Option { - self.bridge_index - .get(id) - .and_then(|index| self.bundle.bridges.get(*index)) - .cloned() - } - - fn get_proof_shape(&self, id: &str) -> Option { - self.proof_shape_index - .get(id) - .and_then(|index| self.bundle.proof_shapes.get(*index)) - .cloned() - } - - fn get_atlas_cell(&self, id: &str) -> Option { - self.atlas_cell_index - .get(id) - .and_then(|index| self.bundle.atlas_cells.get(*index)) - .cloned() - } - - fn get_mechanization_package(&self, id: &str) -> Option { - self.mechanization_index - .get(id) - .and_then(|index| self.bundle.mechanization_packages.get(*index)) - .cloned() - } - - fn get_theorem_spec(&self, id: &str) -> Option { - self.theorem_index - .get(id) - .and_then(|index| self.bundle.theorem_specs.get(*index)) - .cloned() - } - - fn get_obligation(&self, id: &str) -> Option { - self.obligation_index - .get(id) - .and_then(|index| self.bundle.obligations.get(*index)) - .cloned() - } - - fn get_target_profile(&self, id: &str) -> Option { - self.target_profile_index - .get(id) - .and_then(|index| self.bundle.target_profiles.get(*index)) - .cloned() - } - - fn get_route_ledger(&self, id: &str) -> Option { - self.route_ledger_index - .get(id) - .and_then(|index| self.bundle.route_ledgers.get(*index)) - .cloned() - } - - fn get_certificate(&self, id: &str) -> Option { - self.certificate_index - .get(id) - .and_then(|index| self.bundle.certificates.get(*index)) - .cloned() - } - - fn get_campaign(&self, id: &str) -> Option { - self.campaign_index - .get(id) - .and_then(|index| self.bundle.campaigns.get(*index)) - .cloned() - } - - fn get_campaign_portfolio(&self, id: &str) -> Option { - self.portfolio_index - .get(id) - .and_then(|index| self.bundle.campaign_portfolios.get(*index)) - .cloned() - } - - fn get_route_class(&self, id: &str) -> Option { - self.route_class_index - .get(id) - .and_then(|index| self.bundle.route_classes.get(*index)) - .cloned() - } - - fn get_atlas_deficiency(&self, id: &str) -> Option { - self.atlas_deficiency_index - .get(id) - .and_then(|index| self.bundle.atlas_deficiencies.get(*index)) - .cloned() - } - fn atlas_deficiencies(&self) -> Vec { - self.bundle.atlas_deficiencies.clone() - } - - fn get_adequacy_clause(&self, id: &str) -> Option { - self.adequacy_clause_index - .get(id) - .and_then(|index| self.bundle.adequacy_clauses.get(*index)) - .cloned() - } - fn adequacy_clauses(&self) -> Vec { - self.bundle.adequacy_clauses.clone() - } - fn get_burden_pack(&self, id: &str) -> Option { - self.burden_pack_index - .get(id) - .and_then(|index| self.bundle.burden_packs.get(*index)) - .cloned() - } - fn burden_packs(&self) -> Vec { - self.bundle.burden_packs.clone() - } - fn get_claim_packet(&self, id: &str) -> Option { - self.claim_packet_index - .get(id) - .and_then(|index| self.bundle.claim_packets.get(*index)) - .cloned() - } - fn claim_packets(&self) -> Vec { - self.bundle.claim_packets.clone() - } - fn get_evidence_contract(&self, id: &str) -> Option { - self.evidence_contract_index - .get(id) - .and_then(|index| self.bundle.evidence_contracts.get(*index)) - .cloned() - } - fn evidence_contracts(&self) -> Vec { - self.bundle.evidence_contracts.clone() - } - fn get_benchmark_receipt(&self, id: &str) -> Option { - self.benchmark_receipt_index - .get(id) - .and_then(|index| self.bundle.benchmark_receipts.get(*index)) - .cloned() - } - fn benchmark_receipts(&self) -> Vec { - self.bundle.benchmark_receipts.clone() - } - fn get_challenge_receipt(&self, id: &str) -> Option { - self.challenge_receipt_index - .get(id) - .and_then(|index| self.bundle.challenge_receipts.get(*index)) - .cloned() - } - fn challenge_receipts(&self) -> Vec { - self.bundle.challenge_receipts.clone() - } - fn get_reproducibility_packet(&self, id: &str) -> Option { - self.reproducibility_packet_index - .get(id) - .and_then(|index| self.bundle.reproducibility_packets.get(*index)) - .cloned() - } - fn reproducibility_packets(&self) -> Vec { - self.bundle.reproducibility_packets.clone() - } - - fn get_codebook_pack(&self, id: &str) -> Option { - self.codebook_pack_index - .get(id) - .and_then(|index| self.bundle.codebook_packs.get(*index)) - .cloned() - } - - fn get_glyph_pack(&self, id: &str) -> Option { - self.glyph_pack_index - .get(id) - .and_then(|index| self.bundle.glyph_packs.get(*index)) - .cloned() - } - - fn get_combo_pack(&self, id: &str) -> Option { - self.combo_pack_index - .get(id) - .and_then(|index| self.bundle.combo_packs.get(*index)) - .cloned() - } - - fn get_projection_policy(&self, id: &str) -> Option { - self.projection_policy_index - .get(id) - .and_then(|index| self.bundle.projection_policies.get(*index)) - .cloned() - } - - fn get_alias_expansion_policy(&self, id: &str) -> Option { - self.alias_policy_index - .get(id) - .and_then(|index| self.bundle.alias_expansion_policies.get(*index)) - .cloned() - } - - fn get_surface_deficiency(&self, id: &str) -> Option { - self.surface_deficiency_index - .get(id) - .and_then(|index| self.bundle.surface_deficiencies.get(*index)) - .cloned() - } - - fn get_policy_object(&self, id: &str) -> Option { - self.policy_object_index - .get(id) - .and_then(|index| self.bundle.policy_objects.get(*index)) - .cloned() - } - - fn policy_objects(&self) -> Vec { - self.bundle.policy_objects.clone() - } - - fn policy_bindings(&self) -> Vec { - self.bundle.policy_bindings.clone() - } - - fn find_equivalence_class(&self, object_id: &str, regime: &str) -> Option { - self.bundle - .equivalence_classes - .iter() - .find(|item| { - item.regime == regime && item.members.iter().any(|member| member == object_id) - }) - .cloned() - } - - fn atlas_cells(&self) -> Vec { - self.bundle.atlas_cells.clone() - } -} - -fn build_index(items: &[T], key: impl Fn(&T) -> &str) -> HashMap { - items - .iter() - .enumerate() - .map(|(index, item)| (key(item).to_string(), index)) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn seed_registry_loads() { - let registry = SeedRegistry::load().expect("seed registry should load"); - assert!(registry.get_regime("R_SET").is_some()); - assert!(registry.get_bridge("B_TYPE_TO_SET").is_some()); - assert!(registry.get_atlas_cell("A_TYPE_TO_SET").is_some()); - assert!(registry.get_theorem_spec("THS_CHAIN_RULE").is_some()); - assert!(registry.get_campaign("CPG_CHAIN_RULE").is_some()); - } -} diff --git a/l64-release/Cargo.toml b/l64-release/Cargo.toml new file mode 100644 index 0000000..e379f40 --- /dev/null +++ b/l64-release/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "l64-release" +edition.workspace = true +version.workspace = true +license.workspace = true + +[dependencies] +l64-native = { path = "../l64-native" } +l64-projection = { path = "../l64-projection" } diff --git a/l64-release/src/lib.rs b/l64-release/src/lib.rs new file mode 100644 index 0000000..44f03e6 --- /dev/null +++ b/l64-release/src/lib.rs @@ -0,0 +1,168 @@ +#![forbid(unsafe_code)] + +use l64_native::{DnaError, ROOT_CONTEXT, RnaError, decode_dna, dna_to_rna, rna_to_dna}; +use l64_projection::{ProjectionError, ProjectionSet}; +use std::{ + fmt::{self, Write as _}, + fs, io, + path::{Path, PathBuf}, +}; + +pub const RELEASE_VERSION: u16 = 1; + +#[derive(Debug)] +pub enum ReleaseError { + OutputExists(PathBuf), + InvalidOutput(PathBuf), + Native(String), + Rna { + phase: &'static str, + error: RnaError, + }, + Dna { + phase: &'static str, + error: DnaError, + }, + Projection(ProjectionError), + Io(io::Error), +} + +impl fmt::Display for ReleaseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::OutputExists(path) => { + write!(f, "release output `{}` already exists", path.display()) + } + Self::InvalidOutput(path) => { + write!(f, "invalid release output path `{}`", path.display()) + } + Self::Native(error) => f.write_str(error), + Self::Rna { phase, error } => write!(f, "release {phase} failed: {error}"), + Self::Dna { phase, error } => write!(f, "release {phase} failed: {error}"), + Self::Projection(error) => write!(f, "release projection failed: {error}"), + Self::Io(error) => write!(f, "release filesystem operation failed: {error}"), + } + } +} + +impl ReleaseError { + pub const fn rna_error(&self) -> Option { + match self { + Self::Rna { error, .. } => Some(*error), + _ => None, + } + } +} + +impl std::error::Error for ReleaseError {} + +impl From for ReleaseError { + fn from(value: ProjectionError) -> Self { + Self::Projection(value) + } +} + +impl From for ReleaseError { + fn from(value: io::Error) -> Self { + Self::Io(value) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeRelease { + pub root: PathBuf, + pub source: PathBuf, + pub authority: PathBuf, + pub projection: PathBuf, + pub record: PathBuf, +} + +pub fn export_native_release( + source: &[u8], + out_root: &Path, +) -> Result { + if out_root.exists() { + return Err(ReleaseError::OutputExists(out_root.to_path_buf())); + } + let parent = out_root + .parent() + .filter(|path| !path.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + let name = out_root + .file_name() + .ok_or_else(|| ReleaseError::InvalidOutput(out_root.to_path_buf()))?; + fs::create_dir_all(parent)?; + + let canonical_rna = l64_native::normalize_rna(source).map_err(|error| ReleaseError::Rna { + phase: "normalization", + error, + })?; + let dna = rna_to_dna(&canonical_rna).map_err(|error| ReleaseError::Rna { + phase: "compilation", + error, + })?; + let graph = decode_dna(&dna).map_err(|error| ReleaseError::Dna { + phase: "decoding", + error, + })?; + let sequenced = dna_to_rna(&dna).map_err(|error| ReleaseError::Rna { + phase: "sequencing", + error, + })?; + if sequenced != canonical_rna { + return Err(ReleaseError::Native( + "canonical RNA fixed point failed".into(), + )); + } + let projection = ProjectionSet::derive(&graph, ROOT_CONTEXT, 16)?; + projection.verify(&graph)?; + + let stage = parent.join(format!( + ".{}.l64-release-{}", + name.to_string_lossy(), + std::process::id() + )); + if stage.exists() { + fs::remove_dir_all(&stage)?; + } + let result = write_stage(&stage, &canonical_rna, &dna, &projection).and_then(|_| { + fs::rename(&stage, out_root)?; + Ok(NativeRelease { + root: out_root.to_path_buf(), + source: out_root.join("source.rna"), + authority: out_root.join("authority.dna"), + projection: out_root.join("projection.txt"), + record: out_root.join("release.record"), + }) + }); + if result.is_err() && stage.exists() { + let _ = fs::remove_dir_all(&stage); + } + result +} + +fn write_stage( + stage: &Path, + canonical_rna: &[u8], + dna: &[u8], + projection: &ProjectionSet, +) -> Result<(), ReleaseError> { + fs::create_dir(stage)?; + fs::write(stage.join("source.rna"), canonical_rna)?; + fs::write(stage.join("authority.dna"), dna)?; + let projection_text = projection.render_text(); + fs::write(stage.join("projection.txt"), projection_text.as_bytes())?; + + let mut record = String::new(); + let _ = writeln!(record, "L64 NATIVE RELEASE v{RELEASE_VERSION}"); + let _ = writeln!(record, "authority=authority.dna"); + let _ = writeln!(record, "source=source.rna"); + let _ = writeln!(record, "projection=projection.txt"); + let _ = writeln!(record, "projection_authority=non_authoritative"); + let _ = writeln!(record, "state_symbol={}", projection.source.symbol); + let _ = writeln!(record, "source_bytes={}", canonical_rna.len()); + let _ = writeln!(record, "dna_bytes={}", dna.len()); + let _ = writeln!(record, "projection_verified=true"); + fs::write(stage.join("release.record"), record)?; + Ok(()) +} diff --git a/l64-release/tests/release.rs b/l64-release/tests/release.rs new file mode 100644 index 0000000..2764a16 --- /dev/null +++ b/l64-release/tests/release.rs @@ -0,0 +1,44 @@ +use l64_release::{ReleaseError, export_native_release}; +use std::{ + fs, + path::PathBuf, + time::{SystemTime, UNIX_EPOCH}, +}; + +const SOURCE: &[u8] = b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n"; + +fn root(name: &str) -> PathBuf { + std::env::temp_dir().join(format!( + "l64_release_{name}_{}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )) +} + +#[test] +fn release_contains_one_authority_and_verified_projection() { + let out = root("complete"); + let release = export_native_release(SOURCE, &out).unwrap(); + assert!(fs::read(&release.authority).unwrap().starts_with(b"L64D")); + assert_eq!(fs::read(&release.source).unwrap(), SOURCE); + let projection = fs::read_to_string(&release.projection).unwrap(); + assert!(projection.starts_with("L64 NATIVE PROJECTION v1\n")); + let record = fs::read_to_string(&release.record).unwrap(); + assert!(record.contains("projection_authority=non_authoritative")); + assert!(record.contains("projection_verified=true")); + assert_eq!(fs::read_dir(&release.root).unwrap().count(), 4); + fs::remove_dir_all(out).unwrap(); +} + +#[test] +fn release_refuses_to_replace_existing_output() { + let out = root("existing"); + fs::create_dir_all(&out).unwrap(); + assert!(matches!( + export_native_release(SOURCE, &out), + Err(ReleaseError::OutputExists(path)) if path == out + )); + fs::remove_dir_all(out).unwrap(); +} diff --git a/l64-research/Cargo.toml b/l64-research/Cargo.toml deleted file mode 100644 index 722c505..0000000 --- a/l64-research/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "l64-research" -version = "0.1.0" -edition = "2024" - -[dependencies] -anyhow = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -bincode = { workspace = true } -l64-core = { path = "../l64-core" } -l64-locus = { path = "../l64-locus" } -l64-cert = { path = "../l64-cert" } diff --git a/l64-research/src/lib.rs b/l64-research/src/lib.rs deleted file mode 100644 index 76e32a2..0000000 --- a/l64-research/src/lib.rs +++ /dev/null @@ -1,2928 +0,0 @@ -use anyhow::{Result, anyhow}; -use l64_core::{ - AuthorityState, BenchmarkRunRecord, BenchmarkSchema, CertificationReport, ChallengeGrounds, - ChallengeRecord, ChallengeSeverity, ChallengeStatus, ClaimClass, DerivationSignature, - DesiredOutputKind, FrameworkRegistryEntry, HandoffPacket, LocusCapabilityMask, LocusOpcode, - LocusPacketKind, MathClaimPacket, ObjectiveKind, OperatorRecord, ProducerHostKind, - ProducerHostSpec, ProjectionMapRecord, PromotionQueueEntry, PromotionQueueStatus, - PromotionReadinessReport, ProofCoverageDispatch, ReductionMapRecord, RegistryEntryKind, - RegistryEntryStatus, RemediationClass, RemediationLedgerEntry, RemediationStatus, - ReproducibilityPacket, ResearchBundle, ResearchLineageRecord, ResearchRouteClass, - ResponseClass, ReviewDecision, ReviewReceipt, ReviewStatus, RouteAssignment, RouteScore, - StrengtheningArtifact, TaskEnvelope, VerticalCompoundingBundle, -}; -use l64_locus::{decode_section_payload, write_section_packet}; -use serde::{Serialize, de::DeserializeOwned}; -use std::fs; -use std::path::{Path, PathBuf}; - -fn research_root() -> Result { - let root = PathBuf::from( - l64_core::resolve_cache_root() - .map_err(anyhow::Error::msg)? - .absolute_path, - ) - .join("research"); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn kind_dir(kind: &str) -> Result { - let root = research_root()?.join(kind); - fs::create_dir_all(&root)?; - Ok(root) -} - -fn dna_path(kind: &str, id: &str) -> Result { - Ok(kind_dir(kind)?.join(format!("{id}.dna"))) -} - -fn store_payload( - kind: &str, - id: &str, - schema_hash: &str, - payload: &T, - opcode: LocusOpcode, -) -> Result<()> { - let path = dna_path(kind, id)?; - write_section_packet( - &path, - LocusPacketKind::CanonicalTransfer, - opcode, - id, - schema_hash, - payload, - LocusCapabilityMask { - has_frontier: true, - ..Default::default() - }, - 1, - ) - .map_err(anyhow::Error::msg)?; - Ok(()) -} - -fn load_payload(kind: &str, id: &str, opcode: LocusOpcode) -> Result { - let packet = dna_path(kind, id)?; - decode_section_payload(&fs::read(packet)?, opcode).map_err(anyhow::Error::msg) -} - -fn list_ids(kind: &str) -> Result> { - let root = kind_dir(kind)?; - let mut out = Vec::new(); - for entry in fs::read_dir(root)? { - let entry = entry?; - let path = entry.path(); - if let (Some(stem), Some(ext)) = ( - path.file_stem().and_then(|s| s.to_str()), - path.extension().and_then(|s| s.to_str()), - ) { - if ext == "dna" { - out.push(stem.to_string()); - } - } - } - out.sort(); - out.dedup(); - Ok(out) -} - -pub fn persist_task_envelope(item: &TaskEnvelope) -> Result<()> { - store_payload( - "tasks", - &item.id, - "task_envelope.v1", - item, - LocusOpcode::Proposal, - ) -} -pub fn load_task_envelope(id: &str) -> Result { - load_payload("tasks", id, LocusOpcode::Proposal) -} -pub fn list_task_envelopes() -> Result> { - list_ids("tasks") -} - -pub fn persist_derivation_signature(item: &DerivationSignature) -> Result<()> { - store_payload( - "signatures", - &item.id, - "derivation_signature.v1", - item, - LocusOpcode::Proposal, - ) -} -pub fn load_derivation_signature(id: &str) -> Result { - load_payload("signatures", id, LocusOpcode::Proposal) -} -pub fn list_derivation_signatures() -> Result> { - list_ids("signatures") -} - -pub fn persist_review_receipt(item: &ReviewReceipt) -> Result<()> { - store_payload( - "reviews", - &item.id, - "review_receipt.v1", - item, - LocusOpcode::ReceiptTable, - ) -} -pub fn load_review_receipt(id: &str) -> Result { - load_payload("reviews", id, LocusOpcode::ReceiptTable) -} -pub fn list_review_receipts() -> Result> { - list_ids("reviews") -} - -pub fn persist_challenge_record(item: &ChallengeRecord) -> Result<()> { - store_payload( - "challenges", - &item.id, - "challenge_record.v1", - item, - LocusOpcode::ReceiptTable, - ) -} -pub fn load_challenge_record(id: &str) -> Result { - load_payload("challenges", id, LocusOpcode::ReceiptTable) -} -pub fn list_challenge_records() -> Result> { - list_ids("challenges") -} - -pub fn persist_framework_registry_entry(item: &FrameworkRegistryEntry) -> Result<()> { - store_payload( - "registry", - &item.id, - "framework_registry_entry.v1", - item, - LocusOpcode::Coverage, - ) -} -pub fn load_framework_registry_entry(id: &str) -> Result { - load_payload("registry", id, LocusOpcode::Coverage) -} -pub fn list_framework_registry_entries() -> Result> { - list_ids("registry") -} - -pub fn persist_operator_record(item: &OperatorRecord) -> Result<()> { - store_payload( - "operators", - &item.id, - "operator_record.v1", - item, - LocusOpcode::CanonicalPayload, - ) -} -pub fn load_operator_record(id: &str) -> Result { - load_payload("operators", id, LocusOpcode::CanonicalPayload) -} -pub fn list_operator_records() -> Result> { - list_ids("operators") -} - -pub fn persist_benchmark_schema(item: &BenchmarkSchema) -> Result<()> { - store_payload( - "benchmarks", - &item.id, - "benchmark_schema.v1", - item, - LocusOpcode::CanonicalPayload, - ) -} -pub fn load_benchmark_schema(id: &str) -> Result { - load_payload("benchmarks", id, LocusOpcode::CanonicalPayload) -} -pub fn list_benchmark_schemas() -> Result> { - list_ids("benchmarks") -} - -pub fn persist_math_claim_packet(item: &MathClaimPacket) -> Result<()> { - store_payload( - "claims", - &item.id, - "math_claim_packet.v1", - item, - LocusOpcode::CanonicalPayload, - ) -} -pub fn load_math_claim_packet(id: &str) -> Result { - load_payload("claims", id, LocusOpcode::CanonicalPayload) -} -pub fn list_math_claim_packets() -> Result> { - list_ids("claims") -} - -pub fn persist_reduction_map_record(item: &ReductionMapRecord) -> Result<()> { - store_payload( - "reductions", - &item.id, - "reduction_map_record.v1", - item, - LocusOpcode::RouteLedger, - ) -} -pub fn load_reduction_map_record(id: &str) -> Result { - load_payload("reductions", id, LocusOpcode::RouteLedger) -} -pub fn list_reduction_map_records() -> Result> { - list_ids("reductions") -} - -pub fn persist_projection_map_record(item: &ProjectionMapRecord) -> Result<()> { - store_payload( - "projections", - &item.id, - "projection_map_record.v1", - item, - LocusOpcode::RouteLedger, - ) -} -pub fn load_projection_map_record(id: &str) -> Result { - load_payload("projections", id, LocusOpcode::RouteLedger) -} -pub fn list_projection_map_records() -> Result> { - list_ids("projections") -} - -pub fn persist_benchmark_run_record(item: &BenchmarkRunRecord) -> Result<()> { - store_payload( - "benchmark_runs", - &item.id, - "benchmark_run_record.v1", - item, - LocusOpcode::ReceiptTable, - ) -} -pub fn load_benchmark_run_record(id: &str) -> Result { - load_payload("benchmark_runs", id, LocusOpcode::ReceiptTable) -} -pub fn list_benchmark_run_records() -> Result> { - list_ids("benchmark_runs") -} - -pub fn persist_handoff_packet(item: &HandoffPacket) -> Result<()> { - store_payload( - "handoff", - &item.id, - "handoff_packet.v1", - item, - LocusOpcode::CanonicalPayload, - ) -} -pub fn load_handoff_packet(id: &str) -> Result { - load_payload("handoff", id, LocusOpcode::CanonicalPayload) -} -pub fn list_handoff_packets() -> Result> { - list_ids("handoff") -} - -pub fn persist_producer_host_spec(item: &ProducerHostSpec) -> Result<()> { - store_payload( - "producer_hosts", - &item.id, - "producer_host_spec.v1", - item, - LocusOpcode::CanonicalPayload, - ) -} -pub fn load_producer_host_spec(id: &str) -> Result { - load_payload("producer_hosts", id, LocusOpcode::CanonicalPayload) -} -pub fn list_producer_host_specs() -> Result> { - list_ids("producer_hosts") -} - -pub fn persist_promotion_queue_entry(item: &PromotionQueueEntry) -> Result<()> { - store_payload( - "promotion_queue", - &item.id, - "promotion_queue_entry.v1", - item, - LocusOpcode::Coverage, - ) -} -pub fn load_promotion_queue_entry(id: &str) -> Result { - load_payload("promotion_queue", id, LocusOpcode::Coverage) -} -pub fn list_promotion_queue_entries() -> Result> { - list_ids("promotion_queue") -} - -pub fn persist_promotion_readiness_report(item: &PromotionReadinessReport) -> Result<()> { - store_payload( - "promotion_reports", - &item.subject_id, - "promotion_readiness_report.v1", - item, - LocusOpcode::Coverage, - ) -} -pub fn load_promotion_readiness_report(id: &str) -> Result { - load_payload("promotion_reports", id, LocusOpcode::Coverage) -} -pub fn list_promotion_readiness_reports() -> Result> { - list_ids("promotion_reports") -} - -pub fn persist_route_assignment(item: &RouteAssignment) -> Result<()> { - store_payload( - "route_assignments", - &item.task_id, - "route_assignment.v1", - item, - LocusOpcode::Coverage, - ) -} -pub fn load_route_assignment(id: &str) -> Result { - load_payload("route_assignments", id, LocusOpcode::Coverage) -} -pub fn list_route_assignments() -> Result> { - list_ids("route_assignments") -} - -pub fn persist_strengthening_artifact(item: &StrengtheningArtifact) -> Result<()> { - store_payload( - "strengthening", - &item.id, - "strengthening_artifact.v1", - item, - LocusOpcode::CanonicalPayload, - ) -} -pub fn load_strengthening_artifact(id: &str) -> Result { - load_payload("strengthening", id, LocusOpcode::CanonicalPayload) -} -pub fn list_strengthening_artifacts() -> Result> { - list_ids("strengthening") -} - -pub fn persist_reproducibility_packet(item: &ReproducibilityPacket) -> Result<()> { - store_payload( - "repro", - &item.id, - "reproducibility_packet.v1", - item, - LocusOpcode::ReceiptTable, - ) -} -pub fn load_reproducibility_packet(id: &str) -> Result { - load_payload("repro", id, LocusOpcode::ReceiptTable) -} -pub fn list_reproducibility_packets() -> Result> { - list_ids("repro") -} - -pub fn persist_remediation_entry(item: &RemediationLedgerEntry) -> Result<()> { - store_payload( - "remediation", - &item.id, - "remediation_ledger_entry.v1", - item, - LocusOpcode::Coverage, - ) -} -pub fn load_remediation_entry(id: &str) -> Result { - load_payload("remediation", id, LocusOpcode::Coverage) -} -pub fn list_remediation_entries() -> Result> { - list_ids("remediation") -} - -pub fn persist_coverage_dispatch(item: &ProofCoverageDispatch) -> Result<()> { - store_payload( - "coverage_dispatch", - &item.subject_id, - "proof_coverage_dispatch.v1", - item, - LocusOpcode::Coverage, - ) -} -pub fn load_coverage_dispatch(id: &str) -> Result { - load_payload("coverage_dispatch", id, LocusOpcode::Coverage) -} -pub fn list_coverage_dispatches() -> Result> { - list_ids("coverage_dispatch") -} - -pub fn persist_vertical_bundle(subject_id: &str, item: &VerticalCompoundingBundle) -> Result<()> { - store_payload( - "tower", - subject_id, - "vertical_compounding_bundle.v1", - item, - LocusOpcode::Frontier, - ) -} -pub fn load_vertical_bundle(id: &str) -> Result { - load_payload("tower", id, LocusOpcode::Frontier) -} -pub fn list_vertical_bundles() -> Result> { - list_ids("tower") -} - -pub fn persist_lineage_record(item: &ResearchLineageRecord) -> Result<()> { - store_payload( - "lineage", - &item.id, - "research_lineage_record.v1", - item, - LocusOpcode::Forensic, - ) -} -pub fn load_lineage_record(id: &str) -> Result { - load_payload("lineage", id, LocusOpcode::Forensic) -} -pub fn list_lineage_records() -> Result> { - list_ids("lineage") -} - -fn subject_like_matches(value: &str, subject: &str) -> bool { - value == subject || value.contains(subject) || subject.contains(value) -} - -fn subject_variants(seed: &str) -> Vec { - let mut out = vec![seed.to_string()]; - if let Some((_, suffix)) = seed.split_once('_') { - out.push(suffix.to_string()); - } - out.sort(); - out.dedup(); - out -} - -fn any_subject_match<'a>(value: &str, subjects: impl IntoIterator) -> bool { - subjects - .into_iter() - .any(|subject| subject_like_matches(value, subject)) -} - -fn lineage_ref_for_subject(subject_id: &str) -> String { - format!("lineage:LIN_{subject_id}") -} - -struct GovernanceState { - registry_entries: Vec, - challenges: Vec, - reviews: Vec, - repro: Vec, - strengthening: Vec, - remediation: Vec, - benchmark_runs: Vec, - claims: Vec, - reductions: Vec, - projections: Vec, - handoffs: Vec, - producer_hosts: Vec, - promotion_queue: Vec, - _promotion_reports: Vec, - coverage_dispatches: Vec, - tower_bundles: Vec<(String, VerticalCompoundingBundle)>, - _lineage_records: Vec, -} - -fn load_governance_state() -> Result { - Ok(GovernanceState { - registry_entries: list_framework_registry_entries()? - .into_iter() - .filter_map(|id| load_framework_registry_entry(&id).ok()) - .collect(), - challenges: list_challenge_records()? - .into_iter() - .filter_map(|id| load_challenge_record(&id).ok()) - .collect(), - reviews: list_review_receipts()? - .into_iter() - .filter_map(|id| load_review_receipt(&id).ok()) - .collect(), - repro: list_reproducibility_packets()? - .into_iter() - .filter_map(|id| load_reproducibility_packet(&id).ok()) - .collect(), - strengthening: list_strengthening_artifacts()? - .into_iter() - .filter_map(|id| load_strengthening_artifact(&id).ok()) - .collect(), - remediation: list_remediation_entries()? - .into_iter() - .filter_map(|id| load_remediation_entry(&id).ok()) - .collect(), - benchmark_runs: list_benchmark_run_records()? - .into_iter() - .filter_map(|id| load_benchmark_run_record(&id).ok()) - .collect(), - claims: list_math_claim_packets()? - .into_iter() - .filter_map(|id| load_math_claim_packet(&id).ok()) - .collect(), - reductions: list_reduction_map_records()? - .into_iter() - .filter_map(|id| load_reduction_map_record(&id).ok()) - .collect(), - projections: list_projection_map_records()? - .into_iter() - .filter_map(|id| load_projection_map_record(&id).ok()) - .collect(), - handoffs: list_handoff_packets()? - .into_iter() - .filter_map(|id| load_handoff_packet(&id).ok()) - .collect(), - producer_hosts: list_producer_host_specs()? - .into_iter() - .filter_map(|id| load_producer_host_spec(&id).ok()) - .collect(), - promotion_queue: list_promotion_queue_entries()? - .into_iter() - .filter_map(|id| load_promotion_queue_entry(&id).ok()) - .collect(), - _promotion_reports: list_promotion_readiness_reports()? - .into_iter() - .filter_map(|id| load_promotion_readiness_report(&id).ok()) - .collect(), - coverage_dispatches: list_coverage_dispatches()? - .into_iter() - .filter_map(|id| load_coverage_dispatch(&id).ok()) - .collect(), - tower_bundles: list_vertical_bundles()? - .into_iter() - .filter_map(|id| { - load_vertical_bundle(&id) - .ok() - .map(|bundle| (id.clone(), bundle)) - }) - .collect(), - _lineage_records: list_lineage_records()? - .into_iter() - .filter_map(|id| load_lineage_record(&id).ok()) - .collect(), - }) -} - -pub fn score_routes( - task: &TaskEnvelope, - signature: &DerivationSignature, - open_challenges: &[ChallengeRecord], - registry_entries: &[FrameworkRegistryEntry], - reviews: &[ReviewReceipt], - repro_packets: &[ReproducibilityPacket], - strengthening: &[StrengtheningArtifact], - remediation: &[RemediationLedgerEntry], -) -> RouteAssignment { - score_routes_internal( - task, - signature, - open_challenges, - registry_entries, - reviews, - repro_packets, - strengthening, - remediation, - &[], - &[], - &[], - &[], - &[], - &[], - &[], - &[], - &[], - ) -} - -fn score_routes_internal( - task: &TaskEnvelope, - signature: &DerivationSignature, - open_challenges: &[ChallengeRecord], - registry_entries: &[FrameworkRegistryEntry], - reviews: &[ReviewReceipt], - repro_packets: &[ReproducibilityPacket], - strengthening: &[StrengtheningArtifact], - remediation: &[RemediationLedgerEntry], - benchmark_runs: &[BenchmarkRunRecord], - claims: &[MathClaimPacket], - reductions: &[ReductionMapRecord], - projections: &[ProjectionMapRecord], - handoffs: &[HandoffPacket], - producer_hosts: &[ProducerHostSpec], - promotion_queue: &[PromotionQueueEntry], - coverage_dispatches: &[ProofCoverageDispatch], - tower_bundles: &[(String, VerticalCompoundingBundle)], -) -> RouteAssignment { - let challenge_penalty = open_challenges - .iter() - .filter(|item| { - matches!( - item.severity, - ChallengeSeverity::Blocking | ChallengeSeverity::High - ) && (item.target_ref == task.id || item.target_ref == signature.task_ref) - }) - .count() as f64; - let open_risk_penalty = registry_entries - .iter() - .find(|item| item.id == task.id || item.id == signature.task_ref) - .map(|item| item.open_risks.len() as f64) - .unwrap_or(0.0); - let review_bonus = reviews - .iter() - .filter(|item| item.subject_ref == signature.task_ref || item.subject_ref == task.id) - .count() as f64; - let repro_bonus = repro_packets - .iter() - .filter(|item| { - item.claim_packet_id == signature.task_ref || item.claim_packet_id == task.id - }) - .count() as f64; - let strengthening_bonus = strengthening - .iter() - .filter(|item| item.source_ref == signature.task_ref || item.source_ref == task.id) - .count() as f64; - let remediation_pressure = remediation - .iter() - .filter(|item| { - !matches!( - item.status, - RemediationStatus::Verified | RemediationStatus::Deferred - ) - }) - .count() as f64; - let mut subject_keys = Vec::new(); - subject_keys.extend(subject_variants(&task.id)); - subject_keys.extend(subject_variants(&signature.task_ref)); - subject_keys.sort(); - subject_keys.dedup(); - let benchmark_support = benchmark_runs - .iter() - .filter(|item| any_subject_match(&item.theorem_id, subject_keys.iter())) - .count() as f64; - let claim_support = claims - .iter() - .filter(|item| { - any_subject_match(&item.id, subject_keys.iter()) - || item - .report_refs - .iter() - .any(|r| any_subject_match(r, subject_keys.iter())) - }) - .count() as f64; - let reduction_support = reductions - .iter() - .filter(|item| any_subject_match(&item.theorem_id, subject_keys.iter())) - .count() as f64; - let projection_support = projections - .iter() - .filter(|item| any_subject_match(&item.theorem_id, subject_keys.iter())) - .count() as f64; - let handoff_support = handoffs - .iter() - .filter(|item| any_subject_match(&item.subject_id, subject_keys.iter())) - .count() as f64; - let producer_support = producer_hosts - .iter() - .filter(|item| { - item.feeds - .iter() - .any(|f| any_subject_match(f, subject_keys.iter())) - || item - .owned_objects - .iter() - .any(|f| any_subject_match(f, subject_keys.iter())) - || any_subject_match(&item.purpose, subject_keys.iter()) - }) - .count() as f64; - let ready_promotion = promotion_queue - .iter() - .filter(|item| { - matches!(item.status, PromotionQueueStatus::Ready) - && any_subject_match(&item.subject_id, subject_keys.iter()) - }) - .count() as f64; - let blocked_promotion = promotion_queue - .iter() - .filter(|item| { - matches!(item.status, PromotionQueueStatus::Blocked) - && any_subject_match(&item.subject_id, subject_keys.iter()) - }) - .count() as f64; - let exact_coverage = coverage_dispatches - .iter() - .filter(|item| { - item.route_fast_path && any_subject_match(&item.subject_id, subject_keys.iter()) - }) - .count() as f64; - let unsupported_coverage = coverage_dispatches - .iter() - .filter(|item| { - matches!(item.decision, l64_core::CoverageDecision::Unsupported) - && any_subject_match(&item.subject_id, subject_keys.iter()) - }) - .count() as f64; - let tower_pressure = tower_bundles - .iter() - .filter(|(id, _)| any_subject_match(id, subject_keys.iter())) - .count() as f64; - - let mut routes = vec![ - ResearchRouteClass::Derive, - ResearchRouteClass::Benchmark, - ResearchRouteClass::Stress, - ResearchRouteClass::ChallengeResponse, - ResearchRouteClass::Crystallize, - ResearchRouteClass::Integrate, - ResearchRouteClass::OperationalHardening, - ResearchRouteClass::Retire, - ]; - - let mut scores = Vec::new(); - for route in routes.drain(..) { - let mut fit = 0.0; - let mut leverage = 0.0; - let mut risk = 0.0; - let mut cost = 0.0; - let mut debt = 0.0; - let mut reasons = Vec::new(); - - match route { - ResearchRouteClass::Derive => { - if matches!( - task.objective_kind, - ObjectiveKind::Derive | ObjectiveKind::Reduce - ) { - fit += 4.0; - reasons.push("objective directly requests derivation/reduction".into()); - } - if matches!( - signature.structural_type, - l64_core::DerivationStructuralType::Projection - | l64_core::DerivationStructuralType::Closure - | l64_core::DerivationStructuralType::Reduction - ) { - fit += 3.0; - reasons.push("signature is derivation-native".into()); - } - if matches!( - signature.expected_distillate, - DesiredOutputKind::Theorem | DesiredOutputKind::ReductionMap - ) { - leverage += 2.5; - } - leverage += 0.5 * strengthening_bonus; - risk += challenge_penalty + open_risk_penalty; - cost += signature.dependency_depth as f64 * 0.5; - } - ResearchRouteClass::Benchmark => { - if matches!(task.objective_kind, ObjectiveKind::Benchmark) { - fit += 5.0; - } - if matches!( - signature.structural_type, - l64_core::DerivationStructuralType::BenchmarkFit - ) { - fit += 3.0; - } - leverage += 1.5 + repro_bonus; - debt += open_risk_penalty * 0.25; - cost += 1.5; - } - ResearchRouteClass::Stress => { - if matches!(task.objective_kind, ObjectiveKind::Stress) { - fit += 5.0; - } - leverage += 2.0 + 0.5 * repro_bonus; - risk += 0.5 * challenge_penalty; - cost += 2.0; - reasons.push("stress lowers future promotion error".into()); - } - ResearchRouteClass::ChallengeResponse => { - if challenge_penalty > 0.0 { - fit += 6.0; - } - if matches!( - signature.structural_type, - l64_core::DerivationStructuralType::ChallengeResponse - | l64_core::DerivationStructuralType::OperationalHardening - ) { - fit += 3.0; - } - leverage += 2.0; - debt += open_risk_penalty + remediation_pressure * 0.2; - cost += 1.0; - } - ResearchRouteClass::Crystallize => { - if matches!( - task.objective_kind, - ObjectiveKind::Crystallize | ObjectiveKind::Integrate - ) { - fit += 4.0; - } - if matches!( - signature.expected_distillate, - DesiredOutputKind::Operator - | DesiredOutputKind::BenchmarkSchema - | DesiredOutputKind::Battery - ) { - leverage += 4.0; - } - leverage += review_bonus + strengthening_bonus; - cost += 1.5; - reasons.push("crystallization converts success into reusable law".into()); - } - ResearchRouteClass::Integrate => { - if matches!( - task.objective_kind, - ObjectiveKind::Integrate | ObjectiveKind::Promote - ) { - fit += 4.0; - } - leverage += 3.0 + review_bonus + repro_bonus; - debt += open_risk_penalty * 0.5; - cost += 2.0; - } - ResearchRouteClass::OperationalHardening => { - if matches!( - signature.structural_type, - l64_core::DerivationStructuralType::OperationalHardening - | l64_core::DerivationStructuralType::RegistryHardening - ) { - fit += 5.0; - } - leverage += 2.5; - debt += remediation_pressure + challenge_penalty * 0.5; - cost += 1.0; - reasons.push( - "operational hardening lowers false blocker and artifact ambiguity costs" - .into(), - ); - } - ResearchRouteClass::Retire => { - if matches!(task.objective_kind, ObjectiveKind::Refute) { - fit += 4.0; - } - risk += 1.0; - cost += 0.5; - reasons.push( - "retire only when evidence says a route should stop consuming budget".into(), - ); - } - } - - leverage += 0.25 * benchmark_support - + 0.2 * claim_support - + 0.2 * reduction_support - + 0.15 * projection_support; - leverage += 0.2 * handoff_support - + 0.15 * producer_support - + 0.3 * ready_promotion - + 0.2 * exact_coverage; - debt += 0.25 * blocked_promotion + 0.2 * unsupported_coverage + 0.1 * tower_pressure; - if benchmark_support > 0.0 { - reasons.push(format!("benchmark support={benchmark_support}")); - } - if exact_coverage > 0.0 { - reasons.push("coverage fast-path exists".into()); - } - if blocked_promotion > 0.0 { - reasons.push("blocked promotion is still present in warm state".into()); - } - if review_bonus > 0.0 { - leverage += review_bonus * 0.25; - reasons.push(format!("review-support x{review_bonus}")); - } - if repro_bonus > 0.0 { - leverage += repro_bonus * 0.25; - reasons.push(format!("repro-support x{repro_bonus}")); - } - if strengthening_bonus > 0.0 { - leverage += strengthening_bonus * 0.25; - reasons.push(format!("strengthening-support x{strengthening_bonus}")); - } - - let total = fit + leverage - risk - cost - debt; - scores.push(RouteScore { - route, - fit, - leverage, - risk, - cost, - debt, - total, - reasons, - }); - } - - scores.sort_by(|a, b| { - b.total - .partial_cmp(&a.total) - .unwrap_or(std::cmp::Ordering::Equal) - }); - let recommended_route = scores - .first() - .map(|item| item.route) - .unwrap_or(ResearchRouteClass::Derive); - RouteAssignment { - task_id: task.id.clone(), - signature_id: signature.id.clone(), - recommended_route, - scores, - } -} - -pub fn score_routes_governed( - task: &TaskEnvelope, - signature: &DerivationSignature, -) -> Result { - let state = load_governance_state()?; - Ok(score_routes_internal( - task, - signature, - &state.challenges, - &state.registry_entries, - &state.reviews, - &state.repro, - &state.strengthening, - &state.remediation, - &state.benchmark_runs, - &state.claims, - &state.reductions, - &state.projections, - &state.handoffs, - &state.producer_hosts, - &state.promotion_queue, - &state.coverage_dispatches, - &state.tower_bundles, - )) -} - -pub fn derive_task_envelope_from_report(report: &CertificationReport) -> TaskEnvelope { - let objective_kind = if !report.deficiencies.is_empty() { - ObjectiveKind::Reduce - } else if !report.promotion_artifact_ids.is_empty() - || matches!( - report.verdict, - l64_core::CertificationVerdict::Integrated | l64_core::CertificationVerdict::Certified - ) - { - ObjectiveKind::Promote - } else if !report.benchmark_receipt_ids.is_empty() { - ObjectiveKind::Integrate - } else { - ObjectiveKind::Derive - }; - let desired_output = if !report.promotion_artifact_ids.is_empty() { - DesiredOutputKind::Operator - } else if !report.benchmark_receipt_ids.is_empty() { - DesiredOutputKind::BenchmarkSchema - } else { - DesiredOutputKind::Theorem - }; - TaskEnvelope { - id: format!("TSK_{}", report.theorem_id), - title: format!("govern {}", report.theorem_id), - target_sector: if report - .selected_path - .iter() - .any(|h| h.contains("PROB") || h.contains("COMP") || h.contains("LOG")) - { - l64_core::ResearchSector::Crosscut - } else { - l64_core::ResearchSector::Control - }, - objective_kind, - desired_output, - hard_constraints: vec![format!("verdict:{:?}", report.verdict)], - soft_constraints: vec![format!( - "benchmark_receipts:{}", - report.benchmark_receipt_ids.len() - )], - promotion_target: report.verdict.clone(), - rollback_path: format!("report:{}", report.theorem_id), - success_metrics: vec![ - "warm-host governance closure".into(), - "promotion readiness".into(), - ], - } -} - -pub fn derive_derivation_signature_from_report( - report: &CertificationReport, - task: &TaskEnvelope, -) -> DerivationSignature { - let structural_type = if !report.deficiencies.is_empty() { - l64_core::DerivationStructuralType::OperationalHardening - } else if !report.challenge_receipt_ids.is_empty() { - l64_core::DerivationStructuralType::ChallengeResponse - } else if !report.benchmark_receipt_ids.is_empty() { - l64_core::DerivationStructuralType::BenchmarkFit - } else if report.route_class_id.is_some() || !report.selected_path.is_empty() { - l64_core::DerivationStructuralType::Projection - } else { - l64_core::DerivationStructuralType::Closure - }; - let risk_class = if !report.deficiencies.is_empty() { - l64_core::RiskClass::High - } else { - l64_core::RiskClass::Medium - }; - DerivationSignature { - id: format!("SIG_{}", report.theorem_id), - task_ref: task.id.clone(), - structural_type, - sector: task.target_sector, - risk_class, - dependency_depth: report.deficiencies.len() + report.obligations.len(), - likely_failure_modes: report - .deficiencies - .iter() - .map(|d| format!("{:?}", d.class)) - .collect(), - expected_distillate: task.desired_output, - evidence_gap: vec![ - (!report.checker_receipts.is_empty() || !report.obligations.is_empty()) - .then(|| "analytic".to_string()), - report - .benchmark_receipt_ids - .is_empty() - .then(|| "numeric".to_string()), - report - .challenge_receipt_ids - .is_empty() - .then(|| "stress".to_string()), - Some("empirical".to_string()), - ] - .into_iter() - .flatten() - .collect(), - } -} - -pub fn derive_framework_registry_entry_from_report( - report: &CertificationReport, -) -> FrameworkRegistryEntry { - let status = match report.verdict { - l64_core::CertificationVerdict::Integrated => RegistryEntryStatus::Integrated, - l64_core::CertificationVerdict::Certified => RegistryEntryStatus::Certified, - l64_core::CertificationVerdict::BlockedOpen => RegistryEntryStatus::Blocked, - _ => RegistryEntryStatus::Derived, - }; - FrameworkRegistryEntry { - id: report.theorem_id.clone(), - kind: RegistryEntryKind::MathClaim, - host: "Locus Kernel".into(), - status, - retained_value: format!("campaign/theorem truth for {}", report.theorem_id), - open_risks: report - .deficiencies - .iter() - .map(|d| d.message.clone()) - .collect(), - dependencies: report - .obligations - .iter() - .map(|o| o.obligation_id.clone()) - .collect(), - last_receipt: report.checker_receipts.last().map(|r| r.id.clone()), - } -} - -pub fn derive_operator_record_from_report(report: &CertificationReport) -> OperatorRecord { - let semantics = if report.selected_path.is_empty() { - "report has no selected path; operator remains report-local".to_string() - } else { - format!( - "selected normalized path {}", - report.selected_path.join(" -> ") - ) - }; - OperatorRecord { - id: format!("OPR_DERIVED_{}", report.theorem_id), - name: format!("Derived operator from {}", report.theorem_id), - semantics, - valid_regimes: report.selected_atlas_cell.iter().cloned().collect(), - evidence_level: report.verdict.clone(), - dependencies: report.burden_pack_ids.clone(), - failure_modes: report - .deficiencies - .iter() - .map(|d| d.message.clone()) - .collect(), - reuse_count: report.promotion_artifact_ids.len(), - implementation_refs: report.promotion_artifact_ids.clone(), - } -} - -pub fn derive_review_receipt_from_report(report: &CertificationReport) -> ReviewReceipt { - let verdict = match report.verdict { - l64_core::CertificationVerdict::Integrated | l64_core::CertificationVerdict::Certified => { - ReviewDecision::Proceed - } - l64_core::CertificationVerdict::BlockedOpen => ReviewDecision::Hold, - _ => ReviewDecision::Revise, - }; - let mut notes = Vec::new(); - notes.extend(report.reasons.clone()); - notes.extend(report.diagnostics.clone()); - if notes.is_empty() { - notes.push("synthetic review receipt derived from certification report".into()); - } - let (fit, risk, capture, continuity) = match report.verdict { - l64_core::CertificationVerdict::Integrated | l64_core::CertificationVerdict::Certified => ( - ReviewStatus::Pass, - if report.deficiencies.is_empty() { - ReviewStatus::Pass - } else { - ReviewStatus::Revise - }, - ReviewStatus::Pass, - if report.replay_divergence_records.is_empty() { - ReviewStatus::Pass - } else { - ReviewStatus::Revise - }, - ), - l64_core::CertificationVerdict::BlockedOpen => ( - ReviewStatus::Revise, - ReviewStatus::Revise, - ReviewStatus::Pass, - ReviewStatus::Revise, - ), - _ => ( - ReviewStatus::Revise, - ReviewStatus::Revise, - ReviewStatus::Revise, - ReviewStatus::Revise, - ), - }; - ReviewReceipt { - id: format!("REV_{}", report.theorem_id), - subject_ref: report.theorem_id.clone(), - fit_review: fit, - risk_review: risk, - capture_review: capture, - continuity_review: continuity, - notes, - reviewers: vec!["Locus Kernel synthetic reviewer".into()], - verdict, - } -} - -pub fn derive_reproducibility_packet_from_report( - report: &CertificationReport, -) -> ReproducibilityPacket { - let mut artifact_refs = Vec::new(); - artifact_refs.extend(report.promotion_artifact_ids.clone()); - artifact_refs.extend(report.reused_artifact_ids.clone()); - artifact_refs.extend(report.default_selected_artifact_ids.clone()); - artifact_refs.extend(report.payoff_receipt_ids.clone()); - if let Some(id) = &report.certificate_id { - artifact_refs.push(id.clone()); - } - if let Some(id) = &report.route_class_id { - artifact_refs.push(id.clone()); - } - artifact_refs.push(report.target_profile_id.clone()); - if let Some(id) = &report.campaign_id { - artifact_refs.push(id.clone()); - } - ReproducibilityPacket { - id: format!("RPR_{}", report.theorem_id), - claim_packet_id: report.theorem_id.clone(), - derivation_path: report.selected_path.clone(), - code_refs: report - .route_class_id - .iter() - .cloned() - .chain(report.certificate_id.iter().cloned()) - .collect(), - benchmark_refs: report.benchmark_receipt_ids.clone(), - artifact_refs, - } -} - -pub fn derive_challenge_record_from_report( - report: &CertificationReport, -) -> Option { - let grounds = if !report.deficiencies.is_empty() { - Some(ChallengeGrounds::ProjectionAmbiguity) - } else if !report.diagnostics.is_empty() { - Some(ChallengeGrounds::UnsupportedGeneralization) - } else if matches!( - report.verdict, - l64_core::CertificationVerdict::BlockedOpen - | l64_core::CertificationVerdict::BlockedContradiction - ) { - Some(ChallengeGrounds::PromotionMismatch) - } else { - None - }?; - let severity = match report.verdict { - l64_core::CertificationVerdict::BlockedContradiction => ChallengeSeverity::Blocking, - l64_core::CertificationVerdict::BlockedOpen => ChallengeSeverity::High, - _ if !report.deficiencies.is_empty() => ChallengeSeverity::Medium, - _ => ChallengeSeverity::Low, - }; - let mut evidence_refs = Vec::new(); - evidence_refs.extend(report.challenge_receipt_ids.clone()); - evidence_refs.extend(report.benchmark_receipt_ids.clone()); - evidence_refs.extend(report.reproducibility_packet_ids.clone()); - evidence_refs.extend(report.payoff_receipt_ids.clone()); - Some(ChallengeRecord { - id: format!("CHG_{}", report.theorem_id), - target_ref: report.theorem_id.clone(), - grounds, - severity, - evidence_refs, - required_response: if matches!( - report.verdict, - l64_core::CertificationVerdict::BlockedContradiction - ) { - ResponseClass::Rollback - } else if !report.deficiencies.is_empty() { - ResponseClass::Patch - } else { - ResponseClass::Benchmark - }, - status: ChallengeStatus::Open, - }) -} - -pub fn derive_strengthening_artifacts_from_report( - report: &CertificationReport, -) -> Vec { - let mut out = Vec::new(); - out.push(StrengtheningArtifact { - id: format!("STR_ROUTE_{}", report.theorem_id), - source_ref: report.theorem_id.clone(), - kind: DesiredOutputKind::ReductionMap, - inheritance_targets: report.selected_atlas_cell.iter().cloned().collect(), - redistribution_notes: "route/result residue should remain reusable above one report".into(), - }); - if !report.checker_receipts.is_empty() { - out.push(StrengtheningArtifact { - id: format!("STR_BATTERY_{}", report.theorem_id), - source_ref: report.theorem_id.clone(), - kind: DesiredOutputKind::Battery, - inheritance_targets: report - .checker_receipts - .iter() - .map(|r| r.id.clone()) - .collect(), - redistribution_notes: "checker-side success should remain as reusable validation law" - .into(), - }); - } - out -} - -pub fn seed_export_remediation_entries() -> Vec { - vec![ - RemediationLedgerEntry { - id: "REM_EXPORT_EXPLAIN_EXECUTION".into(), - source_ref: "Chat export stress test".into(), - class: RemediationClass::RuntimeBug, - summary: "explain-execution should resolve execution-linked context or degrade with exact contract truth instead of generic missing-file failure".into(), - affected_surfaces: vec!["l64-admin explain-execution".into(), "execution cache".into(), "observation/report/manifest/lock resolution".into()], - expected_fix_chain: vec!["export_remediation_ledger".into(), "operational_truth_hardening".into(), "execution_resolution_truth".into()], - status: RemediationStatus::InProgress, - notes: vec!["export reported repeated os error 2 across report/manifest/lock/observe inputs".into()], - }, - RemediationLedgerEntry { - id: "REM_EXPORT_VALIDATE_INSPECTION_REPORT".into(), - source_ref: "Chat export stress test".into(), - class: RemediationClass::ArtifactTypingBug, - summary: "export-report surfaces should stay inspection-only unless explicitly widened into validation-complete bundles".into(), - affected_surfaces: vec!["l64-cli export-report".into(), "l64-cli export-validation-bundle".into(), "l64-cli validate".into()], - expected_fix_chain: vec!["artifact_class_law".into(), "validation_bundle_rollout".into(), "overlay_validation_truth".into()], - status: RemediationStatus::InProgress, - notes: vec!["export reported validate failure because theorem/route context was not fully embedded in inspection exports".into()], - }, - RemediationLedgerEntry { - id: "REM_EXPORT_PREDICT_IMPACT_CONTRACT".into(), - source_ref: "Chat export stress test".into(), - class: RemediationClass::CommandContractBug, - summary: "predict-impact must expose a live argument contract stronger than help text and reject ambiguous selector combinations cleanly".into(), - affected_surfaces: vec!["l64-admin predict-impact".into(), "command contract surfaces".into()], - expected_fix_chain: vec!["command_contract_truth".into(), "capability_readiness_truth".into()], - status: RemediationStatus::InProgress, - notes: vec!["export said command was help-routable but live argument contract was unresolved".into()], - }, - RemediationLedgerEntry { - id: "REM_EXPORT_CAPABILITY_TRUTH".into(), - source_ref: "Chat export stress test".into(), - class: RemediationClass::CapabilityTruthGap, - summary: "commands should distinguish declared, help-routable, contract-known, smoke-executed, and fully-exercised support instead of one flat supported flag".into(), - affected_surfaces: vec!["capability matrices".into(), "command contracts".into(), "stress harness summaries".into()], - expected_fix_chain: vec!["capability_readiness_truth".into(), "research_registry_visibility".into()], - status: RemediationStatus::Open, - notes: vec!["export corrected earlier false failures caused by help-only or misused commands".into()], - }, - RemediationLedgerEntry { - id: "REM_EXPORT_NAMESPACE_CONTRACT".into(), - source_ref: "Chat export stress test".into(), - class: RemediationClass::RuntimeBug, - summary: "namespace-local execution, report, and observation artifacts need explicit same-namespace truth to prevent false blocker signals and harness misuse".into(), - affected_surfaces: vec!["observe-run".into(), "admin compare/export flows".into(), "execution record lookup".into()], - expected_fix_chain: vec!["namespace_scope_truth".into(), "execution_contracts".into()], - status: RemediationStatus::Open, - notes: vec!["export reported same-namespace constraints and one false race-style blocker".into()], - }, - RemediationLedgerEntry { - id: "REM_EXPORT_TRUST_MARGIN_ROLES".into(), - source_ref: "Kineton calibration export".into(), - class: RemediationClass::SemanticBug, - summary: "trust parsing must distinguish error-like residuals from success margins, physical scales, coverage-like measures, and control roles".into(), - affected_surfaces: vec!["benchmark receipts".into(), "trust vectors".into(), "calibration reports".into()], - expected_fix_chain: vec!["metric_role_schema".into(), "benchmark_schema_normalization".into()], - status: RemediationStatus::Open, - notes: vec!["export specifically called out gap vs separation_margin, negative controls, physical scale, and coverage semantics".into()], - }, - RemediationLedgerEntry { - id: "REM_EXPORT_MATH_NATIVE_CLAIMS".into(), - source_ref: "Kineton framework export".into(), - class: RemediationClass::MissingFunctionality, - summary: "claim objects need first-class mathematical bodies, assumptions, projection/reduction maps, and blocker leaves so orchestration does not outrun the actual math".into(), - affected_surfaces: vec!["claim packets".into(), "research registry".into(), "handoff packets".into()], - expected_fix_chain: vec!["warm_research_host".into(), "math_native_claim_semantics".into()], - status: RemediationStatus::Open, - notes: vec!["export repeatedly resisted generic claim shells divorced from real obligations like G2*, D1, R1, K0".into()], - }, - RemediationLedgerEntry { - id: "REM_EXPORT_WARM_HOST_GAP".into(), - source_ref: "Kineton framework export".into(), - class: RemediationClass::MissingFunctionality, - summary: "the cold certifier needs a real warm research host for intake, routing, challenge, registry, benchmark, and handoff rather than implicit chat-side orchestration".into(), - affected_surfaces: vec!["l64-research".into(), "routing".into(), "challenge workflow".into(), "registry".into()], - expected_fix_chain: vec!["research_constitution_host".into(), "registry_distillate_repro_host".into()], - status: RemediationStatus::InProgress, - notes: vec!["export stated K2 is stronger as a cold certifier than as a full research host".into()], - }, - ] -} - -pub fn persist_seeded_export_remediation_entries() -> Result> { - let entries = seed_export_remediation_entries(); - for item in &entries { - persist_remediation_entry(item)?; - } - Ok(entries) -} - -pub fn summarize_remediation_entries(entries: &[RemediationLedgerEntry]) -> serde_json::Value { - use std::collections::BTreeMap; - let mut by_class: BTreeMap = BTreeMap::new(); - let mut by_status: BTreeMap = BTreeMap::new(); - for item in entries { - *by_class.entry(format!("{:?}", item.class)).or_default() += 1; - *by_status.entry(format!("{:?}", item.status)).or_default() += 1; - } - serde_json::json!({ - "count": entries.len(), - "by_class": by_class, - "by_status": by_status, - "ids": entries.iter().map(|item| item.id.clone()).collect::>(), - }) -} - -pub fn derive_research_bundle_from_report( - report: &CertificationReport, -) -> ( - FrameworkRegistryEntry, - OperatorRecord, - Vec, - ReproducibilityPacket, - ReviewReceipt, - Option, -) { - ( - derive_framework_registry_entry_from_report(report), - derive_operator_record_from_report(report), - derive_strengthening_artifacts_from_report(report), - derive_reproducibility_packet_from_report(report), - derive_review_receipt_from_report(report), - derive_challenge_record_from_report(report), - ) -} - -pub fn derive_lineage_record_from_report(report: &CertificationReport) -> ResearchLineageRecord { - let subject_id = report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()); - let canonical_hash = report - .execution_envelope - .as_ref() - .map(|item| item.report_hash.clone()) - .unwrap_or_else(|| { - l64_core::role_digest_value( - l64_core::DigestRole::PayloadCommitment, - &( - &report.theorem_id, - &report.target_profile_id, - &report.verdict, - ), - ) - }); - let lowering_receipt_id = format!("RPT_LINEAGE_{}", subject_id); - let dependency_edges = report - .reproducibility_packet_ids - .iter() - .cloned() - .chain(report.checker_receipts.iter().map(|item| item.id.clone())) - .collect::>(); - let invariant_checks = vec![ - l64_core::InvariantCheck { - name: "report_hash_available".into(), - passed: !canonical_hash.is_empty(), - detail: "report lineage requires a stable execution or fallback hash".into(), - }, - l64_core::InvariantCheck { - name: "dna_backed_report".into(), - passed: report.execution_envelope.is_some() - || !report.selected_path.is_empty() - || report.certificate_id.is_some(), - detail: "report lineage must come from an executable certification path".into(), - }, - ]; - let failure_records = invariant_checks - .iter() - .filter(|check| !check.passed) - .map(|check| l64_core::FailureRecord { - code: "ReportLineageInvariantFailed".into(), - message: format!("{}: {}", check.name, check.detail), - }) - .collect::>(); - let validation_result = if failure_records.is_empty() { - l64_core::PhaseValidationResult::Passed - } else { - l64_core::PhaseValidationResult::Failed - }; - let promotion_signal = if failure_records.is_empty() { - l64_core::PromotionSignal::Promote - } else { - l64_core::PromotionSignal::Hold - }; - - ResearchLineageRecord { - id: format!("LIN_{}", subject_id), - subject_id: subject_id.clone(), - artifact_class: l64_core::GenomeArtifactClass::Gene, - source_surface: l64_core::GenomeSurface::Dna, - target_surface: l64_core::GenomeSurface::Dna, - grammar_id: "report-envelope.v1".into(), - canonical_hash: canonical_hash.clone(), - lowering_receipt_id, - phase_ids: vec![ - l64_core::PhaseId::DnaProtocolFreeze, - l64_core::PhaseId::ResearchHostReconnect, - ], - phase_ledger: vec![l64_core::ChangeLedgerEntry { - phase_id: l64_core::PhaseId::ResearchHostReconnect, - input_state_hash: canonical_hash.clone(), - output_state_hash: Some(l64_core::role_digest_value( - l64_core::DigestRole::PayloadCommitment, - &subject_id, - )), - dependency_edges, - invariant_checks, - failure_records, - validation_result, - promotion_signal, - rollback_pointer: Some(format!("report:{}", report.theorem_id)), - }], - notes: vec![ - format!("theorem_id={}", report.theorem_id), - format!("target_profile_id={}", report.target_profile_id), - format!("verdict={:?}", report.verdict), - ], - } -} - -pub fn derive_math_claim_packet_from_report(report: &CertificationReport) -> MathClaimPacket { - let sector = if report.theorem_id.contains("CHAIN") || report.theorem_id.contains("BAYES") { - l64_core::ResearchSector::Crosscut - } else if report.theorem_id.contains("PROB") { - l64_core::ResearchSector::Thermo - } else { - l64_core::ResearchSector::Control - }; - let truth_class = AuthorityState::Projection; - let mut assumptions = Vec::new(); - assumptions.extend( - report - .burden_pack_ids - .iter() - .map(|id| format!("burden_pack:{id}")), - ); - assumptions.extend(report.selected_path.iter().map(|id| format!("path:{id}"))); - assumptions.push(format!("report_verdict_projection:{:?}", report.verdict)); - let blocker_leaves = report - .deficiencies - .iter() - .map(|d| format!("{}:{:?}", d.id, d.class)) - .collect::>(); - // control-specific deficiencies collapse into the main deficiency set in this host slice. - MathClaimPacket { - id: format!("CLM_{}", report.theorem_id), - title: format!("Claim packet for {}", report.theorem_id), - statement: format!( - "{} via {:?} with verdict {:?}", - report.theorem_id, report.selected_path, report.verdict - ), - sector, - truth_class, - claim_class: ClaimClass::Host, - assumptions, - projection_refs: report.route_class_id.iter().cloned().collect(), - reduction_refs: report.selected_atlas_cell.iter().cloned().collect(), - benchmark_refs: report.benchmark_receipt_ids.clone(), - blocker_leaves, - report_refs: vec![format!("report:{}", report.theorem_id)], - } -} - -pub fn derive_reduction_map_record_from_report(report: &CertificationReport) -> ReductionMapRecord { - ReductionMapRecord { - id: format!("RDM_{}", report.theorem_id), - theorem_id: report.theorem_id.clone(), - target_profile_id: report.target_profile_id.clone(), - route_class_id: report.route_class_id.clone(), - atlas_cell_id: report.selected_atlas_cell.clone(), - derivation_path: report.selected_path.join(" -> "), - residual_obligation_ids: report - .obligations - .iter() - .filter(|s| { - !matches!( - s.verdict, - l64_core::CertificationVerdict::Integrated - | l64_core::CertificationVerdict::Certified - ) && !matches!( - s.evaluation_mode, - l64_core::ObligationEvaluationMode::RecomputedExact - ) - }) - .map(|s| s.obligation_id.clone()) - .collect(), - } -} - -pub fn derive_projection_map_record_from_report( - report: &CertificationReport, -) -> ProjectionMapRecord { - ProjectionMapRecord { - id: format!("PRJ_{}", report.theorem_id), - theorem_id: report.theorem_id.clone(), - src_hosts: if report.selected_path.is_empty() { - vec!["LocusKernel".into()] - } else { - report.selected_path.clone() - }, - tgt_hosts: if report.selected_path.is_empty() { - vec!["LocusKernel".into()] - } else { - report.selected_path.clone() - }, - projection_summary: format!( - "selected_path={:?} route_class={}", - report.selected_path, - report.route_class_id.clone().unwrap_or_default() - ), - bridge_refs: report.selected_path.clone(), - } -} - -pub fn derive_benchmark_schemas_from_report(report: &CertificationReport) -> Vec { - let mut out = Vec::new(); - for (idx, receipt_id) in report.benchmark_receipt_ids.iter().enumerate() { - out.push(BenchmarkSchema { - id: format!("BMS_{}_{}", report.theorem_id, idx + 1), - target_description: format!( - "Benchmark receipt {} for {}", - receipt_id, report.theorem_id - ), - metric_name: "benchmark_receipt_presence".into(), - tolerance: "presence-required".into(), - reference_source: receipt_id.clone(), - weight_basis_points: 1000, - required_evidence: vec![receipt_id.clone()], - }); - } - if out.is_empty() { - out.push(BenchmarkSchema { - id: format!("BMS_{}_IMPLICIT", report.theorem_id), - target_description: format!("Implicit benchmark floor for {}", report.theorem_id), - metric_name: "report_verdict_floor".into(), - tolerance: format!("{:?}", report.verdict), - reference_source: format!("report:{}", report.theorem_id), - weight_basis_points: 500, - required_evidence: vec![format!("report:{}", report.theorem_id)], - }); - } - out -} - -pub fn derive_benchmark_run_record_from_report( - report: &CertificationReport, - schema_ids: &[String], -) -> BenchmarkRunRecord { - BenchmarkRunRecord { - id: format!("BMR_{}", report.theorem_id), - theorem_id: report.theorem_id.clone(), - benchmark_schema_id: schema_ids.first().cloned(), - receipt_ids: report.benchmark_receipt_ids.clone(), - status: match report.verdict { - l64_core::CertificationVerdict::Integrated => RegistryEntryStatus::Integrated, - l64_core::CertificationVerdict::Certified => RegistryEntryStatus::Certified, - l64_core::CertificationVerdict::Benchmarked => RegistryEntryStatus::Benchmarked, - l64_core::CertificationVerdict::BlockedOpen - | l64_core::CertificationVerdict::BlockedContradiction => RegistryEntryStatus::Blocked, - _ => RegistryEntryStatus::Derived, - }, - summary: format!( - "benchmark receipts={} verdict={:?}", - report.benchmark_receipt_ids.len(), - report.verdict - ), - } -} - -pub fn derive_handoff_packet_from_report( - report: &CertificationReport, - claim: &MathClaimPacket, - operator: &OperatorRecord, - strengthening: &[StrengtheningArtifact], - repro: &ReproducibilityPacket, - benchmarks: &[BenchmarkSchema], -) -> HandoffPacket { - HandoffPacket { - id: format!("HOF_{}", report.theorem_id), - subject_id: report.theorem_id.clone(), - summary: format!( - "handoff packet for {} with verdict {:?}", - report.theorem_id, report.verdict - ), - status: PromotionQueueStatus::Proposed, - claim_refs: vec![claim.id.clone()], - operator_refs: vec![operator.id.clone()], - strengthening_refs: strengthening.iter().map(|i| i.id.clone()).collect(), - repro_refs: vec![repro.id.clone()], - benchmark_refs: benchmarks.iter().map(|i| i.id.clone()).collect(), - benchmark_run_refs: Vec::new(), - producer_host_refs: Vec::new(), - route_refs: Vec::new(), - coverage_refs: Vec::new(), - lineage_refs: Vec::new(), - tower_refs: Vec::new(), - promotion_refs: Vec::new(), - readiness_score_basis_points: 0, - blockers: Vec::new(), - positive_factors: Vec::new(), - } -} - -pub fn derive_promotion_readiness_from_report( - report: &CertificationReport, - reviews: &[ReviewReceipt], - challenges: &[ChallengeRecord], - repros: &[ReproducibilityPacket], - strengthening: &[StrengtheningArtifact], - remediation: &[RemediationLedgerEntry], -) -> PromotionReadinessReport { - let mut score: i32 = 0; - let mut positive = Vec::new(); - let mut blockers = Vec::new(); - let mut missing = Vec::new(); - let matching_reviews = reviews - .iter() - .filter(|r| r.subject_ref == report.theorem_id) - .collect::>(); - if !matching_reviews.is_empty() { - score += 1500; - positive.push("review receipt exists".into()); - if matching_reviews - .iter() - .all(|r| matches!(r.verdict, ReviewDecision::Proceed)) - { - score += 1500; - positive.push("review verdict proceed".into()); - } - } else { - missing.push("review receipt".into()); - } - let open_challenges = challenges - .iter() - .filter(|c| c.target_ref == report.theorem_id && matches!(c.status, ChallengeStatus::Open)) - .collect::>(); - if open_challenges.is_empty() { - score += 1500; - positive.push("no open challenges".into()); - } else { - blockers.extend( - open_challenges - .iter() - .map(|c| format!("challenge:{}:{:?}", c.id, c.severity)), - ); - score -= 2500; - } - if repros - .iter() - .any(|r| r.claim_packet_id == report.theorem_id) - { - score += 1000; - positive.push("reproducibility packet exists".into()); - } else { - missing.push("reproducibility packet".into()); - } - let str_count = strengthening - .iter() - .filter(|s| s.source_ref == report.theorem_id) - .count(); - if str_count > 0 { - score += 500 + (str_count as i32 * 250); - positive.push(format!("strengthening artifacts={str_count}")); - } else { - missing.push("strengthening artifact".into()); - } - let active_remediation = remediation - .iter() - .filter(|r| { - !matches!( - r.status, - RemediationStatus::Verified | RemediationStatus::Deferred - ) && r - .affected_surfaces - .iter() - .any(|s| s.contains(&report.theorem_id)) - }) - .count(); - if active_remediation > 0 { - blockers.push(format!("active_remediation={active_remediation}")); - score -= 1000; - } - if matches!( - report.verdict, - l64_core::CertificationVerdict::Integrated | l64_core::CertificationVerdict::Certified - ) { - score += 2500; - positive.push(format!("report verdict {:?}", report.verdict)); - } else { - blockers.push(format!("report verdict {:?}", report.verdict)); - score -= 1500; - } - if !report.deficiencies.is_empty() { - blockers.push("deficiencies present".into()); - score -= 2000; - } else { - score += 1000; - positive.push("no outstanding deficiencies".into()); - } - let score = score.clamp(0, 10000) as u16; - let status = if !blockers.is_empty() { - PromotionQueueStatus::Blocked - } else if score >= 8000 { - PromotionQueueStatus::Ready - } else { - PromotionQueueStatus::Proposed - }; - PromotionReadinessReport { - subject_id: report.theorem_id.clone(), - readiness_score_basis_points: score, - status, - positive_factors: positive, - blockers, - missing_refs: missing, - } -} - -pub fn derive_governed_promotion_readiness_from_report( - report: &CertificationReport, -) -> Result { - let state = load_governance_state()?; - let mut readiness = derive_promotion_readiness_from_report( - report, - &state.reviews, - &state.challenges, - &state.repro, - &state.strengthening, - &state.remediation, - ); - if state.claims.iter().any(|c| { - c.report_refs - .iter() - .any(|r| r.ends_with(&report.theorem_id)) - || c.id.ends_with(&report.theorem_id) - }) { - readiness.readiness_score_basis_points = - readiness.readiness_score_basis_points.saturating_add(300); - readiness - .positive_factors - .push("math claim packet exists".into()); - } else { - readiness - .missing_refs - .push(format!("claim:CLM_{}", report.theorem_id)); - } - if state - .reductions - .iter() - .any(|c| c.theorem_id == report.theorem_id) - { - readiness.readiness_score_basis_points = - readiness.readiness_score_basis_points.saturating_add(250); - readiness - .positive_factors - .push("reduction map exists".into()); - } - if state - .projections - .iter() - .any(|c| c.theorem_id == report.theorem_id) - { - readiness.readiness_score_basis_points = - readiness.readiness_score_basis_points.saturating_add(250); - readiness - .positive_factors - .push("projection map exists".into()); - } - let bench_runs = state - .benchmark_runs - .iter() - .filter(|b| b.theorem_id == report.theorem_id) - .collect::>(); - if !bench_runs.is_empty() { - readiness.readiness_score_basis_points = - readiness.readiness_score_basis_points.saturating_add(500); - readiness - .positive_factors - .push(format!("benchmark runs={}", bench_runs.len())); - if bench_runs - .iter() - .any(|b| matches!(b.status, RegistryEntryStatus::Blocked)) - { - readiness - .blockers - .push("blocked benchmark run present".into()); - } - } - let subject_id = report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()); - let coverage = state - .coverage_dispatches - .iter() - .find(|c| c.subject_id == report.theorem_id || c.subject_id == subject_id); - if let Some(coverage) = coverage { - readiness - .positive_factors - .push(format!("coverage {:?}", coverage.decision)); - if coverage.route_fast_path { - readiness.readiness_score_basis_points = - readiness.readiness_score_basis_points.saturating_add(350); - readiness - .positive_factors - .push("fast-path reuse is available".into()); - } - if coverage - .lineage_refs - .iter() - .any(|item| item == &lineage_ref_for_subject(&subject_id)) - { - readiness.readiness_score_basis_points = - readiness.readiness_score_basis_points.saturating_add(150); - readiness - .positive_factors - .push("coverage lineage linked".into()); - } else { - readiness.blockers.push("coverage lineage missing".into()); - } - if matches!(coverage.decision, l64_core::CoverageDecision::Unsupported) { - readiness.blockers.push("coverage unsupported".into()); - } - } else { - readiness - .missing_refs - .push(format!("coverage:{}", report.theorem_id)); - } - let producer_host_count = state - .producer_hosts - .iter() - .filter(|h| h.id.ends_with(&report.theorem_id)) - .count(); - if producer_host_count > 0 { - readiness.readiness_score_basis_points = readiness - .readiness_score_basis_points - .saturating_add((producer_host_count.min(5) as u16) * 80); - readiness - .positive_factors - .push(format!("producer hosts={producer_host_count}")); - } else { - readiness - .missing_refs - .push(format!("producer-hosts:{}", report.theorem_id)); - } - let lineage_record = state - ._lineage_records - .iter() - .find(|item| item.subject_id == subject_id || item.subject_id == report.theorem_id); - if let Some(lineage) = lineage_record { - readiness.readiness_score_basis_points = - readiness.readiness_score_basis_points.saturating_add(400); - readiness - .positive_factors - .push(format!("lineage {}", lineage.id)); - if lineage - .phase_ledger - .iter() - .any(|entry| entry.validation_result != l64_core::PhaseValidationResult::Passed) - { - readiness - .blockers - .push("lineage validation not fully passed".into()); - } - } else { - readiness - .missing_refs - .push(lineage_ref_for_subject(&subject_id)); - readiness.blockers.push("lineage missing".into()); - } - if let Some((_, tower)) = state - .tower_bundles - .iter() - .find(|(id, _)| id == &report.theorem_id) - { - readiness.positive_factors.push(format!( - "tower recipes={} promotion_candidates={}", - tower.recipes.len(), - tower.promotion_candidates.len() - )); - if tower.lineage_required - && !tower.lineage_refs.iter().any(|item| { - item == &format!("LIN_{}", report.theorem_id) - || item == &format!("LIN_{}", subject_id) - }) - { - readiness.blockers.push("tower lineage missing".into()); - } - if !tower.help_requests.is_empty() { - readiness - .blockers - .push(format!("help_requests={}", tower.help_requests.len())); - } - if tower - .calibration_pressure - .as_ref() - .map(|c| c.override_pressure) - .unwrap_or_default() - > 0 - { - readiness.blockers.push("override pressure remains".into()); - } - } - readiness.readiness_score_basis_points = readiness.readiness_score_basis_points.min(10_000); - readiness.status = if !readiness.blockers.is_empty() { - PromotionQueueStatus::Blocked - } else if readiness.readiness_score_basis_points >= 8500 { - PromotionQueueStatus::Ready - } else { - PromotionQueueStatus::Proposed - }; - Ok(readiness) -} - -pub fn derive_governed_handoff_packet_from_report( - report: &CertificationReport, - claim: &MathClaimPacket, - operator: &OperatorRecord, - strengthening: &[StrengtheningArtifact], - repro: &ReproducibilityPacket, - benchmarks: &[BenchmarkSchema], - lineage: &ResearchLineageRecord, - readiness: &PromotionReadinessReport, - route_assignment: Option<&RouteAssignment>, - benchmark_runs: &[BenchmarkRunRecord], - producer_hosts: &[ProducerHostSpec], - coverage: Option<&ProofCoverageDispatch>, - tower: Option<&VerticalCompoundingBundle>, -) -> HandoffPacket { - let mut packet = derive_handoff_packet_from_report( - report, - claim, - operator, - strengthening, - repro, - benchmarks, - ); - packet.status = readiness.status; - packet.readiness_score_basis_points = readiness.readiness_score_basis_points; - packet.blockers = readiness.blockers.clone(); - packet.positive_factors = readiness.positive_factors.clone(); - packet.summary = format!( - "governed handoff for {} status {:?} readiness {}", - report.theorem_id, readiness.status, readiness.readiness_score_basis_points - ); - packet.benchmark_run_refs = benchmark_runs.iter().map(|b| b.id.clone()).collect(); - packet.producer_host_refs = producer_hosts.iter().map(|h| h.id.clone()).collect(); - if let Some(route) = route_assignment { - packet.route_refs.push(route.task_id.clone()); - } - if let Some(coverage) = coverage { - packet.coverage_refs.push(coverage.subject_id.clone()); - } - packet.lineage_refs.push(lineage.id.clone()); - if tower.is_some() { - packet.tower_refs.push(report.theorem_id.clone()); - } - packet - .promotion_refs - .push(format!("PQU_{}", report.theorem_id)); - packet -} - -pub fn govern_report_from_cold_result( - report: &CertificationReport, -) -> Result<( - TaskEnvelope, - DerivationSignature, - RouteAssignment, - PromotionReadinessReport, - HandoffPacket, -)> { - let state = load_governance_state()?; - let task = derive_task_envelope_from_report(report); - let signature = derive_derivation_signature_from_report(report, &task); - let route = score_routes_internal( - &task, - &signature, - &state.challenges, - &state.registry_entries, - &state.reviews, - &state.repro, - &state.strengthening, - &state.remediation, - &state.benchmark_runs, - &state.claims, - &state.reductions, - &state.projections, - &state.handoffs, - &state.producer_hosts, - &state.promotion_queue, - &state.coverage_dispatches, - &state.tower_bundles, - ); - let claim = derive_math_claim_packet_from_report(report); - let operator = derive_operator_record_from_report(report); - let strengthening = derive_strengthening_artifacts_from_report(report); - let repro = derive_reproducibility_packet_from_report(report); - let benchmarks = derive_benchmark_schemas_from_report(report); - let readiness = derive_governed_promotion_readiness_from_report(report)?; - let benchmark_runs = vec![derive_benchmark_run_record_from_report( - report, - &benchmarks.iter().map(|b| b.id.clone()).collect::>(), - )]; - let producer_hosts = derive_producer_host_specs_from_report(report); - let lineage = derive_lineage_record_from_report(report); - let coverage = state - .coverage_dispatches - .iter() - .find(|c| c.subject_id == report.theorem_id); - let tower = state - .tower_bundles - .iter() - .find(|(id, _)| id == &report.theorem_id) - .map(|(_, t)| t); - let handoff = derive_governed_handoff_packet_from_report( - report, - &claim, - &operator, - &strengthening, - &repro, - &benchmarks, - &lineage, - &readiness, - Some(&route), - &benchmark_runs, - &producer_hosts, - coverage, - tower, - ); - Ok((task, signature, route, readiness, handoff)) -} - -pub fn derive_producer_host_specs_from_report( - report: &CertificationReport, -) -> Vec { - vec![ - ProducerHostSpec { - id: format!("HST_REDUCTION_{}", report.theorem_id), - kind: ProducerHostKind::Reduction, - purpose: format!("reduction host for {}", report.theorem_id), - owned_objects: vec![format!("RDM_{}", report.theorem_id)], - feeds: vec![ - format!("CLM_{}", report.theorem_id), - format!("REG_{}", report.theorem_id), - ], - notes: vec!["owns reduction maps and residual-obligation compression".into()], - }, - ProducerHostSpec { - id: format!("HST_PROJECTION_{}", report.theorem_id), - kind: ProducerHostKind::Projection, - purpose: format!("projection host for {}", report.theorem_id), - owned_objects: vec![format!("PRJ_{}", report.theorem_id)], - feeds: vec![format!("CLM_{}", report.theorem_id)], - notes: vec!["owns projection-algebra and bridge-facing summaries".into()], - }, - ProducerHostSpec { - id: format!("HST_BENCHMARK_{}", report.theorem_id), - kind: ProducerHostKind::Benchmark, - purpose: format!("benchmark host for {}", report.theorem_id), - owned_objects: vec![format!("BMR_{}", report.theorem_id)], - feeds: vec![format!("HOF_{}", report.theorem_id)], - notes: vec!["owns benchmark schemas and benchmark-floor execution surfaces".into()], - }, - ProducerHostSpec { - id: format!("HST_CHALLENGE_{}", report.theorem_id), - kind: ProducerHostKind::ChallengeResolution, - purpose: format!("challenge host for {}", report.theorem_id), - owned_objects: vec![format!("CHG_{}", report.theorem_id)], - feeds: vec![format!("PQU_{}", report.theorem_id)], - notes: vec![ - "owns contradiction handling, challenge response, and rollback narrowing".into(), - ], - }, - ProducerHostSpec { - id: format!("HST_HANDOFF_{}", report.theorem_id), - kind: ProducerHostKind::Handoff, - purpose: format!("handoff host for {}", report.theorem_id), - owned_objects: vec![format!("HOF_{}", report.theorem_id)], - feeds: vec![ - format!("RPR_{}", report.theorem_id), - format!("OPR_{}", report.theorem_id), - ], - notes: vec!["owns downstream integration packets and reusable exported law".into()], - }, - ] -} - -pub fn derive_promotion_queue_entry_from_report( - report: &CertificationReport, - readiness: &PromotionReadinessReport, -) -> PromotionQueueEntry { - let mut required_refs = Vec::new(); - required_refs.push(format!("review:RVR_{}", report.theorem_id)); - required_refs.push(format!("repro:RPR_{}", report.theorem_id)); - let subject_id = report - .campaign_id - .clone() - .unwrap_or_else(|| report.theorem_id.clone()); - required_refs.push(lineage_ref_for_subject(&subject_id)); - let mut evidence_refs = report.benchmark_receipt_ids.clone(); - evidence_refs.extend(report.challenge_receipt_ids.clone()); - evidence_refs.extend(report.payoff_receipt_ids.clone()); - PromotionQueueEntry { - id: format!("PQU_{}", report.theorem_id), - subject_id: report.theorem_id.clone(), - status: readiness.status, - readiness_score_basis_points: readiness.readiness_score_basis_points, - blockers: readiness.blockers.clone(), - required_refs, - evidence_refs, - } -} - -pub fn derive_complete_research_bundle_from_report( - report: &CertificationReport, - reviews: &[ReviewReceipt], - challenges: &[ChallengeRecord], - repros: &[ReproducibilityPacket], - strengthening_existing: &[StrengtheningArtifact], - remediation: &[RemediationLedgerEntry], -) -> ( - ResearchBundle, - FrameworkRegistryEntry, - OperatorRecord, - Vec, - ReproducibilityPacket, - ReviewReceipt, - Option, - PromotionReadinessReport, -) { - let task = derive_task_envelope_from_report(report); - let signature = derive_derivation_signature_from_report(report, &task); - let route_assignment = score_routes( - &task, - &signature, - challenges, - &[], - reviews, - repros, - strengthening_existing, - remediation, - ); - let claim = derive_math_claim_packet_from_report(report); - let reduction = derive_reduction_map_record_from_report(report); - let projection = derive_projection_map_record_from_report(report); - let strengthening = derive_strengthening_artifacts_from_report(report); - let repro = derive_reproducibility_packet_from_report(report); - let review = derive_review_receipt_from_report(report); - let challenge = derive_challenge_record_from_report(report); - let entry = derive_framework_registry_entry_from_report(report); - let operator = derive_operator_record_from_report(report); - let benchmarks = derive_benchmark_schemas_from_report(report); - let bench_ids = benchmarks.iter().map(|b| b.id.clone()).collect::>(); - let benchmark_run = derive_benchmark_run_record_from_report(report, &bench_ids); - let producer_hosts = derive_producer_host_specs_from_report(report); - let lineage = derive_lineage_record_from_report(report); - let mut all_reviews = reviews.to_vec(); - all_reviews.push(review.clone()); - let mut all_challenges = challenges.to_vec(); - if let Some(c) = challenge.clone() { - all_challenges.push(c); - } - let mut all_repros = repros.to_vec(); - all_repros.push(repro.clone()); - let mut all_strengthening = strengthening_existing.to_vec(); - all_strengthening.extend(strengthening.clone()); - let readiness = derive_promotion_readiness_from_report( - report, - &all_reviews, - &all_challenges, - &all_repros, - &all_strengthening, - remediation, - ); - let promotion_queue = derive_promotion_queue_entry_from_report(report, &readiness); - let handoff = derive_governed_handoff_packet_from_report( - report, - &claim, - &operator, - &strengthening, - &repro, - &benchmarks, - &lineage, - &readiness, - Some(&route_assignment), - &[benchmark_run.clone()], - &producer_hosts, - None, - None, - ); - let bundle = ResearchBundle { - tasks: vec![task], - signatures: vec![signature], - route_assignments: vec![route_assignment], - claims: vec![claim], - reduction_maps: vec![reduction], - projection_maps: vec![projection], - benchmark_runs: vec![benchmark_run], - handoff_packets: vec![handoff], - producer_hosts, - promotion_queue: vec![promotion_queue], - promotion_reports: vec![readiness.clone()], - lineage_records: vec![lineage], - }; - ( - bundle, - entry, - operator, - strengthening, - repro, - review, - challenge, - readiness, - ) -} - -pub fn derive_governed_complete_research_bundle_from_report( - report: &CertificationReport, -) -> Result<( - ResearchBundle, - FrameworkRegistryEntry, - OperatorRecord, - Vec, - ReproducibilityPacket, - ReviewReceipt, - Option, - PromotionReadinessReport, - HandoffPacket, - RouteAssignment, -)> { - let state = load_governance_state()?; - let task = derive_task_envelope_from_report(report); - let signature = derive_derivation_signature_from_report(report, &task); - let route_assignment = score_routes_internal( - &task, - &signature, - &state.challenges, - &state.registry_entries, - &state.reviews, - &state.repro, - &state.strengthening, - &state.remediation, - &state.benchmark_runs, - &state.claims, - &state.reductions, - &state.projections, - &state.handoffs, - &state.producer_hosts, - &state.promotion_queue, - &state.coverage_dispatches, - &state.tower_bundles, - ); - let claim = derive_math_claim_packet_from_report(report); - let reduction = derive_reduction_map_record_from_report(report); - let projection = derive_projection_map_record_from_report(report); - let strengthening = derive_strengthening_artifacts_from_report(report); - let repro = derive_reproducibility_packet_from_report(report); - let review = derive_review_receipt_from_report(report); - let challenge = derive_challenge_record_from_report(report); - let entry = derive_framework_registry_entry_from_report(report); - let operator = derive_operator_record_from_report(report); - let benchmarks = derive_benchmark_schemas_from_report(report); - let bench_ids = benchmarks.iter().map(|b| b.id.clone()).collect::>(); - let benchmark_run = derive_benchmark_run_record_from_report(report, &bench_ids); - let producer_hosts = derive_producer_host_specs_from_report(report); - let lineage = derive_lineage_record_from_report(report); - let readiness = derive_governed_promotion_readiness_from_report(report)?; - let coverage = state - .coverage_dispatches - .iter() - .find(|c| c.subject_id == report.theorem_id); - let tower = state - .tower_bundles - .iter() - .find(|(id, _)| id == &report.theorem_id) - .map(|(_, t)| t); - let handoff = derive_governed_handoff_packet_from_report( - report, - &claim, - &operator, - &strengthening, - &repro, - &benchmarks, - &lineage, - &readiness, - Some(&route_assignment), - &[benchmark_run.clone()], - &producer_hosts, - coverage, - tower, - ); - let promotion_queue = derive_promotion_queue_entry_from_report(report, &readiness); - let bundle = ResearchBundle { - tasks: vec![task], - signatures: vec![signature], - route_assignments: vec![route_assignment.clone()], - claims: vec![claim], - reduction_maps: vec![reduction], - projection_maps: vec![projection], - benchmark_runs: vec![benchmark_run], - handoff_packets: vec![handoff.clone()], - producer_hosts, - promotion_queue: vec![promotion_queue], - promotion_reports: vec![readiness.clone()], - lineage_records: vec![lineage], - }; - Ok(( - bundle, - entry, - operator, - strengthening, - repro, - review, - challenge, - readiness, - handoff, - route_assignment, - )) -} - -pub fn research_status_summary() -> Result { - let reviews = list_review_receipts()?; - let challenges = list_challenge_records()?; - let registry = list_framework_registry_entries()?; - let operators = list_operator_records()?; - let benchmarks = list_benchmark_schemas()?; - let benchmark_runs = list_benchmark_run_records()?; - let claims = list_math_claim_packets()?; - let reductions = list_reduction_map_records()?; - let projections = list_projection_map_records()?; - let handoffs = list_handoff_packets()?; - let producer_hosts = list_producer_host_specs()?; - let promotion_queue = list_promotion_queue_entries()?; - let promotion_reports = list_promotion_readiness_reports()?; - let route_assignments = list_route_assignments()?; - let strengthening = list_strengthening_artifacts()?; - let remediation = list_remediation_entries()?; - let repro = list_reproducibility_packets()?; - let coverage = list_coverage_dispatches()?; - let towers = list_vertical_bundles()?; - let lineage = list_lineage_records()?; - - let open_challenges = challenges - .iter() - .filter_map(|id| load_challenge_record(id).ok()) - .filter(|c| matches!(c.status, ChallengeStatus::Open)) - .count(); - let blocking_challenges = challenges - .iter() - .filter_map(|id| load_challenge_record(id).ok()) - .filter(|c| matches!(c.severity, ChallengeSeverity::Blocking)) - .count(); - let blocked_registry = registry - .iter() - .filter_map(|id| load_framework_registry_entry(id).ok()) - .filter(|r| matches!(r.status, RegistryEntryStatus::Blocked)) - .count(); - let remediation_open = remediation - .iter() - .filter_map(|id| load_remediation_entry(id).ok()) - .filter(|r| { - !matches!( - r.status, - RemediationStatus::Verified | RemediationStatus::Deferred - ) - }) - .count(); - let ready_promotion = promotion_queue - .iter() - .filter_map(|id| load_promotion_queue_entry(id).ok()) - .filter(|q| matches!(q.status, PromotionQueueStatus::Ready)) - .count(); - let blocked_promotion = promotion_queue - .iter() - .filter_map(|id| load_promotion_queue_entry(id).ok()) - .filter(|q| matches!(q.status, PromotionQueueStatus::Blocked)) - .count(); - let ready_handoffs = handoffs - .iter() - .filter_map(|id| load_handoff_packet(id).ok()) - .filter(|h| matches!(h.status, PromotionQueueStatus::Ready)) - .count(); - let blocked_handoffs = handoffs - .iter() - .filter_map(|id| load_handoff_packet(id).ok()) - .filter(|h| matches!(h.status, PromotionQueueStatus::Blocked)) - .count(); - - Ok(serde_json::json!({ - "counts": { - "reviews": reviews.len(), - "challenges": challenges.len(), - "registry": registry.len(), - "operators": operators.len(), - "benchmarks": benchmarks.len(), - "benchmark_runs": benchmark_runs.len(), - "claims": claims.len(), - "reductions": reductions.len(), - "projections": projections.len(), - "handoffs": handoffs.len(), - "producer_hosts": producer_hosts.len(), - "promotion_queue": promotion_queue.len(), - "promotion_reports": promotion_reports.len(), - "route_assignments": route_assignments.len(), - "strengthening": strengthening.len(), - "remediation": remediation.len(), - "repro": repro.len(), - "coverage_dispatch": coverage.len(), - "tower_bundles": towers.len(), - "lineage": lineage.len(), - }, - "open": { - "challenges": open_challenges, - "blocking_challenges": blocking_challenges, - "blocked_registry": blocked_registry, - "remediation": remediation_open, - "ready_promotion": ready_promotion, - "blocked_promotion": blocked_promotion, - "ready_handoffs": ready_handoffs, - "blocked_handoffs": blocked_handoffs, - }, - "ids": { - "claims": claims, - "registry": registry, - "promotion_queue": promotion_queue, - "promotion_reports": promotion_reports, - "route_assignments": route_assignments, - "handoff": handoffs, - "producer_hosts": producer_hosts, - "repro": repro, - "coverage_dispatch": coverage, - "tower_bundles": towers, - "remediation": remediation, - "lineage": lineage, - } - })) -} - -pub fn load_json_file(path: &Path) -> Result { - let text = fs::read_to_string(path)?; - Ok(serde_json::from_str(&text)?) -} - -pub fn write_json_stdout(value: &T) -> Result<()> { - println!("{}", serde_json::to_string_pretty(value)?); - Ok(()) -} - -pub fn persist_research_import(kind: &str, path: &Path) -> Result { - match kind { - "task" => { - let item: TaskEnvelope = load_json_file(path)?; - let id = item.id.clone(); - persist_task_envelope(&item)?; - Ok(id) - } - "signature" => { - let item: DerivationSignature = load_json_file(path)?; - let id = item.id.clone(); - persist_derivation_signature(&item)?; - Ok(id) - } - "review" => { - let item: ReviewReceipt = load_json_file(path)?; - let id = item.id.clone(); - persist_review_receipt(&item)?; - Ok(id) - } - "challenge" => { - let item: ChallengeRecord = load_json_file(path)?; - let id = item.id.clone(); - persist_challenge_record(&item)?; - Ok(id) - } - "registry" => { - let item: FrameworkRegistryEntry = load_json_file(path)?; - let id = item.id.clone(); - persist_framework_registry_entry(&item)?; - Ok(id) - } - "operator" => { - let item: OperatorRecord = load_json_file(path)?; - let id = item.id.clone(); - persist_operator_record(&item)?; - Ok(id) - } - "benchmark" => { - let item: BenchmarkSchema = load_json_file(path)?; - let id = item.id.clone(); - persist_benchmark_schema(&item)?; - Ok(id) - } - "claim" => { - let item: MathClaimPacket = load_json_file(path)?; - let id = item.id.clone(); - persist_math_claim_packet(&item)?; - Ok(id) - } - "reduction" => { - let item: ReductionMapRecord = load_json_file(path)?; - let id = item.id.clone(); - persist_reduction_map_record(&item)?; - Ok(id) - } - "projection" => { - let item: ProjectionMapRecord = load_json_file(path)?; - let id = item.id.clone(); - persist_projection_map_record(&item)?; - Ok(id) - } - "benchmark-run" => { - let item: BenchmarkRunRecord = load_json_file(path)?; - let id = item.id.clone(); - persist_benchmark_run_record(&item)?; - Ok(id) - } - "handoff" => { - let item: HandoffPacket = load_json_file(path)?; - let id = item.id.clone(); - persist_handoff_packet(&item)?; - Ok(id) - } - "producer-host" => { - let item: ProducerHostSpec = load_json_file(path)?; - let id = item.id.clone(); - persist_producer_host_spec(&item)?; - Ok(id) - } - "route-assignment" => { - let item: RouteAssignment = load_json_file(path)?; - let id = item.task_id.clone(); - persist_route_assignment(&item)?; - Ok(id) - } - "promotion-report" => { - let item: PromotionReadinessReport = load_json_file(path)?; - let id = item.subject_id.clone(); - persist_promotion_readiness_report(&item)?; - Ok(id) - } - "promotion" => { - let item: PromotionQueueEntry = load_json_file(path)?; - let id = item.id.clone(); - persist_promotion_queue_entry(&item)?; - Ok(id) - } - "strengthening" => { - let item: StrengtheningArtifact = load_json_file(path)?; - let id = item.id.clone(); - persist_strengthening_artifact(&item)?; - Ok(id) - } - "repro" => { - let item: ReproducibilityPacket = load_json_file(path)?; - let id = item.id.clone(); - persist_reproducibility_packet(&item)?; - Ok(id) - } - "remediation" => { - let item: RemediationLedgerEntry = load_json_file(path)?; - let id = item.id.clone(); - persist_remediation_entry(&item)?; - Ok(id) - } - "coverage" => { - let item: ProofCoverageDispatch = load_json_file(path)?; - let id = item.subject_id.clone(); - persist_coverage_dispatch(&item)?; - Ok(id) - } - "tower" => { - let item: VerticalCompoundingBundle = load_json_file(path)?; - let id = item - .frontier_ledger - .frontiers - .first() - .map(|f| f.id.clone()) - .unwrap_or_else(|| "tower".into()); - persist_vertical_bundle(&id, &item)?; - Ok(id) - } - "lineage" => { - let item: ResearchLineageRecord = load_json_file(path)?; - let id = item.id.clone(); - persist_lineage_record(&item)?; - Ok(id) - } - _ => Err(anyhow!("unknown research import kind `{kind}`")), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use l64_core::{ - CertificationReport, CertificationVerdict, ChangeLedgerEntry, - DeterministicExecutionEnvelope, GenomeArtifactClass, GenomeSurface, InvariantCheck, - PhaseId, PhaseValidationResult, PromotionSignal, ReplayStatus, - }; - - #[test] - fn lineage_record_roundtrip_persists_through_research_store() { - let namespace = format!("test_lineage_roundtrip_{}", std::process::id()); - unsafe { - std::env::set_var("MF_CACHE_NAMESPACE", &namespace); - } - - let record = ResearchLineageRecord { - id: "LINEAGE_TEST_1".into(), - subject_id: "CHAIN_RULE".into(), - artifact_class: GenomeArtifactClass::Gene, - source_surface: GenomeSurface::Rna, - target_surface: GenomeSurface::Dna, - grammar_id: "rna.v1".into(), - canonical_hash: "abc123".into(), - lowering_receipt_id: "SLR_abc123".into(), - phase_ids: vec![ - PhaseId::RnaNormalization, - PhaseId::StructuralResolution, - PhaseId::CanonicalNormalization, - ], - phase_ledger: vec![ChangeLedgerEntry { - phase_id: PhaseId::RnaNormalization, - input_state_hash: "in".into(), - output_state_hash: Some("out".into()), - dependency_edges: Vec::new(), - invariant_checks: vec![InvariantCheck { - name: "deterministic".into(), - passed: true, - detail: "ok".into(), - }], - failure_records: Vec::new(), - validation_result: PhaseValidationResult::Passed, - promotion_signal: PromotionSignal::Promote, - rollback_pointer: Some("retain raw RNA".into()), - }], - notes: vec!["test".into()], - }; - - persist_lineage_record(&record).expect("persist lineage"); - let loaded = load_lineage_record(&record.id).expect("load lineage"); - assert_eq!(loaded, record); - let listed = list_lineage_records().expect("list lineage"); - assert!(listed.contains(&record.id)); - } - - #[test] - fn report_derivation_emits_lineage_record() { - let report = CertificationReport { - theorem_id: "THS_CHAIN_RULE".into(), - campaign_id: Some("CPG_CHAIN_RULE".into()), - target_profile_id: "TP_CHAIN_RULE".into(), - verdict: CertificationVerdict::Integrated, - selected_atlas_cell: Some("CELL_CHAIN".into()), - selected_path: vec!["B_TOP_TO_CALC".into()], - route_class_id: Some("RLC_CHAIN".into()), - certificate_id: Some("CERT_CHAIN".into()), - candidates: Vec::new(), - obligations: Vec::new(), - reasons: vec!["ok".into()], - diagnostics: Vec::new(), - deficiencies: Vec::new(), - adequacy_records: Vec::new(), - checker_receipts: Vec::new(), - burden_pack_ids: Vec::new(), - claim_packet_ids: Vec::new(), - evidence_contract_ids: Vec::new(), - benchmark_receipt_ids: Vec::new(), - challenge_receipt_ids: Vec::new(), - reproducibility_packet_ids: vec!["RPK_CHAIN".into()], - promotion_artifact_ids: Vec::new(), - reused_artifact_ids: Vec::new(), - default_selected_artifact_ids: Vec::new(), - payoff_receipt_ids: Vec::new(), - policy_resolution: None, - route_explanation: None, - execution_envelope: Some(DeterministicExecutionEnvelope { - bundle_hash: "bundle".into(), - bundle_id: None, - policy_hash: "policy".into(), - policy_resolution_id: None, - manifest_id: None, - lock_id: None, - route_winner_hash: "winner".into(), - obligation_replay_keys: Vec::new(), - report_hash: "reporthash".into(), - replay_status: ReplayStatus::Fresh, - executed_plan_id: None, - reconciliation_id: None, - }), - reconciliation_summary: Vec::new(), - obligation_plan: None, - obligation_lanes: Vec::new(), - obligation_ordering_receipt: None, - obligation_merge_receipt: None, - replay_legality_checks: Vec::new(), - replay_barrier_receipts: Vec::new(), - replay_merge_receipt: None, - replay_divergence_records: Vec::new(), - obligation_cache_shards: Vec::new(), - reuse_legality_receipts: Vec::new(), - reuse_decision_receipts: Vec::new(), - residual_verification_receipts: Vec::new(), - obligation_write_sets: Vec::new(), - obligation_collision_reports: Vec::new(), - obligation_namespace_receipt: None, - }; - - let lineage = derive_lineage_record_from_report(&report); - assert_eq!(lineage.subject_id, "CPG_CHAIN_RULE"); - assert_eq!(lineage.source_surface, GenomeSurface::Dna); - assert_eq!(lineage.target_surface, GenomeSurface::Dna); - assert_eq!(lineage.canonical_hash, "reporthash"); - assert!(lineage.phase_ids.contains(&PhaseId::ResearchHostReconnect)); - assert_eq!(lineage.phase_ledger.len(), 1); - assert_eq!( - lineage.phase_ledger[0].validation_result, - PhaseValidationResult::Passed - ); - - let claim = derive_math_claim_packet_from_report(&report); - assert_eq!(claim.truth_class, l64_core::AuthorityState::Projection); - assert!( - claim - .assumptions - .iter() - .any(|item| item == "report_verdict_projection:Integrated") - ); - } - - #[test] - fn promotion_and_handoff_include_lineage_requirements() { - let report = CertificationReport { - theorem_id: "THS_CHAIN_RULE".into(), - campaign_id: Some("CPG_CHAIN_RULE".into()), - target_profile_id: "TGT_CHAIN_RULE".into(), - verdict: CertificationVerdict::Integrated, - selected_atlas_cell: Some("CELL_CHAIN".into()), - selected_path: vec!["B_TOP_TO_CALC".into()], - route_class_id: Some("RLC_CHAIN".into()), - certificate_id: Some("CERT_CHAIN".into()), - candidates: Vec::new(), - obligations: Vec::new(), - reasons: vec!["ok".into()], - diagnostics: Vec::new(), - deficiencies: Vec::new(), - adequacy_records: Vec::new(), - checker_receipts: Vec::new(), - burden_pack_ids: Vec::new(), - claim_packet_ids: Vec::new(), - evidence_contract_ids: Vec::new(), - benchmark_receipt_ids: Vec::new(), - challenge_receipt_ids: Vec::new(), - reproducibility_packet_ids: vec!["RPK_CHAIN".into()], - promotion_artifact_ids: Vec::new(), - reused_artifact_ids: Vec::new(), - default_selected_artifact_ids: Vec::new(), - payoff_receipt_ids: Vec::new(), - policy_resolution: None, - route_explanation: None, - execution_envelope: Some(DeterministicExecutionEnvelope { - bundle_hash: "bundle".into(), - bundle_id: None, - policy_hash: "policy".into(), - policy_resolution_id: None, - manifest_id: None, - lock_id: None, - route_winner_hash: "winner".into(), - obligation_replay_keys: Vec::new(), - report_hash: "reporthash".into(), - replay_status: ReplayStatus::Fresh, - executed_plan_id: None, - reconciliation_id: None, - }), - reconciliation_summary: Vec::new(), - obligation_plan: None, - obligation_lanes: Vec::new(), - obligation_ordering_receipt: None, - obligation_merge_receipt: None, - replay_legality_checks: Vec::new(), - replay_barrier_receipts: Vec::new(), - replay_merge_receipt: None, - replay_divergence_records: Vec::new(), - obligation_cache_shards: Vec::new(), - reuse_legality_receipts: Vec::new(), - reuse_decision_receipts: Vec::new(), - residual_verification_receipts: Vec::new(), - obligation_write_sets: Vec::new(), - obligation_collision_reports: Vec::new(), - obligation_namespace_receipt: None, - }; - - let lineage = derive_lineage_record_from_report(&report); - let readiness = PromotionReadinessReport { - subject_id: report.theorem_id.clone(), - readiness_score_basis_points: 9000, - status: PromotionQueueStatus::Ready, - positive_factors: vec!["lineage present".into()], - blockers: Vec::new(), - missing_refs: Vec::new(), - }; - let claim = derive_math_claim_packet_from_report(&report); - let operator = derive_operator_record_from_report(&report); - let strengthening = derive_strengthening_artifacts_from_report(&report); - let repro = derive_reproducibility_packet_from_report(&report); - let benchmarks = derive_benchmark_schemas_from_report(&report); - let benchmark_runs = vec![derive_benchmark_run_record_from_report( - &report, - &benchmarks.iter().map(|b| b.id.clone()).collect::>(), - )]; - let producer_hosts = derive_producer_host_specs_from_report(&report); - let route_assignment = RouteAssignment { - task_id: "TSK_THS_CHAIN_RULE".into(), - signature_id: "SIG_THS_CHAIN_RULE".into(), - recommended_route: ResearchRouteClass::Integrate, - scores: Vec::new(), - }; - - let promotion = derive_promotion_queue_entry_from_report(&report, &readiness); - assert!( - promotion - .required_refs - .iter() - .any(|item| item == "lineage:LIN_CPG_CHAIN_RULE") - ); - - let handoff = derive_governed_handoff_packet_from_report( - &report, - &claim, - &operator, - &strengthening, - &repro, - &benchmarks, - &lineage, - &readiness, - Some(&route_assignment), - &benchmark_runs, - &producer_hosts, - None, - None, - ); - assert!( - handoff - .lineage_refs - .iter() - .any(|item| item == "LIN_CPG_CHAIN_RULE") - ); - } -} diff --git a/l64-runtime/.gitignore b/l64-runtime/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/l64-runtime/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/l64-runtime/Cargo.toml b/l64-runtime/Cargo.toml deleted file mode 100644 index 3c1faf1..0000000 --- a/l64-runtime/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "l64-runtime" -edition.workspace = true -version.workspace = true -license.workspace = true - -[dependencies] -l64-core = { path = "../l64-core" } -l64-registry = { path = "../l64-registry" } -serde = { workspace = true } -thiserror = { workspace = true } -bincode = { workspace = true } diff --git a/l64-runtime/src/lib.rs b/l64-runtime/src/lib.rs deleted file mode 100644 index ea1e688..0000000 --- a/l64-runtime/src/lib.rs +++ /dev/null @@ -1,753 +0,0 @@ -use l64_core::{NatToll, TollValue}; -use l64_registry::SeedRegistry; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use thiserror::Error; - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct SymbolId(pub u32); - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct RuntimeObjectId(pub u32); - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SymbolInterner { - symbols: Vec, - index: HashMap, -} - -impl Default for SymbolInterner { - fn default() -> Self { - Self { - symbols: Vec::new(), - index: HashMap::new(), - } - } -} - -impl SymbolInterner { - pub fn intern(&mut self, value: impl Into) -> SymbolId { - let value = value.into(); - if let Some(id) = self.index.get(&value) { - return *id; - } - let id = SymbolId(self.symbols.len() as u32); - self.symbols.push(value.clone()); - self.index.insert(value, id); - id - } - - pub fn resolve(&self, id: SymbolId) -> Option<&str> { - self.symbols.get(id.0 as usize).map(String::as_str) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RuntimeObject { - pub id: RuntimeObjectId, - pub symbol: SymbolId, - pub regime: SymbolId, - pub head: SymbolId, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RuntimeWorld { - pub interner: SymbolInterner, - pub objects: Vec, - pub object_by_name: HashMap, -} - -impl RuntimeWorld { - pub fn compile_seed(registry: &SeedRegistry) -> Self { - let mut interner = SymbolInterner::default(); - let mut objects = Vec::new(); - let mut object_by_name = HashMap::new(); - - for object in ®istry.bundle().objects { - let id = RuntimeObjectId(objects.len() as u32); - let symbol = interner.intern(object.id.clone()); - let regime = interner.intern(object.constraint.regime.clone()); - let head = interner.intern(object.structural.head.clone()); - objects.push(RuntimeObject { - id, - symbol, - regime, - head, - }); - object_by_name.insert(object.id.clone(), id); - } - - Self { - interner, - objects, - object_by_name, - } - } - - pub fn lookup_object(&self, name: &str) -> Option { - self.object_by_name.get(name).copied() - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub enum HostExecutionResult { - Set { - cardinality: usize, - union_cardinality: usize, - intersection_cardinality: usize, - subset_holds: bool, - extensional_equal: bool, - powerset_bound: usize, - total_function_graph: bool, - injective: bool, - surjective: bool, - }, - Algebra { - closure_holds: bool, - associative: bool, - identity_holds: bool, - inverse_holds: bool, - distributive: bool, - quotient_compatible: bool, - homomorphism_preserving: bool, - operation_rows: usize, - }, - Topology { - open_sets: usize, - cover_legal: bool, - continuity_holds: bool, - overlap_compatible: bool, - gluing_compatible: bool, - obstruction: Option, - }, - Calculus { - local_linear_witness: bool, - finite_difference_derivative: bool, - accumulation_ok: bool, - symbolic_only: bool, - }, - Probability { - support_size: usize, - normalized: bool, - expectation: RationalRuntime, - conditioning_legal: bool, - independent: bool, - pushforward_ok: bool, - }, - Computation { - steps: usize, - reached_normal_form: bool, - observationally_equivalent: bool, - cost: NatToll, - replayable_trace: bool, - }, - Logic { - proposition_well_formed: bool, - witness_available: bool, - }, - TypeTheory { - witness_inhabited: bool, - normalization_correspondence: bool, - }, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RationalRuntime { - pub num: u64, - pub den: u64, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct JetRepresentative { - pub rows: usize, - pub cols: usize, - pub entries: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ChainRuleJetComposeWitness { - pub local_linear_form_agrees: bool, - pub normalized_representative_agrees: bool, - pub reduction_preserves_form: bool, - pub chart_overlap_compatible: bool, - pub transition_transport_agrees: bool, - pub gauge_normalized_representative_agrees: bool, - pub direct: JetRepresentative, - pub composed: JetRepresentative, - pub direct_in_transition: JetRepresentative, - pub composed_in_transition: JetRepresentative, - pub residual_boundary: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct ChainRuleReductionWitness { - pub finite_difference_agrees: bool, - pub reduction_normal_form_preserved: bool, - pub remainder_transport_compatible: bool, - pub remainder_exact_zero: bool, - pub direct_difference: Vec, - pub composed_difference: Vec, - pub remainder_normal_form: Vec, - pub residual_boundary: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TypeNormalizationWitness { - pub inhabitance_preserved: bool, - pub beta_eta_normalization_exact: bool, - pub carrier_collapse_exact: bool, - pub extensional_normal_form_agrees: bool, - pub direct_normal_form: Vec, - pub collapsed_normal_form: Vec, - pub residual_boundary: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct TypeInheritanceWitness { - pub inhabitance_transport_exact: bool, - pub carrier_lift_exact: bool, - pub quotient_transport_exact: bool, - pub homomorphism_preserved_exact: bool, - pub proof_term_transport_exact: bool, - pub proof_term_normal_form_agrees: bool, - pub proof_relevance_preserved: bool, - pub direct_carrier: Vec, - pub lifted_carrier: Vec, - pub direct_proof_terms: Vec, - pub lifted_proof_terms: Vec, - pub residual_boundary: Option, -} - -#[derive(Debug, Error)] -pub enum RuntimeError { - #[error("unsupported executable regime `{0}`")] - UnsupportedRegime(String), -} - -pub fn exec_host(regime: &str, _object: Option<&str>) -> Result { - match regime { - "R_SET" => Ok(run_set_kernel()), - "R_ALG" => Ok(run_algebra_kernel()), - "R_TOP" => Ok(run_topology_kernel()), - "R_CALC" => Ok(run_calculus_kernel()), - "R_PROB" => Ok(run_probability_kernel()), - "R_COMP" => Ok(run_computation_kernel()), - "R_LOG" => Ok(run_logic_kernel()), - "R_TYP" => Ok(run_type_kernel()), - _ => Err(RuntimeError::UnsupportedRegime(regime.to_string())), - } -} - -pub fn exec_chain_rule_jet_compose() -> Result { - let topology = exec_host("R_TOP", None)?; - let calculus = exec_host("R_CALC", None)?; - let df = [[2_i64, 0_i64], [1_i64, 1_i64]]; - let dg = [[3_i64, 1_i64], [0_i64, 2_i64]]; - let direct = multiply_2x2(dg, df); - let composed = multiply_2x2(dg, df); - let direct_repr = JetRepresentative { - rows: 2, - cols: 2, - entries: normalize_matrix_2x2(direct), - }; - let composed_repr = JetRepresentative { - rows: 2, - cols: 2, - entries: normalize_matrix_2x2(composed), - }; - let transition = [[1_i64, 1_i64], [0_i64, 1_i64]]; - let transition_inv = [[1_i64, -1_i64], [0_i64, 1_i64]]; - let direct_in_transition = multiply_2x2(multiply_2x2(transition, direct), transition_inv); - let composed_in_transition = multiply_2x2(multiply_2x2(transition, composed), transition_inv); - let direct_transition_repr = JetRepresentative { - rows: 2, - cols: 2, - entries: normalize_matrix_2x2(direct_in_transition), - }; - let composed_transition_repr = JetRepresentative { - rows: 2, - cols: 2, - entries: normalize_matrix_2x2(composed_in_transition), - }; - let chart_overlap_compatible = matches!( - topology, - HostExecutionResult::Topology { - overlap_compatible: true, - continuity_holds: true, - .. - } - ); - let transition_transport_agrees = direct_in_transition == composed_in_transition; - let gauge_normalized_representative_agrees = direct_transition_repr == composed_transition_repr; - let reduction_preserves_form = matches!( - calculus, - HostExecutionResult::Calculus { - local_linear_witness: true, - finite_difference_derivative: true, - symbolic_only: false, - .. - } - ) && matches!( - topology, - HostExecutionResult::Topology { - overlap_compatible: true, - gluing_compatible: true, - .. - } - ); - Ok(ChainRuleJetComposeWitness { - local_linear_form_agrees: direct == composed, - normalized_representative_agrees: direct_repr == composed_repr, - reduction_preserves_form, - chart_overlap_compatible, - transition_transport_agrees, - gauge_normalized_representative_agrees, - direct: direct_repr, - composed: composed_repr, - direct_in_transition: direct_transition_repr, - composed_in_transition: composed_transition_repr, - residual_boundary: if chart_overlap_compatible - && transition_transport_agrees - && gauge_normalized_representative_agrees - { - None - } else { - Some( - "chart-global gauge identification for the composed first-order jet still fails under the active transition witness" - .into(), - ) - }, - }) -} - -pub fn exec_chain_rule_reduction() -> Result { - let topology = exec_host("R_TOP", None)?; - let calculus = exec_host("R_CALC", None)?; - let base = [2_i64, 1_i64]; - let step = [1_i64, 0_i64]; - let f = |x: [i64; 2]| -> [i64; 2] { [2 * x[0], x[0] + x[1]] }; - let g = |u: [i64; 2]| -> [i64; 2] { [3 * u[0] + u[1], 2 * u[1]] }; - let compose = |x: [i64; 2]| -> [i64; 2] { g(f(x)) }; - let jac_f = [[2_i64, 0_i64], [1_i64, 1_i64]]; - let jac_g = [[3_i64, 1_i64], [0_i64, 2_i64]]; - let jac_comp = multiply_2x2(jac_g, jac_f); - let predicted = apply_2x2(jac_comp, step); - let compose_delta = subtract_2(compose(add_2(base, step)), compose(base)); - let remainder = subtract_2(compose_delta, predicted); - let reduction_normal_form = normalize_vector_2(remainder); - let finite_difference_agrees = compose_delta == predicted; - let reduction_normal_form_preserved = reduction_normal_form == vec![0, 0]; - let remainder_transport_compatible = matches!( - topology, - HostExecutionResult::Topology { - overlap_compatible: true, - gluing_compatible: true, - .. - } - ) && matches!( - calculus, - HostExecutionResult::Calculus { - local_linear_witness: true, - finite_difference_derivative: true, - symbolic_only: false, - .. - } - ); - let remainder_exact_zero = remainder == [0, 0]; - Ok(ChainRuleReductionWitness { - finite_difference_agrees, - reduction_normal_form_preserved, - remainder_transport_compatible, - remainder_exact_zero, - direct_difference: vec![predicted[0], predicted[1]], - composed_difference: vec![compose_delta[0], compose_delta[1]], - remainder_normal_form: reduction_normal_form, - residual_boundary: if finite_difference_agrees - && reduction_normal_form_preserved - && remainder_transport_compatible - && remainder_exact_zero - { - None - } else { - Some( - "route-local remainder witness still leaves a nonzero first-order defect in the active finite model" - .into(), - ) - }, - }) -} - -pub fn exec_ch_norm_type_witness() -> Result { - let typ = exec_host("R_TYP", None)?; - let direct_normal_form = vec!["lam".to_string(), "x".to_string()]; - let collapsed_normal_form = vec!["lam".to_string(), "x".to_string()]; - let inhabitance_preserved = matches!( - typ, - HostExecutionResult::TypeTheory { - witness_inhabited: true, - .. - } - ); - let beta_eta_normalization_exact = matches!( - typ, - HostExecutionResult::TypeTheory { - normalization_correspondence: true, - .. - } - ); - let carrier_collapse_exact = inhabitance_preserved && beta_eta_normalization_exact; - let extensional_normal_form_agrees = direct_normal_form == collapsed_normal_form; - Ok(TypeNormalizationWitness { - inhabitance_preserved, - beta_eta_normalization_exact, - carrier_collapse_exact, - extensional_normal_form_agrees, - direct_normal_form, - collapsed_normal_form, - residual_boundary: if inhabitance_preserved - && beta_eta_normalization_exact - && carrier_collapse_exact - && extensional_normal_form_agrees - { - None - } else { - Some( - "typed normalization witness still fails to align its extensional carrier normal form on the active route" - .into(), - ) - }, - }) -} - -pub fn exec_ch_inh_type_witness() -> Result { - let typ = exec_host("R_TYP", None)?; - let alg = exec_host("R_ALG", None)?; - let direct_carrier = vec!["e".to_string(), "a".to_string()]; - let lifted_carrier = vec!["e".to_string(), "a".to_string()]; - let direct_proof_terms = vec!["refl:e".to_string(), "refl:a".to_string()]; - let lifted_proof_terms = vec!["refl:e".to_string(), "refl:a".to_string()]; - let inhabitance_transport_exact = matches!( - typ, - HostExecutionResult::TypeTheory { - witness_inhabited: true, - .. - } - ); - let carrier_lift_exact = matches!( - alg, - HostExecutionResult::Algebra { - closure_holds: true, - associative: true, - .. - } - ) && direct_carrier == lifted_carrier; - let quotient_transport_exact = matches!( - alg, - HostExecutionResult::Algebra { - quotient_compatible: true, - .. - } - ); - let homomorphism_preserved_exact = matches!( - alg, - HostExecutionResult::Algebra { - homomorphism_preserving: true, - .. - } - ); - let proof_term_transport_exact = direct_proof_terms.len() == lifted_proof_terms.len() - && direct_proof_terms - .iter() - .zip(lifted_proof_terms.iter()) - .all(|(left, right)| left.split(':').nth(1) == right.split(':').nth(1)); - let proof_term_normal_form_agrees = direct_proof_terms == lifted_proof_terms; - let proof_relevance_preserved = proof_term_transport_exact && proof_term_normal_form_agrees; - Ok(TypeInheritanceWitness { - inhabitance_transport_exact, - carrier_lift_exact, - quotient_transport_exact, - homomorphism_preserved_exact, - proof_term_transport_exact, - proof_term_normal_form_agrees, - proof_relevance_preserved, - direct_carrier, - lifted_carrier, - direct_proof_terms, - lifted_proof_terms, - residual_boundary: if proof_relevance_preserved { - None - } else { - Some( - "proof-relevant extensional identification for the inherited algebra carrier is not yet executable on the active type-to-alg route" - .into(), - ) - }, - }) -} - -fn multiply_2x2(left: [[i64; 2]; 2], right: [[i64; 2]; 2]) -> [[i64; 2]; 2] { - let mut out = [[0_i64; 2]; 2]; - for row in 0..2 { - for col in 0..2 { - out[row][col] = left[row][0] * right[0][col] + left[row][1] * right[1][col]; - } - } - out -} - -fn apply_2x2(matrix: [[i64; 2]; 2], vector: [i64; 2]) -> [i64; 2] { - [ - matrix[0][0] * vector[0] + matrix[0][1] * vector[1], - matrix[1][0] * vector[0] + matrix[1][1] * vector[1], - ] -} - -fn add_2(left: [i64; 2], right: [i64; 2]) -> [i64; 2] { - [left[0] + right[0], left[1] + right[1]] -} - -fn subtract_2(left: [i64; 2], right: [i64; 2]) -> [i64; 2] { - [left[0] - right[0], left[1] - right[1]] -} - -fn normalize_vector_2(vector: [i64; 2]) -> Vec { - let mut entries = vec![vector[0], vector[1]]; - let gcd = entries - .iter() - .copied() - .fold(0_i64, |acc, value| gcd_i64(acc, value.abs())) - .max(1); - for entry in &mut entries { - *entry /= gcd; - } - if let Some(first_nonzero) = entries.iter().copied().find(|value| *value != 0) { - if first_nonzero < 0 { - for entry in &mut entries { - *entry = -*entry; - } - } - } - entries -} - -fn normalize_matrix_2x2(matrix: [[i64; 2]; 2]) -> Vec { - let mut entries = vec![matrix[0][0], matrix[0][1], matrix[1][0], matrix[1][1]]; - let gcd = entries - .iter() - .copied() - .fold(0_i64, |acc, value| gcd_i64(acc, value.abs())) - .max(1); - for entry in &mut entries { - *entry /= gcd; - } - if let Some(first_nonzero) = entries.iter().copied().find(|value| *value != 0) { - if first_nonzero < 0 { - for entry in &mut entries { - *entry = -*entry; - } - } - } - entries -} - -fn gcd_i64(a: i64, b: i64) -> i64 { - if b == 0 { a.abs() } else { gcd_i64(b, a % b) } -} - -fn run_set_kernel() -> HostExecutionResult { - let a = [true, true, false, true]; - let b = [true, false, false, true]; - let cardinality = a.iter().filter(|item| **item).count(); - let union_cardinality = a - .iter() - .zip(b.iter()) - .filter(|(left, right)| **left || **right) - .count(); - let intersection_cardinality = a - .iter() - .zip(b.iter()) - .filter(|(left, right)| **left && **right) - .count(); - let subset_holds = b.iter().zip(a.iter()).all(|(left, right)| !*left || *right); - let extensional_equal = a == [true, true, false, true]; - HostExecutionResult::Set { - cardinality, - union_cardinality, - intersection_cardinality, - subset_holds, - extensional_equal, - powerset_bound: 1usize << cardinality, - total_function_graph: true, - injective: true, - surjective: true, - } -} - -fn run_algebra_kernel() -> HostExecutionResult { - let table = [[0usize, 1], [1, 0]]; - let associative = (0..2) - .all(|a| (0..2).all(|b| (0..2).all(|c| table[table[a][b]][c] == table[a][table[b][c]]))); - let identity_holds = (0..2).all(|x| table[0][x] == x && table[x][0] == x); - HostExecutionResult::Algebra { - closure_holds: true, - associative, - identity_holds, - inverse_holds: true, - distributive: true, - quotient_compatible: true, - homomorphism_preserving: true, - operation_rows: table.len(), - } -} - -fn run_topology_kernel() -> HostExecutionResult { - let open_sets = vec![0b0000u8, 0b0001, 0b0011, 0b1111]; - let cover_legal = open_sets.iter().any(|set| *set == 0b1111); - let continuity_holds = true; - let overlap_compatible = true; - let gluing_compatible = true; - HostExecutionResult::Topology { - open_sets: open_sets.len(), - cover_legal, - continuity_holds, - overlap_compatible, - gluing_compatible, - obstruction: None, - } -} - -fn run_calculus_kernel() -> HostExecutionResult { - HostExecutionResult::Calculus { - local_linear_witness: true, - finite_difference_derivative: true, - accumulation_ok: true, - symbolic_only: false, - } -} - -fn run_probability_kernel() -> HostExecutionResult { - let support = [(0u64, 1u64), (1, 3), (2, 2)]; - let total: u64 = support.iter().map(|(_, weight)| *weight).sum(); - let numerator: u64 = support.iter().map(|(value, weight)| value * weight).sum(); - HostExecutionResult::Probability { - support_size: support.len(), - normalized: total == 6, - expectation: RationalRuntime { - num: numerator, - den: total, - }, - conditioning_legal: true, - independent: false, - pushforward_ok: true, - } -} - -fn run_computation_kernel() -> HostExecutionResult { - let steps = 3usize; - let reached_normal_form = true; - let observationally_equivalent = true; - let cost = NatToll::one().add(&NatToll(steps as u64)); - HostExecutionResult::Computation { - steps, - reached_normal_form, - observationally_equivalent, - cost, - replayable_trace: true, - } -} - -fn run_logic_kernel() -> HostExecutionResult { - HostExecutionResult::Logic { - proposition_well_formed: true, - witness_available: true, - } -} - -fn run_type_kernel() -> HostExecutionResult { - HostExecutionResult::TypeTheory { - witness_inhabited: true, - normalization_correspondence: true, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn runtime_world_interns_seed_objects() { - let registry = SeedRegistry::load().unwrap(); - let world = RuntimeWorld::compile_seed(®istry); - assert!(world.lookup_object("OBJ_CTX_SET").is_some()); - } - - #[test] - fn executable_probability_kernel_runs() { - let result = exec_host("R_PROB", None).unwrap(); - match result { - HostExecutionResult::Probability { - normalized, - support_size, - .. - } => { - assert!(normalized); - assert_eq!(support_size, 3); - } - _ => panic!("expected probability result"), - } - } - - #[test] - fn chain_rule_jet_compose_witness_is_deterministic() { - let witness = exec_chain_rule_jet_compose().unwrap(); - assert!(witness.local_linear_form_agrees); - assert!(witness.normalized_representative_agrees); - assert!(witness.reduction_preserves_form); - assert!(witness.chart_overlap_compatible); - assert!(witness.transition_transport_agrees); - assert!(witness.gauge_normalized_representative_agrees); - assert_eq!(witness.direct.entries, witness.composed.entries); - assert_eq!( - witness.direct_in_transition.entries, - witness.composed_in_transition.entries - ); - assert!(witness.residual_boundary.is_none()); - } - - #[test] - fn chain_rule_reduction_witness_is_exact() { - let witness = exec_chain_rule_reduction().unwrap(); - assert!(witness.finite_difference_agrees); - assert!(witness.reduction_normal_form_preserved); - assert!(witness.remainder_transport_compatible); - assert!(witness.remainder_exact_zero); - assert_eq!(witness.remainder_normal_form, vec![0, 0]); - assert!(witness.residual_boundary.is_none()); - } - - #[test] - fn ch_norm_type_witness_is_exact() { - let witness = exec_ch_norm_type_witness().unwrap(); - assert!(witness.inhabitance_preserved); - assert!(witness.beta_eta_normalization_exact); - assert!(witness.carrier_collapse_exact); - assert!(witness.extensional_normal_form_agrees); - assert_eq!(witness.direct_normal_form, witness.collapsed_normal_form); - assert!(witness.residual_boundary.is_none()); - } - - #[test] - fn ch_inh_type_witness_preserves_proof_relevant_identity_on_active_slice() { - let witness = exec_ch_inh_type_witness().unwrap(); - assert!(witness.inhabitance_transport_exact); - assert!(witness.carrier_lift_exact); - assert!(witness.quotient_transport_exact); - assert!(witness.homomorphism_preserved_exact); - assert!(witness.proof_term_transport_exact); - assert!(witness.proof_term_normal_form_agrees); - assert!(witness.proof_relevance_preserved); - assert_eq!(witness.direct_carrier, witness.lifted_carrier); - assert_eq!(witness.direct_proof_terms, witness.lifted_proof_terms); - assert!(witness.residual_boundary.is_none()); - } -} diff --git a/l64-selector/.gitignore b/l64-selector/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/l64-selector/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/l64-selector/Cargo.toml b/l64-selector/Cargo.toml deleted file mode 100644 index ed08036..0000000 --- a/l64-selector/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "l64-selector" -version = "0.1.0" -edition = "2024" - -[dependencies] -l64-core = { path = "../l64-core" } -l64-kernel = { path = "../l64-kernel" } - -[dev-dependencies] -l64-testkit = { path = "../l64-testkit" } diff --git a/l64-selector/src/lib.rs b/l64-selector/src/lib.rs deleted file mode 100644 index 74be075..0000000 --- a/l64-selector/src/lib.rs +++ /dev/null @@ -1,730 +0,0 @@ -use l64_core::{ - AtlasCell, Budget, CertificationCandidate, CertificationReport, CertificationVerdict, - ComposeBridge, ObligationStatus, RegistryLookup, RequiredProofShapeFamily, RouteSelection, - SelectRoute, WinnerState, -}; -use l64_kernel::ConstitutionKernel; - -#[derive(Debug, Clone)] -pub struct AtlasSelector { - registry: R, -} - -impl AtlasSelector { - pub fn new(registry: R) -> Self { - Self { registry } - } - - pub fn registry(&self) -> &R { - &self.registry - } -} - -impl SelectRoute for AtlasSelector -where - R: l64_core::RegistryLookup, -{ - fn select_route( - &self, - src: &str, - tgt: &str, - proof_target: Option<&str>, - budget: Option<&Budget>, - ) -> Result { - let mut candidates = self - .registry - .atlas_cells() - .into_iter() - .filter(|cell| cell.source_regime == src && cell.target_regime == tgt) - .filter(|cell| { - proof_target - .map(|target| cell.proof_target == target) - .unwrap_or(true) - }) - .filter(|cell| { - budget - .map(|budget| { - cell.loss_profile.items.len() <= budget.max_loss - && (budget.allow_lossy_supported || cell.loss_profile.items.is_empty()) - }) - .unwrap_or(true) - }) - .collect::>(); - - candidates.sort_by(|left, right| left.id.cmp(&right.id)); - - let winner = candidates.iter().find(|cell| { - cell.winner_state == WinnerState::SeedWinner - && cell.candidate_paths.contains(&cell.normalized_winner) - }); - - let reasons = if let Some(winner) = winner { - vec![ - format!("selected atlas cell `{}`", winner.id), - format!("winner path `{}`", winner.normalized_winner.join(" -> ")), - ] - } else if candidates.is_empty() { - vec!["no atlas cell matched the request".into()] - } else { - vec!["candidate cells exist but none declare a seed winner".into()] - }; - - Ok(RouteSelection { - candidates: candidates.clone(), - winner: winner.cloned(), - reasons, - route_explanation: None, - }) - } -} - -#[derive(Debug)] -pub struct CampaignCertifier { - registry: R, - kernel: ConstitutionKernel, -} - -impl CampaignCertifier { - pub fn new(registry: R) -> Self { - Self { - registry, - kernel: ConstitutionKernel, - } - } -} - -impl CampaignCertifier -where - R: RegistryLookup, -{ - pub fn certify_campaign(&self, campaign_id: &str) -> Result { - let campaign = self - .registry - .get_campaign(campaign_id) - .ok_or_else(|| format!("unknown campaign `{campaign_id}`"))?; - let target = self - .registry - .get_target_profile(&campaign.target_profile) - .ok_or_else(|| format!("unknown target profile `{}`", campaign.target_profile))?; - self.certify_theorem_with_target(&campaign.theorem, &target.id, Some(campaign.id.as_str())) - } - - pub fn certify_theorem_with_target( - &self, - theorem_id: &str, - target_profile_id: &str, - campaign_id: Option<&str>, - ) -> Result { - let theorem = self - .registry - .get_theorem_spec(theorem_id) - .ok_or_else(|| format!("unknown theorem `{theorem_id}`"))?; - let target = self - .registry - .get_target_profile(target_profile_id) - .ok_or_else(|| format!("unknown target profile `{target_profile_id}`"))?; - - self.kernel - .validate_theorem_spec(&theorem, &self.registry) - .map_err(|err| err.to_string())?; - self.kernel - .validate_target_profile(&target) - .map_err(|err| err.to_string())?; - - let src = target - .host_cluster - .first() - .ok_or_else(|| format!("target profile `{}` has empty host cluster", target.id))?; - let tgt = target - .host_cluster - .last() - .ok_or_else(|| format!("target profile `{}` has empty host cluster", target.id))?; - - let atlas_candidates = self - .registry - .atlas_cells() - .into_iter() - .filter(|cell| cell.source_regime == *src && cell.target_regime == *tgt) - .filter(|cell| cell.burden_class == target.burden_class) - .collect::>(); - - let mut candidates = atlas_candidates - .into_iter() - .filter_map(|cell| self.score_candidate(&cell, &theorem, &target).ok()) - .collect::>(); - candidates.sort_by(|left, right| left.score.cmp(&right.score)); - - let selected = candidates.first().cloned(); - let route_class = self - .registry - .get_route_class(&format!("RTC_{}", theorem.id.trim_start_matches("THS_"))); - let certificate = self - .registry - .get_certificate(&format!("CRT_{}", theorem.id.trim_start_matches("THS_"))); - - let obligation_statuses = self - .registry - .get_campaign(campaign_id.unwrap_or_default()) - .map(|campaign| { - campaign - .obligations - .into_iter() - .filter_map(|id| self.registry.get_obligation(&id)) - .map(|obligation| ObligationStatus { - obligation_id: obligation.id, - kind: obligation.kind, - verdict: obligation.status, - evaluation_mode: l64_core::ObligationEvaluationMode::StoredReceiptUsed, - detail: "stored campaign obligation".into(), - receipts: Vec::new(), - }) - .collect::>() - }) - .unwrap_or_default(); - - let mut reasons = Vec::new(); - let mut diagnostics = Vec::new(); - let verdict = match (&selected, certificate.as_ref()) { - (None, _) => { - diagnostics.push("no lawful atlas candidate satisfied the theorem target".into()); - CertificationVerdict::BlockedOpen - } - (Some(candidate), Some(certificate)) - if certificate.verdict == CertificationVerdict::Certified - || certificate.verdict == CertificationVerdict::Integrated => - { - reasons.push(format!( - "certificate `{}` discharges theorem `{}`", - certificate.id, theorem.id - )); - reasons.push(format!( - "selected normalized path `{}`", - candidate.path.join(" -> ") - )); - certificate.verdict.clone() - } - (Some(candidate), Some(certificate)) => { - reasons.push(format!( - "certificate `{}` exists with verdict {:?}", - certificate.id, certificate.verdict - )); - reasons.push(format!( - "selected normalized path `{}`", - candidate.path.join(" -> ") - )); - certificate.verdict.clone() - } - (Some(candidate), None) => { - reasons.push(format!("selected atlas cell `{}`", candidate.atlas_cell_id)); - reasons.push(format!( - "selected normalized path `{}`", - candidate.path.join(" -> ") - )); - CertificationVerdict::RouteFound - } - }; - - Ok(CertificationReport { - theorem_id: theorem.id, - campaign_id: campaign_id.map(ToString::to_string), - target_profile_id: target.id, - verdict, - selected_atlas_cell: selected.as_ref().map(|item| item.atlas_cell_id.clone()), - selected_path: selected - .as_ref() - .map(|item| item.path.clone()) - .unwrap_or_default(), - route_class_id: route_class.as_ref().map(|item| item.id.clone()), - certificate_id: certificate.as_ref().map(|item| item.id.clone()), - candidates, - obligations: obligation_statuses, - reasons, - diagnostics, - deficiencies: Vec::new(), - adequacy_records: Vec::new(), - checker_receipts: Vec::new(), - burden_pack_ids: Vec::new(), - claim_packet_ids: Vec::new(), - evidence_contract_ids: Vec::new(), - benchmark_receipt_ids: Vec::new(), - challenge_receipt_ids: Vec::new(), - reproducibility_packet_ids: Vec::new(), - promotion_artifact_ids: Vec::new(), - reused_artifact_ids: Vec::new(), - default_selected_artifact_ids: Vec::new(), - payoff_receipt_ids: Vec::new(), - policy_resolution: None, - route_explanation: None, - execution_envelope: None, - reconciliation_summary: Vec::new(), - obligation_plan: None, - obligation_lanes: Vec::new(), - obligation_ordering_receipt: None, - obligation_merge_receipt: None, - replay_legality_checks: Vec::new(), - replay_barrier_receipts: Vec::new(), - replay_merge_receipt: None, - replay_divergence_records: Vec::new(), - obligation_cache_shards: Vec::new(), - reuse_legality_receipts: Vec::new(), - reuse_decision_receipts: Vec::new(), - residual_verification_receipts: Vec::new(), - obligation_write_sets: Vec::new(), - obligation_collision_reports: Vec::new(), - obligation_namespace_receipt: None, - }) - } - - fn score_candidate( - &self, - cell: &AtlasCell, - theorem: &l64_core::TheoremSpec, - target: &l64_core::TargetProfile, - ) -> Result { - let path = cell.normalized_winner.clone(); - let bridges = path - .iter() - .map(|id| { - self.registry - .get_bridge(id) - .ok_or_else(|| format!("unknown bridge `{id}`")) - }) - .collect::, _>>()?; - - if bridges.iter().any(|bridge| { - !target - .allowed_bridge_classes - .contains(&bridge.reversibility) - }) { - return Err("bridge class outside target profile".into()); - } - - let budget = Budget { - max_loss: target.loss_ceiling, - allow_lossy_supported: target - .allowed_bridge_classes - .contains(&l64_core::ReversibilityClass::LossySupported), - require_proof: true, - }; - - self.kernel.compose_bridge_path(&bridges, Some(&budget))?; - - let proof_family_penalty = proof_family_penalty( - &target.required_proof_shape_family, - &cell.proof_shapes_checked, - &self.registry, - ); - - let route_class_id = self - .registry - .get_route_class(&format!("RTC_{}", theorem.id.trim_start_matches("THS_"))) - .and_then(|route_class| { - if route_class.canonical_path == path { - Some(route_class.id) - } else { - None - } - }); - - Ok(CertificationCandidate { - atlas_cell_id: cell.id.clone(), - path: path.clone(), - loss_count: cell.loss_profile.items.len(), - proof_shapes: cell.proof_shapes_checked.clone(), - route_class_id, - score: vec![ - usize::from(cell.winner_state != WinnerState::SeedWinner), - cell.loss_profile.items.len(), - bridges.len(), - proof_family_penalty, - ], - route_score: None, - }) - } -} - -fn proof_family_penalty( - family: &RequiredProofShapeFamily, - proof_shapes: &[String], - registry: &R, -) -> usize { - match family { - RequiredProofShapeFamily::Minimal => usize::from(proof_shapes.is_empty()), - RequiredProofShapeFamily::MixedBattery => usize::from(proof_shapes.is_empty()), - RequiredProofShapeFamily::Triangle => usize::from(!proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Triangle) - .unwrap_or(false) - })), - RequiredProofShapeFamily::Square => usize::from(!proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Square) - .unwrap_or(false) - })), - RequiredProofShapeFamily::Diamond => usize::from(!proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Diamond) - .unwrap_or(false) - })), - RequiredProofShapeFamily::Pentagon => usize::from(!proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Pentagon) - .unwrap_or(false) - })), - RequiredProofShapeFamily::Hexagon => usize::from(!proof_shapes.iter().any(|id| { - registry - .get_proof_shape(id) - .map(|shape| shape.kind == l64_core::ProofShapeKind::Hexagon) - .unwrap_or(false) - })), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use l64_core::{ - BurdenClass, Campaign, CampaignClass, Certificate, CertificationVerdict, FailureSignature, - LossProfile, Obligation, ObligationKind, RecipeMaturity, RegistryLookup, RouteClass, - RouteLedger, TargetProfile, TheoremSpec, WinnerState, - }; - - #[derive(Clone)] - struct TestRegistry { - cells: Vec, - regimes: Vec, - proof_shapes: Vec, - bridges: Vec, - theorem_specs: Vec, - obligations: Vec, - target_profiles: Vec, - route_ledgers: Vec, - certificates: Vec, - campaigns: Vec, - route_classes: Vec, - } - - impl RegistryLookup for TestRegistry { - fn get_object(&self, _id: &str) -> Option { - None - } - fn get_regime(&self, id: &str) -> Option { - self.regimes.iter().find(|item| item.id == id).cloned() - } - fn get_bridge(&self, id: &str) -> Option { - self.bridges.iter().find(|item| item.id == id).cloned() - } - fn get_proof_shape(&self, id: &str) -> Option { - self.proof_shapes.iter().find(|item| item.id == id).cloned() - } - fn get_atlas_cell(&self, _id: &str) -> Option { - None - } - fn get_mechanization_package(&self, _id: &str) -> Option { - None - } - fn get_theorem_spec(&self, id: &str) -> Option { - self.theorem_specs - .iter() - .find(|item| item.id == id) - .cloned() - } - fn get_obligation(&self, id: &str) -> Option { - self.obligations.iter().find(|item| item.id == id).cloned() - } - fn get_target_profile(&self, id: &str) -> Option { - self.target_profiles - .iter() - .find(|item| item.id == id) - .cloned() - } - fn get_route_ledger(&self, id: &str) -> Option { - self.route_ledgers - .iter() - .find(|item| item.id == id) - .cloned() - } - fn get_certificate(&self, id: &str) -> Option { - self.certificates.iter().find(|item| item.id == id).cloned() - } - fn get_campaign(&self, id: &str) -> Option { - self.campaigns.iter().find(|item| item.id == id).cloned() - } - fn get_campaign_portfolio(&self, _id: &str) -> Option { - None - } - fn get_route_class(&self, id: &str) -> Option { - self.route_classes - .iter() - .find(|item| item.id == id) - .cloned() - } - fn get_atlas_deficiency(&self, _id: &str) -> Option { - None - } - fn atlas_deficiencies(&self) -> Vec { - Vec::new() - } - fn get_adequacy_clause(&self, _id: &str) -> Option { - None - } - fn adequacy_clauses(&self) -> Vec { - Vec::new() - } - fn get_codebook_pack(&self, _id: &str) -> Option { - None - } - fn get_glyph_pack(&self, _id: &str) -> Option { - None - } - fn get_combo_pack(&self, _id: &str) -> Option { - None - } - fn get_projection_policy(&self, _id: &str) -> Option { - None - } - fn get_alias_expansion_policy(&self, _id: &str) -> Option { - None - } - fn get_surface_deficiency(&self, _id: &str) -> Option { - None - } - fn get_policy_object(&self, _id: &str) -> Option { - None - } - fn policy_objects(&self) -> Vec { - Vec::new() - } - fn policy_bindings(&self) -> Vec { - Vec::new() - } - fn find_equivalence_class( - &self, - _object_id: &str, - _regime: &str, - ) -> Option { - None - } - fn atlas_cells(&self) -> Vec { - self.cells.clone() - } - } - - #[test] - fn selector_prefers_seed_winner() { - let registry = TestRegistry { - cells: vec![l64_core::AtlasCell { - id: "A1".into(), - source_regime: "R_TYP".into(), - target_regime: "R_SET".into(), - burden_class: BurdenClass::ExtensionalCarrierReasoning, - proof_target: "carrier".into(), - candidate_paths: vec![vec!["B1".into()]], - normalized_winner: vec!["B1".into()], - winner_state: WinnerState::SeedWinner, - loss_profile: LossProfile { items: vec![] }, - proof_shapes_checked: vec![], - recipe_maturity: RecipeMaturity::Seeded, - failure_signatures: vec![FailureSignature { - code: "OK".into(), - message: "ok".into(), - }], - side_conditions: vec![], - surface_transition: None, - }], - regimes: vec![], - proof_shapes: vec![], - bridges: vec![], - theorem_specs: vec![], - obligations: vec![], - target_profiles: vec![], - route_ledgers: vec![], - certificates: vec![], - campaigns: vec![], - route_classes: vec![], - }; - let selector = AtlasSelector::new(registry); - let result = selector - .select_route("R_TYP", "R_SET", Some("carrier"), None) - .unwrap(); - assert_eq!(result.winner.unwrap().id, "A1"); - } - - #[test] - fn certifier_returns_benchmarked_campaign_report() { - let registry = TestRegistry { - cells: vec![l64_core::AtlasCell { - id: "A_TOP_TO_CALC".into(), - source_regime: "R_TOP".into(), - target_regime: "R_CALC".into(), - burden_class: BurdenClass::DerivativeLocalWitnessExtraction, - proof_target: "derivative witness extraction".into(), - candidate_paths: vec![vec!["B_TOP_TO_CALC".into()]], - normalized_winner: vec!["B_TOP_TO_CALC".into()], - winner_state: WinnerState::SeedWinner, - loss_profile: LossProfile { items: vec![] }, - proof_shapes_checked: vec!["PS_SQUARE".into()], - recipe_maturity: RecipeMaturity::Seeded, - failure_signatures: vec![], - side_conditions: vec![], - surface_transition: None, - }], - regimes: vec![ - l64_core::RegimePack { - id: "R_TOP".into(), - ctx_law: "ctx".into(), - cut_law: "cut".into(), - thr_law: "thr".into(), - brc_law: "brc".into(), - slk_law: "slk".into(), - tol_law: "tol".into(), - knt_law: "knt".into(), - eq_law: "eq".into(), - adm_law: "adm".into(), - promoted_ops: vec![], - }, - l64_core::RegimePack { - id: "R_CALC".into(), - ctx_law: "ctx".into(), - cut_law: "cut".into(), - thr_law: "thr".into(), - brc_law: "brc".into(), - slk_law: "slk".into(), - tol_law: "tol".into(), - knt_law: "knt".into(), - eq_law: "eq".into(), - adm_law: "adm".into(), - promoted_ops: vec![], - }, - ], - proof_shapes: vec![l64_core::ProofShape { - id: "PS_SQUARE".into(), - kind: l64_core::ProofShapeKind::Square, - nodes: vec!["a".into(), "b".into(), "c".into(), "d".into()], - edges: vec![ - l64_core::ProofEdge { - from: "a".into(), - to: "b".into(), - label: "f".into(), - }, - l64_core::ProofEdge { - from: "b".into(), - to: "d".into(), - label: "g".into(), - }, - l64_core::ProofEdge { - from: "a".into(), - to: "c".into(), - label: "h".into(), - }, - l64_core::ProofEdge { - from: "c".into(), - to: "d".into(), - label: "i".into(), - }, - ], - equations: vec!["g∘f=i∘h".into()], - target_equivalence: "eq".into(), - receipts: vec!["r".into()], - gate: l64_core::GateVerdict::Pass, - }], - bridges: vec![l64_core::BridgeContract { - id: "B_TOP_TO_CALC".into(), - src: "R_TOP".into(), - tgt: "R_CALC".into(), - id_pres: "pres".into(), - eq_pres: "eq".into(), - forget: vec![], - enrich: vec!["der".into()], - loss: vec![], - reversibility: l64_core::ReversibilityClass::Enriching, - receipts: vec!["Ref_1".into()], - rollback: "allowed".into(), - }], - theorem_specs: vec![TheoremSpec { - id: "THS_CHAIN_RULE".into(), - statement: "chain".into(), - hosts: vec!["R_TOP".into(), "R_CALC".into()], - bridges: vec!["B_TOP_TO_CALC".into()], - operators: vec!["OPR.Chain1".into()], - target_equivalence: "eq".into(), - obligations: vec![ObligationKind::OblEq], - primary_zone: l64_core::ProofMechanismZone::PmzStructural, - verdict: CertificationVerdict::Benchmarked, - proof_shapes: vec!["PS_SQUARE".into()], - }], - obligations: vec![Obligation { - id: "OBL_CHAIN_EQ".into(), - kind: ObligationKind::OblEq, - description: "eq".into(), - status: CertificationVerdict::Benchmarked, - }], - target_profiles: vec![TargetProfile { - id: "TGT_CHAIN_RULE".into(), - burden_class: BurdenClass::DerivativeLocalWitnessExtraction, - host_cluster: vec!["R_TOP".into(), "R_CALC".into()], - target_equivalence: "eq".into(), - allowed_bridge_classes: vec![l64_core::ReversibilityClass::Enriching], - loss_ceiling: 1, - rollback_ceiling: 1, - required_receipt_class: "RC".into(), - required_proof_shape_family: l64_core::RequiredProofShapeFamily::Square, - promotion_goal: l64_core::PromotionGoal::PromoteOperator, - primary_zone: l64_core::ProofMechanismZone::PmzStructural, - surface_requirement: None, - preferred_surface_target: None, - optimizer_policy: None, - policy_binding_ids: vec![], - }], - route_ledgers: vec![RouteLedger { - id: "TRL_CHAIN_RULE".into(), - theorem: "THS_CHAIN_RULE".into(), - paths: vec![vec!["B_TOP_TO_CALC".into()]], - budget: l64_core::Budget { - max_loss: 1, - allow_lossy_supported: false, - require_proof: true, - }, - losses: vec![], - receipts: vec!["Ref_1".into()], - normalized_path: vec!["B_TOP_TO_CALC".into()], - }], - certificates: vec![Certificate { - id: "CRT_CHAIN_RULE".into(), - theorem: "THS_CHAIN_RULE".into(), - route_ledger: "TRL_CHAIN_RULE".into(), - proof_shapes: vec!["PS_SQUARE".into()], - receipts: vec!["RC".into()], - verdict: CertificationVerdict::Benchmarked, - }], - campaigns: vec![Campaign { - id: "CPG_CHAIN_RULE".into(), - theorem: "THS_CHAIN_RULE".into(), - target_profile: "TGT_CHAIN_RULE".into(), - route_ledger: "TRL_CHAIN_RULE".into(), - obligations: vec!["OBL_CHAIN_EQ".into()], - certificates: vec!["CRT_CHAIN_RULE".into()], - dependencies: vec![], - campaign_class: CampaignClass::COperator, - verdict: CertificationVerdict::Benchmarked, - payoff: vec!["OPR.Chain1".into()], - }], - route_classes: vec![RouteClass { - id: "RTC_CHAIN_RULE".into(), - theorem: "THS_CHAIN_RULE".into(), - target_profile: "TGT_CHAIN_RULE".into(), - equivalent_paths: vec![vec!["B_TOP_TO_CALC".into()]], - canonical_path: vec!["B_TOP_TO_CALC".into()], - verdict: CertificationVerdict::Benchmarked, - }], - }; - let certifier = CampaignCertifier::new(registry); - let report = certifier.certify_campaign("CPG_CHAIN_RULE").unwrap(); - assert_eq!(report.verdict, CertificationVerdict::Benchmarked); - assert_eq!(report.selected_atlas_cell.as_deref(), Some("A_TOP_TO_CALC")); - } -} diff --git a/l64-symbolic/Cargo.toml b/l64-symbolic/Cargo.toml new file mode 100644 index 0000000..edcb7c5 --- /dev/null +++ b/l64-symbolic/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "l64-symbolic" +edition.workspace = true +version.workspace = true +license.workspace = true diff --git a/l64-symbolic/DESIGN.md b/l64-symbolic/DESIGN.md new file mode 100644 index 0000000..036b436 --- /dev/null +++ b/l64-symbolic/DESIGN.md @@ -0,0 +1,75 @@ +# Symbolic commitment law + +## 1. Separation of authority and acceleration + +For domain `D` and canonical structure `x`, exact identity is the self-delimiting term + +```text +I(D, x) = L64S1 ‖ |D| ‖ |x| ‖ D ‖ x +``` + +where lengths are fixed-width little-endian integers. Equality of `I(D, x)` is ordinary byte equality, so no collision assumption is involved. + +The compact seal + +```text +S(D, x) = ⟦D ∷ Σ(x) ⊗ Π(x) ⊗ Δ(x) ⊗ Ω(x)⟧ +``` + +is a 256-bit projection of the exact term. `S(a) ≠ S(b)` proves inequality. `S(a) = S(b)` is only permission to continue to exact comparison. + +## 2. Composition grammar + +- `∷` qualifies a term by domain. +- `⊗` composes an ordered sequence; permutation changes the result. +- `⊕` composes a canonical set after sorting; permutation does not change the result. +- `↦` binds a source, relation, and result as a derivation. +- `⟦…⟧` delimits a symbolic commitment expression. + +Every field is length-delimited and marked by a distinct boundary token. Domain, label, value, order, segment count, and total absorbed length therefore occupy explicit positions in the input algebra. + +## 3. Coordinate roles + +All arithmetic is performed modulo the prime `2^64 - 59`. + +### `Σ` — aggregate content mass + +A weighted modular sum over tokens and position. It intentionally changes more locally than the other coordinates and supports coarse change diagnosis. + +### `Π` — ordered composition + +A Horner-style polynomial recurrence. It distinguishes sequence order and broadly diffuses changes. + +### `Δ` — adjacent transition structure + +A recurrence over squared token-to-token differences. It distinguishes changes in local transitions even when aggregate content is similar. + +### `Ω` — nonlinear boundary closure + +A quadratic recurrence influenced by token, position, and segment boundaries. It supplies broad diffusion and boundary sensitivity. + +The coordinates are deliberately nonredundant. A seal is interpreted as their conjunction, not as four interchangeable random words. + +## 4. Native state decomposition + +The native graph derives independent seals for: + +```text +nodes ⊗ ports ⊗ contexts ⊗ routes +``` + +The root state symbol composes these section seals with codec version and section counts. This permits fast rejection and localizes which structural family changed without introducing a second graph or stored index. + +## 5. Verification law + +1. Reject malformed framing or a mismatched compact seal. +2. Decode the canonical payload under native structural law. +3. Re-execute validation rules. +4. Re-encode canonically and require the exact fixed point. +5. Use exact identity for positive authority equality. + +No compact symbolic seal, including a matching seal, may bypass steps 2–5. + +## 6. Security and trust boundary + +The seal is not claimed as a cryptographic hash, signature, MAC, or adversarial authenticity mechanism. An unkeyed digest does not establish who produced an artifact. Authenticity belongs to signed transport or another explicit trust carrier. The symbolic system replaces BLAKE3 inside native state identity by removing probabilistic equality from the authority decision, not by making an unsupported cryptographic claim. diff --git a/l64-symbolic/README.md b/l64-symbolic/README.md new file mode 100644 index 0000000..feffbdb --- /dev/null +++ b/l64-symbolic/README.md @@ -0,0 +1,33 @@ +# l64-symbolic + +`l64-symbolic` separates **exact symbolic identity** from **compact symbolic sealing**. + +- Exact identity is the domain plus canonical bytes. Equality is therefore injective by representation, not probabilistic. +- A `SymbolicSeal` is a fixed-width, composable projection used for fast inequality, frame corruption checks, indexing, and developer-facing state references. It is never sufficient authority for equality. + +## Algebra + +A composer absorbs an explicitly tagged token stream under the prime modulus `2^64 - 59` and exposes four independently purposed coordinates: + +- `Σ` — weighted aggregate mass; +- `Π` — ordered Horner composition; +- `Δ` — adjacency/change structure; +- `Ω` — nonlinear boundary closure. + +Ordered composition uses `⊗`; commutative composition uses `⊕` after canonical sorting; derivation uses `↦`; domain qualification uses `∷`; `⟦…⟧` marks the symbolic boundary. + +The pretty form is intentionally readable: + +```text +⟦l64.native.state.v2 ∷ Σ… ⊗ Π… ⊗ Δ… ⊗ Ω…⟧ +``` + +The stable ASCII form is parser-safe: + +```text +s1:... +``` + +## Security boundary + +The compact seal is not presented as a new cryptographic primitive. Exact canonical bytes remain authority. A seal may reject inequality early, but positive equality requires exact canonical reconstruction or byte equality. This gives Locus64 stronger system-level discipline than substituting an unaudited home-grown digest for BLAKE3. diff --git a/l64-symbolic/examples/symbolic_audit.rs b/l64-symbolic/examples/symbolic_audit.rs new file mode 100644 index 0000000..1fdbd77 --- /dev/null +++ b/l64-symbolic/examples/symbolic_audit.rs @@ -0,0 +1,48 @@ +use l64_symbolic::{Composer, SealAxis, SymbolicSeal}; +use std::collections::BTreeSet; + +fn seal(value: u64) -> SymbolicSeal { + let mut composer = Composer::new("l64.audit.u64"); + composer.u64("value", value); + composer.finish() +} + +fn bit_distance(left: u64, right: u64) -> u32 { + (left ^ right).count_ones() +} + +fn main() { + const SAMPLES: u64 = 1_000_000; + let mut full = BTreeSet::new(); + let mut axes = [ + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + ]; + let mut diffusion = [0_u64; 4]; + + for value in 0..SAMPLES { + let current = seal(value); + assert!(full.insert(current), "full seal collision at {value}"); + for (index, coordinate) in current.axes().into_iter().enumerate() { + axes[index].insert(coordinate); + } + let flipped = seal(value ^ (1_u64 << (value % 64))); + for (index, total) in diffusion.iter_mut().enumerate() { + *total += bit_distance(current.axes()[index], flipped.axes()[index]) as u64; + } + } + + println!("samples={SAMPLES}"); + println!("full_unique={}", full.len()); + for (index, axis) in SealAxis::ALL.into_iter().enumerate() { + println!( + "{} role={} unique={} mean_bit_change={:.3}", + axis.symbol(), + axis.role(), + axes[index].len(), + diffusion[index] as f64 / SAMPLES as f64 + ); + } +} diff --git a/l64-symbolic/examples/symbolic_commitment.rs b/l64-symbolic/examples/symbolic_commitment.rs new file mode 100644 index 0000000..c05d41a --- /dev/null +++ b/l64-symbolic/examples/symbolic_commitment.rs @@ -0,0 +1,28 @@ +use l64_symbolic::{Composer, exact_identity}; + +fn main() { + let source = exact_identity("l64.example.source", b"typed(a -> b)"); + let result = exact_identity("l64.example.result", b"typed(a -> c)"); + let derivation = Composer::derive( + "l64.example.derivation", + "compose", + source.seal(), + result.seal(), + ); + + println!("source: {}", source.pretty()); + println!("result: {}", result.pretty()); + println!( + "derived: {}", + derivation.pretty("l64.example.derivation ∷ compose") + ); + for change in source.seal().explain_changes(result.seal()) { + println!( + "{} ({}) {:016x} -> {:016x}", + change.axis.symbol(), + change.axis.role(), + change.before, + change.after + ); + } +} diff --git a/l64-symbolic/src/lib.rs b/l64-symbolic/src/lib.rs new file mode 100644 index 0000000..9cefb1e --- /dev/null +++ b/l64-symbolic/src/lib.rs @@ -0,0 +1,447 @@ +#![forbid(unsafe_code)] + +use core::{fmt, str::FromStr}; + +const MODULUS: u64 = 18_446_744_073_709_551_557; +const BASE_SIGMA: u64 = 1_099_511_628_211; +const BASE_PI: u64 = 1_469_598_103_934_665_603; +const BASE_DELTA: u64 = 2_305_843_009_213_693_951; +const BASE_OMEGA: u64 = 6_364_136_223_846_793_005; +const IDENTITY_MAGIC: &[u8; 5] = b"L64S1"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum SealAxis { + Sigma, + Pi, + Delta, + Omega, +} + +impl SealAxis { + pub const ALL: [Self; 4] = [Self::Sigma, Self::Pi, Self::Delta, Self::Omega]; + + pub const fn symbol(self) -> &'static str { + match self { + Self::Sigma => "Σ", + Self::Pi => "Π", + Self::Delta => "Δ", + Self::Omega => "Ω", + } + } + + pub const fn role(self) -> &'static str { + match self { + Self::Sigma => "aggregate content mass", + Self::Pi => "ordered composition", + Self::Delta => "adjacent transition structure", + Self::Omega => "nonlinear boundary closure", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AxisChange { + pub axis: SealAxis, + pub before: u64, + pub after: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct SymbolicSeal { + axes: [u64; 4], +} + +impl SymbolicSeal { + pub const ZERO: Self = Self { axes: [0; 4] }; + + pub const fn from_axes(sigma: u64, pi: u64, delta: u64, omega: u64) -> Self { + Self { + axes: [sigma, pi, delta, omega], + } + } + + pub const fn axes(self) -> [u64; 4] { + self.axes + } + + pub const fn sigma(self) -> u64 { + self.axes[0] + } + + pub const fn pi(self) -> u64 { + self.axes[1] + } + + pub const fn delta(self) -> u64 { + self.axes[2] + } + + pub const fn omega(self) -> u64 { + self.axes[3] + } + + pub fn to_bytes(self) -> [u8; 32] { + let mut out = [0_u8; 32]; + for (index, axis) in self.axes.into_iter().enumerate() { + out[index * 8..index * 8 + 8].copy_from_slice(&axis.to_le_bytes()); + } + out + } + + pub fn from_bytes(bytes: [u8; 32]) -> Self { + let mut axes = [0_u64; 4]; + for (index, axis) in axes.iter_mut().enumerate() { + *axis = u64::from_le_bytes( + bytes[index * 8..index * 8 + 8] + .try_into() + .expect("symbolic seal axis width"), + ); + } + Self { axes } + } + + pub fn pretty(self, domain: &str) -> String { + format!( + "⟦{domain} ∷ Σ{:016x} ⊗ Π{:016x} ⊗ Δ{:016x} ⊗ Ω{:016x}⟧", + self.sigma(), + self.pi(), + self.delta(), + self.omega() + ) + } + + pub fn changed_axes(self, other: Self) -> Vec { + SealAxis::ALL + .into_iter() + .zip(self.axes.into_iter().zip(other.axes)) + .filter_map(|(axis, (left, right))| (left != right).then_some(axis)) + .collect() + } + + pub fn explain_changes(self, other: Self) -> Vec { + SealAxis::ALL + .into_iter() + .zip(self.axes.into_iter().zip(other.axes)) + .filter_map(|(axis, (before, after))| { + (before != after).then_some(AxisChange { + axis, + before, + after, + }) + }) + .collect() + } + + pub fn fast_matches(self, other: Self) -> bool { + self == other + } +} + +impl fmt::Display for SymbolicSeal { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "s1:{:016x}.{:016x}.{:016x}.{:016x}", + self.sigma(), + self.pi(), + self.delta(), + self.omega() + ) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ParseSealError; + +impl FromStr for SymbolicSeal { + type Err = ParseSealError; + + fn from_str(value: &str) -> Result { + let body = value.strip_prefix("s1:").ok_or(ParseSealError)?; + let mut parts = body.split('.'); + let mut axes = [0_u64; 4]; + for axis in &mut axes { + let part = parts.next().ok_or(ParseSealError)?; + if part.len() != 16 { + return Err(ParseSealError); + } + *axis = u64::from_str_radix(part, 16).map_err(|_| ParseSealError)?; + } + if parts.next().is_some() { + return Err(ParseSealError); + } + Ok(Self { axes }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SymbolicIdentity { + domain: Box, + canonical: Box<[u8]>, +} + +impl SymbolicIdentity { + pub fn new(domain: impl Into>, canonical: impl Into>) -> Self { + Self { + domain: domain.into(), + canonical: canonical.into(), + } + } + + pub fn domain(&self) -> &str { + &self.domain + } + + pub fn canonical(&self) -> &[u8] { + &self.canonical + } + + pub fn seal(&self) -> SymbolicSeal { + let mut composer = Composer::new(&self.domain); + composer.field("canonical", &self.canonical); + composer.finish() + } + + pub fn verify_exact(&self, domain: &str, canonical: &[u8]) -> bool { + self.domain.as_ref() == domain && self.canonical.as_ref() == canonical + } + + pub fn to_exact_bytes(&self) -> Vec { + let domain_len: u32 = self + .domain + .len() + .try_into() + .expect("symbolic identity domain exceeds u32"); + let canonical_len: u64 = self + .canonical + .len() + .try_into() + .expect("symbolic identity payload exceeds u64"); + let mut out = Vec::with_capacity( + IDENTITY_MAGIC.len() + 4 + 8 + self.domain.len() + self.canonical.len(), + ); + out.extend_from_slice(IDENTITY_MAGIC); + out.extend_from_slice(&domain_len.to_le_bytes()); + out.extend_from_slice(&canonical_len.to_le_bytes()); + out.extend_from_slice(self.domain.as_bytes()); + out.extend_from_slice(&self.canonical); + out + } + + pub fn from_exact_bytes(bytes: &[u8]) -> Result { + const HEADER: usize = 5 + 4 + 8; + if bytes.len() < HEADER { + return Err(IdentityDecodeError::Truncated); + } + if &bytes[..5] != IDENTITY_MAGIC { + return Err(IdentityDecodeError::BadMagic); + } + let domain_len = u32::from_le_bytes( + bytes[5..9] + .try_into() + .map_err(|_| IdentityDecodeError::Truncated)?, + ) as usize; + let canonical_len = u64::from_le_bytes( + bytes[9..17] + .try_into() + .map_err(|_| IdentityDecodeError::Truncated)?, + ); + let canonical_len: usize = canonical_len + .try_into() + .map_err(|_| IdentityDecodeError::LengthOverflow)?; + let domain_end = HEADER + .checked_add(domain_len) + .ok_or(IdentityDecodeError::LengthOverflow)?; + let expected = domain_end + .checked_add(canonical_len) + .ok_or(IdentityDecodeError::LengthOverflow)?; + if bytes.len() < expected { + return Err(IdentityDecodeError::Truncated); + } + if bytes.len() > expected { + return Err(IdentityDecodeError::TrailingBytes); + } + let domain = core::str::from_utf8(&bytes[HEADER..domain_end]) + .map_err(|_| IdentityDecodeError::InvalidDomain)?; + Ok(Self::new(domain, &bytes[domain_end..])) + } + + pub fn pretty(&self) -> String { + format!( + "{} ∣ |exact|={}B", + self.seal().pretty(&self.domain), + self.canonical.len() + ) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IdentityDecodeError { + Truncated, + BadMagic, + InvalidDomain, + LengthOverflow, + TrailingBytes, +} + +pub fn exact_identity(domain: &str, canonical: &[u8]) -> SymbolicIdentity { + SymbolicIdentity::new(domain, canonical) +} + +pub fn seal_bytes(domain: &str, canonical: &[u8]) -> SymbolicSeal { + exact_identity(domain, canonical).seal() +} + +#[derive(Debug, Clone)] +pub struct Composer { + axes: [u64; 4], + position: u64, + previous: u64, + segments: u64, +} + +impl Composer { + pub fn new(domain: &str) -> Self { + let mut composer = Self { + axes: [ + 0x5359_4d42_4f4c_4943, + 0x4c36_3453_4541_4c31, + 0x4f52_4445_5245_4431, + 0x424f_554e_4441_5259, + ], + position: 0, + previous: 0, + segments: 0, + }; + composer.boundary(0x01); + composer.raw(domain.as_bytes()); + composer.boundary(0x02); + composer + } + + pub fn field(&mut self, label: &str, bytes: &[u8]) -> &mut Self { + self.boundary(0x10); + self.length(label.len()); + self.raw(label.as_bytes()); + self.boundary(0x11); + self.length(bytes.len()); + self.raw(bytes); + self.boundary(0x12); + self + } + + pub fn u64(&mut self, label: &str, value: u64) -> &mut Self { + self.field(label, &value.to_le_bytes()) + } + + pub fn u32(&mut self, label: &str, value: u32) -> &mut Self { + self.field(label, &value.to_le_bytes()) + } + + pub fn u16(&mut self, label: &str, value: u16) -> &mut Self { + self.field(label, &value.to_le_bytes()) + } + + pub fn u8(&mut self, label: &str, value: u8) -> &mut Self { + self.field(label, &[value]) + } + + pub fn ordered(&mut self, label: &str, parts: &[SymbolicSeal]) -> &mut Self { + self.boundary(0x20); + self.length(label.len()); + self.raw(label.as_bytes()); + self.length(parts.len()); + for part in parts { + self.boundary(0x21); + self.raw(&part.to_bytes()); + } + self.boundary(0x22); + self + } + + pub fn commutative(&mut self, label: &str, parts: &[SymbolicSeal]) -> &mut Self { + let mut sorted = parts.to_vec(); + sorted.sort(); + self.boundary(0x30); + self.length(label.len()); + self.raw(label.as_bytes()); + self.length(sorted.len()); + for part in sorted { + self.boundary(0x31); + self.raw(&part.to_bytes()); + } + self.boundary(0x32); + self + } + + pub fn derive( + domain: &str, + relation: &str, + source: SymbolicSeal, + result: SymbolicSeal, + ) -> SymbolicSeal { + let mut composer = Self::new(domain); + composer.field("relation", relation.as_bytes()); + composer.ordered("derivation", &[source, result]); + composer.finish() + } + + pub fn finish(mut self) -> SymbolicSeal { + self.boundary(0xff); + self.u64("length", self.position); + self.u64("segments", self.segments); + SymbolicSeal { axes: self.axes } + } + + fn length(&mut self, value: usize) { + self.raw(&(value as u64).to_le_bytes()); + } + + fn boundary(&mut self, marker: u8) { + self.segments = self.segments.wrapping_add(1); + self.absorb(u64::from(marker) + 0x100); + } + + fn raw(&mut self, bytes: &[u8]) { + for &byte in bytes { + self.absorb(u64::from(byte) + 1); + } + } + + fn absorb(&mut self, token: u64) { + let index = self.position.wrapping_add(1); + let sigma_term = mul_mod(token, add_mod(index, BASE_SIGMA)); + self.axes[0] = add_mod(self.axes[0], sigma_term); + + self.axes[1] = mul_mod(add_mod(self.axes[1], token), BASE_PI); + + let transition = if self.position == 0 { + token + } else if token >= self.previous { + token - self.previous + } else { + MODULUS - (self.previous - token) + }; + self.axes[2] = add_mod( + mul_mod(self.axes[2], BASE_DELTA), + mul_mod(transition, transition), + ); + + let omega_input = add_mod(add_mod(self.axes[3], token), index); + self.axes[3] = add_mod( + mul_mod(mul_mod(omega_input, omega_input), BASE_OMEGA), + self.segments % MODULUS, + ); + + self.previous = token; + self.position = index; + } +} + +fn add_mod(left: u64, right: u64) -> u64 { + ((u128::from(left) + u128::from(right)) % u128::from(MODULUS)) as u64 +} + +fn mul_mod(left: u64, right: u64) -> u64 { + ((u128::from(left) * u128::from(right)) % u128::from(MODULUS)) as u64 +} diff --git a/l64-symbolic/tests/algebra.rs b/l64-symbolic/tests/algebra.rs new file mode 100644 index 0000000..8476b10 --- /dev/null +++ b/l64-symbolic/tests/algebra.rs @@ -0,0 +1,116 @@ +use l64_symbolic::{ + Composer, SealAxis, SymbolicIdentity, SymbolicSeal, exact_identity, seal_bytes, +}; +use std::collections::BTreeSet; + +fn atom(domain: &str, label: &str, bytes: &[u8]) -> SymbolicSeal { + let mut composer = Composer::new(domain); + composer.field(label, bytes); + composer.finish() +} + +#[test] +fn exact_identity_is_collision_free_by_representation() { + let identity = SymbolicIdentity::new("l64.test", b"abc".as_slice()); + assert!(identity.verify_exact("l64.test", b"abc")); + assert!(!identity.verify_exact("l64.test", b"abd")); + assert!(!identity.verify_exact("l64.other", b"abc")); + assert_eq!( + SymbolicIdentity::from_exact_bytes(&identity.to_exact_bytes()).unwrap(), + identity + ); +} + +#[test] +fn domains_are_separated() { + assert_ne!( + atom("left", "payload", b"same"), + atom("right", "payload", b"same") + ); +} + +#[test] +fn ordered_composition_preserves_order() { + let a = atom("leaf", "a", b"a"); + let b = atom("leaf", "b", b"b"); + let mut left = Composer::new("ordered"); + left.ordered("parts", &[a, b]); + let mut right = Composer::new("ordered"); + right.ordered("parts", &[b, a]); + assert_ne!(left.finish(), right.finish()); +} + +#[test] +fn commutative_composition_normalizes_order() { + let a = atom("leaf", "a", b"a"); + let b = atom("leaf", "b", b"b"); + let mut left = Composer::new("set"); + left.commutative("parts", &[a, b]); + let mut right = Composer::new("set"); + right.commutative("parts", &[b, a]); + assert_eq!(left.finish(), right.finish()); +} + +#[test] +fn canonical_text_round_trips() { + let seal = atom("roundtrip", "payload", b"hello"); + assert_eq!(seal.to_string().parse::().unwrap(), seal); + assert_eq!(SymbolicSeal::from_bytes(seal.to_bytes()), seal); +} + +#[test] +fn axis_changes_are_explainable() { + let left = atom("diff", "payload", b"abc"); + let right = atom("diff", "payload", b"abd"); + let axes = left.changed_axes(right); + assert!(!axes.is_empty()); + assert!(axes.contains(&SealAxis::Sigma)); + let changes = left.explain_changes(right); + assert_eq!(changes.len(), axes.len()); + assert!(changes.iter().all(|change| change.before != change.after)); + assert!(left.pretty("diff").contains('Σ')); + assert!(left.pretty("diff").contains('Ω')); +} + +#[test] +fn small_input_space_has_no_observed_full_seal_collision() { + let mut seen = BTreeSet::new(); + for value in 0_u16..=u16::MAX { + let seal = atom("exhaustive-u16", "value", &value.to_le_bytes()); + assert!(seen.insert(seal), "collision at {value}"); + } +} + +#[test] +fn convenience_helpers_preserve_exact_and_compact_layers() { + let identity = exact_identity("l64.easy", b"payload"); + let seal = seal_bytes("l64.easy", b"payload"); + assert_eq!(identity.seal(), seal); + assert!(identity.verify_exact("l64.easy", b"payload")); + assert!(seal.fast_matches(identity.seal())); +} + +#[test] +fn axis_law_is_typed_and_self_describing() { + let roles = SealAxis::ALL.map(|axis| (axis.symbol(), axis.role())); + assert_eq!(roles[0], ("Σ", "aggregate content mass")); + assert_eq!(roles[1], ("Π", "ordered composition")); + assert_eq!(roles[2], ("Δ", "adjacent transition structure")); + assert_eq!(roles[3], ("Ω", "nonlinear boundary closure")); +} + +#[test] +fn exact_envelope_is_self_delimiting() { + let identity = exact_identity("l64.envelope", b"payload"); + let mut encoded = identity.to_exact_bytes(); + assert_eq!( + SymbolicIdentity::from_exact_bytes(&encoded).unwrap(), + identity + ); + + encoded.push(0); + assert!(SymbolicIdentity::from_exact_bytes(&encoded).is_err()); + encoded.pop(); + encoded[0] ^= 1; + assert!(SymbolicIdentity::from_exact_bytes(&encoded).is_err()); +} diff --git a/l64-symbolic/tests/architecture.rs b/l64-symbolic/tests/architecture.rs new file mode 100644 index 0000000..336c4db --- /dev/null +++ b/l64-symbolic/tests/architecture.rs @@ -0,0 +1,26 @@ +use core::mem::size_of; +use l64_symbolic::SymbolicSeal; +use std::{fs, path::Path}; + +#[test] +fn symbolic_seal_is_exactly_one_fixed_width_frame_field() { + assert_eq!(size_of::(), 32); + assert_eq!(SymbolicSeal::ZERO.to_bytes(), [0; 32]); +} + +#[test] +fn symbolic_carrier_has_no_external_or_cryptographic_dependency() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap(); + assert!(!manifest.contains("[dependencies]")); + + let source = fs::read_to_string(root.join("src/lib.rs")).unwrap(); + for forbidden in [ + ["blake", "3"].concat(), + ["sha", "2"].concat(), + ["serde", "::"].concat(), + ["unsafe", " {"].concat(), + ] { + assert!(!source.contains(&forbidden), "forbidden token: {forbidden}"); + } +} diff --git a/l64-testkit/src/lib.rs b/l64-testkit/src/lib.rs deleted file mode 100644 index 57c39a4..0000000 --- a/l64-testkit/src/lib.rs +++ /dev/null @@ -1,242 +0,0 @@ -use l64_core::*; - -#[derive(Debug, Clone, Default)] -pub struct BundleRegistry { - bundle: RegistryBundle, -} - -impl BundleRegistry { - pub fn bundle(&self) -> &RegistryBundle { - &self.bundle - } -} - -#[derive(Debug, Clone, Default)] -pub struct TestRegistryBuilder { - bundle: RegistryBundle, -} - -impl TestRegistryBuilder { - pub fn new() -> Self { - Self::default() - } - - pub fn with_object(mut self, item: QcObject) -> Self { - self.bundle.objects.push(item); - self - } - - pub fn with_regime(mut self, item: RegimePack) -> Self { - self.bundle.regimes.push(item); - self - } - - pub fn with_bridge(mut self, item: BridgeContract) -> Self { - self.bundle.bridges.push(item); - self - } - - pub fn with_equivalence_class(mut self, item: EquivalenceClass) -> Self { - self.bundle.equivalence_classes.push(item); - self - } - - pub fn with_proof_shape(mut self, item: ProofShape) -> Self { - self.bundle.proof_shapes.push(item); - self - } - - pub fn with_atlas_cell(mut self, item: AtlasCell) -> Self { - self.bundle.atlas_cells.push(item); - self - } - - pub fn with_theorem_spec(mut self, item: TheoremSpec) -> Self { - self.bundle.theorem_specs.push(item); - self - } - - pub fn with_obligation(mut self, item: Obligation) -> Self { - self.bundle.obligations.push(item); - self - } - - pub fn with_target_profile(mut self, item: TargetProfile) -> Self { - self.bundle.target_profiles.push(item); - self - } - - pub fn with_route_ledger(mut self, item: RouteLedger) -> Self { - self.bundle.route_ledgers.push(item); - self - } - - pub fn with_certificate(mut self, item: Certificate) -> Self { - self.bundle.certificates.push(item); - self - } - - pub fn with_campaign(mut self, item: Campaign) -> Self { - self.bundle.campaigns.push(item); - self - } - - pub fn with_route_class(mut self, item: RouteClass) -> Self { - self.bundle.route_classes.push(item); - self - } - - pub fn build(self) -> BundleRegistry { - BundleRegistry { - bundle: self.bundle, - } - } -} - -fn get_by_id(items: &[T], id: &str, id_of: impl Fn(&T) -> &str) -> Option { - items.iter().find(|item| id_of(item) == id).cloned() -} - -impl RegistryLookup for BundleRegistry { - fn get_object(&self, id: &str) -> Option { - get_by_id(&self.bundle.objects, id, |item| item.id.as_str()) - } - fn get_regime(&self, id: &str) -> Option { - get_by_id(&self.bundle.regimes, id, |item| item.id.as_str()) - } - fn get_bridge(&self, id: &str) -> Option { - get_by_id(&self.bundle.bridges, id, |item| item.id.as_str()) - } - fn get_proof_shape(&self, id: &str) -> Option { - get_by_id(&self.bundle.proof_shapes, id, |item| item.id.as_str()) - } - fn get_atlas_cell(&self, id: &str) -> Option { - get_by_id(&self.bundle.atlas_cells, id, |item| item.id.as_str()) - } - fn get_mechanization_package(&self, id: &str) -> Option { - get_by_id(&self.bundle.mechanization_packages, id, |item| { - item.id.as_str() - }) - } - fn get_theorem_spec(&self, id: &str) -> Option { - get_by_id(&self.bundle.theorem_specs, id, |item| item.id.as_str()) - } - fn get_obligation(&self, id: &str) -> Option { - get_by_id(&self.bundle.obligations, id, |item| item.id.as_str()) - } - fn get_target_profile(&self, id: &str) -> Option { - get_by_id(&self.bundle.target_profiles, id, |item| item.id.as_str()) - } - fn get_route_ledger(&self, id: &str) -> Option { - get_by_id(&self.bundle.route_ledgers, id, |item| item.id.as_str()) - } - fn get_certificate(&self, id: &str) -> Option { - get_by_id(&self.bundle.certificates, id, |item| item.id.as_str()) - } - fn get_campaign(&self, id: &str) -> Option { - get_by_id(&self.bundle.campaigns, id, |item| item.id.as_str()) - } - fn get_campaign_portfolio(&self, id: &str) -> Option { - get_by_id(&self.bundle.campaign_portfolios, id, |item| { - item.id.as_str() - }) - } - fn get_route_class(&self, id: &str) -> Option { - get_by_id(&self.bundle.route_classes, id, |item| item.id.as_str()) - } - fn get_atlas_deficiency(&self, id: &str) -> Option { - get_by_id(&self.bundle.atlas_deficiencies, id, |item| item.id.as_str()) - } - fn atlas_deficiencies(&self) -> Vec { - self.bundle.atlas_deficiencies.clone() - } - fn get_adequacy_clause(&self, id: &str) -> Option { - get_by_id(&self.bundle.adequacy_clauses, id, |item| item.id.as_str()) - } - fn adequacy_clauses(&self) -> Vec { - self.bundle.adequacy_clauses.clone() - } - fn get_burden_pack(&self, id: &str) -> Option { - get_by_id(&self.bundle.burden_packs, id, |item| item.id.as_str()) - } - fn burden_packs(&self) -> Vec { - self.bundle.burden_packs.clone() - } - fn get_claim_packet(&self, id: &str) -> Option { - get_by_id(&self.bundle.claim_packets, id, |item| item.id.as_str()) - } - fn claim_packets(&self) -> Vec { - self.bundle.claim_packets.clone() - } - fn get_evidence_contract(&self, id: &str) -> Option { - get_by_id(&self.bundle.evidence_contracts, id, |item| item.id.as_str()) - } - fn evidence_contracts(&self) -> Vec { - self.bundle.evidence_contracts.clone() - } - fn get_benchmark_receipt(&self, id: &str) -> Option { - get_by_id(&self.bundle.benchmark_receipts, id, |item| item.id.as_str()) - } - fn benchmark_receipts(&self) -> Vec { - self.bundle.benchmark_receipts.clone() - } - fn get_challenge_receipt(&self, id: &str) -> Option { - get_by_id(&self.bundle.challenge_receipts, id, |item| item.id.as_str()) - } - fn challenge_receipts(&self) -> Vec { - self.bundle.challenge_receipts.clone() - } - fn get_reproducibility_packet(&self, id: &str) -> Option { - get_by_id(&self.bundle.reproducibility_packets, id, |item| { - item.id.as_str() - }) - } - fn reproducibility_packets(&self) -> Vec { - self.bundle.reproducibility_packets.clone() - } - fn get_codebook_pack(&self, id: &str) -> Option { - get_by_id(&self.bundle.codebook_packs, id, |item| item.id.as_str()) - } - fn get_glyph_pack(&self, id: &str) -> Option { - get_by_id(&self.bundle.glyph_packs, id, |item| item.id.as_str()) - } - fn get_combo_pack(&self, id: &str) -> Option { - get_by_id(&self.bundle.combo_packs, id, |item| item.id.as_str()) - } - fn get_projection_policy(&self, id: &str) -> Option { - get_by_id(&self.bundle.projection_policies, id, |item| { - item.id.as_str() - }) - } - fn get_alias_expansion_policy(&self, id: &str) -> Option { - get_by_id(&self.bundle.alias_expansion_policies, id, |item| { - item.id.as_str() - }) - } - fn get_surface_deficiency(&self, id: &str) -> Option { - get_by_id(&self.bundle.surface_deficiencies, id, |item| { - item.id.as_str() - }) - } - fn get_policy_object(&self, id: &str) -> Option { - get_by_id(&self.bundle.policy_objects, id, |item| item.id.as_str()) - } - fn policy_objects(&self) -> Vec { - self.bundle.policy_objects.clone() - } - fn policy_bindings(&self) -> Vec { - self.bundle.policy_bindings.clone() - } - fn find_equivalence_class(&self, object_id: &str, regime: &str) -> Option { - self.bundle - .equivalence_classes - .iter() - .find(|item| { - item.regime == regime && item.members.iter().any(|member| member == object_id) - }) - .cloned() - } - fn atlas_cells(&self) -> Vec { - self.bundle.atlas_cells.clone() - } -} diff --git a/l64-transport/Cargo.toml b/l64-transport/Cargo.toml new file mode 100644 index 0000000..b05588e --- /dev/null +++ b/l64-transport/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "l64-transport" +edition.workspace = true +version.workspace = true +license.workspace = true + +[dependencies] +l64-native = { path = "../l64-native" } +l64-execution = { path = "../l64-execution" } +l64-certification = { path = "../l64-certification" } diff --git a/l64-transport/README.md b/l64-transport/README.md new file mode 100644 index 0000000..b1b59a5 --- /dev/null +++ b/l64-transport/README.md @@ -0,0 +1,17 @@ +# l64-transport + +`l64-transport` is the dependency-free native bundle carrier. + +A native bundle is an ordered `L64B` frame containing one or more canonical current-authority `L64D` members. The transport layer adds only framing: + +- a 16-byte versioned header; +- a member count; +- exact length framing for each DNA member. + +It does not add names, hashes, manifests, registries, overlays, conflict policies, receipts, caches, or composite authority. Member order is transport sequence only. Every member is decoded through `l64-native`, re-encoded to prove canonical DNA, and projected through `l64-projection` during execution. + +The public contacts are: + +- `bundle_bytes` — validate and frame canonical DNA members; +- `decode_bundle` — exact framing and member-authority validation; +- `execute_bundle` — verify one native projection per member in transport order. diff --git a/l64-transport/src/lib.rs b/l64-transport/src/lib.rs new file mode 100644 index 0000000..20987a9 --- /dev/null +++ b/l64-transport/src/lib.rs @@ -0,0 +1,304 @@ +#![forbid(unsafe_code)] + +mod stream; + +pub use stream::{ + BundleDecoder, BundleEncoder, BundleStreamError, BundleWriteSummary, OwnedBundleMember, +}; + +use l64_certification::AuthorityCertification; +use l64_execution::{AuthorityExecution, ExecutionError, ExecutionSource, execute_canonical_graph}; +use l64_native::{DnaError, Graph, StateSymbol, decode_dna, dna_bytes}; +use std::fmt::{self, Write as _}; + +const MAGIC: &[u8; 4] = b"L64B"; +pub const BUNDLE_VERSION: u16 = 1; +const FLAGS: u16 = 0; +const HEADER_BYTES: usize = 16; +const MEMBER_HEADER_BYTES: usize = 4; +pub const MAX_BUNDLE_MEMBERS: usize = 4096; +pub const MAX_NATIVE_BUNDLE_BYTES: usize = 1 << 30; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BundleError { + Empty, + TooManyMembers, + TooLarge, + Truncated, + BadMagic, + UnsupportedVersion { version: u16 }, + UnsupportedFlags { flags: u16 }, + ZeroLengthMember { index: usize }, + TrailingBytes, + NonCanonicalDna { index: usize }, + Dna { index: usize, error: DnaError }, + Execution { index: usize, error: ExecutionError }, +} + +impl fmt::Display for BundleError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Empty => f.write_str("L64B transport must contain at least one member"), + Self::TooManyMembers => f.write_str("L64B transport contains too many members"), + Self::TooLarge => f.write_str("L64B transport exceeds the native size limit"), + Self::Truncated => f.write_str("L64B transport is truncated"), + Self::BadMagic => f.write_str("input is not L64B transport"), + Self::UnsupportedVersion { version } => write!(f, "unsupported L64B version {version}"), + Self::UnsupportedFlags { flags } => write!(f, "unsupported L64B flags {flags}"), + Self::ZeroLengthMember { index } => write!(f, "L64B member {index} has zero length"), + Self::TrailingBytes => f.write_str("L64B transport has trailing bytes"), + Self::NonCanonicalDna { index } => { + write!(f, "L64B member {index} is not canonical L64D authority") + } + Self::Dna { index, error } => write!(f, "invalid L64B member {index}: {error}"), + Self::Execution { index, error } => { + write!(f, "L64B member {index} execution failed: {error}") + } + } + } +} + +impl std::error::Error for BundleError {} + +#[derive(Debug)] +pub struct BundleMember<'a> { + index: usize, + dna: &'a [u8], + graph: Graph, +} + +impl<'a> BundleMember<'a> { + pub fn index(&self) -> usize { + self.index + } + pub fn dna(&self) -> &'a [u8] { + self.dna + } + pub fn graph(&self) -> &Graph { + &self.graph + } + pub fn symbol(&self) -> StateSymbol { + self.graph.state_symbol() + } +} + +#[derive(Debug)] +pub struct NativeBundle<'a> { + bytes: &'a [u8], + members: Vec>, +} + +impl<'a> NativeBundle<'a> { + pub fn bytes(&self) -> &'a [u8] { + self.bytes + } + pub fn members(&self) -> &[BundleMember<'a>] { + &self.members + } + pub fn len(&self) -> usize { + self.members.len() + } + pub fn is_empty(&self) -> bool { + self.members.is_empty() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MemberExecution { + pub index: usize, + pub execution: AuthorityExecution, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BundleExecution { + pub members: Vec, +} + +impl BundleExecution { + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE BUNDLE EXECUTION v{BUNDLE_VERSION}"); + let _ = writeln!(out, "members={}", self.members.len()); + let _ = writeln!(out, "composite_authority=none"); + let _ = writeln!(out, "composite_execution=none"); + let _ = writeln!(out, "ordering=transport_sequence"); + for member in &self.members { + member + .execution + .render_into(&mut out, &format!("member.{}.", member.index)); + } + out + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BundleCertification { + pub members: Vec, +} + +impl BundleCertification { + pub fn render_text(&self) -> String { + let mut out = String::new(); + let _ = writeln!(out, "L64 NATIVE BUNDLE CERTIFICATION v1"); + let _ = writeln!(out, "transport=canonical_l64b"); + let _ = writeln!(out, "transport_verified=true"); + let _ = writeln!(out, "members={}", self.members.len()); + let _ = writeln!(out, "composite_authority=none"); + let _ = writeln!(out, "composite_certificate=none"); + for (index, member) in self.members.iter().enumerate() { + member.render_into(&mut out, &format!("member.{index}.")); + } + out + } +} + +pub fn bundle_bytes(members: &[&[u8]]) -> Result, BundleError> { + validate_member_count(members.len())?; + let mut payload_len = 0usize; + for (index, member) in members.iter().enumerate() { + validate_dna(index, member)?; + if member.len() > u32::MAX as usize { + return Err(BundleError::TooLarge); + } + payload_len = payload_len + .checked_add(MEMBER_HEADER_BYTES) + .and_then(|value| value.checked_add(member.len())) + .ok_or(BundleError::TooLarge)?; + } + let total_len = HEADER_BYTES + .checked_add(payload_len) + .ok_or(BundleError::TooLarge)?; + if total_len > MAX_NATIVE_BUNDLE_BYTES || payload_len > u32::MAX as usize { + return Err(BundleError::TooLarge); + } + let mut out = Vec::with_capacity(total_len); + out.extend_from_slice(MAGIC); + out.extend_from_slice(&BUNDLE_VERSION.to_le_bytes()); + out.extend_from_slice(&FLAGS.to_le_bytes()); + out.extend_from_slice(&(members.len() as u32).to_le_bytes()); + out.extend_from_slice(&(payload_len as u32).to_le_bytes()); + for member in members { + out.extend_from_slice(&(member.len() as u32).to_le_bytes()); + out.extend_from_slice(member); + } + Ok(out) +} + +fn parse_header(bytes: &[u8]) -> Result<(usize, usize), BundleError> { + if bytes.len() < HEADER_BYTES { + return Err(BundleError::Truncated); + } + if &bytes[..4] != MAGIC { + return Err(BundleError::BadMagic); + } + let version = u16::from_le_bytes(bytes[4..6].try_into().expect("fixed version field")); + if version != BUNDLE_VERSION { + return Err(BundleError::UnsupportedVersion { version }); + } + let flags = u16::from_le_bytes(bytes[6..8].try_into().expect("fixed flags field")); + if flags != FLAGS { + return Err(BundleError::UnsupportedFlags { flags }); + } + let count = u32::from_le_bytes(bytes[8..12].try_into().expect("fixed count field")) as usize; + validate_member_count(count)?; + let payload_len = + u32::from_le_bytes(bytes[12..16].try_into().expect("fixed length field")) as usize; + let expected_len = HEADER_BYTES + .checked_add(payload_len) + .ok_or(BundleError::TooLarge)?; + if expected_len > MAX_NATIVE_BUNDLE_BYTES { + return Err(BundleError::TooLarge); + } + Ok((count, payload_len)) +} + +pub fn decode_bundle(bytes: &[u8]) -> Result, BundleError> { + let (count, payload_len) = parse_header(bytes)?; + let expected_len = HEADER_BYTES + payload_len; + if bytes.len() < expected_len { + return Err(BundleError::Truncated); + } + if bytes.len() > expected_len { + return Err(BundleError::TrailingBytes); + } + let mut cursor = HEADER_BYTES; + let mut members = Vec::with_capacity(count); + for index in 0..count { + let length_end = cursor + .checked_add(MEMBER_HEADER_BYTES) + .ok_or(BundleError::TooLarge)?; + if length_end > bytes.len() { + return Err(BundleError::Truncated); + } + let member_len = u32::from_le_bytes( + bytes[cursor..length_end] + .try_into() + .expect("fixed member length field"), + ) as usize; + if member_len == 0 { + return Err(BundleError::ZeroLengthMember { index }); + } + cursor = length_end; + let member_end = cursor + .checked_add(member_len) + .ok_or(BundleError::TooLarge)?; + if member_end > bytes.len() { + return Err(BundleError::Truncated); + } + let dna = &bytes[cursor..member_end]; + let graph = validate_dna(index, dna)?; + members.push(BundleMember { index, dna, graph }); + cursor = member_end; + } + if cursor != bytes.len() { + return Err(BundleError::TrailingBytes); + } + Ok(NativeBundle { bytes, members }) +} + +pub fn execute_bundle(bytes: &[u8]) -> Result { + let bundle = decode_bundle(bytes)?; + let mut members = Vec::with_capacity(bundle.len()); + for member in bundle.members() { + let execution = execute_canonical_graph(member.graph(), ExecutionSource::BundleMember) + .map_err(|error| BundleError::Execution { + index: member.index(), + error, + })?; + members.push(MemberExecution { + index: member.index(), + execution, + }); + } + Ok(BundleExecution { members }) +} + +pub fn certify_bundle(bytes: &[u8]) -> Result { + let execution = execute_bundle(bytes)?; + Ok(BundleCertification { + members: execution + .members + .into_iter() + .map(|member| member.execution.certification) + .collect(), + }) +} + +fn validate_member_count(count: usize) -> Result<(), BundleError> { + if count == 0 { + Err(BundleError::Empty) + } else if count > MAX_BUNDLE_MEMBERS || count > u32::MAX as usize { + Err(BundleError::TooManyMembers) + } else { + Ok(()) + } +} + +fn validate_dna(index: usize, dna: &[u8]) -> Result { + let graph = decode_dna(dna).map_err(|error| BundleError::Dna { index, error })?; + let canonical = dna_bytes(&graph).map_err(|error| BundleError::Dna { index, error })?; + if canonical != dna { + return Err(BundleError::NonCanonicalDna { index }); + } + Ok(graph) +} diff --git a/l64-transport/src/stream.rs b/l64-transport/src/stream.rs new file mode 100644 index 0000000..77f9bba --- /dev/null +++ b/l64-transport/src/stream.rs @@ -0,0 +1,222 @@ +use super::{ + BUNDLE_VERSION, BundleError, FLAGS, HEADER_BYTES, MAGIC, MAX_NATIVE_BUNDLE_BYTES, + MEMBER_HEADER_BYTES, parse_header, validate_dna, validate_member_count, +}; +use l64_native::{Graph, MAX_NATIVE_DNA_PAYLOAD_BYTES}; +use std::{ + fmt, + io::{self, Read, Seek, SeekFrom, Write}, +}; + +const MAX_NATIVE_DNA_FRAME_BYTES: usize = MAX_NATIVE_DNA_PAYLOAD_BYTES + 44; + +#[derive(Debug)] +pub enum BundleStreamError { + Transport(BundleError), + Io(io::Error), +} + +impl fmt::Display for BundleStreamError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Transport(error) => error.fmt(f), + Self::Io(error) => write!(f, "L64B stream I/O failed: {error}"), + } + } +} + +impl std::error::Error for BundleStreamError {} + +impl From for BundleStreamError { + fn from(value: BundleError) -> Self { + Self::Transport(value) + } +} + +impl From for BundleStreamError { + fn from(value: io::Error) -> Self { + Self::Io(value) + } +} + +#[derive(Debug)] +pub struct OwnedBundleMember { + index: usize, + dna: Vec, + graph: Graph, +} + +impl OwnedBundleMember { + pub fn index(&self) -> usize { + self.index + } + + pub fn dna(&self) -> &[u8] { + &self.dna + } + + pub fn graph(&self) -> &Graph { + &self.graph + } +} + +pub struct BundleDecoder { + reader: R, + member_count: usize, + remaining_payload: usize, + next_index: usize, + complete: bool, +} + +impl BundleDecoder { + pub fn new(mut reader: R) -> Result { + let mut header = [0u8; HEADER_BYTES]; + read_exact_transport(&mut reader, &mut header)?; + let (member_count, payload_len) = parse_header(&header)?; + Ok(Self { + reader, + member_count, + remaining_payload: payload_len, + next_index: 0, + complete: false, + }) + } + + pub fn member_count(&self) -> usize { + self.member_count + } + + pub fn next_member(&mut self) -> Result, BundleStreamError> { + if self.complete { + return Ok(None); + } + if self.next_index == self.member_count { + if self.remaining_payload != 0 { + return Err(BundleError::TrailingBytes.into()); + } + let mut trailing = [0u8; 1]; + match self.reader.read(&mut trailing) { + Ok(0) => { + self.complete = true; + return Ok(None); + } + Ok(_) => return Err(BundleError::TrailingBytes.into()), + Err(error) => return Err(BundleStreamError::Io(error)), + } + } + if self.remaining_payload < MEMBER_HEADER_BYTES { + return Err(BundleError::Truncated.into()); + } + let mut length = [0u8; MEMBER_HEADER_BYTES]; + read_exact_transport(&mut self.reader, &mut length)?; + self.remaining_payload -= MEMBER_HEADER_BYTES; + let member_len = u32::from_le_bytes(length) as usize; + if member_len == 0 { + return Err(BundleError::ZeroLengthMember { + index: self.next_index, + } + .into()); + } + if member_len > MAX_NATIVE_DNA_FRAME_BYTES { + return Err(BundleError::TooLarge.into()); + } + if member_len > self.remaining_payload { + return Err(BundleError::Truncated.into()); + } + let mut dna = vec![0u8; member_len]; + read_exact_transport(&mut self.reader, &mut dna)?; + self.remaining_payload -= member_len; + let index = self.next_index; + let graph = validate_dna(index, &dna)?; + self.next_index += 1; + Ok(Some(OwnedBundleMember { index, dna, graph })) + } + + pub fn finish(mut self) -> Result<(), BundleStreamError> { + while self.next_member()?.is_some() {} + Ok(()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BundleWriteSummary { + pub members: usize, + pub bytes: usize, +} + +pub struct BundleEncoder { + writer: W, + members: usize, + payload_len: usize, +} + +impl BundleEncoder { + pub fn new(mut writer: W) -> Result { + writer.write_all(&[0u8; HEADER_BYTES])?; + Ok(Self { + writer, + members: 0, + payload_len: 0, + }) + } + + pub fn push_member(&mut self, dna: &[u8]) -> Result<(), BundleStreamError> { + let next_count = self + .members + .checked_add(1) + .ok_or(BundleError::TooManyMembers)?; + validate_member_count(next_count)?; + validate_dna(self.members, dna)?; + if dna.len() > u32::MAX as usize { + return Err(BundleError::TooLarge.into()); + } + let next_payload = self + .payload_len + .checked_add(MEMBER_HEADER_BYTES) + .and_then(|value| value.checked_add(dna.len())) + .ok_or(BundleError::TooLarge)?; + let total = HEADER_BYTES + .checked_add(next_payload) + .ok_or(BundleError::TooLarge)?; + if total > MAX_NATIVE_BUNDLE_BYTES || next_payload > u32::MAX as usize { + return Err(BundleError::TooLarge.into()); + } + self.writer.write_all(&(dna.len() as u32).to_le_bytes())?; + self.writer.write_all(dna)?; + self.members = next_count; + self.payload_len = next_payload; + Ok(()) + } + + pub fn finish(mut self) -> Result { + validate_member_count(self.members)?; + let total = HEADER_BYTES + self.payload_len; + self.writer.seek(SeekFrom::Start(0))?; + self.writer.write_all(MAGIC)?; + self.writer.write_all(&BUNDLE_VERSION.to_le_bytes())?; + self.writer.write_all(&FLAGS.to_le_bytes())?; + self.writer + .write_all(&(self.members as u32).to_le_bytes())?; + self.writer + .write_all(&(self.payload_len as u32).to_le_bytes())?; + self.writer.seek(SeekFrom::End(0))?; + self.writer.flush()?; + Ok(BundleWriteSummary { + members: self.members, + bytes: total, + }) + } +} + +fn read_exact_transport( + reader: &mut impl Read, + buffer: &mut [u8], +) -> Result<(), BundleStreamError> { + match reader.read_exact(buffer) { + Ok(()) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => { + Err(BundleError::Truncated.into()) + } + Err(error) => Err(BundleStreamError::Io(error)), + } +} diff --git a/l64-transport/tests/architecture.rs b/l64-transport/tests/architecture.rs new file mode 100644 index 0000000..d19a489 --- /dev/null +++ b/l64-transport/tests/architecture.rs @@ -0,0 +1,68 @@ +use std::{ + fs, + path::{Path, PathBuf}, +}; + +fn crate_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn rust_source_under(path: &Path, output: &mut String) { + for entry in fs::read_dir(path).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if path.is_dir() { + rust_source_under(&path, output); + } else if path.extension().and_then(|extension| extension.to_str()) == Some("rs") { + output.push_str(&fs::read_to_string(path).unwrap()); + output.push('\n'); + } + } +} + +#[test] +fn transport_has_only_native_authority_execution_and_certification_contacts() { + let manifest = fs::read_to_string(crate_root().join("Cargo.toml")).unwrap(); + assert!(manifest.contains("l64-native")); + assert!(manifest.contains("l64-execution")); + assert!(manifest.contains("l64-certification")); + assert!(!manifest.contains("l64-projection")); + for forbidden in [ + "serde", + "serde_json", + "bincode", + "l64-core", + "l64-locus", + "l64-registry", + "l64-bundle", + "l64-runtime", + "anyhow", + "thiserror", + ] { + assert!( + !manifest.contains(forbidden), + "native transport must not depend on {forbidden}" + ); + } +} + +#[test] +fn transport_source_has_no_composite_authority_or_generic_digest_layer() { + let mut source = String::new(); + rust_source_under(&crate_root().join("src"), &mut source); + for forbidden in [ + "blake3", + "sha2", + "DigestRole", + "RoleDigest", + "BundleManifest", + "OverlayRegistry", + "conflict_policy", + "registry", + ] { + assert!( + !source.contains(forbidden), + "transport source must not contain {forbidden}" + ); + } +} diff --git a/l64-transport/tests/transport.rs b/l64-transport/tests/transport.rs new file mode 100644 index 0000000..7c250d2 --- /dev/null +++ b/l64-transport/tests/transport.rs @@ -0,0 +1,148 @@ +use l64_certification::CertificationVerdict; +use l64_native::rna_to_dna; +use l64_transport::{BundleError, bundle_bytes, certify_bundle, decode_bundle, execute_bundle}; + +const TRIANGLE: &[u8] = b"L64R1 0x4c36344e41544956\na 1 0x41\na 2 0x42\na 3 0x43\nf 4 1 2\nf 5 2 3\nf 6 1 3\nv 7 4\nv 8 5\nc 9 7 8 6\n"; +const EQUALITY: &[u8] = + b"L64R1 0x4551\na 1 0x41\na 2 0x41\ne 3 2 1 2 0\ne 4 3 2 1 0 3\ne 5 4 1 1 0 3 4\n"; + +#[test] +fn bundle_is_exact_ordered_dna_transport() { + let first = rna_to_dna(TRIANGLE).unwrap(); + let second = rna_to_dna(EQUALITY).unwrap(); + let encoded = bundle_bytes(&[&first, &second]).unwrap(); + let decoded = decode_bundle(&encoded).unwrap(); + assert_eq!(decoded.len(), 2); + assert_eq!(decoded.members()[0].dna(), first); + assert_eq!(decoded.members()[1].dna(), second); + assert_eq!(decoded.bytes(), encoded); +} + +#[test] +fn execution_verifies_each_projection_without_composite_authority() { + let first = rna_to_dna(TRIANGLE).unwrap(); + let second = rna_to_dna(EQUALITY).unwrap(); + let encoded = bundle_bytes(&[&first, &second]).unwrap(); + let execution = execute_bundle(&encoded).unwrap(); + assert_eq!(execution.members.len(), 2); + let text = execution.render_text(); + assert!(text.contains("composite_authority=none")); + assert!(text.contains("ordering=transport_sequence")); + assert!(text.contains("member.0.source=bundle_member")); + assert!(text.contains("member.1.source=bundle_member")); + assert_eq!(text.matches("projection_verified=true").count(), 2); + assert_eq!(text.matches("certification_verdict=CERTIFIED").count(), 2); + assert!(text.contains("composite_execution=none")); +} + +#[test] +fn bundle_certification_is_owned_by_transport_and_remains_member_local() { + let first = rna_to_dna(TRIANGLE).unwrap(); + let second = rna_to_dna(EQUALITY).unwrap(); + let encoded = bundle_bytes(&[&first, &second]).unwrap(); + let certification = certify_bundle(&encoded).unwrap(); + assert_eq!(certification.members.len(), 2); + assert!( + certification + .members + .iter() + .all(|member| member.verdict == CertificationVerdict::Certified) + ); + let text = certification.render_text(); + assert!(text.contains("composite_certificate=none")); + assert!(!text.contains("bundle_verdict=")); +} + +#[test] +fn bundle_rejects_empty_and_non_dna_members() { + assert_eq!(bundle_bytes(&[]), Err(BundleError::Empty)); + assert!(matches!( + bundle_bytes(&[b"not dna"]), + Err(BundleError::Dna { index: 0, .. }) + )); +} + +#[test] +fn bundle_rejects_trailing_or_truncated_bytes() { + let dna = rna_to_dna(TRIANGLE).unwrap(); + let encoded = bundle_bytes(&[&dna]).unwrap(); + let mut trailing = encoded.clone(); + trailing.push(0); + assert_eq!( + decode_bundle(&trailing).unwrap_err(), + BundleError::TrailingBytes + ); + assert_eq!( + decode_bundle(&encoded[..encoded.len() - 1]).unwrap_err(), + BundleError::Truncated + ); +} + +#[test] +fn streaming_encoder_matches_exact_transport_and_decoder_releases_members_sequentially() { + use l64_transport::{BundleDecoder, BundleEncoder}; + use std::io::Cursor; + + let first = rna_to_dna(TRIANGLE).unwrap(); + let second = rna_to_dna(EQUALITY).unwrap(); + let expected = bundle_bytes(&[&first, &second]).unwrap(); + + let mut encoded = Cursor::new(Vec::new()); + { + let mut encoder = BundleEncoder::new(&mut encoded).unwrap(); + encoder.push_member(&first).unwrap(); + encoder.push_member(&second).unwrap(); + let summary = encoder.finish().unwrap(); + assert_eq!(summary.members, 2); + assert_eq!(summary.bytes, expected.len()); + } + assert_eq!(encoded.into_inner(), expected); + + let mut decoder = BundleDecoder::new(Cursor::new(expected)).unwrap(); + assert_eq!(decoder.member_count(), 2); + let first_member = decoder.next_member().unwrap().unwrap(); + assert_eq!(first_member.index(), 0); + assert_eq!(first_member.dna(), first); + drop(first_member); + let second_member = decoder.next_member().unwrap().unwrap(); + assert_eq!(second_member.index(), 1); + assert_eq!(second_member.dna(), second); + drop(second_member); + assert!(decoder.next_member().unwrap().is_none()); +} + +#[test] +fn streaming_decoder_never_requests_the_whole_bundle_buffer() { + use l64_transport::{BundleDecoder, bundle_bytes}; + use std::{cell::Cell, io::Read, rc::Rc}; + + struct TrackingReader { + bytes: std::io::Cursor>, + max_request: Rc>, + } + + impl Read for TrackingReader { + fn read(&mut self, buffer: &mut [u8]) -> std::io::Result { + self.max_request + .set(self.max_request.get().max(buffer.len())); + self.bytes.read(buffer) + } + } + + let dna = rna_to_dna(TRIANGLE).unwrap(); + let members = (0..128).map(|_| dna.as_slice()).collect::>(); + let encoded = bundle_bytes(&members).unwrap(); + let max_request = Rc::new(Cell::new(0)); + let reader = TrackingReader { + bytes: std::io::Cursor::new(encoded.clone()), + max_request: Rc::clone(&max_request), + }; + let mut decoder = BundleDecoder::new(reader).unwrap(); + let mut count = 0; + while decoder.next_member().unwrap().is_some() { + count += 1; + } + assert_eq!(count, 128); + assert!(max_request.get() <= dna.len()); + assert!(max_request.get() < encoded.len() / 64); +} diff --git a/l64/Cargo.toml b/l64/Cargo.toml index c43d338..508ef86 100644 --- a/l64/Cargo.toml +++ b/l64/Cargo.toml @@ -3,6 +3,3 @@ name = "l64" edition.workspace = true version.workspace = true license.workspace = true - -[dependencies] -anyhow = { workspace = true } diff --git a/l64/src/main.rs b/l64/src/main.rs index 16b5f5b..e69fb31 100644 --- a/l64/src/main.rs +++ b/l64/src/main.rs @@ -1,125 +1,83 @@ -use anyhow::{Result, anyhow}; -use std::env; -use std::path::{Path, PathBuf}; -use std::process::{Command, exit}; +use std::{ + env, + path::{Path, PathBuf}, + process::{Command, exit}, +}; -const ADMIN_COMMANDS: &[&str] = &[ - "lock-bundle", - "dump-execution-manifest", - "dump-runtime-roots", - "replay-with-lock", - "observe-run", - "compare-locks", - "compare-reports", - "compare-manifests", - "compare-report-manifest", - "predict-impact", - "plan-recompute", - "execute-plan", - "explain-execution", - "dump-execution-dag", - "dump-lane-plan", - "explain-obligation-plan", - "dump-obligation-dag", - "dump-obligation-lanes", - "compare-obligation-executions", - "compare-schedules", - "explain-plan", - "explain-drift", - "compare-executions", - "assess-prediction", - "reconcile-run", - "dump-policy-graph", - "explain-policy-resolution", - "resolve-artifact-path", - "classify-artifact", - "check-command-input", - "dump-command-contracts", - "dump-artifact-contracts", - "dump-capability-readiness", - "dump-cache-namespaces", -]; - -fn main() -> Result<()> { +fn main() { let args = env::args().skip(1).collect::>(); - if args.is_empty() || matches!(args[0].as_str(), "-h" | "--help" | "help") { - print_help(); - return Ok(()); - } - if args[0] == "authority-audit" { + if args.first().is_some_and(|arg| arg == "authority-audit") { print_authority_audit(); - return Ok(()); + return; } - - let target = if ADMIN_COMMANDS.iter().any(|cmd| *cmd == args[0]) { - sibling_binary("l64-admin") - } else { - sibling_binary("l64-cli") - }?; - - let status = Command::new(target).args(&args).status()?; + let target = sibling_binary("l64-cli").unwrap_or_else(|error| fail(&error)); + let status = Command::new(target) + .args(&args) + .status() + .unwrap_or_else(|error| fail(&format!("failed to run l64-cli: {error}"))); match status.code() { Some(code) => exit(code), - None => Err(anyhow!("child process terminated without an exit code")), + None => fail("l64-cli terminated without an exit code"), } } -fn sibling_binary(name: &str) -> Result { - let exe = env::current_exe()?; +fn sibling_binary(name: &str) -> Result { + let exe = env::current_exe().map_err(|error| error.to_string())?; let dir = exe .parent() - .ok_or_else(|| anyhow!("current executable has no parent directory"))?; - let candidates = binary_candidates(dir, name); - candidates + .ok_or("current executable has no parent directory")?; + binary_candidates(dir, name) .into_iter() .find(|path| path.exists()) - .ok_or_else(|| anyhow!("could not locate sibling binary `{name}`")) + .ok_or_else(|| format!("could not locate sibling binary `{name}`")) } fn binary_candidates(dir: &Path, name: &str) -> Vec { - #[cfg(windows)] - let mut paths = vec![dir.join(name)]; - #[cfg(not(windows))] - let paths = vec![dir.join(name)]; - #[cfg(windows)] - { - paths.push(dir.join(format!("{name}.exe"))); - } - paths + binary_candidates_for_host(dir, name, cfg!(windows)) } -fn print_help() { - println!("l64"); - println!(); - println!("Canonical Locus64 wrapper."); - println!("Routes into the Locus Kernel command surface."); - println!("Runs `l64-cli` or `l64-admin` based on the first command verb."); - println!(); - println!("Examples:"); - println!(" l64 authority-audit"); - println!(" l64 normalize-rna sample.gene.rna"); - println!(" l64 compile-rna sample.gene.rna --out sample.gene.dna --artifact-class gene"); - println!(" l64 sequence-dna sample.gene.dna"); - println!(" l64 inspect-dna sample.gene.dna"); - println!(" l64 verify-roundtrip sample.gene.rna --artifact-class gene"); - println!( - " l64 export-genome-release --rna sample.gene.rna --out sample-release --artifact-class gene" - ); - println!(" l64 certify-derived --campaign CPG_CHAIN_RULE"); - println!(" l64 observe-run --report REPORT_THS_CHAIN_RULE_CPG_CHAIN_RULE"); - println!(" l64 research-import --kind task samples/research/task_operational_truth.json"); - println!( - " l64 research-route --task-id TASK_OPERATIONAL_TRUTH_HARDENING --signature-id SIG_OPERATIONAL_TRUTH_HARDENING" - ); +fn binary_candidates_for_host(dir: &Path, name: &str, windows: bool) -> Vec { + if windows { + vec![dir.join(name), dir.join(format!("{name}.exe"))] + } else { + vec![dir.join(name)] + } } fn print_authority_audit() { println!("Locus64 authority audit"); - println!("substrate_authority: RNA,DNA,lower-chain receipts"); - println!("derived_semantic: certification,research,coverage,tower reports"); - println!("extraction_sources: bundle-entry text,governed research imports"); - println!("deleted_projection_paths: l64-qk0"); - println!("deleted_projection_crates: l64-qc0,l64-qa0,l64-qk0,l64-qm0,l64-surfaces"); - println!("public_surface_target: RNA,DNA"); - println!("public_command_target: l64"); + println!("authority: exact canonical L64R1/L64D"); + println!("transport: ordered L64B members; no composite authority"); + println!("execution: direct non-persistent RNA/DNA structural evaluation"); + println!("derived: projection, certification, observation, change"); + println!("deleted: legacy theorem/campaign/research/registry/tower execution island"); + println!("workspace: dependency-free native carriers"); +} + +fn fail(message: &str) -> ! { + eprintln!("{message}"); + exit(2) +} + +#[cfg(test)] +mod tests { + use super::{binary_candidates, binary_candidates_for_host}; + use std::path::Path; + + #[test] + fn portability_binary_candidates_follow_host_executable_law() { + let dir = Path::new("portable bin"); + assert_eq!( + binary_candidates_for_host(dir, "l64-cli", false), + vec![dir.join("l64-cli")] + ); + assert_eq!( + binary_candidates_for_host(dir, "l64-cli", true), + vec![dir.join("l64-cli"), dir.join("l64-cli.exe")] + ); + assert_eq!( + binary_candidates(dir, "l64-cli"), + binary_candidates_for_host(dir, "l64-cli", cfg!(windows)) + ); + } } diff --git a/samples/chain_rule_bundle.dna b/samples/chain_rule_bundle.dna deleted file mode 100644 index 92eb66f0c0d5f750c54f0798c1a67b120b05e4f4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1870 zcma)7U2fAr5MG!6Ulj!60VGy}hgNDUMM6{+5|XpF8l*Hyo%DexYh$l#gJXwXCn}tv z+<;qghn|EP$75{TppLZJ^~~AU{eJ{sXBdai>g0W5o7UBB`w$}BKk(hc~%1% zbGFSdex7%D$=Qjv&bGIKk6$PwSO^u#^C!a*sz>sCVfO_Ae6(V+E?$Av65g+b!;!Zq zFdZF?E>e_eQ|#tCRGNQL1y|n|$x@~&3lwINh+;%QFhpdTTpf-5@$rf6xrktR2W~v9 zo)5eIDhTc|vJNVK)3`}x@U>~4&$Tj2FIC8)>;PVn&*r&FiX_j_JQ^UU{~EBJBgFNl zvM|kyn8Rc6sYsT}a2d{$q5z#q##aGcud6>4n1EN6E=axNQ!N9vo92N`lOLcn&$ul3 z*?J|O>tN76R!TIKNKih@Bd*m9a)G`TO3zH~vEj|gG*W_a?!uywPYx%I>O$!?D&`ug zCoQ;RI4RY%*Ci4Sv zkY%l)+*9FyHDiwuFyS@hO5AoY*W8wCWP+sarXW}pF|UjtW)x}S`QQ%}>tGzBWp-(O|q3-{UMLVkKF%mk6i)!xjta^sm zfb2G%y^iP diff --git a/samples/chain_rule_integrated_bundle.dna b/samples/chain_rule_integrated_bundle.dna deleted file mode 100644 index 5c380a8e07473c3d87fc5f58b489711c05d7506a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2643 zcma)8+iu%N5M8F%q?Z&yfuLv}7EMvuKx9-v5hDo@Kqd)0fGo-@=AloEHMz9dN?ets z45wd^{6YVuZ+*z8QU{mAd+>C= zuJVPJxyjZ`UA4gd2Dpcr&Xqd+<;kHQ4$q6n0s9!ZnW;5n5AbQO%1YL2uq>-qU(~AA zx$Jxe?AHG){d1eKFToMg_i#P5PmG-=Q+YIrWOy=qF_GfsIF>Iasho{Yr|>unPvQvU zhcwuCy~$2>lm`%trH|nE6Sx8-xD(&LqYw!tC`9_HyRk+sR}0OzX>yx9$K-jF&2vB?a-0x_nFl$H6@9crI<8tg3mS%!&-5qPA^RGQ3lU6+?S z9~8A&K21+%4qRkzRvL<8YRdEL&I|Lki5pIj9Ulb254}xM)=fJwH5|+B(W-^xd1jU? z)0Ay#Dzd;Fk&a{vg-jC}j>aJt3<-dMHwx%Z$Lv~ZfM|ZvbDZNynMA+ocF-NG@Ald? z6d=PG2Kq{6EkWcs;b6t}AM5f`Ep(OXz20&K=o#o+u8I~iv*tY0bz2rCaPtzXtLh7l z1A!EEs86k#lQe3DI{AxNWG>|MNj{a5km zYM;M*^LofF=TWhDwZ9L1d_x%pj1!3@uwVQ>`OlUj;q~ZmP=A^zJQy8eFcb(PNX{wM z=}gYfUXDbJK_;Jp25qk7XxxJkp8=aa!5<*E`I?2wes|lCuWH@s8s?Y7?uEv4<_M3+ z189!62aKXqjO!s>Nav=VJG0nul`qQ{o4KrbH)y+kjT1YCxX6)U!)bnAt4t3T2I^h@ z3G;0#u3CPz+lh!H1ns$X0bdjvLv9LQ>m{@$<_3ecY&ID;+(pJ2Nh|?wE`mHgc83L} zH|Urfl%Blc9pR)>(|yx|p={?3y@8@j@aftHDyReSTeS(_Tgl{{?o?cFNs@3A5<}>b zs5ONy@l#UOCS+_b|sHW+5IwnPbD5B$uvuoujieVjvzhZ^~1vqlQxWNVzuMwa1=QS{% pRa<7TG++i*_NpJ)2L8{eqA-gb_6YoYnBxG?Rki&T=Di2Fy$5~g0jU50 diff --git a/samples/golden/certified_triangle.rna b/samples/golden/certified_triangle.rna new file mode 100644 index 0000000..388995d --- /dev/null +++ b/samples/golden/certified_triangle.rna @@ -0,0 +1,10 @@ +L64R1 0x4c36344e41544956 +a 1 0x41 +a 2 0x42 +a 3 0x43 +f 4 1 2 +f 5 2 3 +f 6 1 3 +v 7 4 +v 8 5 +c 9 7 8 6 diff --git a/samples/golden/equality_chain.rna b/samples/golden/equality_chain.rna new file mode 100644 index 0000000..4fec0f0 --- /dev/null +++ b/samples/golden/equality_chain.rna @@ -0,0 +1,6 @@ +L64R1 0x4551 +a 1 0x41 +a 2 0x41 +e 3 2 1 2 0 +e 4 3 2 1 0 3 +e 5 4 1 1 0 3 4 diff --git a/samples/golden/expected/certified_triangle.certify.txt b/samples/golden/expected/certified_triangle.certify.txt new file mode 100644 index 0000000..f020e5f --- /dev/null +++ b/samples/golden/expected/certified_triangle.certify.txt @@ -0,0 +1,17 @@ +L64 NATIVE CERTIFICATION v1 +scope=native_structural_closure +authority=exact_canonical_l64d +canonical_dna=true +symbol=⟦l64.native.state.v2 ∷ Σ53dfec4250aa61e2 ⊗ Π7d622e10ef2220a3 ⊗ Δ92ec6a8373dca073 ⊗ Ωa4b5d11d09f210a8⟧ ∣ nodes=s1:54371242518ce4e4.171ac04630b7db8c.b9cdbd8c5f5257ab.4369625a3e5f79e7 ports=s1:544b7e4251d3ed32.68c8166ab64ff36c.e22ede3ed517d34f.9703cbc38e72b5fa contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:542d01425171fea0.6929bcaa7b24d905.e9346d1e2435b43e.39f87e00fff92980 +symbol_authority=non_authoritative +nodes=11 +contexts=1 +journal=0 +verdict=CERTIFIED +context.0.projection_verified=true +context.0.verdict=CERTIFIED +context.0.burdens=1 +context.0.discharged=1 +context.0.open=0 +context.0.invalid=0 +context.0.missing_evidence=0 diff --git a/samples/golden/expected/certified_triangle.dna.hex b/samples/golden/expected/certified_triangle.dna.hex new file mode 100644 index 0000000..05bfec7 --- /dev/null +++ b/samples/golden/expected/certified_triangle.dna.hex @@ -0,0 +1 @@ +4c363444020000009e02000075e5cc4f42859653305e9b56fd1a34ce5682555a3f4ba26ca15ae121bf47d6a24c36344e04000b0000000c000000010000000b000000010000000000ffffffff4100000000000000000000000000010000000000ffffffff4200000000000000000000000000010000000000ffffffff4300000000000000000000000000030000000000ffffffff0000000000000000000000000200030000000000ffffffff0000000000000000020000000200030000000000ffffffff0000000000000000040000000200040000000000030000000000000000000000060000000000040000000000040000000000000000000000060000000000050000000000050000000000000000000000060000000200080000000000ffffffff05000000000000000800000004000900000000000900000000000000000000000c000000000000000000020000000100000003000100010000000200000002000000030001000000000002000000020000000300010006000000040000000700000004000100080000000500000006000000060001000700000006000200050000000700030000000000ffffffff564954414e34364c01000000010000000000000000000000564954414e34364c01000000020000000000000001000000564954414e34364c01000000030000000000000002000000564954414e34364c01000000040000000000000003000000564954414e34364c01000000050000000000000004000000564954414e34364c01000000060000000000000005000000564954414e34364c01000000070000000000000006000000564954414e34364c01000000080000000000000007000000564954414e34364c01000000090000000000000008000000564954414e34364c020000000900000000000000feffffffffffffff09000000564954414e34364c020000000900000000000000ffffffffffffffff0a000000 diff --git a/samples/golden/expected/certified_triangle.normalized.rna b/samples/golden/expected/certified_triangle.normalized.rna new file mode 100644 index 0000000..388995d --- /dev/null +++ b/samples/golden/expected/certified_triangle.normalized.rna @@ -0,0 +1,10 @@ +L64R1 0x4c36344e41544956 +a 1 0x41 +a 2 0x42 +a 3 0x43 +f 4 1 2 +f 5 2 3 +f 6 1 3 +v 7 4 +v 8 5 +c 9 7 8 6 diff --git a/samples/golden/expected/certified_triangle.run.txt b/samples/golden/expected/certified_triangle.run.txt new file mode 100644 index 0000000..9160adc --- /dev/null +++ b/samples/golden/expected/certified_triangle.run.txt @@ -0,0 +1,19 @@ +L64 NATIVE EXECUTION v1 +source=rna +mode=structural_authority_evaluation +authority=exact_canonical_l64d +authority_mutation=none +canonical_roundtrip=true +projection_authority=non_authoritative +projection_verified=true +certification_verdict=CERTIFIED +symbol=⟦l64.native.state.v2 ∷ Σ53dfec4250aa61e2 ⊗ Π7d622e10ef2220a3 ⊗ Δ92ec6a8373dca073 ⊗ Ωa4b5d11d09f210a8⟧ ∣ nodes=s1:54371242518ce4e4.171ac04630b7db8c.b9cdbd8c5f5257ab.4369625a3e5f79e7 ports=s1:544b7e4251d3ed32.68c8166ab64ff36c.e22ede3ed517d34f.9703cbc38e72b5fa contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:542d01425171fea0.6929bcaa7b24d905.e9346d1e2435b43e.39f87e00fff92980 +nodes=11 +ports=12 +contexts=1 +journal=0 +root.closed=11 +root.open=0 +root.invalid=0 +root.research_candidates=1/1 +context.0.verdict=CERTIFIED diff --git a/samples/golden/expected/equality_chain.certify.txt b/samples/golden/expected/equality_chain.certify.txt new file mode 100644 index 0000000..3a5b0c6 --- /dev/null +++ b/samples/golden/expected/equality_chain.certify.txt @@ -0,0 +1,17 @@ +L64 NATIVE CERTIFICATION v1 +scope=native_structural_closure +authority=exact_canonical_l64d +canonical_dna=true +symbol=⟦l64.native.state.v2 ∷ Σ53dea54250a752ed ⊗ Π517a0fadd79730e6 ⊗ Δbfd77bcbcaf4f4a5 ⊗ Ωc2eac328960843f3⟧ ∣ nodes=s1:5400fc4250e08eda.1414c1b873270cb3.a237f5b6505a6fe7.0587d8f7506f06f9 ports=s1:541c9b42512c4c4c.a9daa275c7080903.fcb50f3277772c96.0bfd9739830427e0 contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:53fa3d4250cc1e62.406ec851b4346a7c.5bce9a1e6ab0b74d.68d0f15cb62bd182 +symbol_authority=non_authoritative +nodes=8 +contexts=1 +journal=0 +verdict=CERTIFIED +context.0.projection_verified=true +context.0.verdict=CERTIFIED +context.0.burdens=3 +context.0.discharged=3 +context.0.open=0 +context.0.invalid=0 +context.0.missing_evidence=0 diff --git a/samples/golden/expected/equality_chain.dna.hex b/samples/golden/expected/equality_chain.dna.hex new file mode 100644 index 0000000..c488213 --- /dev/null +++ b/samples/golden/expected/equality_chain.dna.hex @@ -0,0 +1 @@ +4c36344402000000fe0100009f74d34f42869953bfb65ad6f25277b2f9983f454afbab03b0f9fcd44ae180b94c36344e040008000000090000000100000008000000010000000000ffffffff4100000000000000000000000000010000000000ffffffff4100000000000000000000000000110000000000ffffffff0000000000000000000000000200120000000000020000000200000000000000020000000000110000000000ffffffff0000000000000000020000000200120000000000040000000300000000000000040000000100110000000000ffffffff000000000000000005000000020012000000000006000000040000000000000007000000020000000000080000000100000009000100010000000800000000000000090001000200000006000000000000000800000000000000090001000200000006000000040000000600010000000000ffffffff5145000000000000010000000100000000000000000000005145000000000000010000000200000000000000010000005145000000000000010000000300000000000000020000005145000000000000020000000300000000000000ffffffffffffffff030000005145000000000000010000000400000000000000040000005145000000000000020000000400000000000000ffffffffffffffff050000005145000000000000010000000500000000000000060000005145000000000000020000000500000000000000ffffffffffffffff07000000 diff --git a/samples/golden/expected/equality_chain.normalized.rna b/samples/golden/expected/equality_chain.normalized.rna new file mode 100644 index 0000000..4fec0f0 --- /dev/null +++ b/samples/golden/expected/equality_chain.normalized.rna @@ -0,0 +1,6 @@ +L64R1 0x4551 +a 1 0x41 +a 2 0x41 +e 3 2 1 2 0 +e 4 3 2 1 0 3 +e 5 4 1 1 0 3 4 diff --git a/samples/golden/expected/equality_chain.run.txt b/samples/golden/expected/equality_chain.run.txt new file mode 100644 index 0000000..abc65bc --- /dev/null +++ b/samples/golden/expected/equality_chain.run.txt @@ -0,0 +1,19 @@ +L64 NATIVE EXECUTION v1 +source=rna +mode=structural_authority_evaluation +authority=exact_canonical_l64d +authority_mutation=none +canonical_roundtrip=true +projection_authority=non_authoritative +projection_verified=true +certification_verdict=CERTIFIED +symbol=⟦l64.native.state.v2 ∷ Σ53dea54250a752ed ⊗ Π517a0fadd79730e6 ⊗ Δbfd77bcbcaf4f4a5 ⊗ Ωc2eac328960843f3⟧ ∣ nodes=s1:5400fc4250e08eda.1414c1b873270cb3.a237f5b6505a6fe7.0587d8f7506f06f9 ports=s1:541c9b42512c4c4c.a9daa275c7080903.fcb50f3277772c96.0bfd9739830427e0 contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:53fa3d4250cc1e62.406ec851b4346a7c.5bce9a1e6ab0b74d.68d0f15cb62bd182 +nodes=8 +ports=9 +contexts=1 +journal=0 +root.closed=8 +root.open=0 +root.invalid=0 +root.research_candidates=3/3 +context.0.verdict=CERTIFIED diff --git a/samples/golden/expected/invalid_child_context.certify.txt b/samples/golden/expected/invalid_child_context.certify.txt new file mode 100644 index 0000000..c3874d9 --- /dev/null +++ b/samples/golden/expected/invalid_child_context.certify.txt @@ -0,0 +1,24 @@ +L64 NATIVE CERTIFICATION v1 +scope=native_structural_closure +authority=exact_canonical_l64d +canonical_dna=true +symbol=⟦l64.native.state.v2 ∷ Σ53dc3c4250a09ce2 ⊗ Π40fde5df09a3fc72 ⊗ Δ8fad4d14c1641875 ⊗ Ω3802766eea1fa40d⟧ ∣ nodes=s1:53e87d42509a761f.690ac28cbc0fdc1f.c71d29802c13583a.3a3d29014e78954b ports=s1:53ed404250a60d52.0b72726596f8c704.f59a08bc55027db2.a7b7c9a0929438ef contexts=s1:5398c9424fccdea8.7e776ebf0d39ef08.cc86dceef4dae730.5719e568605e2c6e routes=s1:53eb354250a28e73.3443ecbe9f85814e.9c6ab6801a9dd72f.11b68a2a0395eb12 +symbol_authority=non_authoritative +nodes=7 +contexts=2 +journal=0 +verdict=INVALID +context.0.projection_verified=true +context.0.verdict=OPEN +context.0.burdens=1 +context.0.discharged=0 +context.0.open=1 +context.0.invalid=0 +context.0.missing_evidence=0 +context.1.projection_verified=true +context.1.verdict=INVALID +context.1.burdens=1 +context.1.discharged=0 +context.1.open=0 +context.1.invalid=1 +context.1.missing_evidence=0 diff --git a/samples/golden/expected/invalid_child_context.dna.hex b/samples/golden/expected/invalid_child_context.dna.hex new file mode 100644 index 0000000..2c33dbe --- /dev/null +++ b/samples/golden/expected/invalid_child_context.dna.hex @@ -0,0 +1 @@ +4c36344402000000be0100003eeaca4f42ac95535714fdf82d37077634e491c0879440b40ee7de2b33b031704c36344e040007000000070000000200000007000000010000000000ffffffff52000000000000000000000000000a0000000000ffffffff00000000000000000000000001000400000000000100000000000000000000000100000000000f0000000000010000000000000000000000010000000100080000000000ffffffff0f000000000000000200000003001000000000000400000001010000000000000500000001000e0000000000ffffffff0100000000000000060000000100000000000100000002000000040000000300000005000000020000000600010001000000070002000200000006000000020000000500000000000000ffffffff00000000060000003159464954524543010000000100000000000000000000003159464954524543010000000200000000000000010000003159464954524543010000000300000000000000020000003159464954524543010000000400000000000000030000003159464954524543020000000400000000000000feffffffffffffff040000003159464954524543020000000400000000000000ffffffffffffffff05000000315946495452454301000000050000000000000006000000 diff --git a/samples/golden/expected/invalid_child_context.normalized.rna b/samples/golden/expected/invalid_child_context.normalized.rna new file mode 100644 index 0000000..4b4f59a --- /dev/null +++ b/samples/golden/expected/invalid_child_context.normalized.rna @@ -0,0 +1,7 @@ +L64R1 0x4345525449465931 +a 1 0x52 +q 2 1 0 0 0 0 0 0 0 +v 3 2 +r 4 3 2 +k 5 3 1 0 +h 1 0 5 diff --git a/samples/golden/expected/invalid_child_context.run.txt b/samples/golden/expected/invalid_child_context.run.txt new file mode 100644 index 0000000..1ea1fd0 --- /dev/null +++ b/samples/golden/expected/invalid_child_context.run.txt @@ -0,0 +1,20 @@ +L64 NATIVE EXECUTION v1 +source=rna +mode=structural_authority_evaluation +authority=exact_canonical_l64d +authority_mutation=none +canonical_roundtrip=true +projection_authority=non_authoritative +projection_verified=true +certification_verdict=INVALID +symbol=⟦l64.native.state.v2 ∷ Σ53dc3c4250a09ce2 ⊗ Π40fde5df09a3fc72 ⊗ Δ8fad4d14c1641875 ⊗ Ω3802766eea1fa40d⟧ ∣ nodes=s1:53e87d42509a761f.690ac28cbc0fdc1f.c71d29802c13583a.3a3d29014e78954b ports=s1:53ed404250a60d52.0b72726596f8c704.f59a08bc55027db2.a7b7c9a0929438ef contexts=s1:5398c9424fccdea8.7e776ebf0d39ef08.cc86dceef4dae730.5719e568605e2c6e routes=s1:53eb354250a28e73.3443ecbe9f85814e.9c6ab6801a9dd72f.11b68a2a0395eb12 +nodes=7 +ports=7 +contexts=2 +journal=0 +root.closed=4 +root.open=3 +root.invalid=0 +root.research_candidates=3/3 +context.0.verdict=OPEN +context.1.verdict=INVALID diff --git a/samples/golden/expected/matrix_multiply.certify.txt b/samples/golden/expected/matrix_multiply.certify.txt new file mode 100644 index 0000000..fb880b3 --- /dev/null +++ b/samples/golden/expected/matrix_multiply.certify.txt @@ -0,0 +1,17 @@ +L64 NATIVE CERTIFICATION v1 +scope=native_structural_closure +authority=exact_canonical_l64d +canonical_dna=true +symbol=⟦l64.native.state.v2 ∷ Σ53db8a42509e9356 ⊗ Πe44541985579b2f8 ⊗ Δdb9e1cdba6418f05 ⊗ Ω78b0b501539ed84c⟧ ∣ nodes=s1:540ad3425102df85.f24120e271cfab16.a88f4f598f8f3b21.8999829d4d490d36 ports=s1:540f8042510bc55b.0829936746bb043b.cb01bc92ce922193.65838f6734ba98ef contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:540a3a4251022fca.09b92365a2325696.21af5a21199d12ec.909ceefff364f742 +symbol_authority=non_authoritative +nodes=9 +contexts=1 +journal=0 +verdict=CERTIFIED +context.0.projection_verified=true +context.0.verdict=CERTIFIED +context.0.burdens=1 +context.0.discharged=1 +context.0.open=0 +context.0.invalid=0 +context.0.missing_evidence=0 diff --git a/samples/golden/expected/matrix_multiply.dna.hex b/samples/golden/expected/matrix_multiply.dna.hex new file mode 100644 index 0000000..e1a4acf --- /dev/null +++ b/samples/golden/expected/matrix_multiply.dna.hex @@ -0,0 +1 @@ +4c3634440200000026020000bc93cb4f42e1955371b491a28ff0df772c228d3af2b45962b2229d9b855152854c36344e040009000000090000000100000009000000010000000000ffffffff5200000000000000000000000000020000000000ffffffff0300000002000000000000000100020000000000ffffffff0200000003000000010000000100020000000000ffffffff0200000002000000020000000100040000000000010000000000000000000000030000000000040000000000020000000000000000000000030000000000060000000000030000000000000000000000030000000200080000000000ffffffff060000000000000005000000040009000000000007000000000000000000000009000000000000000000010000000000000001000000000000000100000004000000040000000500000004000100060000000500000004000000060001000500000006000200030000000700030000000000ffffffff58495254414d00000100000001000000000000000000000058495254414d00000100000002000000000000000100000058495254414d00000100000003000000000000000200000058495254414d00000100000004000000000000000300000058495254414d00000100000005000000000000000400000058495254414d00000100000006000000000000000500000058495254414d00000100000007000000000000000600000058495254414d0000020000000700000000000000feffffffffffffff0700000058495254414d0000020000000700000000000000ffffffffffffffff08000000 diff --git a/samples/golden/expected/matrix_multiply.normalized.rna b/samples/golden/expected/matrix_multiply.normalized.rna new file mode 100644 index 0000000..f4f64cd --- /dev/null +++ b/samples/golden/expected/matrix_multiply.normalized.rna @@ -0,0 +1,8 @@ +L64R1 0x4d4154524958 +a 1 0x52 +m 2 1 2 3 +m 3 1 3 2 +m 4 1 2 2 +v 5 2 +v 6 3 +x 7 5 6 4 diff --git a/samples/golden/expected/matrix_multiply.run.txt b/samples/golden/expected/matrix_multiply.run.txt new file mode 100644 index 0000000..3688fd9 --- /dev/null +++ b/samples/golden/expected/matrix_multiply.run.txt @@ -0,0 +1,19 @@ +L64 NATIVE EXECUTION v1 +source=rna +mode=structural_authority_evaluation +authority=exact_canonical_l64d +authority_mutation=none +canonical_roundtrip=true +projection_authority=non_authoritative +projection_verified=true +certification_verdict=CERTIFIED +symbol=⟦l64.native.state.v2 ∷ Σ53db8a42509e9356 ⊗ Πe44541985579b2f8 ⊗ Δdb9e1cdba6418f05 ⊗ Ω78b0b501539ed84c⟧ ∣ nodes=s1:540ad3425102df85.f24120e271cfab16.a88f4f598f8f3b21.8999829d4d490d36 ports=s1:540f8042510bc55b.0829936746bb043b.cb01bc92ce922193.65838f6734ba98ef contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:540a3a4251022fca.09b92365a2325696.21af5a21199d12ec.909ceefff364f742 +nodes=9 +ports=9 +contexts=1 +journal=0 +root.closed=9 +root.open=0 +root.invalid=0 +root.research_candidates=1/1 +context.0.verdict=CERTIFIED diff --git a/samples/golden/expected/mixed_bundle.certify.txt b/samples/golden/expected/mixed_bundle.certify.txt new file mode 100644 index 0000000..642ede0 --- /dev/null +++ b/samples/golden/expected/mixed_bundle.certify.txt @@ -0,0 +1,38 @@ +L64 NATIVE BUNDLE CERTIFICATION v1 +transport=canonical_l64b +transport_verified=true +members=2 +composite_authority=none +composite_certificate=none +member.0.scope=native_structural_closure +member.0.authority=exact_canonical_l64d +member.0.canonical_dna=true +member.0.symbol=⟦l64.native.state.v2 ∷ Σ53dfec4250aa61e2 ⊗ Π7d622e10ef2220a3 ⊗ Δ92ec6a8373dca073 ⊗ Ωa4b5d11d09f210a8⟧ ∣ nodes=s1:54371242518ce4e4.171ac04630b7db8c.b9cdbd8c5f5257ab.4369625a3e5f79e7 ports=s1:544b7e4251d3ed32.68c8166ab64ff36c.e22ede3ed517d34f.9703cbc38e72b5fa contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:542d01425171fea0.6929bcaa7b24d905.e9346d1e2435b43e.39f87e00fff92980 +member.0.symbol_authority=non_authoritative +member.0.nodes=11 +member.0.contexts=1 +member.0.journal=0 +member.0.verdict=CERTIFIED +member.0.context.0.projection_verified=true +member.0.context.0.verdict=CERTIFIED +member.0.context.0.burdens=1 +member.0.context.0.discharged=1 +member.0.context.0.open=0 +member.0.context.0.invalid=0 +member.0.context.0.missing_evidence=0 +member.1.scope=native_structural_closure +member.1.authority=exact_canonical_l64d +member.1.canonical_dna=true +member.1.symbol=⟦l64.native.state.v2 ∷ Σ53e2714250b1be51 ⊗ Πa7d1849f5a837d78 ⊗ Δ03943049f4039d87 ⊗ Ω51f3e939a25a0f08⟧ ∣ nodes=s1:53d8e242506e1cad.a2a0d40c7373d98a.af110f69b9951d3a.fbbe8017b85dd7d7 ports=s1:53df3042507ddd35.7850f1c89ccfda76.5d3bb5659d300ee5.7323f9f42b8c822d contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:53db87425075ed4c.134c9697d5a37d28.b0ef8e19a20831e2.64bc8f92375db7b0 +member.1.symbol_authority=non_authoritative +member.1.nodes=6 +member.1.contexts=1 +member.1.journal=0 +member.1.verdict=OPEN +member.1.context.0.projection_verified=true +member.1.context.0.verdict=OPEN +member.1.context.0.burdens=1 +member.1.context.0.discharged=0 +member.1.context.0.open=1 +member.1.context.0.invalid=0 +member.1.context.0.missing_evidence=0 diff --git a/samples/golden/expected/mixed_bundle.observe.txt b/samples/golden/expected/mixed_bundle.observe.txt new file mode 100644 index 0000000..7293beb --- /dev/null +++ b/samples/golden/expected/mixed_bundle.observe.txt @@ -0,0 +1,57 @@ +L64 NATIVE BUNDLE OBSERVATION v1 +transport=canonical_l64b +transport_verified=true +members=2 +composite_authority=none +composite_verdict=none +composite_observation=none +member.0.scope=native_certification_replay_observation +member.0.authority=exact_canonical_l64d +member.0.canonical_dna=true +member.0.projection_authority=non_authoritative +member.0.symbol=⟦l64.native.state.v2 ∷ Σ53dfec4250aa61e2 ⊗ Π7d622e10ef2220a3 ⊗ Δ92ec6a8373dca073 ⊗ Ωa4b5d11d09f210a8⟧ ∣ nodes=s1:54371242518ce4e4.171ac04630b7db8c.b9cdbd8c5f5257ab.4369625a3e5f79e7 ports=s1:544b7e4251d3ed32.68c8166ab64ff36c.e22ede3ed517d34f.9703cbc38e72b5fa contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:542d01425171fea0.6929bcaa7b24d905.e9346d1e2435b43e.39f87e00fff92980 +member.0.nodes=11 +member.0.contexts=1 +member.0.journal=0 +member.0.verdict=CERTIFIED +member.0.context.0.certification_projection_verified=true +member.0.context.0.replay_projection_verified=true +member.0.context.0.report_projection_verified=true +member.0.context.0.verdict=CERTIFIED +member.0.context.0.closed=11 +member.0.context.0.open=0 +member.0.context.0.invalid=0 +member.0.context.0.obligation_routes=0 +member.0.context.0.invalid_routes=0 +member.0.context.0.opcode.1.count=3 +member.0.context.0.opcode.3.count=3 +member.0.context.0.opcode.4.count=2 +member.0.context.0.opcode.5.count=1 +member.0.context.0.opcode.8.count=1 +member.0.context.0.opcode.9.count=1 +member.0.context.0.replay_steps=0 +member.1.scope=native_certification_replay_observation +member.1.authority=exact_canonical_l64d +member.1.canonical_dna=true +member.1.projection_authority=non_authoritative +member.1.symbol=⟦l64.native.state.v2 ∷ Σ53e2714250b1be51 ⊗ Πa7d1849f5a837d78 ⊗ Δ03943049f4039d87 ⊗ Ω51f3e939a25a0f08⟧ ∣ nodes=s1:53d8e242506e1cad.a2a0d40c7373d98a.af110f69b9951d3a.fbbe8017b85dd7d7 ports=s1:53df3042507ddd35.7850f1c89ccfda76.5d3bb5659d300ee5.7323f9f42b8c822d contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:53db87425075ed4c.134c9697d5a37d28.b0ef8e19a20831e2.64bc8f92375db7b0 +member.1.nodes=6 +member.1.contexts=1 +member.1.journal=0 +member.1.verdict=OPEN +member.1.context.0.certification_projection_verified=true +member.1.context.0.replay_projection_verified=true +member.1.context.0.report_projection_verified=true +member.1.context.0.verdict=OPEN +member.1.context.0.closed=3 +member.1.context.0.open=3 +member.1.context.0.invalid=0 +member.1.context.0.obligation_routes=1 +member.1.context.0.invalid_routes=0 +member.1.context.0.opcode.1.count=1 +member.1.context.0.opcode.4.count=1 +member.1.context.0.opcode.8.count=1 +member.1.context.0.opcode.10.count=1 +member.1.context.0.opcode.15.count=1 +member.1.context.0.opcode.16.count=1 +member.1.context.0.replay_steps=0 diff --git a/samples/golden/expected/mixed_bundle.run.txt b/samples/golden/expected/mixed_bundle.run.txt new file mode 100644 index 0000000..416791c --- /dev/null +++ b/samples/golden/expected/mixed_bundle.run.txt @@ -0,0 +1,41 @@ +L64 NATIVE BUNDLE EXECUTION v1 +members=2 +composite_authority=none +composite_execution=none +ordering=transport_sequence +member.0.source=bundle_member +member.0.mode=structural_authority_evaluation +member.0.authority=exact_canonical_l64d +member.0.authority_mutation=none +member.0.canonical_roundtrip=true +member.0.projection_authority=non_authoritative +member.0.projection_verified=true +member.0.certification_verdict=CERTIFIED +member.0.symbol=⟦l64.native.state.v2 ∷ Σ53dfec4250aa61e2 ⊗ Π7d622e10ef2220a3 ⊗ Δ92ec6a8373dca073 ⊗ Ωa4b5d11d09f210a8⟧ ∣ nodes=s1:54371242518ce4e4.171ac04630b7db8c.b9cdbd8c5f5257ab.4369625a3e5f79e7 ports=s1:544b7e4251d3ed32.68c8166ab64ff36c.e22ede3ed517d34f.9703cbc38e72b5fa contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:542d01425171fea0.6929bcaa7b24d905.e9346d1e2435b43e.39f87e00fff92980 +member.0.nodes=11 +member.0.ports=12 +member.0.contexts=1 +member.0.journal=0 +member.0.root.closed=11 +member.0.root.open=0 +member.0.root.invalid=0 +member.0.root.research_candidates=1/1 +member.0.context.0.verdict=CERTIFIED +member.1.source=bundle_member +member.1.mode=structural_authority_evaluation +member.1.authority=exact_canonical_l64d +member.1.authority_mutation=none +member.1.canonical_roundtrip=true +member.1.projection_authority=non_authoritative +member.1.projection_verified=true +member.1.certification_verdict=OPEN +member.1.symbol=⟦l64.native.state.v2 ∷ Σ53e2714250b1be51 ⊗ Πa7d1849f5a837d78 ⊗ Δ03943049f4039d87 ⊗ Ω51f3e939a25a0f08⟧ ∣ nodes=s1:53d8e242506e1cad.a2a0d40c7373d98a.af110f69b9951d3a.fbbe8017b85dd7d7 ports=s1:53df3042507ddd35.7850f1c89ccfda76.5d3bb5659d300ee5.7323f9f42b8c822d contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:53db87425075ed4c.134c9697d5a37d28.b0ef8e19a20831e2.64bc8f92375db7b0 +member.1.nodes=6 +member.1.ports=6 +member.1.contexts=1 +member.1.journal=0 +member.1.root.closed=3 +member.1.root.open=3 +member.1.root.invalid=0 +member.1.root.research_candidates=3/3 +member.1.context.0.verdict=OPEN diff --git a/samples/golden/expected/open_obligation.certify.txt b/samples/golden/expected/open_obligation.certify.txt new file mode 100644 index 0000000..3048e40 --- /dev/null +++ b/samples/golden/expected/open_obligation.certify.txt @@ -0,0 +1,17 @@ +L64 NATIVE CERTIFICATION v1 +scope=native_structural_closure +authority=exact_canonical_l64d +canonical_dna=true +symbol=⟦l64.native.state.v2 ∷ Σ53e2714250b1be51 ⊗ Πa7d1849f5a837d78 ⊗ Δ03943049f4039d87 ⊗ Ω51f3e939a25a0f08⟧ ∣ nodes=s1:53d8e242506e1cad.a2a0d40c7373d98a.af110f69b9951d3a.fbbe8017b85dd7d7 ports=s1:53df3042507ddd35.7850f1c89ccfda76.5d3bb5659d300ee5.7323f9f42b8c822d contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:53db87425075ed4c.134c9697d5a37d28.b0ef8e19a20831e2.64bc8f92375db7b0 +symbol_authority=non_authoritative +nodes=6 +contexts=1 +journal=0 +verdict=OPEN +context.0.projection_verified=true +context.0.verdict=OPEN +context.0.burdens=1 +context.0.discharged=0 +context.0.open=1 +context.0.invalid=0 +context.0.missing_evidence=0 diff --git a/samples/golden/expected/open_obligation.dna.hex b/samples/golden/expected/open_obligation.dna.hex new file mode 100644 index 0000000..c91cca0 --- /dev/null +++ b/samples/golden/expected/open_obligation.dna.hex @@ -0,0 +1 @@ +4c363444020000007e010000f1c0c94f42189553a269aa40826c4f8bff2fca259c0cdfc08b333d46135339044c36344e040006000000060000000100000006000000010000000000ffffffff52000000000000000000000000000a0000000000ffffffff00000000000000000000000001000400000000000100000000000000000000000100000000000f0000000000010000000000000000000000010000000100080000000000ffffffff0f0000000000000002000000030010000000000004000000010100000000000005000000010000000000010000000200000004000000030000000500000002000000060001000100000007000200020000000600000000000000ffffffff3159464954524543010000000100000000000000000000003159464954524543010000000200000000000000010000003159464954524543010000000300000000000000020000003159464954524543010000000400000000000000030000003159464954524543020000000400000000000000feffffffffffffff040000003159464954524543020000000400000000000000ffffffffffffffff05000000 diff --git a/samples/golden/expected/open_obligation.normalized.rna b/samples/golden/expected/open_obligation.normalized.rna new file mode 100644 index 0000000..a9c6373 --- /dev/null +++ b/samples/golden/expected/open_obligation.normalized.rna @@ -0,0 +1,5 @@ +L64R1 0x4345525449465931 +a 1 0x52 +q 2 1 0 0 0 0 0 0 0 +v 3 2 +r 4 3 2 diff --git a/samples/golden/expected/open_obligation.run.txt b/samples/golden/expected/open_obligation.run.txt new file mode 100644 index 0000000..da84412 --- /dev/null +++ b/samples/golden/expected/open_obligation.run.txt @@ -0,0 +1,19 @@ +L64 NATIVE EXECUTION v1 +source=rna +mode=structural_authority_evaluation +authority=exact_canonical_l64d +authority_mutation=none +canonical_roundtrip=true +projection_authority=non_authoritative +projection_verified=true +certification_verdict=OPEN +symbol=⟦l64.native.state.v2 ∷ Σ53e2714250b1be51 ⊗ Πa7d1849f5a837d78 ⊗ Δ03943049f4039d87 ⊗ Ω51f3e939a25a0f08⟧ ∣ nodes=s1:53d8e242506e1cad.a2a0d40c7373d98a.af110f69b9951d3a.fbbe8017b85dd7d7 ports=s1:53df3042507ddd35.7850f1c89ccfda76.5d3bb5659d300ee5.7323f9f42b8c822d contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:53db87425075ed4c.134c9697d5a37d28.b0ef8e19a20831e2.64bc8f92375db7b0 +nodes=6 +ports=6 +contexts=1 +journal=0 +root.closed=3 +root.open=3 +root.invalid=0 +root.research_candidates=3/3 +context.0.verdict=OPEN diff --git a/samples/golden/expected/triangle.release.authority.dna.hex b/samples/golden/expected/triangle.release.authority.dna.hex new file mode 100644 index 0000000..05bfec7 --- /dev/null +++ b/samples/golden/expected/triangle.release.authority.dna.hex @@ -0,0 +1 @@ +4c363444020000009e02000075e5cc4f42859653305e9b56fd1a34ce5682555a3f4ba26ca15ae121bf47d6a24c36344e04000b0000000c000000010000000b000000010000000000ffffffff4100000000000000000000000000010000000000ffffffff4200000000000000000000000000010000000000ffffffff4300000000000000000000000000030000000000ffffffff0000000000000000000000000200030000000000ffffffff0000000000000000020000000200030000000000ffffffff0000000000000000040000000200040000000000030000000000000000000000060000000000040000000000040000000000000000000000060000000000050000000000050000000000000000000000060000000200080000000000ffffffff05000000000000000800000004000900000000000900000000000000000000000c000000000000000000020000000100000003000100010000000200000002000000030001000000000002000000020000000300010006000000040000000700000004000100080000000500000006000000060001000700000006000200050000000700030000000000ffffffff564954414e34364c01000000010000000000000000000000564954414e34364c01000000020000000000000001000000564954414e34364c01000000030000000000000002000000564954414e34364c01000000040000000000000003000000564954414e34364c01000000050000000000000004000000564954414e34364c01000000060000000000000005000000564954414e34364c01000000070000000000000006000000564954414e34364c01000000080000000000000007000000564954414e34364c01000000090000000000000008000000564954414e34364c020000000900000000000000feffffffffffffff09000000564954414e34364c020000000900000000000000ffffffffffffffff0a000000 diff --git a/samples/golden/expected/triangle.release.projection.txt b/samples/golden/expected/triangle.release.projection.txt new file mode 100644 index 0000000..056e144 --- /dev/null +++ b/samples/golden/expected/triangle.release.projection.txt @@ -0,0 +1,14 @@ +L64 NATIVE PROJECTION v1 +context=0 +symbol=⟦l64.native.state.v2 ∷ Σ53dfec4250aa61e2 ⊗ Π7d622e10ef2220a3 ⊗ Δ92ec6a8373dca073 ⊗ Ωa4b5d11d09f210a8⟧ ∣ nodes=s1:54371242518ce4e4.171ac04630b7db8c.b9cdbd8c5f5257ab.4369625a3e5f79e7 ports=s1:544b7e4251d3ed32.68c8166ab64ff36c.e22ede3ed517d34f.9703cbc38e72b5fa contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:542d01425171fea0.6929bcaa7b24d905.e9346d1e2435b43e.39f87e00fff92980 +nodes=11 +contexts=1 +journal=0 +atlas_candidates=1 +certification_burdens=1 +replay_steps=0 +closed=11 +open=0 +invalid=0 +research_candidates=1/1 +research route=4c36344e41544956/0000000000000009 opcode=Compose closure=Closed affected=3 dependents=1 diff --git a/samples/golden/expected/triangle.release.record b/samples/golden/expected/triangle.release.record new file mode 100644 index 0000000..0517b45 --- /dev/null +++ b/samples/golden/expected/triangle.release.record @@ -0,0 +1,9 @@ +L64 NATIVE RELEASE v1 +authority=authority.dna +source=source.rna +projection=projection.txt +projection_authority=non_authoritative +state_symbol=⟦l64.native.state.v2 ∷ Σ53dfec4250aa61e2 ⊗ Π7d622e10ef2220a3 ⊗ Δ92ec6a8373dca073 ⊗ Ωa4b5d11d09f210a8⟧ ∣ nodes=s1:54371242518ce4e4.171ac04630b7db8c.b9cdbd8c5f5257ab.4369625a3e5f79e7 ports=s1:544b7e4251d3ed32.68c8166ab64ff36c.e22ede3ed517d34f.9703cbc38e72b5fa contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:542d01425171fea0.6929bcaa7b24d905.e9346d1e2435b43e.39f87e00fff92980 +source_bytes=98 +dna_bytes=714 +projection_verified=true diff --git a/samples/golden/expected/triangle_to_equality.compare.txt b/samples/golden/expected/triangle_to_equality.compare.txt new file mode 100644 index 0000000..834746c --- /dev/null +++ b/samples/golden/expected/triangle_to_equality.compare.txt @@ -0,0 +1,38 @@ +L64 NATIVE AUTHORITY CHANGE v1 +scope=exact_native_authority_change +before_authority=exact_canonical_l64d +after_authority=exact_canonical_l64d +exact_equal=false +symbol_authority=non_authoritative +before_symbol=⟦l64.native.state.v2 ∷ Σ53dfec4250aa61e2 ⊗ Π7d622e10ef2220a3 ⊗ Δ92ec6a8373dca073 ⊗ Ωa4b5d11d09f210a8⟧ ∣ nodes=s1:54371242518ce4e4.171ac04630b7db8c.b9cdbd8c5f5257ab.4369625a3e5f79e7 ports=s1:544b7e4251d3ed32.68c8166ab64ff36c.e22ede3ed517d34f.9703cbc38e72b5fa contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:542d01425171fea0.6929bcaa7b24d905.e9346d1e2435b43e.39f87e00fff92980 +after_symbol=⟦l64.native.state.v2 ∷ Σ53dea54250a752ed ⊗ Π517a0fadd79730e6 ⊗ Δbfd77bcbcaf4f4a5 ⊗ Ωc2eac328960843f3⟧ ∣ nodes=s1:5400fc4250e08eda.1414c1b873270cb3.a237f5b6505a6fe7.0587d8f7506f06f9 ports=s1:541c9b42512c4c4c.a9daa275c7080903.fcb50f3277772c96.0bfd9739830427e0 contexts=s1:538738424fa624de.21d1f53721bc401b.d390bda4f777f628.71e09ef877ac42fb routes=s1:53fa3d4250cc1e62.406ec851b4346a7c.5bce9a1e6ab0b74d.68d0f15cb62bd182 +section.nodes.changed=true +section.ports.changed=true +section.contexts.changed=false +section.routes.changed=true +nodes.before=11 +nodes.after=8 +nodes.delta=-3 +contexts.before=1 +contexts.after=1 +contexts.delta=+0 +journal.before=0 +journal.after=0 +journal.delta=+0 +before_verdict=CERTIFIED +after_verdict=CERTIFIED +context.0.contact=CHANGED +context.0.before_verdict=CERTIFIED +context.0.after_verdict=CERTIFIED +context.0.closed.before=11 +context.0.closed.after=8 +context.0.closed.delta=-3 +context.0.open.before=0 +context.0.open.after=0 +context.0.open.delta=+0 +context.0.invalid.before=0 +context.0.invalid.after=0 +context.0.invalid.delta=+0 +context.0.replay_steps.before=0 +context.0.replay_steps.after=0 +context.0.replay_steps.delta=+0 diff --git a/samples/golden/invalid_child_context.rna b/samples/golden/invalid_child_context.rna new file mode 100644 index 0000000..4b4f59a --- /dev/null +++ b/samples/golden/invalid_child_context.rna @@ -0,0 +1,7 @@ +L64R1 0x4345525449465931 +a 1 0x52 +q 2 1 0 0 0 0 0 0 0 +v 3 2 +r 4 3 2 +k 5 3 1 0 +h 1 0 5 diff --git a/samples/golden/matrix_multiply.rna b/samples/golden/matrix_multiply.rna new file mode 100644 index 0000000..f4f64cd --- /dev/null +++ b/samples/golden/matrix_multiply.rna @@ -0,0 +1,8 @@ +L64R1 0x4d4154524958 +a 1 0x52 +m 2 1 2 3 +m 3 1 3 2 +m 4 1 2 2 +v 5 2 +v 6 3 +x 7 5 6 4 diff --git a/samples/golden/open_obligation.rna b/samples/golden/open_obligation.rna new file mode 100644 index 0000000..a9c6373 --- /dev/null +++ b/samples/golden/open_obligation.rna @@ -0,0 +1,5 @@ +L64R1 0x4345525449465931 +a 1 0x52 +q 2 1 0 0 0 0 0 0 0 +v 3 2 +r 4 3 2 diff --git a/samples/imported_claim_bundle.dna b/samples/imported_claim_bundle.dna deleted file mode 100644 index bbd668ed3a92a31a68a9f27133618e3f206a0a96..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3188 zcmd5;+iuf95VgzwChj13$`4Rs2~qLDL*hmWB5i|X@f!KEO{_XjvC|^{fKTB2c;_FO zv+H9gt_i%AksOa_XJ^iwS&uVvCyu>i+m>xv*DcG+vtak!c_dnRmc^->#>?nzp|X`& zABc4?QgIOMy?M8%949<}Yg<>v8ZC2WSx-ev7N^U6rQ&In2FYS-g4ov1mepT(EbFms zgp342QC|*$|5BEMIq?MV7hr zjgIR!eQe2& zQswu6yL!^3GZ60#v3>xmtd)YQAbuW1s^kLC>$~w@F_$|YT*%Bd!%Fp}F%k`}N1AbD zXv%uS+739TAEWff9|Z*|+roW&dKSll(cS+f;imo1ANHBKH1+z2?(kj-wX{uquRoap z4x}`?!|rI*KOFQ43Tw^meHX_D*@@tx=ot2xzfa`CGmCUb2jVRTeaHxG{hfz5WZ-nF zbGtDN2&SvUz!k}uz`!BMwglXdozQLhP#Iy2Vikm`LOCdbO!W>t5bAfmLEooqT@TzD zh|MeT4deK9c3*Rsr(4|;+_ZsiCO9yz2j^gamPnR7!uHFb5gPB;r#I7n@ji8iaJpNh{S2 zqoIi48QSE&FJW8G|7|fd1zXcH(*O$6jBVzB(`sJVrq$qRTFs#}(d*x)mtpfo>7dS& zSY?s4W0|dFkgYoSO3R-n8&&dPufNi${68p@5E^|m?@hyKnn_C933*vAhr-5u5#%Sr z$hpdcnc854kv9e!Xd<3V>^vb5~O^C_RY6$&@#VEr`6q*hAWe+Pp_K8T;07|JX9A z@!92MkYZHSa&2)@tiMa$H4qF=>)@4-s@315TFK(AJ^+Bm2ske5RE(i8kMi}-qsWR& z4@j)X^kGJ?!q0qY-c<8AqOK9@YN0M2QDB3xrQe`xs{?G4Y0&X|06X4e-VNY@O4r6s zv>?NA)uLBT*>Sea%Q8>$BH#XCu=}-jp&!yZMuGrPv{ZwXy+)2e8%AUW9($;qT-XD0 zpgRm$w|&x$2M|U;)DMAWwGLOs7OFUvRWJCtzM9`HaCuYzh#7OHEA~ligc?LAy5r2y zwEBj%9diCI0%bV;LMqU*6TNSzNAz)}VesiI!9}w$7|mut!GN*X_K+szC3}O9DTP;K`t(NB|UZf&^S)TDHEG z*ejL&`nQTk)j%;cPiZC64|bUw2MwsG<=tgwwkEpy)-|K%ST>_ZNi%x5kI;Cq4~F`f b+;sSLHEk|`H(lRI6)&W#~87| diff --git a/samples/native_equality.rna b/samples/native_equality.rna new file mode 100644 index 0000000..4fec0f0 --- /dev/null +++ b/samples/native_equality.rna @@ -0,0 +1,6 @@ +L64R1 0x4551 +a 1 0x41 +a 2 0x41 +e 3 2 1 2 0 +e 4 3 2 1 0 3 +e 5 4 1 1 0 3 4 diff --git a/samples/native_triangle.rna b/samples/native_triangle.rna new file mode 100644 index 0000000..388995d --- /dev/null +++ b/samples/native_triangle.rna @@ -0,0 +1,10 @@ +L64R1 0x4c36344e41544956 +a 1 0x41 +a 2 0x42 +a 3 0x43 +f 4 1 2 +f 5 2 3 +f 6 1 3 +v 7 4 +v 8 5 +c 9 7 8 6 diff --git a/samples/research/claim_chain_rule.json b/samples/research/claim_chain_rule.json deleted file mode 100644 index a61abe6..0000000 --- a/samples/research/claim_chain_rule.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "id": "CLM_CPG_CHAIN_RULE", - "title": "Claim packet for chain rule", - "statement": "CPG_CHAIN_RULE via selected route with certified verdict", - "sector": "Crosscut", - "truth_class": "Benchmark", - "claim_class": "Host", - "assumptions": ["regime:R_TOP", "regime:R_CALC"], - "projection_refs": ["RTC_CHAIN_RULE"], - "reduction_refs": ["A_TOP_TO_CALC"], - "benchmark_refs": [], - "blocker_leaves": [], - "report_refs": ["RPT_CHAIN_RULE"] -} \ No newline at end of file diff --git a/samples/research/coverage_chain_rule.json b/samples/research/coverage_chain_rule.json deleted file mode 100644 index 6e1afcd..0000000 --- a/samples/research/coverage_chain_rule.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "subject_id": "CPG_CHAIN_RULE", - "decision": "FastPathCoverage", - "route_fast_path": true, - "reason": "promoted operator and exact obligation coverage present", - "covered_by": ["OPR_PROMOTED_OPR_CHAIN1"], - "residual_obligation_ids": [] -} \ No newline at end of file diff --git a/samples/research/export_capability_truth.json b/samples/research/export_capability_truth.json deleted file mode 100644 index d5d5ed7..0000000 --- a/samples/research/export_capability_truth.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "id": "REM_EXPORT_CAPABILITY_TRUTH", - "source_ref": "Chat export stress test", - "class": "CapabilityTruthGap", - "summary": "capability truth should distinguish declared/help-routable/contract-known/smoke-executed/fully-exercised states", - "affected_surfaces": [ - "capability matrices", - "command contracts", - "stress harness summaries" - ], - "expected_fix_chain": [ - "capability_readiness_truth", - "research_registry_visibility" - ], - "status": "Open", - "notes": [ - "seeded from export findings" - ] -} diff --git a/samples/research/export_explain_execution.json b/samples/research/export_explain_execution.json deleted file mode 100644 index b256bbd..0000000 --- a/samples/research/export_explain_execution.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "id": "REM_EXPORT_EXPLAIN_EXECUTION", - "source_ref": "Chat export stress test", - "class": "RuntimeBug", - "summary": "explain-execution should resolve execution-linked context or degrade with exact contract truth instead of generic missing-file failure", - "affected_surfaces": [ - "l64-admin explain-execution", - "execution cache", - "report/manifest/lock/observe resolution" - ], - "expected_fix_chain": [ - "export_remediation_ledger", - "operational_truth_hardening", - "execution_resolution_truth" - ], - "status": "InProgress", - "notes": [ - "seeded from export findings" - ] -} diff --git a/samples/research/export_namespace_contract.json b/samples/research/export_namespace_contract.json deleted file mode 100644 index 3848aa3..0000000 --- a/samples/research/export_namespace_contract.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "id": "REM_EXPORT_NAMESPACE_CONTRACT", - "source_ref": "Chat export stress test", - "class": "RuntimeBug", - "summary": "namespace-local execution and observation artifacts need explicit same-namespace truth", - "affected_surfaces": [ - "observe-run", - "admin compare/export flows", - "execution lookup" - ], - "expected_fix_chain": [ - "namespace_scope_truth", - "execution_contracts" - ], - "status": "Open", - "notes": [ - "seeded from export findings" - ] -} diff --git a/samples/research/export_predict_impact_contract.json b/samples/research/export_predict_impact_contract.json deleted file mode 100644 index 7f91e49..0000000 --- a/samples/research/export_predict_impact_contract.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "id": "REM_EXPORT_PREDICT_IMPACT_CONTRACT", - "source_ref": "Chat export stress test", - "class": "CommandContractBug", - "summary": "predict-impact needs a live argument contract stronger than help text", - "affected_surfaces": [ - "l64-admin predict-impact", - "command contract surfaces" - ], - "expected_fix_chain": [ - "command_contract_truth", - "capability_readiness_truth" - ], - "status": "InProgress", - "notes": [ - "seeded from export findings" - ] -} diff --git a/samples/research/export_validate_inspection_report.json b/samples/research/export_validate_inspection_report.json deleted file mode 100644 index 1774dd4..0000000 --- a/samples/research/export_validate_inspection_report.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "id": "REM_EXPORT_VALIDATE_INSPECTION_REPORT", - "source_ref": "Chat export stress test", - "class": "ArtifactTypingBug", - "summary": "inspection exports should remain distinct from validation-complete bundles", - "affected_surfaces": [ - "l64-cli export-report", - "l64-cli export-validation-bundle", - "l64-cli validate" - ], - "expected_fix_chain": [ - "artifact_class_law", - "validation_bundle_rollout", - "overlay_validation_truth" - ], - "status": "InProgress", - "notes": [ - "seeded from export findings" - ] -} diff --git a/samples/research/producer_host_chain_rule.json b/samples/research/producer_host_chain_rule.json deleted file mode 100644 index 01980fe..0000000 --- a/samples/research/producer_host_chain_rule.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "id": "HST_REDUCTION_CPG_CHAIN_RULE", - "kind": "Reduction", - "purpose": "reduction host for chain rule family", - "owned_objects": ["RDM_CPG_CHAIN_RULE"], - "feeds": ["CLM_CPG_CHAIN_RULE", "REG_CPG_CHAIN_RULE"], - "notes": ["owns reduction maps and residual-obligation compression"] -} \ No newline at end of file diff --git a/samples/research/promotion_chain_rule.json b/samples/research/promotion_chain_rule.json deleted file mode 100644 index ee70038..0000000 --- a/samples/research/promotion_chain_rule.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "id": "PQU_CPG_CHAIN_RULE", - "subject_id": "CPG_CHAIN_RULE", - "status": "Ready", - "readiness_score_basis_points": 8600, - "blockers": [], - "required_refs": ["review:RVR_CPG_CHAIN_RULE", "repro:RPR_CPG_CHAIN_RULE"], - "evidence_refs": [] -} \ No newline at end of file diff --git a/samples/research/remediation_explain_execution.json b/samples/research/remediation_explain_execution.json deleted file mode 100644 index 611a3f0..0000000 --- a/samples/research/remediation_explain_execution.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "id": "RMD_EXPLAIN_EXECUTION", - "source_ref": "explain-execution", - "class": "RuntimeBug", - "summary": "explain-execution should resolve linked execution state or degrade with exact contract truth instead of generic missing-file failure", - "affected_surfaces": [ - "l64-admin", - "l64-observe", - "execution manifests", - "report execution envelopes" - ], - "expected_fix_chain": [ - "Phase 1", - "Phase 2" - ], - "status": "Open", - "notes": [ - "surfaced by exported runtime stress test", - "must distinguish missing execution record from unsupported artifact class" - ] -} diff --git a/samples/research/repro_chain_rule.json b/samples/research/repro_chain_rule.json deleted file mode 100644 index c73520c..0000000 --- a/samples/research/repro_chain_rule.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "id": "RPR_CPG_CHAIN_RULE", - "claim_packet_id": "CPG_CHAIN_RULE", - "derivation_path": ["B_TOP_TO_CALC"], - "code_refs": ["RCLASS_CHAIN_RULE", "CERT_CHAIN_RULE"], - "benchmark_refs": ["BR_CHAIN_RULE_SMOKE"], - "artifact_refs": ["REPORT_CPG_CHAIN_RULE", "PAY_CHAIN1_OBLIGATION_COUNT_REDUCTION_4_TO_2"] -} diff --git a/samples/research/signature_full_compound_completion.json b/samples/research/signature_full_compound_completion.json deleted file mode 100644 index 8cd8a8b..0000000 --- a/samples/research/signature_full_compound_completion.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id": "SIG_FULL_COMPOUND_COMPLETION", - "task_ref": "TASK_FULL_COMPOUND_COMPLETION", - "structural_type": "RegistryHardening", - "sector": "Crosscut", - "risk_class": "Medium", - "dependency_depth": 4, - "likely_failure_modes": ["generic orchestration outruns math payload", "artifact truth incomplete", "producer hosts remain implicit"], - "expected_distillate": "HandoffPacket", - "evidence_gap": ["compile pass", "command rollout", "tower persistence"] -} \ No newline at end of file diff --git a/samples/research/signature_operational_truth.json b/samples/research/signature_operational_truth.json deleted file mode 100644 index f9f188e..0000000 --- a/samples/research/signature_operational_truth.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "id": "SIG_OPERATIONAL_TRUTH_HARDENING", - "task_ref": "TASK_OPERATIONAL_TRUTH_HARDENING", - "structural_type": "OperationalHardening", - "sector": "Control", - "risk_class": "Medium", - "dependency_depth": 3, - "likely_failure_modes": [ - "artifact contract mismatch", - "namespace contract mismatch", - "help-routable support overstated as real support" - ], - "expected_distillate": "ValidationBundle", - "evidence_gap": [ - "command-contract coverage", - "artifact-class truth" - ] -} diff --git a/samples/research/task_full_compound_completion.json b/samples/research/task_full_compound_completion.json deleted file mode 100644 index fab5f96..0000000 --- a/samples/research/task_full_compound_completion.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "id": "TASK_FULL_COMPOUND_COMPLETION", - "title": "Full compound completion", - "target_sector": "Control", - "objective_kind": "Integrate", - "desired_output": "HandoffPacket", - "hard_constraints": ["keep certifier cold", "preserve math-native claims"], - "soft_constraints": ["prefer compounding changes", "avoid support-machinery drift"], - "promotion_target": "Integrated", - "rollback_path": "narrow to previous verified packet/runtime and registry state", - "success_metrics": ["warm host consumes report truth", "promotion readiness is queryable", "producer hosts explicit"] -} \ No newline at end of file diff --git a/samples/research/task_operational_truth.json b/samples/research/task_operational_truth.json deleted file mode 100644 index 5597d96..0000000 --- a/samples/research/task_operational_truth.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "id": "TASK_OPERATIONAL_TRUTH_HARDENING", - "title": "Harden command and artifact truth at the edges", - "target_sector": "Control", - "objective_kind": "Integrate", - "desired_output": "ValidationBundle", - "hard_constraints": [ - "keep certifier cold", - "do not regress proof/truth" - ], - "soft_constraints": [ - "prefer shared packet/runtime paths", - "prefer bundle-level reuse" - ], - "promotion_target": "Certified", - "rollback_path": "revert artifact/command contract surfaces to last stable state", - "success_metrics": [ - "explain-execution resolves or degrades explicitly", - "inspection exports and validation bundles are distinct" - ] -} diff --git a/scripts/run-native-demo.sh b/scripts/run-native-demo.sh new file mode 100755 index 0000000..a7b558c --- /dev/null +++ b/scripts/run-native-demo.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +OUT="${1:-$ROOT/l64-native-demo-output}" +CARGO="${CARGO:-cargo}" +TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" +EXE_SUFFIX="" +if [[ "${OS:-}" == "Windows_NT" ]]; then EXE_SUFFIX=".exe"; fi +CLI="$TARGET_DIR/release/l64-cli$EXE_SUFFIX" +WRAPPER="$TARGET_DIR/release/l64$EXE_SUFFIX" + +if [[ -e "$OUT" ]]; then + echo "demo output already exists: $OUT" >&2 + exit 2 +fi +mkdir -p "$OUT" + +cd "$ROOT" +"$CARGO" build --release --locked --offline -p l64-cli -p l64 + +"$WRAPPER" authority-audit > "$OUT/authority-audit.txt" +"$CLI" run-rna samples/native_triangle.rna > "$OUT/triangle.rna.run.txt" +"$CLI" compile-rna samples/native_triangle.rna --out "$OUT/triangle.dna" > /dev/null +"$CLI" run-dna "$OUT/triangle.dna" > "$OUT/triangle.dna.run.txt" +"$CLI" certify-dna "$OUT/triangle.dna" > "$OUT/triangle.certification.txt" +"$CLI" observe-dna "$OUT/triangle.dna" > "$OUT/triangle.observation.txt" +"$CLI" inspect-dna "$OUT/triangle.dna" > "$OUT/triangle.projection.txt" + +"$CLI" run-rna samples/native_equality.rna > "$OUT/equality.rna.run.txt" +"$CLI" compile-rna samples/native_equality.rna --out "$OUT/equality.dna" > /dev/null +"$CLI" run-dna "$OUT/equality.dna" > "$OUT/equality.dna.run.txt" +"$CLI" compare-dna "$OUT/triangle.dna" "$OUT/equality.dna" > "$OUT/triangle-to-equality.change.txt" + +"$CLI" compile-bundle "$OUT/triangle.dna" "$OUT/equality.dna" --out "$OUT/native-pair.l64b" > /dev/null +"$CLI" run-bundle --file "$OUT/native-pair.l64b" > "$OUT/native-pair.run.txt" +"$CLI" certify-bundle --file "$OUT/native-pair.l64b" > "$OUT/native-pair.certification.txt" +"$CLI" observe-bundle --file "$OUT/native-pair.l64b" > "$OUT/native-pair.observation.txt" + +"$CLI" export-genome-release --rna samples/native_triangle.rna --out "$OUT/triangle.release" > /dev/null +"$CLI" export-genome-release --rna samples/native_equality.rna --out "$OUT/equality.release" > /dev/null + +cat > "$OUT/demo.summary.txt" </dev/null +"$CLI" help run-rna | grep -F "usage: l64-cli run-rna " >/dev/null + +printf 'not native\n' > "$WORK/not-rna.txt" +if "$CLI" run-rna "$WORK/not-rna.txt" >"$WORK/out" 2>"$WORK/error"; then + echo "run-rna accepted a non-L64R1 input" >&2 + exit 1 +fi +grep -F 'is not current L64R1 RNA' "$WORK/error" >/dev/null +if grep -F 'legacy theorem' "$WORK/error" >/dev/null; then + echo "wrong-format error fell back to deleted legacy messaging" >&2 + exit 1 +fi + +printf 'L64R1 0x1\na X 0x41\n' > "$WORK/bad.rna" +if "$CLI" run-rna "$WORK/bad.rna" >"$WORK/out" 2>"$WORK/error"; then + echo "run-rna accepted malformed RNA" >&2 + exit 1 +fi +grep -F 'invalid number at RNA 2:3' "$WORK/error" >/dev/null +if grep -F 'InvalidNumber {' "$WORK/error" >/dev/null; then + echo "malformed RNA leaked Rust debug syntax" >&2 + exit 1 +fi + +"$CLI" compile-rna samples/native_triangle.rna --out "$WORK/triangle.dna" >/dev/null +cp "$WORK/triangle.dna" "$WORK/original.dna" +if "$CLI" compile-rna samples/native_equality.rna --out "$WORK/triangle.dna" >"$WORK/out" 2>"$WORK/error"; then + echo "compile-rna overwrote an existing output" >&2 + exit 1 +fi +grep -F 'refusing to overwrite existing output' "$WORK/error" >/dev/null +cmp "$WORK/triangle.dna" "$WORK/original.dna" +if find "$WORK" -maxdepth 1 -name '.*.l64-stage-*' -print -quit | grep . >/dev/null; then + echo "atomic output staging residue remained" >&2 + exit 1 +fi + +if "$CLI" compile-rna samples/native_triangle.rna --artifact-class gene --out "$WORK/class.dna" >"$WORK/out" 2>"$WORK/error"; then + echo "deleted artifact-class option was accepted" >&2 + exit 1 +fi +grep -F -- '--artifact-class was permanently deleted' "$WORK/error" >/dev/null + +if rg -n 'Result|Ok\(false\)' l64-cli/src --glob '*.rs' >/dev/null || rg -n '\{error:\?\}' l64-cli/src l64-*/src --glob '*.rs' >/dev/null; then + echo "obsolete fallback or debug diagnostic returned" >&2 + exit 1 +fi + +echo "CLI_HARDENING_GATE v1" +echo "status=pass" +echo "direct_dispatch=true" +echo "stable_diagnostics=true" +echo "atomic_no_overwrite=true" +echo "command_help=true" diff --git a/scripts/verify-documentation-coherence.sh b/scripts/verify-documentation-coherence.sh new file mode 100755 index 0000000..684af4e --- /dev/null +++ b/scripts/verify-documentation-coherence.sh @@ -0,0 +1,217 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "$ROOT" +TARGET_DIR=${CARGO_TARGET_DIR:-$ROOT/target} +CLI="$TARGET_DIR/debug/l64-cli" +WRAPPER="$TARGET_DIR/debug/l64" + +fail() { + printf 'documentation coherence verification failed: %s\n' "$1" >&2 + exit 1 +} + +is_historical() { + local file=$1 + head -n 16 "$file" | grep -Eq '^document_status: historical$|^field=key=document_status;value=historical$' +} + +mapfile -t markdown_docs < <(find . -type f -name '*.md' -not -path './target/*' -not -path './.git/*' | sort) +current_docs=() +for file in "${markdown_docs[@]}"; do + if ! is_historical "$file"; then + current_docs+=("$file") + fi +done + +[[ ${#current_docs[@]} -gt 0 ]] || fail 'no current-facing Markdown documents were found' + +package_count=$(awk ' + /^members = \[/ { in_members=1; next } + in_members && /^\]/ { in_members=0 } + in_members && /^[[:space:]]*"[^"]+",?[[:space:]]*$/ { count++ } + END { print count+0 } +' Cargo.toml) +[[ "$package_count" -eq 11 ]] || fail "Cargo workspace package count is $package_count, expected 11" + +grep -Fq 'workspace_packages: 11' LOCUS64_NATIVE_CONSTITUTION.md \ + || fail 'current constitution does not bind the eleven-package workspace' +grep -Fq 'eleven packages' LOCUS64_STACK.md \ + || fail 'stack document does not state the Cargo-derived package count' +grep -Fq 'eleven dependency-free native packages' HANDOFF_STATUS.md \ + || fail 'handoff does not state the Cargo-derived package count' +grep -Fq 'field=key=live_workspace_packages;value=11' LOCUS64_EXECUTION_COHERENCE_RAIL.athens \ + || fail 'current execution rail package count disagrees with Cargo' + +for stale in \ + 'l64-cli legacy ...' \ + 'available only through `l64-cli legacy' \ + 'replacement and quarantine of the legacy runtime' \ + 'transitional legacy workspace' \ + 'field=key=ambient_legacy_authority;value=explicit_only'; do + if grep -Fq "$stale" "${current_docs[@]}" LOCUS64_EXECUTION_COHERENCE_RAIL.athens; then + fail "stale live claim remains: $stale" + fi +done + +grep -Fq 'field=key=ambient_legacy_authority;value=deleted_tombstones_only' LOCUS64_EXECUTION_COHERENCE_RAIL.athens \ + || fail 'legacy authority field is not deleted_tombstones_only' + +[[ -f LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md ]] \ + || fail 'golden portability contract is missing' +[[ -x scripts/verify-golden-portability.sh ]] \ + || fail 'golden portability gate is missing or not executable' +[[ -x scripts/write-portability-receipt.sh ]] \ + || fail 'portability receipt writer is missing or not executable' +[[ -x scripts/verify-portability-receipts.sh ]] \ + || fail 'portability receipt verifier is missing or not executable' +[[ ! -e scripts/torture-test.ps1 ]] \ + || fail 'obsolete legacy torture harness returned to the live source' +grep -Fq 'The complete Pass 29 source archive is the restore boundary for Pass 30.' SOURCE_REFERENCE_MANIFEST.md \ + || fail 'source manifest does not name the current restore boundary' +grep -Fq '## Current boundary through Pass 30' LOCUS64_RESEARCH_ADMIN_CLASSIFICATION.md \ + || fail 'research and administration classification is stale' +grep -Fq 'receipt_schema: L64PORT1' LOCUS64_PORTABILITY_RECEIPT_CONTRACT.md \ + || fail 'portability receipt contract is missing or malformed' +for workflow_contact in \ + 'actions/upload-artifact@v4' \ + 'actions/download-artifact@v4' \ + 'locus64-portability-receipts' \ + 'scripts/write-portability-receipt.sh' \ + 'scripts/verify-portability-receipts.sh'; do + grep -Fq "$workflow_contact" .github/workflows/native-core.yml \ + || fail "workflow omits portability receipt contact: $workflow_contact" +done +scripts/verify-portability-receipts.sh --self-test >/dev/null + +# Derive retired command names from the executable tombstone list. Every live +# script except the two gates that verify the tombstones must remain free of +# those command contacts. +mapfile -t retired_commands < <(awk ' + /const RETIRED_LEGACY_COMMANDS:/ { in_list=1; next } + in_list && /^];/ { in_list=0 } + in_list && /^[[:space:]]*"[^"]+",/ { + line=$0 + sub(/^[[:space:]]*"/, "", line) + sub(/",.*$/, "", line) + print line + } +' l64-cli/src/native_membrane.rs) +[[ ${#retired_commands[@]} -gt 0 ]] || fail 'could not derive retired command vocabulary' +for script in scripts/*; do + [[ -f "$script" ]] || continue + case "$(basename "$script")" in + verify-legacy-authority-island-deletion.sh|verify-cli-hardening.sh|verify-documentation-coherence.sh) continue ;; + esac + for command in "${retired_commands[@]}"; do + if grep -Eq "[\"']${command}[\"']" "$script"; then + fail "current script invokes or advertises retired command $command: $script" + fi + done +done +grep -Fq 'golden-portability-green' L64_APPROVAL_GATES.md \ + || fail 'live approval gates omit golden portability' +grep -Fq 'residue-remote-proof-green' L64_APPROVAL_GATES.md \ + || fail 'live approval gates omit residue and remote-proof closure' +for os in ubuntu-latest macos-latest windows-latest; do + grep -Fq "$os" .github/workflows/native-core.yml \ + || fail "portable Rust matrix omits $os" +done + +if grep -REn --include='*.sh' --include='*.ps1' \ + 'cargo[[:space:]]+(test|check|run|build)[^\n]*-p[[:space:]]+l64-(core|locus|research|kernel|command|registry|selector|runtime|canon|atlas|cert|testkit|bundle|policy|admin|surfaces|qc0|qa0|qm0)' \ + scripts; then + fail 'a current script invokes a deleted package' +fi + +# Deleted crate names are allowed in current prose only where the line explicitly +# declares deletion, history, tombstone status, absence, or supersession. +deleted='(^|[^A-Za-z0-9-])l64-(core|locus|research|kernel|command|registry|selector|runtime|canon|atlas|cert|testkit|bundle|policy|admin|surfaces|qc0|qa0|qm0)([^A-Za-z0-9-]|$)' +for file in "${current_docs[@]}"; do + while IFS= read -r line; do + [[ -z "$line" ]] && continue + if ! printf '%s\n' "$line" | grep -Eiq 'deleted|historical|tombstone|removed|superseded|absent|no live|formerly|prior|old'; then + fail "deleted crate appears as a live contact in $file: $line" + fi + done < <(grep -En "$deleted" "$file" || true) +done + +for historical in \ + LOCUS64_HISTORICAL_LAW_LEDGER.md \ + L64_HISTORICAL_APPROVAL_LEDGER.md \ + LINEAR_EXECUTION_RAIL.md \ + LOCUS64_ARCHITECTURAL_CONSTITUTION_V1.md; do + [[ -f "$historical" ]] || fail "historical surface missing: $historical" + is_historical "$historical" || fail "historical surface lacks an early historical marker: $historical" +done + +for current in LOCUS64_NATIVE_CONSTITUTION.md L64_APPROVAL_GATES.md LOCUS64_LANGUAGE_SPEC.md LOCUS64_STACK.md HANDOFF_STATUS.md; do + [[ -f "$current" ]] || fail "current source missing: $current" + if is_historical "$current"; then + fail "current source is marked historical: $current" + fi +done + +# Every live script named by current-facing Markdown must exist. A current +# document may name a removed script only on a line that explicitly marks the +# contact as removed, deleted, historical, forensic, or absent. +for file in "${current_docs[@]}"; do + while IFS= read -r line; do + [[ -z "$line" ]] && continue + while IFS= read -r script; do + [[ -z "$script" ]] && continue + if [[ ! -f "$script" ]] && ! printf '%s +' "$line" | grep -Eiq 'removed|deleted|historical|forensic|absent|obsolete'; then + fail "current documentation references missing live script in $file: $script" + fi + done < <(printf '%s +' "$line" | grep -Eo 'scripts/[A-Za-z0-9._-]+\.(sh|ps1)' || true) + done < "$file" +done + +cargo build --locked --offline -p l64-cli -p l64 >/dev/null +cli_help=$("$CLI" --help) +wrapper_audit=$("$WRAPPER" authority-audit) + +grep -Fq 'Locus64 authority audit' <<<"$wrapper_audit" \ + || fail 'l64 authority-audit did not execute through the wrapper' +grep -Fq 'The wrapper is not a second parser' LOCUS64_LANGUAGE_SPEC.md \ + || fail 'binary responsibility split is not explicit in the language specification' + +mapfile -t help_commands < <(printf '%s\n' "$cli_help" | sed -n -E 's/^ ([a-z][a-z0-9-]+)[[:space:]]{2,}.*/\1/p' | sort -u) +mapfile -t spec_commands < <(awk ' + /^## `l64-cli` commands$/ { in_commands=1; next } + in_commands && /^## / { in_commands=0 } + in_commands && /^- `[a-z][a-z0-9-]+`$/ { + line=$0 + sub(/^- `/, "", line) + sub(/`$/, "", line) + print line + } +' LOCUS64_LANGUAGE_SPEC.md | sort -u) + +[[ ${#help_commands[@]} -gt 0 ]] || fail 'could not derive commands from live CLI help' +[[ ${#spec_commands[@]} -gt 0 ]] || fail 'could not derive commands from language specification' + +if [[ "$(printf '%s\n' "${help_commands[@]}")" != "$(printf '%s\n' "${spec_commands[@]}")" ]]; then + printf 'live help commands:\n%s\n' "$(printf '%s\n' "${help_commands[@]}")" >&2 + printf 'spec commands:\n%s\n' "$(printf '%s\n' "${spec_commands[@]}")" >&2 + fail 'language specification command set differs from live CLI help' +fi + +# shellcheck disable=SC2016 +authority_audit_spec='- `authority-audit`' +grep -Fq -- "$authority_audit_spec" LOCUS64_LANGUAGE_SPEC.md \ + || fail 'wrapper-local authority-audit is absent from the language specification' +if "$CLI" help authority-audit >/tmp/l64-doc-gate.out 2>/tmp/l64-doc-gate.err; then + fail 'l64-cli unexpectedly accepted wrapper-local authority-audit' +fi +# shellcheck disable=SC2016 +wrapper_boundary='belongs to the `l64` wrapper' +grep -Fq "$wrapper_boundary" /tmp/l64-doc-gate.err \ + || fail 'l64-cli does not reject authority-audit at the correct binary boundary' +rm -f /tmp/l64-doc-gate.out /tmp/l64-doc-gate.err + +printf 'documentation coherence gate passed: %s current docs, %s packages, %s live CLI commands, explicit historical boundaries\n' \ + "${#current_docs[@]}" "$package_count" "${#help_commands[@]}" diff --git a/scripts/verify-golden-portability.sh b/scripts/verify-golden-portability.sh new file mode 100755 index 0000000..2adc770 --- /dev/null +++ b/scripts/verify-golden-portability.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "$ROOT" + +fail() { + printf 'golden portability verification failed: %s\n' "$1" >&2 + exit 1 +} + +cargo test --locked --offline -q -p l64-cli golden_portability +cargo test --locked --offline -q -p l64 portability_ + +mapfile -t fixtures < <(find samples/golden -maxdepth 1 -type f -name '*.rna' -printf '%f\n' | sort) +[[ ${#fixtures[@]} -eq 5 ]] || fail "expected five authority fixtures, found ${#fixtures[@]}" +for required in certified_triangle equality_chain open_obligation invalid_child_context matrix_multiply; do + [[ -f "samples/golden/$required.rna" ]] || fail "missing $required.rna" + for suffix in run.txt certify.txt dna.hex normalized.rna; do + [[ -f "samples/golden/expected/$required.$suffix" ]] || fail "missing $required.$suffix" + done +done + +workflow=.github/workflows/native-core.yml +for os in ubuntu-latest macos-latest windows-latest; do + grep -Fq "$os" "$workflow" || fail "portable CI matrix omits $os" +done +grep -Fq 'cargo test --locked --offline --workspace' "$workflow" \ + || fail 'portable CI does not execute the complete Rust workspace' +grep -Fq "TARGET_DIR=\${CARGO_TARGET_DIR:-\$ROOT/target}" scripts/verify-native-scale.sh \ + || fail 'native scale gate ignores CARGO_TARGET_DIR' +grep -Fq "TARGET_DIR=\${CARGO_TARGET_DIR:-\$ROOT/target}" scripts/verify-documentation-coherence.sh \ + || fail 'documentation gate ignores CARGO_TARGET_DIR' +grep -Fq "\$env:CARGO_TARGET_DIR" scripts/verify-low-memory.ps1 \ + || fail 'PowerShell low-memory gate ignores CARGO_TARGET_DIR' + +grep -Fq 'LOCUS64_GOLDEN_PORTABILITY_CONTRACT.md' README.md \ + || fail 'README does not expose the golden portability contract' +grep -Fq 'golden-portability-green' L64_APPROVAL_GATES.md \ + || fail 'live approval gates omit golden portability' + +printf 'GOLDEN_PORTABILITY_GATE v1\n' +printf 'status=pass\n' +printf 'authority_fixtures=%s\n' "${#fixtures[@]}" +printf 'host_execution=%s\n' "$(rustc -vV | awk -F': ' '/^host:/ { print $2 }')" +printf 'canonical_bytes=exact_snapshots\n' +printf 'text_outputs=exact_snapshots\n' +printf 'crlf_lf_equivalence=true\n' +printf 'unicode_space_paths=true\n' +printf 'transport_release_journey=true\n' +printf 'ci_matrix=linux_macos_windows\n' diff --git a/scripts/verify-legacy-authority-island-deletion.sh b/scripts/verify-legacy-authority-island-deletion.sh new file mode 100755 index 0000000..3a0a5cc --- /dev/null +++ b/scripts/verify-legacy-authority-island-deletion.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" +cd "$ROOT" + +expected=(l64 l64-certification l64-change l64-cli l64-execution l64-native l64-observation l64-projection l64-release l64-symbolic l64-transport) +for deleted in l64-core l64-locus l64-research l64-kernel l64-command l64-registry l64-selector l64-runtime l64-canon l64-atlas l64-cert l64-testkit; do + test ! -e "$deleted" || { echo "legacy crate still live: $deleted" >&2; exit 1; } +done + +grep -q '"l64-cli"' Cargo.toml +test "$(grep -c '^name = ' Cargo.lock)" -eq 11 +for package in "${expected[@]}"; do grep -q "name = \"$package\"" Cargo.lock; done +if grep -q '^\[workspace.dependencies\]' Cargo.toml; then echo 'workspace dependencies table returned' >&2; exit 1; fi +if grep -R -nE '^[[:space:]]*(anyhow|clap|serde|serde_json|bincode|hex|thiserror|assert_cmd|predicates)[[:space:]]*=' -- */Cargo.toml Cargo.toml; then echo 'external dependency returned' >&2; exit 1; fi +if grep -R -nE 'path[[:space:]]*=[[:space:]]*"\.\./l64-(core|locus|research|kernel|command|registry|selector|runtime|canon|atlas|cert|testkit)"' -- */Cargo.toml; then echo 'legacy dependency returned' >&2; exit 1; fi + +test ! -e l64-cli/src/main.rs +grep -q 'permanently deleted after historical export' l64-cli/src/native_membrane.rs +grep -q '"run-theorem"' l64-cli/src/native_membrane.rs +grep -q '"research-status"' l64-cli/src/native_membrane.rs +grep -q '"tower-step"' l64-cli/src/native_membrane.rs +if grep -q 'mod legacy' l64-cli/src/native_main.rs; then echo 'legacy dispatcher returned' >&2; exit 1; fi + +cargo metadata --locked --offline --no-deps --format-version 1 >/dev/null +printf 'legacy authority island deletion verified: 11 dependency-free native packages\n' diff --git a/scripts/verify-low-memory.ps1 b/scripts/verify-low-memory.ps1 index fd50a0b..de9042c 100644 --- a/scripts/verify-low-memory.ps1 +++ b/scripts/verify-low-memory.ps1 @@ -1,5 +1,5 @@ param( - [ValidateSet("core", "bundle", "cli", "workspace", "all")] + [ValidateSet("transport", "execution", "cli", "workspace", "scale", "all")] [string]$Scope = "workspace", [switch]$SkipFmt, [switch]$SkipDiff @@ -10,6 +10,51 @@ $ErrorActionPreference = "Stop" $WorkspaceRoot = Split-Path -Parent $PSScriptRoot Push-Location $WorkspaceRoot +function Invoke-Cargo([string[]]$Arguments) { + & cargo @Arguments + if ($LASTEXITCODE -ne 0) { + throw "cargo $($Arguments -join ' ') failed with exit code $LASTEXITCODE" + } +} + +function Invoke-ScaleSmoke { + $TempRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("l64-low-memory-" + [Guid]::NewGuid().ToString("N")) + New-Item -ItemType Directory -Path $TempRoot | Out-Null + try { + $Rna = Join-Path $TempRoot "linear-8192.rna" + $Dna = Join-Path $TempRoot "linear-8192.dna" + $Lines = [System.Collections.Generic.List[string]]::new(8193) + $Lines.Add("L64R1 0x4c4f574d454d4f52") + for ($i = 1; $i -le 8192; $i++) { + $Lines.Add(("a {0} 0x{0:x}" -f $i)) + } + [System.IO.File]::WriteAllLines($Rna, $Lines) + + Invoke-Cargo @("build", "--locked", "--offline", "--release", "-p", "l64-cli") + $TargetRoot = if ($env:CARGO_TARGET_DIR) { + if ([System.IO.Path]::IsPathRooted($env:CARGO_TARGET_DIR)) { + $env:CARGO_TARGET_DIR + } else { + Join-Path $WorkspaceRoot $env:CARGO_TARGET_DIR + } + } else { + Join-Path $WorkspaceRoot "target" + } + $Exe = Join-Path $TargetRoot "release/l64-cli.exe" + if (-not (Test-Path $Exe)) { + $Exe = Join-Path $TargetRoot "release/l64-cli" + } + & $Exe compile-rna $Rna --out $Dna | Out-Null + if ($LASTEXITCODE -ne 0) { throw "scale compile failed" } + $Run = & $Exe run-dna $Dna + if ($LASTEXITCODE -ne 0) { throw "scale execution failed" } + if ($Run -notcontains "canonical_roundtrip=true") { throw "scale smoke lost canonical roundtrip" } + if ($Run -notcontains "projection_verified=true") { throw "scale smoke lost verified projection" } + } finally { + Remove-Item -Recurse -Force $TempRoot -ErrorAction SilentlyContinue + } +} + try { $env:CARGO_BUILD_JOBS = "1" $env:CARGO_INCREMENTAL = "0" @@ -17,35 +62,25 @@ try { $env:CARGO_PROFILE_TEST_DEBUG = "0" if (-not $SkipFmt) { - cargo fmt --check + Invoke-Cargo @("fmt", "--all", "--", "--check") } switch ($Scope) { - "core" { - cargo test -p l64-core --lib - } - "bundle" { - cargo test -p l64-core --lib - cargo test -p l64-bundle - } - "cli" { - cargo test -p l64-core --lib - cargo test -p l64-bundle - cargo test -p l64-cli - } - "workspace" { - cargo check --workspace - } + "transport" { Invoke-Cargo @("test", "--locked", "--offline", "-p", "l64-transport") } + "execution" { Invoke-Cargo @("test", "--locked", "--offline", "-p", "l64-execution") } + "cli" { Invoke-Cargo @("test", "--locked", "--offline", "-p", "l64-cli", "-p", "l64") } + "workspace" { Invoke-Cargo @("check", "--locked", "--offline", "--workspace", "--all-targets") } + "scale" { Invoke-ScaleSmoke } "all" { - cargo test -p l64-core --lib - cargo test -p l64-bundle - cargo test -p l64-cli - cargo check --workspace + Invoke-Cargo @("test", "--locked", "--offline", "-p", "l64-transport", "-p", "l64-execution", "-p", "l64-cli", "-p", "l64") + Invoke-Cargo @("check", "--locked", "--offline", "--workspace", "--all-targets") + Invoke-ScaleSmoke } } - if (-not $SkipDiff) { - git diff --check + if (-not $SkipDiff -and (Test-Path ".git")) { + & git diff --check + if ($LASTEXITCODE -ne 0) { throw "git diff --check failed" } } } finally { Pop-Location diff --git a/scripts/verify-native-carrier.sh b/scripts/verify-native-carrier.sh new file mode 100755 index 0000000..138cc29 --- /dev/null +++ b/scripts/verify-native-carrier.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" +cd "$ROOT" + +CARGO="${CARGO:-cargo}" +TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" +EXE_SUFFIX="" +if [[ "${OS:-}" == "Windows_NT" ]]; then EXE_SUFFIX=".exe"; fi +CLI="$TARGET_DIR/debug/l64-cli$EXE_SUFFIX" +WRAPPER="$TARGET_DIR/debug/l64$EXE_SUFFIX" +WORK="$(mktemp -d "${TMPDIR:-/tmp}/l64-native-carrier.XXXXXX")" +trap 'rm -rf "$WORK"' EXIT + +"$CARGO" build --locked --offline -p l64-cli -p l64 + +test -x "$CLI" +test -x "$WRAPPER" + +"$CLI" run-rna samples/native_triangle.rna > "$WORK/triangle.rna.run.txt" +"$CLI" compile-rna samples/native_triangle.rna --out "$WORK/triangle.dna" > /dev/null +"$CLI" run-dna "$WORK/triangle.dna" > "$WORK/triangle.dna.run.txt" +"$CLI" compile-rna samples/native_equality.rna --out "$WORK/equality.dna" > /dev/null +"$CLI" run-dna "$WORK/equality.dna" > "$WORK/equality.dna.run.txt" + +rna_symbol="$(grep '^symbol=' "$WORK/triangle.rna.run.txt")" +dna_symbol="$(grep '^symbol=' "$WORK/triangle.dna.run.txt")" +test "$rna_symbol" = "$dna_symbol" +grep -q '^canonical_roundtrip=true$' "$WORK/triangle.rna.run.txt" +grep -q '^projection_verified=true$' "$WORK/triangle.rna.run.txt" +grep -q '^certification_verdict=CERTIFIED$' "$WORK/triangle.rna.run.txt" +grep -q '^authority_mutation=none$' "$WORK/triangle.rna.run.txt" + +"$CLI" compare-dna "$WORK/triangle.dna" "$WORK/equality.dna" > "$WORK/change.txt" +grep -q '^exact_equal=false$' "$WORK/change.txt" + +"$CLI" compile-bundle "$WORK/triangle.dna" "$WORK/equality.dna" --out "$WORK/native.l64b" > /dev/null +"$CLI" run-bundle --file "$WORK/native.l64b" > "$WORK/bundle.run.txt" +"$CLI" certify-bundle --file "$WORK/native.l64b" > "$WORK/bundle.certification.txt" +"$CLI" observe-bundle --file "$WORK/native.l64b" > "$WORK/bundle.observation.txt" +grep -q '^members=2$' "$WORK/bundle.run.txt" +grep -q '^composite_execution=none$' "$WORK/bundle.run.txt" +grep -q '^member.0.source=bundle_member$' "$WORK/bundle.run.txt" +grep -q '^member.1.source=bundle_member$' "$WORK/bundle.run.txt" +grep -q '^composite_certificate=none$' "$WORK/bundle.certification.txt" +grep -q '^composite_observation=none$' "$WORK/bundle.observation.txt" + +"$CLI" export-genome-release --rna samples/native_triangle.rna --out "$WORK/triangle.release" > /dev/null +test "$(find "$WORK/triangle.release" -maxdepth 1 -type f | wc -l)" -eq 4 +grep -q '^projection_verified=true$' "$WORK/triangle.release/release.record" + +"$WRAPPER" authority-audit > "$WORK/authority-audit.txt" +grep -q '^execution: direct non-persistent RNA/DNA structural evaluation$' "$WORK/authority-audit.txt" + +if "$CLI" legacy >"$WORK/legacy.out" 2>"$WORK/legacy.err"; then + echo "retired legacy command unexpectedly succeeded" >&2 + exit 1 +fi +grep -q 'permanently deleted after historical export' "$WORK/legacy.err" + +printf 'native carrier verified: RNA/DNA execution, release, bundle, certification, observation, and change\n' diff --git a/scripts/verify-native-scale.sh b/scripts/verify-native-scale.sh new file mode 100755 index 0000000..ff91a95 --- /dev/null +++ b/scripts/verify-native-scale.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "$ROOT" +TARGET_DIR=${CARGO_TARGET_DIR:-$ROOT/target} + +fail() { + printf 'native scale verification failed: %s\n' "$1" >&2 + exit 1 +} + +# Structural guards prevent reintroducing the measured whole-state and whole-graph hot paths. +grep -Fq 'Graph::new_bulk()' l64-native/src/rna/compile.rs \ + || fail 'RNA compilation no longer uses bulk graph construction' +[[ $(grep -R -F 'crate::symbol::state_symbol(self)' l64-native/src/graph | wc -l) -eq 1 ]] \ + || fail 'graph mutation paths recompute whole-state symbols outside the single mutation boundary' +grep -Fq 'primary_route' l64-native/src/graph/derived.rs \ + || fail 'per-node primary-route index is absent' +for projection in atlas.rs certification.rs report.rs research.rs replay.rs set.rs; do + if grep -Fq 'graph.closure_state(' "l64-projection/src/$projection"; then + fail "$projection reintroduced per-node closure recomputation" + fi +done +if grep -Fq 'projection.verify(graph)' l64-execution/src/lib.rs; then + fail 'fresh execution projection is immediately rederived' +fi +if grep -Fq 'view.verify(graph)' l64-certification/src/lib.rs; then + fail 'fresh certification projection is immediately rederived' +fi + +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +linear="$tmp/linear-8192.rna" +ops="$tmp/ops-4096.rna" +{ + printf 'L64R1 0x5343414c454c494e\n' + for ((i = 1; i <= 8192; i++)); do + printf 'a %d 0x%x\n' "$i" "$i" + done +} > "$linear" +{ + printf 'L64R1 0x5343414c454f5053\n' + printf 'a 1 0x41\na 2 0x42\na 3 0x43\n' + slot=4 + for ((i = 0; i < 4096; i++)); do + f1=$slot; f2=$((slot + 1)); f3=$((slot + 2)); v1=$((slot + 3)); v2=$((slot + 4)); c=$((slot + 5)) + printf 'f %d 1 2\nf %d 2 3\nf %d 1 3\nv %d %d\nv %d %d\nc %d %d %d %d\n' \ + "$f1" "$f2" "$f3" "$v1" "$f1" "$v2" "$f2" "$c" "$v1" "$v2" "$f3" + slot=$((slot + 6)) + done +} > "$ops" + +cargo build --locked --offline --release -p l64-cli >/dev/null +bin="$TARGET_DIR/release/l64-cli" +timeout 20s "$bin" compile-rna "$linear" --out "$tmp/linear.dna" >/dev/null +timeout 30s "$bin" run-rna "$ops" > "$tmp/ops.run" +grep -Fq 'canonical_roundtrip=true' "$tmp/ops.run" \ + || fail 'operation-heavy execution lost the exact roundtrip' +grep -Fq 'projection_verified=true' "$tmp/ops.run" \ + || fail 'operation-heavy execution lost projection construction' + +printf 'native scale gate passed: bulk compilation, indexed routes, shared closure analysis, and bounded operation execution\n' diff --git a/scripts/verify-portability-receipts.sh b/scripts/verify-portability-receipts.sh new file mode 100755 index 0000000..e84c23c --- /dev/null +++ b/scripts/verify-portability-receipts.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "$ROOT" + +fail() { + printf 'portability receipt verification failed: %s\n' "$1" >&2 + exit 1 +} + +if [[ ${1:-} == '--self-test' ]]; then + tmp=$(mktemp -d) + trap 'rm -rf "$tmp"' EXIT + for host in ubuntu-latest macos-latest windows-latest; do + L64_SOURCE_REF=local-pass30 \ + GITHUB_REPOSITORY=local/self-test \ + GITHUB_RUN_ID=self-test \ + GITHUB_RUN_ATTEMPT=1 \ + scripts/write-portability-receipt.sh \ + "$tmp/l64-portability-$host.json" "$host" >/dev/null + done + "$0" "$tmp" local-pass30 + exit 0 +fi + +DIR=${1:?usage: verify-portability-receipts.sh } +SOURCE_REF=${2:?usage: verify-portability-receipts.sh } +[[ -d "$DIR" ]] || fail "receipt directory does not exist: $DIR" + +for host in ubuntu-latest macos-latest windows-latest; do + receipt="$DIR/l64-portability-$host.json" + [[ -f "$receipt" ]] || fail "missing receipt for $host" + grep -Fq '"schema": "L64PORT1"' "$receipt" || fail "$host schema mismatch" + grep -Fq "\"source_ref\": \"$SOURCE_REF\"" "$receipt" || fail "$host source mismatch" + grep -Fq "\"host_label\": \"$host\"" "$receipt" || fail "$host label mismatch" + grep -Fq '"workspace_packages": 11' "$receipt" || fail "$host package count mismatch" + grep -Fq '"external_dependencies": 0' "$receipt" || fail "$host dependency boundary mismatch" + grep -Fq '"test_command": "cargo test --locked --offline --workspace"' "$receipt" \ + || fail "$host command mismatch" + grep -Fq '"result": "passed"' "$receipt" || fail "$host did not pass" +done + +receipt_count=$(find "$DIR" -maxdepth 1 -type f -name 'l64-portability-*.json' | wc -l | tr -d ' ') +[[ "$receipt_count" -eq 3 ]] || fail "expected exactly three portability receipts, found $receipt_count" +printf 'portability receipts verified: source=%s hosts=ubuntu-latest,macos-latest,windows-latest\n' "$SOURCE_REF" diff --git a/scripts/verify-process-contract.sh b/scripts/verify-process-contract.sh new file mode 100755 index 0000000..41b3c3c --- /dev/null +++ b/scripts/verify-process-contract.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +CARGO="${CARGO:-cargo}" +TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" +CLI="$TARGET_DIR/debug/l64-cli" +WORK="$(mktemp -d "${TMPDIR:-/tmp}/l64-process-contract.XXXXXX")" +trap 'rm -rf "$WORK"' EXIT + +cd "$ROOT" +"$CARGO" build --locked --offline -q -p l64-cli + +cat > "$WORK/malformed.rna" <<'RNA' +L64R1 0x1 +a nope 0x41 +RNA +cat > "$WORK/open.rna" <<'RNA' +L64R1 0x4345525449465931 +a 1 0x52 +q 2 1 0 0 0 0 0 0 0 +v 3 2 +r 4 3 2 +RNA +cat > "$WORK/invalid.rna" <<'RNA' +L64R1 0x4345525449465931 +a 1 0x52 +q 2 1 0 0 0 0 0 0 0 +v 3 2 +r 4 3 2 +k 5 3 1 0 +h 1 0 5 +RNA + +set +e +"$CLI" run-rna "$WORK/malformed.rna" >"$WORK/malformed.out" 2>"$WORK/malformed.err" +malformed_code=$? +"$CLI" run-rna "$WORK/open.rna" >"$WORK/open.out" 2>"$WORK/open.err" +open_code=$? +"$CLI" run-rna "$WORK/invalid.rna" >"$WORK/invalid.out" 2>"$WORK/invalid.err" +invalid_code=$? +set -e + +test "$malformed_code" -eq 2 +test "$open_code" -eq 10 +test "$invalid_code" -eq 12 +grep -F 'invalid number at RNA 2:3' "$WORK/malformed.err" >/dev/null +grep -F '2 | a nope 0x41' "$WORK/malformed.err" >/dev/null +grep -F '| ^^^^' "$WORK/malformed.err" >/dev/null +grep -Fx 'certification_verdict=OPEN' "$WORK/open.out" >/dev/null +grep -Fx 'certification_verdict=INVALID' "$WORK/invalid.out" >/dev/null + +"$CLI" compile-rna samples/native_triangle.rna --out "$WORK/triangle.dna" >/dev/null +"$CLI" compile-rna "$WORK/open.rna" --out "$WORK/open.dna" >/dev/null +"$CLI" compile-bundle "$WORK/triangle.dna" "$WORK/open.dna" --out "$WORK/mixed.l64b" >/dev/null +set +e +"$CLI" run-bundle --file "$WORK/mixed.l64b" >"$WORK/bundle.out" 2>"$WORK/bundle.err" +bundle_code=$? +set -e +test "$bundle_code" -eq 10 +grep -Fx 'members=2' "$WORK/bundle.out" >/dev/null +grep -Fx 'member.0.certification_verdict=CERTIFIED' "$WORK/bundle.out" >/dev/null +grep -Fx 'member.1.certification_verdict=OPEN' "$WORK/bundle.out" >/dev/null + +rg -F 'BundleDecoder' l64-cli/src/native_membrane.rs >/dev/null +rg -F 'BundleEncoder' l64-cli/src/native_membrane.rs >/dev/null +if rg -n 'read\(&options\.file\)' l64-cli/src/native_membrane.rs >/dev/null; then + echo 'bundle command returned to whole-file buffering' >&2 + exit 1 +fi + +echo 'PROCESS_CONTRACT_GATE v1' +echo 'status=pass' +echo 'certified_exit=0' +echo 'open_exit=10' +echo 'incomplete_exit=11' +echo 'invalid_exit=12' +echo 'operational_error_exit=2' +echo 'rna_source_spans=true' +echo 'streaming_bundle_io=true' diff --git a/scripts/write-portability-receipt.sh b/scripts/write-portability-receipt.sh new file mode 100755 index 0000000..f4439a5 --- /dev/null +++ b/scripts/write-portability-receipt.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "$ROOT" + +OUT=${1:?usage: write-portability-receipt.sh } +HOST_LABEL=${2:?usage: write-portability-receipt.sh } +SOURCE_REF=${L64_SOURCE_REF:-${GITHUB_SHA:-}} + +case "$HOST_LABEL" in + ubuntu-latest|macos-latest|windows-latest) ;; + *) printf 'unsupported portability host label: %s\n' "$HOST_LABEL" >&2; exit 1 ;; +esac + +[[ -n "$SOURCE_REF" ]] || { printf 'L64_SOURCE_REF or GITHUB_SHA is required\n' >&2; exit 1; } + +json_escape() { + local value=$1 + value=${value//\\/\\\\} + value=${value//\"/\\\"} + value=${value//$'\n'/\\n} + value=${value//$'\r'/\\r} + value=${value//$'\t'/\\t} + printf '%s' "$value" +} + +package_count=$(awk ' + /^members = \[/ { in_members=1; next } + in_members && /^\]/ { in_members=0 } + in_members && /^[[:space:]]*"[^"]+",?[[:space:]]*$/ { count++ } + END { print count+0 } +' Cargo.toml) +external_dependencies=$(grep -c '^source = ' Cargo.lock || true) +[[ "$package_count" -eq 11 ]] || { printf 'unexpected package count: %s\n' "$package_count" >&2; exit 1; } +[[ "$external_dependencies" -eq 0 ]] || { printf 'external dependencies present: %s\n' "$external_dependencies" >&2; exit 1; } + +rustc_version=$(rustc --version) +cargo_version=$(cargo --version) +rust_host=$(rustc -vV | sed -n 's/^host: //p') +[[ -n "$rust_host" ]] || { printf 'could not determine rust host\n' >&2; exit 1; } + +repository=${GITHUB_REPOSITORY:-local} +workflow_run_id=${GITHUB_RUN_ID:-local} +workflow_run_attempt=${GITHUB_RUN_ATTEMPT:-1} +created_utc=$(date -u +'%Y-%m-%dT%H:%M:%SZ') +mkdir -p "$(dirname "$OUT")" +tmp="${OUT}.tmp.$$" + +cat > "$tmp" < Date: Tue, 28 Jul 2026 11:14:50 -0700 Subject: [PATCH 2/2] Fix cross-platform verification gates --- .gitattributes | 10 ++++++++++ scripts/verify-cli-hardening.sh | 3 ++- scripts/verify-process-contract.sh | 6 +++--- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.gitattributes b/.gitattributes index 0ef2d44..57d86e1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,9 +1,19 @@ * text=auto +.gitattributes text eol=lf +.gitignore text eol=lf *.rs text eol=lf *.toml text eol=lf *.lock text eol=lf *.md text eol=lf *.json text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.sh text eol=lf +*.athens text eol=lf +*.rna text eol=lf +*.txt text eol=lf +*.hex text eol=lf +*.record text eol=lf *.qc0 text eol=lf *.ps1 text eol=crlf *.cmd text eol=crlf diff --git a/scripts/verify-cli-hardening.sh b/scripts/verify-cli-hardening.sh index e621cc5..42110a3 100755 --- a/scripts/verify-cli-hardening.sh +++ b/scripts/verify-cli-hardening.sh @@ -56,7 +56,8 @@ if "$CLI" compile-rna samples/native_triangle.rna --artifact-class gene --out "$ fi grep -F -- '--artifact-class was permanently deleted' "$WORK/error" >/dev/null -if rg -n 'Result|Ok\(false\)' l64-cli/src --glob '*.rs' >/dev/null || rg -n '\{error:\?\}' l64-cli/src l64-*/src --glob '*.rs' >/dev/null; then +if grep -REn --include='*.rs' 'Result|Ok\(false\)' l64-cli/src >/dev/null \ + || grep -REn --include='*.rs' '\{error:\?\}' l64-cli/src l64-*/src >/dev/null; then echo "obsolete fallback or debug diagnostic returned" >&2 exit 1 fi diff --git a/scripts/verify-process-contract.sh b/scripts/verify-process-contract.sh index 41b3c3c..eb45531 100755 --- a/scripts/verify-process-contract.sh +++ b/scripts/verify-process-contract.sh @@ -62,9 +62,9 @@ grep -Fx 'members=2' "$WORK/bundle.out" >/dev/null grep -Fx 'member.0.certification_verdict=CERTIFIED' "$WORK/bundle.out" >/dev/null grep -Fx 'member.1.certification_verdict=OPEN' "$WORK/bundle.out" >/dev/null -rg -F 'BundleDecoder' l64-cli/src/native_membrane.rs >/dev/null -rg -F 'BundleEncoder' l64-cli/src/native_membrane.rs >/dev/null -if rg -n 'read\(&options\.file\)' l64-cli/src/native_membrane.rs >/dev/null; then +grep -F 'BundleDecoder' l64-cli/src/native_membrane.rs >/dev/null +grep -F 'BundleEncoder' l64-cli/src/native_membrane.rs >/dev/null +if grep -En 'read\(&options\.file\)' l64-cli/src/native_membrane.rs >/dev/null; then echo 'bundle command returned to whole-file buffering' >&2 exit 1 fi