From 39c95034e708eb93c30ed4c06d2bc2e7818dc588 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 16:23:38 +0800 Subject: [PATCH 01/51] research: propose obligation-ledger recurrence with falsifiable Lean gates --- .../OLR_01_OBLIGATION_LEDGER_RECURRENCE.md | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_01_OBLIGATION_LEDGER_RECURRENCE.md diff --git a/research/lean_cgrt_hrm400/OLR_01_OBLIGATION_LEDGER_RECURRENCE.md b/research/lean_cgrt_hrm400/OLR_01_OBLIGATION_LEDGER_RECURRENCE.md new file mode 100644 index 000000000..76567c1a5 --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_01_OBLIGATION_LEDGER_RECURRENCE.md @@ -0,0 +1,132 @@ +# OLR-01: Obligation Ledger Recurrence for a compact looped transformer + +**Status:** Architectural research proposal, not an experimental success claim +**Date:** 2026-11-23 +**Codebase:** MoralityLabAI/LoopedTransformers, research/lean_cgrt_hrm400 +**Source checkpoint:** 3df3d5efaff77686bcc46190fe01c05dd053da2b +**Primary source:** [PPT_RESIDUAL_TRANSFER.md](PPT_RESIDUAL_TRANSFER.md) +**Experiment classification:** Exploratory design. Any implementation first needs a frozen prospective protocol; earlier opened cohorts remain development/audit data. + +## Why pursue this architecture? + +The registered 1217 repaired prospective transfer favored the 7,369-parameter, tied, gated two-slot proof model over a 10,393-parameter full-history TRM on **directed BPD proof residuals**. At two target-call budgets over 32 roots, its source-stopped reward checkpoint completed 20/192 scored scenarios at root utility 0.079167. The TRM reward checkpoint completed 5/192 at -0.010677. A same-architecture imitation checkpoint completed 20/192 at 0.046354, and a native search-tree reference completed 32/192 at 0.158333. The reward fit's utility increment over imitation was +0.032813, primarily from fewer sibling/check expenditures, **not additional proofs**. The reward/TRM utility increment was +0.089844, descriptive root bootstrap [0.060547, 0.119922]. + +These are one-seed, specialized transfer results. All learned/calibrated arms closed the 84 equality scenarios; the reward, TRM, and imitation arms each closed 11/92 Horn scenarios. The earlier development study's paired message-status sham was inconclusive, and the prospective 1217 report does not demonstrate a direction-specific causal mechanism. See [PPT_RESIDUAL_SEARCH.md](PPT_RESIDUAL_SEARCH.md) and [PPT_RESIDUAL_TRANSFER.md](PPT_RESIDUAL_TRANSFER.md). + +The nearby [PPT_HYBRID_RL_TRANSPORT.md](PPT_HYBRID_RL_TRANSPORT.md) supplies a second clue. On a reused 12-pair graph pilot, a frozen-backbone transport readout reached 19/24 certified worlds while fully trained transport RL remained at 12/24. Incoming messages had been averaged over premises; that average can transmit partial support for a rule that requires *every* premise. The development results show architecture and training-objective bottlenecks; they leave the role of learned graph propagation unsettled. + +The [LOCAL_SCALING_RESULTS.md](LOCAL_SCALING_RESULTS.md) control studies also favor simple tied loops in some shortcut-free cases while recording strong seed variance and negative depth extrapolation on other settings. Thus OLR must be tested against an ordinary tied transformer with equal information, FLOPs, and verified search calls. + +## Hypothesis + +**Represent the task remaining after each action as an explicit obligation ledger, couple it to a forward evidence ledger, and refine both through a shared recurrent block.** A loop should transport *requirements* backward from the goal as well as *verified support* forward from the environment. + +A useful OLR result would show that these two coupled channels improve native Lean proof completion over the two-slot actor, ordinary loop, frozen readout, and exact structural planning controls on **new** theorem lineages. Better calibration and call efficiency are separately valuable endpoints. + +## Architecture + +Public state -> prelude -> {EVIDENCE ledger, OBLIGATION ledger} -> repeated tied update K times -> action/value/continue coda -> native Lean verifier. Real feedback enters the next decision. Hidden target scripts, hindsight oracle values, proof certificates, and query labels never appear in a predecision observation. + +The minimal state contains: + +- **Evidence:** available local facts, verified tactic outcomes, current public goals, hypothesized rule applicability, and a confidence/status mask separating native facts from predictions. +- **Obligation:** active goal and all pending subgoals, candidate prerequisites, action costs, remaining Lean-call budget, speculative continuation costs, and branch rollback state. +- **Budget and control:** terminal-success mask, checked/censored/rejected feedback, kernel status, a local step counter, and an optional continue/STOP readout. + +Treat proof rules as **AND-OR hyperedges**. An edge r -> v may require a set P(r) of premises; multiple edges into v are alternative derivations. This is an explicit distinction absent from simple mean aggregation over incoming facts. + +### Structural tree-cost recurrence + +For an acyclic, fully observed Horn hypergraph with positive action costs, define: + + D_0(v) = 0 if v is a given fact; +infinity otherwise + D_{k+1}(v) = min( + D_k(v), + min_{r -> v} [c(r) + sum_{u in P(r)} D_k(u)] + ). + +An empty premise set has sum 0. Given an acyclic graph and enough rounds to reach every dependency, the fixed point gives **minimum derivation-tree cost** under these assumptions. Shared premises may be counted repeatedly, so this recurrence is not automatically the least-cost proof DAG or the actual Lean tactic-call count. Cyclic, dependent, or computational side conditions require explicit treatment. For integer proof depth, an analogous Boolean reachability update is exact when source facts and rule truth are known. + +Use the structural channel as a predictable reference and train an auxiliary neural channel for real Lean state semantics: + + z_{k+1} = SharedBlock(z_k, context, evidence_k, obligations_k) + delta(r,k) = CorrectionHead(z_k, edge_r, budget) + C(r,k) = c(r) + sum_{u in P(r)} D_hat_k(u) + softplus(delta(r,k)) + D_hat_{k+1}(v) = SoftMin_{r -> v} C(r,k). + +The learned correction is *an estimated difficulty penalty*, not a certified lower bound. SoftMin can undercut the hard minimum; no bound claim follows from it. Preserve a separately computed hard structural channel for exact fragments and use strictly learned estimates only as tactic-rank features for broader Lean. Mask any infeasible edge and always include STOP as an action with its own measured penalty. + +### Forward channel + +For the restricted Horn/AND-OR pilot, a Boolean evidence recurrence gives an interpretable oracle: + + E_{k+1}(v) = E_k(v) OR any_{r -> v} all_{u in P(r)} E_k(u). + +At inference, only actual public and verifier-confirmed facts receive certified E=1. Predicted applicability lives in a separate channel and never overwrites a certified status. A smooth surrogate can train message weights, but the exact Boolean channel remains available as a control. Direction-specific message gates let evidence and obligations influence each other while retaining separately accessible slots. + +### Recurrent budget allocation + +Each repeated block reads the same public packet and the updated two-ledger state. Initially train K in {2,4,8} with budget-specific targets and test K=1,2,4,8,12,16 after freezing the checkpoint. Record actual per-pass compute and coda expense. Early exit should use measured improvement from an extra pass and calibrated wall/compute cost; a hard Lean certificate ends a proof externally. + +Cross-pass memory is ephemeral within one decision. Persisted verifier feedback is a separate object. DRAM/fast-weight updates are excluded from OLR-01 so causal interpretation remains focused on graph structure and tied recurrence; G04 found no clear online-SGD advantage at its reported final dose. + +## Pilot model and intervention ladder + +Start with a small sidecar in **ppt_gym** that consumes the already public Horn graph and candidate menu, produces an action-value correction, and leaves the native Lean server as the only proof authority. Retain the existing [ppt_gym/live_quote_policy.py](ppt_gym/live_quote_policy.py) two-slot reward actor and [ppt_gym/residual_search.py](ppt_gym/residual_search.py) search controller for comparison. The gate must permit a true zero-correction identity; trainable value weights and expected FLOPs need reported values. + +Register these arms **before seeing new scores**: + +| Arm | Purpose | +| --- | --- | +| Source-frozen two-slot checkpoint | Reproduce the published reference on audited data | +| Newly trained two-slot actor | Same train distribution, seed roster, and optimizer as OLR | +| OLR, true graph, learned correction | Main candidate | +| OLR with randomized/premise-permuted edges | Structure-specific control | +| OLR with recurrent body frozen | Head/calibration explanation | +| Exact structural Horn cost/search controller | Strong algorithmic baseline, using the same available graph | +| Ordinary tied transformer, equal input | Architecture/representation control | +| FLOP- and parameter-matched nonrecurrent model | Additional-compute control | + +For a mechanism test, patch an evidence bit that is native-known, or switch a single distant fact between paired worlds that require *opposite actions*. Compare action-margin perturbations with same-margin, norm-matched random interventions and an edge-shuffled sham. Recalculate and count full Lean proofs under the unchanged budget; feature or logit sensitivity alone is an auxiliary observation. + +### Data and experimental gates + +1. **Training and dev:** Use separate new graph fingerprints and family-disjoint theorem ancestries. Archived 1201/1211/1217 tapes may serve only as development and reproducibility material unless a fresh protocol explicitly assigns some to training; they cannot also become held-out transfer. +2. **Reachability:** Independently execute all planned witness scripts and validate menu identifiers *before* scoring. The 1211 binder-grammar mismatch previously left just two of 96 primary residuals reachable at the registered depth. +3. **Unsaturated evaluation:** Include paired source-fact-switch graphs with equal local lexical cues, joins with 2-4 prerequisites, dead-end decoys, two simultaneously pending Lean goals, and independent held-out dependency distances. Also include computational-guard and symbol-binding stress cases, separately stratified. +4. **Primary endpoint:** root-macro, Lean-certified completion at fixed native-check and model-compute budgets. Secondary: root utility, calls, exact attainable coverage, verified successor-goal prediction, false STOP rate, halting passes, wall time, memory, and robust seed variance. +5. **Threshold:** preregister a +0.025 root-utility floor over the best learned comparator as a pilot target. Require prospective root-paired and seed-level intervals and a direction-specific improvement exceeding the matched-sham envelope before claiming a mechanism. Use EvalMath's FSI-01 floor rather than repeating the earlier power-limited sham design. +6. **Kernel provenance:** retain theorem statement, independent script compilation, Lean/compiler hashes, allowed axiom audit, root lineage, structural graph fingerprint, exact checkpoint/memory hash, all scored failures, and resource budget receipts. + +### Failures that should redirect design + +- Exact structural planning wins on the same graph at a fraction of the compute. Keep OLR as a general-domain proposal only if it adds transfer on tasks where structural semantics are incomplete. +- Newly trained two-slot or frozen-body OLR matches the full recurrence. Investigate encoding and value supervision before allocating parameters to a larger recurrent core. +- The true-edge model behaves like the edge-shuffled sham. Revise message routing and proof dependencies. +- Added loops preserve or decrease certified success at matched FLOPs. Test recurrence dynamics rather than scaling depth by default. +- The selected cohort saturates or the witness menu fails. Register a repaired disjoint cohort before seeing any model outcomes, preserving the failed cohort and its results. + +## Stage gates and possible scaling + +**OLR-01A:** Implement an instrumented, tiny AND-OR cost/evidence module with deterministic unit tests on 1-4 premise joins, cycles, unreachable subgoals, and shared dependencies. Test exact hard recurrence against a small dynamic-programming oracle. + +**OLR-01B:** Replace the existing learned/graph messages one interface at a time, retaining the complete two-slot reward baseline and source-selected stopping. Check parameter counts, gradient paths, zero gate identity, CPU memory, native tactic grammar, and ablations. + +**OLR-01C:** Run matched 3-seed pilot on preregistered fresh Lean roots. Save all outcomes. If significant and causally supported on independent roots, register a sealed confirmatory study. + +**OLR-02:** Test another domain with the same structural interface: DataGoblin's storyworld action prerequisites, causal facts, and budgeted interventions. Separate observed effects from model predictions and evaluate actual environment moves. + +**Scale decision:** Consider a ~5M tied-loop prototype only after a clear improvement in certified completions over simple and structural controls. A larger 20M-55M PPT or DataGoblin graft is a later research choice. + +## Nearby evidence to keep in view + +- [PPT_RESIDUAL_TRANSFER.md](PPT_RESIDUAL_TRANSFER.md): targeted 1217 two-slot reward transfer and budget-calibrated stopping. +- [PPT_RESIDUAL_SEARCH.md](PPT_RESIDUAL_SEARCH.md): source 1201 fit, mixed-source prior, and inconclusive sham. +- [PPT_HYBRID_RL_TRANSPORT.md](PPT_HYBRID_RL_TRANSPORT.md): mean-premise transport and paired credit experiments. +- [PPT_HYBRID_RL_PENDING_RECOVERY.md](PPT_HYBRID_RL_PENDING_RECOVERY.md): pending goals; strong structural solver; RL/imitate/calibrate variability. +- [PPT_COMPUTATIONAL_GUARDS.md](PPT_COMPUTATIONAL_GUARDS.md): rule applicability depends on ground computation; direct-reader and exact-fold controls outperform the two-slot actor. +- [PPT_G04_RESULTS.md](PPT_G04_RESULTS.md): no measured improvement from early DRAM SGD pilot, despite successful verifier-backed replay. +- [PPT_PLAN_A_DRAM_PLASTIC_PROOF_TRANSFORMER.md](PPT_PLAN_A_DRAM_PLASTIC_PROOF_TRANSFORMER.md), [PPT_PLAN_B_INKLING_BLOCK_MESSAGE_MEMORY.md](PPT_PLAN_B_INKLING_BLOCK_MESSAGE_MEMORY.md): existing typed slots and message bank; OLR adds explicit AND-OR semantics. +- [LOCAL_SCALING_RESULTS.md](LOCAL_SCALING_RESULTS.md): simple-tied-loop wins, negative results, and strong seed variance. + +**Current evidence level:** Proposal derived from registered and development runs. OLR has not been trained, benchmarked, or verified to improve any proof completion. From 500a348c649bfb7a7f8d866f6705b5b930cfc201 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 16:27:53 +0800 Subject: [PATCH 02/51] research(olr): add exact AND-OR structural ledger oracle --- .../ppt_gym/obligation_ledger.py | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py b/research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py new file mode 100644 index 000000000..f25ee8620 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py @@ -0,0 +1,130 @@ +"""OLR-01A structural AND-OR oracle and diagnostic, not a Lean proof checker. + +The ledger uses tree-proof costs for a *fully specified* Horn hypergraph. +Public facts and allowed rule applications must come from a trustworthy caller. +No forward-chained state is promoted to a Lean kernel fact by this module. +""" +from __future__ import annotations + +from dataclasses import dataclass +from math import inf, isfinite + + +@dataclass(frozen=True) +class Rule: + """A hyperedge: all premises are needed to establish the head.""" + + head: int + premises: tuple[int, ...] + cost: float = 1.0 + enabled: bool = True + + +@dataclass(frozen=True) +class Hypergraph: + nodes: int + facts: frozenset[int] + rules: tuple[Rule, ...] + + def __post_init__(self) -> None: + if self.nodes <= 0: + raise ValueError("positive node count required") + if any(not 0 <= v < self.nodes for v in self.facts): + raise ValueError("fact vertex outside graph") + for rule in self.rules: + if (not 0 <= rule.head < self.nodes or + any(not 0 <= v < self.nodes for v in rule.premises)): + raise ValueError("rule vertex outside graph") + if not isfinite(rule.cost) or rule.cost <= 0: + raise ValueError("rule cost must be finite and strictly positive") + + +@dataclass(frozen=True) +class LedgerTrace: + costs: tuple[float, ...] + # A real source fact is different from a graph-derived reachable node. + source_facts: tuple[bool, ...] + structurally_reachable: tuple[bool, ...] + steps: int + converged: bool + # State after each synchronous pass; useful for depth/overthinking audits. + trajectory: tuple[tuple[float, ...], ...] + + +def propagate(graph: Hypergraph, max_passes: int = 64) -> LedgerTrace: + """Run monotone min-plus AND-OR propagation with synchronous updates. + + The result is the minimum derivation-TREE cost for the given fragment + when converged. Shared dependencies may be charged more than once. + """ + if max_passes < 0: + raise ValueError("max_passes must be nonnegative") + costs = tuple(0.0 if v in graph.facts else inf for v in range(graph.nodes)) + trajectory = [costs] + converged = False + steps = 0 + for _ in range(max_passes): + updated = list(costs) + for edge in graph.rules: + if not edge.enabled: + continue + inputs = (costs[node] for node in edge.premises) + # Short-circuit unreachable prerequisites, including cycles. + if all(isfinite(d) for d in inputs): + candidate = edge.cost + sum(costs[node] for node in edge.premises) + updated[edge.head] = min(updated[edge.head], candidate) + next_costs = tuple(updated) + steps += 1 + trajectory.append(next_costs) + if next_costs == costs: + converged = True + break + costs = next_costs + return LedgerTrace( + costs=costs, + source_facts=tuple(v in graph.facts for v in range(graph.nodes)), + structurally_reachable=tuple(isfinite(d) for d in costs), + steps=steps, + converged=converged, + trajectory=tuple(trajectory), + ) + + +def needed_obligations(graph: Hypergraph, goal: int, trace: LedgerTrace) -> frozenset[int]: + """Mark outstanding goals along the cheapest known derivation. + + If a goal is still unreachable, conservatively include premises of all + its available producing rules. This is a potential obligation frontier, + not a claim that Lean supplied these as active goals. + """ + if not 0 <= goal < graph.nodes: + raise ValueError("goal vertex outside graph") + needed: set[int] = set() + + def walk(node: int) -> None: + if node in graph.facts or node in needed: + return + needed.add(node) + choices = [ + (rule.cost + sum(trace.costs[p] for p in rule.premises), + len(rule.premises), rule.premises, rule) + for rule in graph.rules + if rule.enabled and rule.head == node and + all(isfinite(trace.costs[p]) for p in rule.premises) + ] + if choices and isfinite(trace.costs[node]): + selected = (min(choices, key=lambda item: item[:3])[-1],) + else: + selected = tuple(r for r in graph.rules if r.enabled and r.head == node) + for rule in selected: + for premise in rule.premises: + walk(premise) + + walk(goal) + return frozenset(needed) + + +def mean_premise_cue(graph: Hypergraph, head: int) -> float: + """Deliberately lossy diagnostic used for a mean-pooling alias test.""" + incoming = [p for e in graph.rules if e.head == head and e.enabled for p in e.premises] + return sum(p in graph.facts for p in incoming) / len(incoming) if incoming else 0.0 From c199488b5200688389899c297ad9cfeb5bb47f08 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 16:28:14 +0800 Subject: [PATCH 03/51] test(olr): cover AND/OR joins, cycles, aliases and budget limits --- .../ppt_gym/tests/test_obligation_ledger.py | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_obligation_ledger.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_obligation_ledger.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_obligation_ledger.py new file mode 100644 index 000000000..268cc6ec8 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_obligation_ledger.py @@ -0,0 +1,81 @@ +"""Deterministic correctness tests for the OLR-01A structural oracle.""" +import unittest +from math import inf + +from ppt_gym.obligation_ledger import Hypergraph, Rule, mean_premise_cue, needed_obligations, propagate + + +class ObligationLedgerTests(unittest.TestCase): + def test_serial_depth_exact_and_early_halt(self): + g = Hypergraph(5, frozenset([0]), tuple(Rule(i + 1, (i,)) for i in range(4))) + result = propagate(g, 12) + self.assertTrue(result.converged) + self.assertEqual(result.costs, (0., 1., 2., 3., 4.)) + self.assertEqual(result.steps, 5) # 4 new edges + convergence check + self.assertEqual(propagate(g, 2).costs[4], inf) + self.assertEqual(needed_obligations(g, 4, result), frozenset([1, 2, 3, 4])) + self.assertEqual(result.source_facts, (True, False, False, False, False)) + + def test_and_join_requires_every_premise(self): + g = Hypergraph(3, frozenset([0]), (Rule(2, (0, 1)),)) + self.assertEqual(propagate(g).costs[2], inf) + both = Hypergraph(3, frozenset([0, 1]), (Rule(2, (0, 1)),)) + self.assertEqual(propagate(both).costs[2], 1.) + + def test_unresolved_backward_frontier_exposes_missing_premise(self): + g = Hypergraph(3, frozenset((0,)), (Rule(2, (0, 1)),)) + self.assertEqual(needed_obligations(g, 2, propagate(g)), frozenset((1, 2))) + + def test_or_alternative_and_costs(self): + g = Hypergraph(4, frozenset([0, 1]), ( + Rule(2, (0, 1), 4.), Rule(2, (1,), 2.), Rule(3, (2,), 1.))) + self.assertEqual(propagate(g).costs[3], 3.) + + def test_no_spontaneous_cycle_and_positive_seeded_cycle(self): + no_seed = Hypergraph(2, frozenset(), (Rule(1, (0,)), Rule(0, (1,)))) + self.assertEqual(propagate(no_seed, 30).costs, (inf, inf)) + seeded = Hypergraph(2, frozenset([0]), no_seed.rules) + self.assertEqual(propagate(seeded, 30).costs, (0., 1.)) + + def test_disabled_rule_is_not_a_verified_fact(self): + g = Hypergraph(2, frozenset([0]), (Rule(1, (0,), 1., False),)) + self.assertEqual(propagate(g).costs, (0., inf)) + + def test_mean_pooling_collision_different_truth(self): + # Same facts, same rule count, same arity, same mean premise cue. + # A,B are true, C,D are false. One pairing includes a complete rule; + # another distributes the true premises across incomplete rules. + facts = frozenset((0, 1)) + with_witness = Hypergraph(5, facts, (Rule(4, (0, 1)), Rule(4, (2, 3)))) + no_witness = Hypergraph(5, facts, (Rule(4, (0, 2)), Rule(4, (1, 3)))) + self.assertEqual(mean_premise_cue(with_witness, 4), 0.5) + self.assertEqual(mean_premise_cue(no_witness, 4), 0.5) + self.assertEqual(propagate(with_witness).costs[4], 1.) + self.assertEqual(propagate(no_witness).costs[4], inf) + + def test_shared_dependency_tree_accounting(self): + # Two branches both need node 1; tree-cost counts that derivation twice. + g = Hypergraph(5, frozenset((0,)), ( + Rule(1, (0,)), Rule(2, (1,)), Rule(3, (1,)), Rule(4, (2, 3)))) + self.assertEqual(propagate(g).costs[4], 5.) + # A DAG with memoized proof of node 1 can use four distinct rules. + + def test_permutation_invariance_of_costs(self): + edges = (Rule(2, (0, 1), 2), Rule(3, (2,), 1), Rule(3, (1,), 5)) + g1 = Hypergraph(4, frozenset([0, 1]), edges) + g2 = Hypergraph(4, frozenset([0, 1]), tuple(reversed(edges))) + self.assertEqual(propagate(g1).costs, propagate(g2).costs) + + def test_zero_budget_and_input_guards(self): + g = Hypergraph(1, frozenset((0,)), tuple()) + r = propagate(g, 0) + self.assertFalse(r.converged) + self.assertEqual(r.steps, 0) + with self.assertRaises(ValueError): + Hypergraph(2, frozenset(), (Rule(2, tuple()),)) + with self.assertRaises(ValueError): + Hypergraph(2, frozenset(), (Rule(1, (0,), -1),)) + + +if __name__ == '__main__': + unittest.main() From c0dc0df2e7c380e92ef8e880d1668097ca451926 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 16:29:14 +0800 Subject: [PATCH 04/51] test(olr): cross-check 400 seeded AND-OR DAGs against independent oracle --- .../tests/test_obligation_ledger_random.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_obligation_ledger_random.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_obligation_ledger_random.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_obligation_ledger_random.py new file mode 100644 index 000000000..12e0b2206 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_obligation_ledger_random.py @@ -0,0 +1,35 @@ +"""OLR-01A: seeded acyclic oracle property check over 400 graphs.""" +import random +import unittest +from math import inf + +from ppt_gym.obligation_ledger import Hypergraph, Rule, propagate + + +class RandomAcyclicOracleTest(unittest.TestCase): + def test_400_random_graphs_against_topological_oracle(self): + rng = random.Random(20261123) + for _ in range(400): + count = rng.randrange(2, 8) + facts = frozenset(v for v in range(count) if rng.random() < .3) + rules = [] + for head in range(count): + for _j in range(rng.randrange(4)): + inputs = tuple(v for v in range(head) if rng.random() < .4) + rules.append(Rule(head, inputs, rng.randrange(1, 5))) + graph = Hypergraph(count, facts, tuple(rules)) + # Separate topological solver; every premise index precedes its head. + exact = [inf] * count + for node in range(count): + if node in facts: + exact[node] = 0. + for rule in rules: + if rule.head == node and all(exact[p] < inf for p in rule.premises): + exact[node] = min(exact[node], rule.cost + sum(exact[p] for p in rule.premises)) + actual = propagate(graph, count + 1) + self.assertTrue(actual.converged) + self.assertEqual(actual.costs, tuple(exact)) + + +if __name__ == "__main__": + unittest.main() From d4146c1f5d0be51d3e3548a2032ca1ea060be9a1 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 16:30:49 +0800 Subject: [PATCH 05/51] research(olr): audit novelty, quantify stopping gain and narrow first Lean gate --- .../lean_cgrt_hrm400/OLR_01_INVESTIGATION.md | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_01_INVESTIGATION.md diff --git a/research/lean_cgrt_hrm400/OLR_01_INVESTIGATION.md b/research/lean_cgrt_hrm400/OLR_01_INVESTIGATION.md new file mode 100644 index 000000000..9b998bc32 --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_01_INVESTIGATION.md @@ -0,0 +1,109 @@ +# OLR-01 investigation: novelty audit, alias witness, and executable structural probe + +**Date:** 2026-11-23 +**Status:** Investigative findings and deterministic correctness tests; no OLR neural training or Lean-certified OLR performance claim +**Companion:** [OLR_01_OBLIGATION_LEDGER_RECURRENCE.md](OLR_01_OBLIGATION_LEDGER_RECURRENCE.md) + +## 1. Re-read of the reported reward advantage + +The published 1217 directed BPD repair counted 192 residual/budget scenarios from 32 roots. The native tactic-tree ceiling is 32 completions. The reward-trained two-slot arm completed 20, the matching imitation two-slot arm also completed 20, and full-history TRM completed five. + +The utility difference between reward and imitation is **exactly accounted for** by action spending at the registered costs: + +| Quantity | Two-slot reward | Two-slot imitation | Difference (reward - imitation) | +| --- | ---: | ---: | ---: | +| Completed scenarios | 20 | 20 | 0 | +| Target tactic calls | 192 | 170 | +22 | +| Charged sibling probes | 0 | 137 | -137 | +| Root utility | 0.079167 | 0.046354 | +0.032813 | + +With each target call charged 0.025 and sibling probe charged 0.05, the derived utility difference is: + + [(137 × 0.05) - (22 × 0.025)] / 192 = 0.0328125. + +The gain is a budget-management result for **the same successful proofs**. The *architecture* comparison with TRM remains substantial (20 vs 5 completions on this one frozen test), but the reward-versus-imitation comparison does not show additional proof-recovery capability. The candidate also reaches 20 of the 32 scenarios accessible to the registered native reference. The rest is headroom whose source needs a future error decomposition. + +This changes the experiment priority: OLR-01 must include a *fixed-call, forced-action diagnostic* separate from the STOP/probe/allocation policy. Otherwise a future efficiency win could again be mistaken for better propagation. + +## 2. Formal mean-pooling collision + +Take four primitive symbols A, B, C, D with evidence A=true, B=true, C=false, D=false and two binary Horn rules producing target T. + +**World W1:** + + A & B -> T + C & D -> T + +**World W2:** + + A & C -> T + B & D -> T + +Both worlds contain the same source facts, the same number of rules, equal arities, and the same multiset of primitive evidence entering T: [1,1,0,0]. An aggregator that collapses the incoming premises to their unstructured mean sees 0.5 in either world. A function whose sole relevant input is this pooled statistic cannot distinguish their targets. However W1 has a satisfied rule, while W2 has none. The AND-OR recurrence obtains T=reachable in W1 and T=unreachable in W2. + +This identifies an information-loss mechanism **for that restricted pooling interface**, and motivates retaining premise-to-rule incidence. It does not prove that a full graph transformer with edge information must fail, or that adding a neural recurrent block yields a gain over exact symbolic evaluation. + +## 3. Executable oracle and local verification + +The branch adds: + +- [ppt_gym/obligation_ledger.py](ppt_gym/obligation_ledger.py): positive-cost AND-OR hypergraph, synchronous min-plus fixed point, immutable source-fact bits, derived reachability, convergence trace and backward possible-obligation frontier. +- [ppt_gym/tests/test_obligation_ledger.py](ppt_gym/tests/test_obligation_ledger.py): ten deterministic tests of serial depth, conjunctive and disjunctive rules, cyclic support, known-inapplicable rules, shared-dependency counting, edge order, remaining-step limits and the pooling collision. +- [ppt_gym/tests/test_obligation_ledger_random.py](ppt_gym/tests/test_obligation_ledger_random.py): 400 seeded acyclic graphs compared with a separately implemented topological tree-cost evaluator. + +**Local probe:** 11 test methods passed, including the 400-case randomized oracle comparison, using Python's unittest on the model workspace. The test run measures a deterministic structural algorithm, with no model weights, Lean theorem calls, independent certificates or performance comparison to existing trained architectures. Run inside the repository's research/lean_cgrt_hrm400 directory using: + + python -m unittest discover -s ppt_gym/tests -p "test_obligation_ledger*.py" -v + +Additional existing PPT regressions and hosted CI should be checked before the branch is merged. + +An important semantics restriction is explicit in the implementation: graph-derived facts represent reachability *under the supplied Horn fragment*, and do not become Lean kernel facts. A rejected tactic excludes or downgrades that action in the current proof state; it does not refute the logical proposition that action attempted to prove. + +## 4. Novelty audit against prior art + +The following ideas have existing literature and must be cited as antecedents: + +| Prior work | Relevant result | What it means for OLR | +| --- | --- | --- | +| Zhu et al., **Neural Bellman-Ford Networks**, NeurIPS 2021, https://proceedings.nips.cc/paper_files/paper/2021/hash/f6a673f09493afcd8b129a0bcf1cd5bc-Abstract.html | Generalized Bellman-Ford with learnable indicator/message/aggregation operators on paths | Learnable semiring-like propagation on graphs is established, so OLR cannot claim its min-plus recurrence alone as new | +| Fang et al., **MC-HNN**, ICML 2026, https://proceedings.mlr.press/v306/fang26g.html | Multi-channel hypergraph learning and rank-collapse/semantic-dependency analysis | Hyperedge identity and multi-channel messages are also established architectural ingredients | +| Movahedi et al., **Fixed-Point Reasoners**, 2026, https://arxiv.org/abs/2606.18206 | Stable recurrent updates and convergence-based compute allocation | Halting at a fixed point is prior work; OLR should evaluate a semantics-based residual as an additional control | +| Liang et al., **Beyond the Training Horizon**, Sep 2026, https://arxiv.org/abs/2609.33144 | Recurrent latent content has a computational status (fresh/aged or live/consumed), and longer runs can lose usable state | Motivates explicitly measuring active/pending/consumed obligation channels, with causal interventions | +| Labovich, **Stability and Generalization in Looped Transformers**, latest Nov 2026, https://arxiv.org/abs/2604.15259 | Recall and normalization conditions for input-dependent fixed points | Inspires explicit re-injection of the immutable public proof context | +| Popescu et al., **Adaptive Depth in Looped Transformers**, 2026, https://arxiv.org/abs/2607.20519 | Halting gate and trained trajectory are intertwined; frozen-trajectory readouts can be competitive | Fit stopping after architecture training and retain the same saved recurrent trajectories for every stopping control | + +The candidate research contribution is therefore **a task-facing coupling**: an AND-OR obligation ledger, an independently marked native-evidence ledger, a weight-tied semantic updater, and a strict accounting controller, all on live Lean proof transitions. These are components with antecedents whose usefulness as a whole still needs a direct experiment. + +## 5. Critical limitation: symbolic Horn planning is already strong + +In [PPT_HYBRID_RL_PENDING_RECOVERY.md](PPT_HYBRID_RL_PENDING_RECOVERY.md), the public Horn structural solver chose the certified branch on all 128 worlds. In [PPT_COMPUTATIONAL_GUARDS.md](PPT_COMPUTATIONAL_GUARDS.md), the exact arithmetic fold oracle certified all 80 worlds, while the learned Bellman two-slot actor completed 38. The former shows that a fully exposed graph can make learning unnecessary; the latter shows that symbolic reachability alone misses computational applicability. + +Thus a benchmark built solely out of fully parsed, deterministic Horn graphs would mostly test whether the neural model can imitate the exact oracle. Keep these as **correctness controls** and train the neural extension on *partially specified and computationally conditional* proof transitions. + +Three questions should decide OLR-01B: + +1. Can the learned semantic channel recognize candidate tactics whose syntactic prerequisites look identical but whose delayed computational or dependent-type guards differ? +2. Does the obligation channel preserve the identity of pending and shared subgoals across a real, externally verified tactic step and bounded rollback? +3. At matched calls and FLOPs, does removing the obligation channel reduce **new certified completions**, and does an equal-dose matched margin sham leave the claimed direction-specific effect intact? + +A small sidecar can operate on the public graph and legal menu while leaving existing Lean 4.19 action execution and proof certificates untouched. A learned applicability head needs a third status for unobserved/unknown actions, keeping timeouts and model failures censored. + +## 6. Refined OLR-01B contract + +Keep the experiment narrow: + +**Inputs.** Public Lean goal(s), local hypotheses and binder scope, legal tactic candidates, their visible premise hyperedges when parseable, failed/native-accepted result history, remaining calls, and saved proof-tree state. Preserve exact source strings for unsupported arithmetic or dependent fragments and mark unparsed structure as unknown. + +**Two recurrent channels.** A frozen, exact structural ledger for known Horn subgraphs and a trainable semantic/status ledger over the same edge identities. The learned model ranks tactics and predicts successor obligations. It cannot mutate native facts, source budgets or certificates. + +**Dynamic computation.** Seed hidden-state recurrence from public input every pass, apply shared weights and small residual scaling, and report per-pass change in the structural and learned value states. Stop fitting separate compute-readout gates until the action trajectory is frozen. A stalled structural ledger does not imply the learned semantic layer is converged. + +**Strong controls.** Source two-slot reward, newly fitted two-slot reward/imitation, structural oracle, direct learned guard reader, frozen-body OLR, shuffled hyperedges, head-only/linear calibration, plain tied loop, and a matched FLOP variant. Every model receives the same legally visible cues. + +**Preflight and prospective cohorts.** Freeze enough new roots with independently witnessed nontrivial candidate outcomes before fitting or scoring. Stratify directed propositional joins, pending multi-goal proofs, opaque computational guards, and shared-witness dependent rewrites. Avoid saturated Horn/equality sets as the primary target. Account at the root level and by independent seeds. + +**Next implementation gate.** Construct a native-facing adapter and a single paired forced-action test from newly generated 2-premise cases. Verify that an edge swap changes the oracle value, that the same candidate menu stays legal, that both worlds independently compile in Lean, and that all arms are scored at the same calls. Proceed to trainable OLR only after this gate. + +## 7. Outcome of the investigation + +The hard AND-OR structural component is easy to execute and test; its representation preserves an important distinction lost by unstructured incoming means. This supplies an algorithmic reference, not evidence of a superior looped transformer. The first scientific opportunity is in **uncertain applicability with delayed native feedback** and in **matching the cost of keeping multiple obligations live**, where exact Horn closure and ordinary candidate calibration leave genuine headroom. From f12020d4e8d207839e4b2efaff67c950a1a97d7c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 18:14:07 +0800 Subject: [PATCH 06/51] feat(olr): parameterize fact-application cost for Lean tactic accounting --- research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py b/research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py index f25ee8620..e2ddc3c10 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py +++ b/research/lean_cgrt_hrm400/ppt_gym/obligation_ledger.py @@ -51,15 +51,20 @@ class LedgerTrace: trajectory: tuple[tuple[float, ...], ...] -def propagate(graph: Hypergraph, max_passes: int = 64) -> LedgerTrace: +def propagate(graph: Hypergraph, max_passes: int = 64, *, fact_cost: float = 0.0) -> LedgerTrace: """Run monotone min-plus AND-OR propagation with synchronous updates. The result is the minimum derivation-TREE cost for the given fragment when converged. Shared dependencies may be charged more than once. + A positive fact_cost counts the action required to discharge each fact. """ if max_passes < 0: raise ValueError("max_passes must be nonnegative") - costs = tuple(0.0 if v in graph.facts else inf for v in range(graph.nodes)) + if not isfinite(fact_cost) or fact_cost < 0: + raise ValueError("fact_cost must be finite and nonnegative") + # Fact_cost=1 matches a separate "apply h" tactic in the restricted + # backward-chaining Lean fragment. Zero gives logical derivation edge cost. + costs = tuple(float(fact_cost) if v in graph.facts else inf for v in range(graph.nodes)) trajectory = [costs] converged = False steps = 0 From bd9fa66ab362f3404c0a66fcf13124b93d1fdd98 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 18:15:31 +0800 Subject: [PATCH 07/51] feat(olr): native paired Horn proof preflight with public-only ledger and replay --- .../lean_cgrt_hrm400/ppt_gym/olr_native.py | 378 ++++++++++++++++++ 1 file changed, 378 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/olr_native.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_native.py b/research/lean_cgrt_hrm400/ppt_gym/olr_native.py new file mode 100644 index 000000000..1f34ce1c8 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_native.py @@ -0,0 +1,378 @@ +"""OLR-01B: independent native Lean paired-world preflight. + +This is a structured-graph oracle and verifier-integration test. It contains +zero learned parameters. A good result cannot establish a neural architecture +advantage. The scorer consumes only public Lean goal/hypothesis JSON. +""" +from __future__ import annotations + +import argparse +import json +import random +import re +from dataclasses import dataclass, replace +from math import inf, isfinite +from pathlib import Path + +from lcgrt import config, fragment as F +from lcgrt.certify import certify, decl_name +from lcgrt.lean_repl import LeanRepl +from .data import canonical, digest, sha256_file +from .live_lean import candidate_menu, public_state +from .obligation_ledger import Hypergraph, Rule, mean_premise_cue, propagate + +SCHEMA = "ppt_gym.olr_native_pair_preflight.v1" +ARMS = ("ledger", "mean_only", "edge_swap", "force_r0", "force_r1") +NAME = re.compile(r"^P([0-9]{1,4})$") +TACTIC = re.compile(r"^apply ([hr][0-9]{1,4})$") + + +@dataclass(frozen=True) +class PairWorld: + pair: str + world: str + theorem: F.Theorem + # Private witness used for auditing outcomes ONLY; never passed to rank(). + witness: str + lineage: str + + +@dataclass(frozen=True) +class ParsedGoal: + graph: Hypergraph + target: int + rules: dict[str, Rule] + facts: dict[str, int] + unparsed: tuple[str, ...] + + +def pair_worlds(seed: int, variant: int) -> tuple[PairWorld, PairWorld]: + """Two paired Horn worlds: same atoms, same facts, opposite viable root. + + Nuisance-chain length varies across pairs, giving distinct structural + fingerprints in the preflight; rule-name and atom-position cues are shuffled. + """ + if not 0 <= variant < 8: + raise ValueError("bounded structural variant 0..7 required") + rng = random.Random(f"olr-native-pair-v1/{seed}/{variant}") + indices = list(range(5 + variant)) + rng.shuffle(indices) + a, b, c, d, target = indices[:5] + extras = indices[5:] + facts = [a, b] + rng.shuffle(facts) + decoys = [] + previous = c + for node in extras: + decoys.append([[previous], node]) + previous = node + # Both worlds have exactly one feasible binary candidate rule to the goal. + producers = ([[a, b], target], [[c, d], target]) + pairs = [] + for world, chosen in (("w0", 0), ("w1", 1)): + order = producers if world == "w0" else producers[::-1] + thm = F.Theorem( + tid=f"olr01b_{seed}_{variant}_{world}", + family="olr01b-native-paired", depth=2, seed=seed, + n_atoms=len(indices), facts=list(facts), + rules=[[[*premises], head] for premises, head in (*order, *decoys)], + goal=[target], gen={"evidence": "preflight_reference_only"}, + ) + pairs.append(PairWorld( + pair=f"olr01b_{seed}_{variant}", world=world, theorem=thm, + witness=f"apply r{chosen}", lineage=F.canonical_hash(thm), + )) + if pairs[0].lineage != pairs[1].lineage: + raise AssertionError("paired worlds must share an unlabeled hypergraph") + return tuple(pairs) + + +def atom(term: object) -> int | None: + if isinstance(term, dict) and type(term.get("a")) is str: + m = NAME.fullmatch(term["a"]) + return int(m.group(1)) if m else None + return None + + +def horn_type(term: object) -> tuple[tuple[int, ...], int] | None: + """Parse only the public fragment of Lean's propJson. Raw types stay unknown.""" + inputs = [] + while isinstance(term, dict) and "imp" in term: + parts = term["imp"] + if not isinstance(parts, list) or len(parts) != 2: + return None + premise = atom(parts[0]) + if premise is None: + return None + inputs.append(premise) + term = parts[1] + head = atom(term) + return (tuple(inputs), head) if head is not None else None + + +def parse_public(visible: dict) -> ParsedGoal: + goals = visible.get("goals", []) + if not isinstance(goals, list) or len(goals) != 1: + raise ValueError("OLR-01B root parser requires exactly one native Lean goal") + goal = goals[0] + target = atom(goal.get("target")) + if target is None: + raise ValueError("OLR-01B root target is outside simple Horn subset") + facts, rules, unparsed = {}, {}, [] + nodes = {target} + for hyp in goal.get("hypotheses", []): + name = hyp.get("name") + if not isinstance(name, str): + continue + if not TACTIC.fullmatch("apply " + name): + continue + parsed = horn_type(hyp.get("type")) + if parsed is None: + unparsed.append(name) + continue + premises, head = parsed + nodes.update((*premises, head)) + if premises: + rules[name] = Rule(head, premises) + elif name.startswith("h"): + facts[name] = head + else: + unparsed.append(name) + graph = Hypergraph( + nodes=max(nodes) + 1, + facts=frozenset(facts.values()), + rules=tuple(rules.values()), + ) + return ParsedGoal(graph, target, rules, facts, tuple(unparsed)) + + +def rule_swap(parsed: ParsedGoal) -> ParsedGoal: + """Sham: alter *only* paired r0/r1 premise grouping in the readout.""" + if "r0" not in parsed.rules or "r1" not in parsed.rules: + raise ValueError("paired-edge sham requires both root producers") + left, right = parsed.rules["r0"], parsed.rules["r1"] + if left.head != right.head or len(left.premises) != len(right.premises): + raise ValueError("paired rules changed arity/target") + changed = dict(parsed.rules) + changed["r0"] = replace(left, premises=right.premises) + changed["r1"] = replace(right, premises=left.premises) + return replace(parsed, graph=replace(parsed.graph, rules=tuple(changed.values())), rules=changed) + + +def rank(visible: dict, menu: tuple[str, ...], arm: str, *, at_root: bool) -> tuple[str, dict]: + """Decision uses native public data only. No witness/metadata argument.""" + if not menu: + raise ValueError("rank called with an empty menu") + if arm not in ARMS: + raise ValueError("unrecognized structural arm") + if at_root and arm.startswith("force_"): + forced = "apply " + arm.removeprefix("force_") + if forced not in menu: + raise ValueError("forced root tactic absent from public grammar") + return forced, {"forced_witness": True} + parsed = parse_public(visible) + if arm == "mean_only" and at_root: + # Aggregate all incoming premise bits into one pooled head cue, then + # tie-break the two original candidate IDs without edge information. + return sorted(menu)[0], {"pooled_cue": mean_premise_cue(parsed.graph, parsed.target)} + if arm == "edge_swap" and at_root: + parsed = rule_swap(parsed) + tr = propagate(parsed.graph, max_passes=16, fact_cost=1.) + cost = {} + for choice in menu: + match = TACTIC.fullmatch(choice) + name = match.group(1) if match else None + if name in parsed.facts and parsed.facts[name] == parsed.target: + value = 1. + elif name in parsed.rules and parsed.rules[name].head == parsed.target: + rule = parsed.rules[name] + value = rule.cost + sum(tr.costs[p] for p in rule.premises) + else: + value = inf + cost[choice] = value + action = min(menu, key=lambda t: (cost[t], t)) + return action, {"cost": {k: float(v) if isfinite(v) else None + for k, v in cost.items()}, + "converged": tr.converged, "passes": tr.steps, + "unparsed": list(parsed.unparsed)} + + +def run_episode(lean: LeanRepl, world: PairWorld, arm: str, *, checks: int = 3) -> dict: + if not 1 <= checks <= 8: + raise ValueError("bounded native tactic budget required") + lean.reset() + state = lean.init(F.statement(world.theorem), pp=True) + expected_menu = ("apply r0", "apply r1") + original = public_state(lean, state) + root_menu = candidate_menu(lean, state) + if root_menu != expected_menu: + raise ValueError(f"registered Lean root menu changed: {root_menu}") + root_cue = mean_premise_cue(parse_public(original).graph, parse_public(original).target) + if root_cue != 0.5: + raise ValueError("the registered mean-alias cue changed") + spent, events = 0, [] + status = "budget_exhausted" + for step in range(checks): + visible = public_state(lean, state) + menu = candidate_menu(lean, state) + if not menu: + status = "no_candidates" + break + # Only root mode changes; continuation uses the same public-only + # structural action selection for every arm. + tactic, info = rank(visible, menu, arm if step == 0 else "ledger", at_root=step == 0) + before = digest(visible) + reply = lean.run(state["sid"], tactic) + spent += 1 + event = {"step": spent, "tactic": tactic, "menu": list(menu), + "before": before, "rank": info, "ok": reply["ok"]} + if not reply["ok"]: + status = "rejected" + event["after"] = before + events.append(event) + break + state = reply["state"] + new = public_state(lean, state) + event["after"] = digest(new) + event["goals_after"] = len(new["goals"]) + events.append(event) + if not new["goals"]: + cert = lean.kernel(state["sid"]) + if cert.get("ok") is True and cert.get("axioms") == []: + status = "kernel_closed" + else: + status = "certificate_rejected" + event["kernel"] = {"ok": cert.get("ok"), "axioms": cert.get("axioms")} + break + return { + "root": digest(F.statement(world.theorem)), "pair": world.pair, + "world": world.world, "lineage": world.lineage, + "arm": arm, "menu": list(root_menu), "root_cue": root_cue, + "status": status, "checks": spent, "budget": checks, + "script": [e["tactic"] for e in events if e["ok"]], + "events": events, + } + + +def replay(lean: LeanRepl, world: PairWorld, episode: dict) -> bool: + """Replay public menus, verified transitions and terminal kernel checks.""" + if episode["root"] != digest(F.statement(world.theorem)): + raise ValueError("changed native theorem statement") + lean.reset() + state = lean.init(F.statement(world.theorem), pp=True) + for event in episode["events"]: + public = public_state(lean, state) + menu = candidate_menu(lean, state) + if (event["before"] != digest(public) or + event["menu"] != list(menu) or event["tactic"] not in menu): + raise ValueError("replayed root/choice/menu differs") + reply = lean.run(state["sid"], event["tactic"]) + if reply["ok"] != event["ok"]: + raise ValueError("replayed tactic verdict differs") + if not reply["ok"]: + if event["after"] != digest(public): + raise ValueError("replayed tactic rejection differs") + break + state = reply["state"] + new = public_state(lean, state) + if event["after"] != digest(new) or event["goals_after"] != len(new["goals"]): + raise ValueError("replayed successor obligations differ") + if not new["goals"]: + cert = lean.kernel(state["sid"]) + if not (cert.get("ok") is True and cert.get("axioms") == []): + raise ValueError("replayed kernel certificate differs") + else: + if episode["status"] == "kernel_closed": + raise ValueError("missing terminal certificate in replay") + return True + + +def verify(seed: int, count: int, out: Path, *, timeout: float = 60.) -> dict: + if not 1 <= count <= 8 or out.exists(): + raise ValueError("1..8 pairs and a new output directory required") + pairs = [pair_worlds(seed + i, i) for i in range(count)] + fingerprints = {pair[0].lineage for pair in pairs} + if len(fingerprints) != count: + raise ValueError("distinct pairs share a structural fingerprint") + episodes = [] + lookup = {} + with LeanRepl(timeout=timeout) as lean: + if not str(lean.version).startswith("4.19.0"): + raise ValueError("requires pinned native Lean 4.19") + version = lean.version + for pair in pairs: + for world in pair: + lookup[(world.pair, world.world)] = world + for arm in ARMS: + ep = run_episode(lean, world, arm) + episodes.append(ep) + for pair in pairs: + per_world = [[e for e in episodes if e["pair"] == w.pair and + e["world"] == w.world] for w in pair] + for world, eps in zip(pair, per_world, strict=True): + assert len(eps) == len(ARMS) + by_arm = {e["arm"]: e for e in eps} + if (by_arm["ledger"]["status"] != "kernel_closed" or + by_arm["edge_swap"]["status"] == "kernel_closed" or + by_arm["force_r0"]["status"] == by_arm["force_r1"]["status"]): + raise ValueError("registered native paired witness outcomes changed") + if (next(e for e in eps if e["arm"] == "ledger")["script"][0] + != world.witness): + raise ValueError("structural action disagreed with independent witness") + if any(e["menu"] != list(("apply r0", "apply r1")) for e in eps): + raise ValueError("unmatched public action menus") + if sum(e["status"] == "kernel_closed" for ws in per_world + for e in ws if e["arm"] == "mean_only") != 1: + raise ValueError("mean-aggregation reference must fail one paired world") + for ep in episodes: + if not replay(lean, lookup[ep["pair"], ep["world"]], ep): + raise ValueError("native replay failed") + winners = [e for e in episodes if e["arm"] == "ledger"] + declarations = [(f"{lookup[e['pair'],e['world']].theorem.tid}_ledger", + lookup[e["pair"],e["world"]].theorem, e["script"]) for e in winners] + out.mkdir(parents=True, exist_ok=False) + cert = certify(declarations, timeout=180, keep=out / "standalone.lean") + if any(cert["status"].get(decl_name(tid)) != "passed" for tid, _, _ in declarations): + raise ValueError(f"standalone Lean certification failed: {cert['rejected']}") + receipt = { + "schema": SCHEMA, + "classification": "structural_preflight_not_neural_architecture_evidence", + "seed": seed, "pairs": count, "worlds": 2*count, + "pair_lineages": sorted(fingerprints), "native_lean_version": version, + "lean_sha256": sha256_file(config.LEAN_EXE), + "repl_sha256": sha256_file(config.REPL_EXE), + "all_root_menus_equal": True, + "same_mean_premise_cue": 0.5, + "independent_compiled_scripts": cert["passed"], + "all_episodes_replayed": len(episodes), + "scorecard": {arm: { + "kernel_closures": sum(e["status"] == "kernel_closed" for e in episodes + if e["arm"] == arm), + "native_tactic_calls": sum(e["checks"] for e in episodes + if e["arm"] == arm), + } for arm in ARMS}, + "architecture_promotion_eligible": False, + } + (out / "episodes.jsonl").write_text( + "".join(canonical(e) + "\n" for e in episodes), encoding="utf-8") + (out / "certificate.json").write_text(canonical(cert) + "\n", encoding="utf-8") + receipt["artifacts"] = {name: sha256_file(out / name) + for name in ("episodes.jsonl", "certificate.json", "standalone.lean")} + (out / "manifest.json").write_text(canonical(receipt) + "\n", encoding="utf-8") + return receipt + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--seed", type=int, default=20261123) + parser.add_argument("--pairs", type=int, default=4) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args(argv) + report = verify(args.seed, args.pairs, args.out) + print(canonical({k: report[k] for k in + ("schema", "pairs", "worlds", "scorecard", + "independent_compiled_scripts", "all_episodes_replayed")})) + + +if __name__ == "__main__": + main() From acd0bc9c217e83667c3f314662814efb38f97311 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 18:15:57 +0800 Subject: [PATCH 08/51] fix(olr): parse focused goals with pending context and terminate replay on kernel closure --- research/lean_cgrt_hrm400/ppt_gym/olr_native.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_native.py b/research/lean_cgrt_hrm400/ppt_gym/olr_native.py index 1f34ce1c8..d0512571f 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/olr_native.py +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_native.py @@ -112,8 +112,10 @@ def horn_type(term: object) -> tuple[tuple[int, ...], int] | None: def parse_public(visible: dict) -> ParsedGoal: goals = visible.get("goals", []) - if not isinstance(goals, list) or len(goals) != 1: - raise ValueError("OLR-01B root parser requires exactly one native Lean goal") + if not isinstance(goals, list) or not goals: + raise ValueError("OLR-01B parser requires an active native Lean goal") + # Parse the focused goal; the other goals remain pending in the native + # packet and are accounted for by Lean across subsequent tactic calls. goal = goals[0] target = atom(goal.get("target")) if target is None: @@ -281,6 +283,7 @@ def replay(lean: LeanRepl, world: PairWorld, episode: dict) -> bool: cert = lean.kernel(state["sid"]) if not (cert.get("ok") is True and cert.get("axioms") == []): raise ValueError("replayed kernel certificate differs") + break else: if episode["status"] == "kernel_closed": raise ValueError("missing terminal certificate in replay") From 5e143d19c22383bed0b22e69a2914cf075d290e8 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 18:16:21 +0800 Subject: [PATCH 09/51] test(olr): probe native public-JSON adapter, paired edge sham and cost ledger --- .../ppt_gym/tests/test_olr_native.py | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_native.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_native.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_native.py new file mode 100644 index 000000000..0b9654ca2 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_native.py @@ -0,0 +1,101 @@ +"""OLR-01B public-data and paired-structural preflight tests. + +These tests create synthetic Lean-shaped JSON for protocol checks only. +Native validity and certificates are checked by the separate CI Lean job. +""" +import unittest + +from lcgrt import fragment as F +from ppt_gym.olr_native import ( + atom, horn_type, pair_worlds, parse_public, rank, rule_swap, +) +from ppt_gym.obligation_ledger import mean_premise_cue, propagate + + +def public_packet(theorem: F.Theorem): + hyps = [{"name": f"h{i}", "type": {"a": f"P{p}"}} + for i, p in enumerate(theorem.facts)] + for i, (premises, head) in enumerate(theorem.rules): + ty = {"a": f"P{head}"} + for p in reversed(premises): + ty = {"imp": [{"a": f"P{p}"}, ty]} + hyps.append({"name": f"r{i}", "type": ty}) + return {"goals": [{"target": {"a": f"P{theorem.goal[0]}"}, + "hypotheses": hyps}]} + + +class OLREvidenceInterfaceTests(unittest.TestCase): + def test_pair_reverses_witness_with_same_cue_and_menu(self): + pair = pair_worlds(20261123, 2) + self.assertEqual(pair[0].lineage, pair[1].lineage) + self.assertNotEqual(F.statement(pair[0].theorem), F.statement(pair[1].theorem)) + self.assertEqual(pair[0].witness, "apply r0") + self.assertEqual(pair[1].witness, "apply r1") + for w in pair: + visible = public_packet(w.theorem) + parsed = parse_public(visible) + self.assertEqual(len(parsed.rules), 4) + self.assertEqual(mean_premise_cue(parsed.graph, parsed.target), 0.5) + trace = propagate(parsed.graph, fact_cost=1.) + self.assertEqual(trace.costs[parsed.target], 3.) + self.assertEqual(rank(visible, ("apply r0", "apply r1"), "ledger", + at_root=True)[0], w.witness) + self.assertNotEqual(rank(visible, ("apply r0", "apply r1"), "edge_swap", + at_root=True)[0], w.witness) + + def test_mean_only_cannot_separate_two_worlds(self): + p = pair_worlds(20261124, 3) + cues = [rank(public_packet(w.theorem), ("apply r0", "apply r1"), + "mean_only", at_root=True) for w in p] + self.assertEqual(cues[0], cues[1]) + self.assertEqual(cues[0][1]["pooled_cue"], 0.5) + + def test_eight_variants_get_structurally_distinct_roots(self): + hashes = [pair_worlds(20261123 + i, i)[0].lineage for i in range(8)] + self.assertEqual(len(set(hashes)), 8) + + def test_parser_uses_active_goal_and_preserves_pending(self): + case = pair_worlds(42, 1)[0] + shown = public_packet(case.theorem) + shown["goals"].append({"target": {"a": "P9999"}, "hypotheses": []}) + parsed = parse_public(shown) + self.assertEqual(parsed.target, case.theorem.goal[0]) + self.assertEqual(len(parsed.rules), 3) + + def test_malformed_and_raw_edges_are_never_promoted(self): + shown = {"goals": [{"target": {"a": "P2"}, "hypotheses": [ + {"name": "h0", "type": {"a": "P0"}}, + {"name": "r0", "type": {"raw": "decide condition"}}, + {"name": "r1", "type": {"imp": [{"a": "P0"}, {"a": "P2"}]}}, + ]}]} + parsed = parse_public(shown) + self.assertEqual(parsed.unparsed, ("r0",)) + self.assertNotIn("r0", parsed.rules) + self.assertEqual(rank(shown, ("apply r0", "apply r1"), + "ledger", at_root=True)[0], "apply r1") + + def test_bad_atoms_and_malformed_implications(self): + self.assertIsNone(atom({"a": "Nat.add"})) + self.assertIsNone(horn_type({"imp": ["P0", {"a": "P1"}]})) + self.assertIsNone(horn_type({"imp": [{"a": "P0"}]})) + with self.assertRaises(ValueError): + parse_public({"goals": []}) + + def test_forced_root_choice_uses_menu_only(self): + shown = public_packet(pair_worlds(77, 0)[0].theorem) + self.assertEqual(rank(shown, ("apply r0", "apply r1"), + "force_r1", at_root=True)[0], "apply r1") + with self.assertRaises(ValueError): + rank(shown, ("apply r0",), "force_r1", at_root=True) + + def test_rule_swap_preserves_graph_size_and_fact_set(self): + p = parse_public(public_packet(pair_worlds(7, 2)[0].theorem)) + q = rule_swap(p) + self.assertEqual(p.graph.nodes, q.graph.nodes) + self.assertEqual(p.graph.facts, q.graph.facts) + self.assertEqual(p.rules["r0"].premises, q.rules["r1"].premises) + self.assertEqual(p.rules["r1"].premises, q.rules["r0"].premises) + + +if __name__ == "__main__": + unittest.main() From 01b87f8833d632765369279371bd8437c58f8833 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 18:16:39 +0800 Subject: [PATCH 10/51] ci(olr): certify four fresh paired native Lean witnesses and replay controls --- .github/workflows/ppt-g03-live-lean.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index be85bd49f..42fb9a187 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -107,6 +107,22 @@ jobs: assert replay_search(lean, case, ep)["replay_passed"] print("PPT-G03B native backtracking and full kernel replay verified") PY + - name: OLR-01B paired native Lean preflight + working-directory: research/lean_cgrt_hrm400 + run: | + python -m ppt_gym.olr_native --seed 20261123 --pairs 4 --out runs/olr-01b-native + python - <<'PY' + import json + m = json.load(open("runs/olr-01b-native/manifest.json", encoding="utf-8")) + assert m["pairs"] == 4 and m["worlds"] == 8, m + assert m["independent_compiled_scripts"] == 8, m + assert m["all_episodes_replayed"] == 40, m + assert m["scorecard"]["ledger"]["kernel_closures"] == 8, m + assert m["scorecard"]["mean_only"]["kernel_closures"] == 4, m + assert m["scorecard"]["edge_swap"]["kernel_closures"] == 0, m + assert m["architecture_promotion_eligible"] is False + print("OLR-01B real Lean paired proof and replay preflight", m["scorecard"]) + PY - name: Fresh generated Lean suite and model smoke working-directory: research/lean_cgrt_hrm400 env: From 1cf526b2dd95d92f1ce9b24913e3b9ee36b9fa15 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 18:20:15 +0800 Subject: [PATCH 11/51] research(olr): document native Lean pair replay and independent certification gate --- .../OLR_01B_NATIVE_PREFLIGHT.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_01B_NATIVE_PREFLIGHT.md diff --git a/research/lean_cgrt_hrm400/OLR_01B_NATIVE_PREFLIGHT.md b/research/lean_cgrt_hrm400/OLR_01B_NATIVE_PREFLIGHT.md new file mode 100644 index 000000000..8f65493ee --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_01B_NATIVE_PREFLIGHT.md @@ -0,0 +1,58 @@ +# OLR-01B: Native paired Horn proof preflight + +**Date:** 2026-11-23 +**Status:** Completed verifier-integration preflight; this is **not a learned neural architecture result**. +**Parent:** [OLR architecture](OLR_01_OBLIGATION_LEDGER_RECURRENCE.md) and [investigation](OLR_01_INVESTIGATION.md). + +**Verified CI:** [native Lean workflow #45154630966](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45154630966), [CPU regression #45154631034](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45154631034). Both completed successfully. + +## Native experiment + +[ppt_gym/olr_native.py](ppt_gym/olr_native.py) generates four fresh pairs of propositional Horn worlds under seed 20261123. Each pair has identical primitive facts, target, two binary candidates, and mean incoming evidence cue (0.5). The grouping of premises within r0/r1 swaps across worlds, so the uniquely certifiable first action also swaps. Nuisance-chain length changes across pairs. + +A native Lean 4.19 REPL supplies every public goal, hypothesis, menu and tactic outcome. The scorer parses only the public Lean JSON with [ppt_gym/live_lean.py](ppt_gym/live_lean.py). The reference winner is reserved for outcome auditing. The correct branch needs one rule application and two fact discharges, with a three-tactic budget. Both branches initially make native progress. The wrong branch leaves unprovable prerequisites. + +The exact AND-OR ledger, a pooled-evidence fixed-tie policy, an edge-swapped structural sham, and forced-r0/forced-r1 references receive the same root menu and 3-tactic limit. Every attempt is replayed from a fresh native session and the successful ledger scripts are independently compiled and axiom-audited. + +## Verified scorecard + +| Arm | Kernel closures / 8 | Native tactic calls | +| --- | ---: | ---: | +| Hard AND-OR ledger | **8** | **24** | +| Pooled premise mean | 4 | 16 | +| Swapped premise-to-rule grouping | 0 | 8 | +| Forced r0 | 4 | 16 | +| Forced r1 | 4 | 16 | + +**Independent standalone Lean certificates:** 8/8. +**Native episode replays:** 40/40. +**Original root menu:** apply r0, apply r1 in every world. +**Pooled incoming premise cue:** 0.5 in both worlds. + +The GitHub Action job log prints the full scorecard and asserts all of these counts. The generated episode manifest and individual source receipts were retained in the CI workspace during the job; their SHA-256 values are reproducible with the checked-in runner. The job is an engineering preflight, not an independently held-out scientific confirmation. + +## What this proves and what remains uncertain + +Explicit hyperedge incidence contains information lost by an unstructured mean over incoming premise bits. The deterministic ledger recovers it and Lean verifies the selected proof scripts. This experiment has **zero learned parameters** and offers no evidence of neural-model gains over exact Horn planning. The proof-tree cost counts repeated dependencies individually; it can exceed the cost of DAG-style premise reuse. + +The public parser supports atomic propositional Horn expressions and chains of implications. It preserves pending Lean goals at the runner level but scores the focused one. Arithmetic or dependent hypotheses marked raw remain unknown. A structural fixed point is never promoted to a Lean kernel fact. + +## Next gate: OLR-01C computational applicability + +Freeze a new lineage-disjoint cohort of computationally conditional and dependent-type proof forks with paired opposite winners and independent certificates. Its public symbolic skeleton should admit both actions while their delayed proof guards differ. Any raw type must be scored as unknown until a real Lean response resolves its status. + +Train a small, weight-tied evidence/obligation cell with semantic applicability and successor-goal heads; compare with the current two-slot reward actor, a newly trained identical actor, a direct guard reader, head-only OLR, edge-shuffled OLR, a FLOP-matched ordinary tied loop, and exact symbolic controls. Separate forced-route proof completion from learned STOP/probe spending. Price every Lean and inference call, retain three or more independent seeds, and request an EvalMath FSI-01 sample/sham-floor preflight before a sealed confirmation. + +A prospective gain requires **additional Lean-certified completions at matched budgets** and a direction-specific causal response stronger than matched shams. Efficiency-only gains should be reported as such. + +## Run locally + +From research/lean_cgrt_hrm400 with the pinned Lean 4.19.0 REPL built: + +~~~sh +python -m unittest discover -s ppt_gym/tests -p "test_obligation_ledger*.py" -v +python -m unittest discover -s ppt_gym/tests -p "test_olr_native.py" -v +python -m ppt_gym.olr_native --seed 20261123 --pairs 4 --out runs/olr-01b-native +~~~ + +The output directory is create-only and contains the episode ledger, compiled standalone source, certificate receipt, and an artifact hash manifest. The native CI assertion is in [.github/workflows/ppt-g03-live-lean.yml](../../.github/workflows/ppt-g03-live-lean.yml). From 0e74b9729fee3501a0eb11a5a458dfaa043e2e52 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 18:21:17 +0800 Subject: [PATCH 12/51] docs(olr): index architecture and native Lean preflight in gym readme --- research/lean_cgrt_hrm400/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/research/lean_cgrt_hrm400/README.md b/research/lean_cgrt_hrm400/README.md index fcf40df68..db327c7fc 100644 --- a/research/lean_cgrt_hrm400/README.md +++ b/research/lean_cgrt_hrm400/README.md @@ -11,6 +11,7 @@ Start with these documents: - [PPT gyms: runnable Plan A/B, DataGoblin importer, DRAM accretion and replay](PPT_GYM_RUNBOOK.md): CPU PyTorch reference implementation, checked-data custody, support/query controls, synthetic smoke tests and CI. - [PPT-G03 live Lean search and verifier-checked data accretion](PPT_G03_RUNBOOK.md): native Lean 4.19 stepper, frozen theorem suites, independent compiled certificates, train-support DRAM updates and replay-gated export. - [PPT-G03B bounded backtracking gym](PPT_G03B_BACKTRACKING.md): saved Lean-state rollback on unprovable branches, separate tactic and host-cost accounting, and exact independent replay. +- [OLR-01 obligation ledger architecture](OLR_01_OBLIGATION_LEDGER_RECURRENCE.md), [novelty investigation](OLR_01_INVESTIGATION.md) and [native Lean paired-proof preflight](OLR_01B_NATIVE_PREFLIGHT.md): exact AND-OR structural baseline, 8/8 kernel closures on 4 paired toy graphs, and the proposed computational-guard learning gate. Prototype is not trained. - [`LOCAL_SCALING_RESULTS.md`](LOCAL_SCALING_RESULTS.md): campaign c1, Lean-certified results; - [`SILICO_400M_HANDOFF.md`](SILICO_400M_HANDOFF.md): decision and ready-to-run 400M specs. - [`RLT_ABLATION_MATRIX.md`](RLT_ABLATION_MATRIX.md): RLT-01 feedback controls and Q5 transfer caveats; [completed two-lane pilot results](results/rlt01/RLT-comparison.md) found no RLT-specific Lean completion gain. From 69e7699a8b022d3db61b058ffc7678b30ae9d6ec Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:37:40 +0800 Subject: [PATCH 13/51] feat(olr): collect paired arithmetic guard outcomes from native Lean and certify scripts --- .../lean_cgrt_hrm400/ppt_gym/olr_guards.py | 292 ++++++++++++++++++ 1 file changed, 292 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/olr_guards.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_guards.py b/research/lean_cgrt_hrm400/ppt_gym/olr_guards.py new file mode 100644 index 000000000..0e477bf5c --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_guards.py @@ -0,0 +1,292 @@ +"""OLR-01C: paired computational-guard Lean theorem collector. + +The true/false status of each candidate is obtained from a *real* Lean tactic +and kernel response. Source-only structural metadata may verify results but +must never enter model features. This is a small CPU research gym. +""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import json +import random +import re +import subprocess +import tempfile +from pathlib import Path + +from lcgrt import config +from lcgrt.lean_repl import LeanRepl +from .data import canonical, digest, sha256_file +from .live_lean import public_state, candidate_menu + +SCHEMA = "ppt.olr-guard-native.v1" +RAW_SUM = re.compile(r"^\s*\(?\s*(\d+)\s*\+\s*(\d+)\s*=\s*(\d+)\s*\)?\s*$") +VALID_TACTIC = re.compile(r"^apply r[01]$") + + +@dataclass(frozen=True) +class GuardPair: + split: str + pair_id: str + a: int + b: int + true_sum: int + false_sum: int + # Witness is generator-private and may only be used for audits. + delta: int + + def world(self, bit: int): + if bit not in (0, 1): + raise ValueError("paired world bit must be 0 or 1") + targets = (self.true_sum, self.false_sum) if bit == 0 else (self.false_sum, self.true_sum) + return GuardWorld(self.split, self.pair_id, bit, self.a, self.b, targets) + + +@dataclass(frozen=True) +class GuardWorld: + split: str + pair_id: str + world: int + a: int + b: int + targets: tuple[int, int] + + def binders(self): + x, y = self.targets + return f"(P : Prop) (r0 : ({self.a} + {self.b} = {x}) → P) (r1 : ({self.a} + {self.b} = {y}) → P)" + + def statement(self): + return "∀ " + self.binders() + ", P" + + def reference_action(self): + # Private registration audit; never supplied to a policy. + return "apply r0" if self.world == 0 else "apply r1" + + +def generate_pairs(split: str, seed: int, count: int, *, low: int, high: int): + """Create unique arithmetic lineages in a declared operand range.""" + if not (0 <= low <= high <= 40 and 1 <= count <= 1024): + raise ValueError("invalid bounded arithmetic sample") + if split not in ("train", "dev", "ood"): + raise ValueError("split must be train, dev or ood") + rng = random.Random(f"olr-guard-v1/{seed}/{split}/{low}/{high}") + used, out = set(), [] + for i in range(count): + for attempt in range(500): + a, b = rng.randint(low, high), rng.randint(low, high) + delta = rng.choice((-3, -2, -1, 1, 2, 3)) + if a+b+delta < 0 or (a, b, delta) in used: + continue + used.add((a,b,delta)) + break + else: + raise ValueError("insufficient distinct operand/offset pairs") + pair_id = digest(["olr-guard-v1", split, seed, a, b, delta]) + out.append(GuardPair(split, pair_id, a, b, a+b, a+b+delta, delta)) + return tuple(out) + + +def read_raw_guards(visible: dict, menu: tuple[str, ...]): + """Extract predecision candidate text *only* from public Lean JSON. + + All equality truth labels must come from native Lean, not Python arithmetic. + """ + goals = visible.get("goals") + if not isinstance(goals, list) or len(goals) != 1: + raise ValueError("expected exactly one public root Lean goal") + hyps = goals[0].get("hypotheses") + if not isinstance(hyps, list): + raise ValueError("missing public Lean hypotheses") + types = {h.get("name"): h.get("type") for h in hyps if isinstance(h, dict)} + guards = [] + for action in menu: + if not VALID_TACTIC.fullmatch(action): + raise ValueError("registered candidate outside r0/r1 menu") + ty = types.get(action.split()[1]) + if not isinstance(ty, dict) or set(ty) != {"imp"}: + raise ValueError("candidate does not have a one-premise implication") + parts = ty["imp"] + if (not isinstance(parts, list) or len(parts) != 2 or + not isinstance(parts[0], dict) or not isinstance(parts[1], dict) or + not isinstance(parts[0].get("raw"), str) or parts[1] != goals[0]["target"]): + raise ValueError("computational guard missing from native public view") + guards.append(parts[0]["raw"]) + return tuple(guards) + + +def numeric_features(raw: str) -> tuple[float, float, float]: + """Extract individual public numerals without evaluating the predicate.""" + match = RAW_SUM.fullmatch(raw) + if match is None: + raise ValueError(f"unrecognized public equality guard: {raw[:120]!r}") + a, b, c = (int(x) for x in match.groups()) + if max(a,b,c) > 100: + raise ValueError("numerals exceed the preregistered range") + return (a / 40., b / 40., c / 80.) + + +def proof_attempt(lean: LeanRepl, world: GuardWorld, tactic: str): + """Spend one root rule application and at most one rfl guard check.""" + if not VALID_TACTIC.fullmatch(tactic): + raise ValueError("invalid native guard tactic") + lean.reset() + state = lean.init(world.statement(), pp=True) + visible = public_state(lean, state) + menu = candidate_menu(lean, state) + if menu != ("apply r0", "apply r1"): + raise ValueError(f"unmatched public root menu: {menu}") + guards = read_raw_guards(visible, menu) + vectors = tuple(numeric_features(g) for g in guards) + root = lean.run(state["sid"], tactic) + if root.get("ok") is not True: + raise ValueError("registered root tactic rejected by Lean") + after = public_state(lean, root["state"]) + if len(after["goals"]) != 1: + raise ValueError("root must create exactly one arithmetic subgoal") + try_guard = lean.run(root["state"]["sid"], "rfl") + success = False + kernel = None + if try_guard.get("ok") is True: + new = public_state(lean, try_guard["state"]) + if new["goals"]: + raise ValueError("rfl unexpectedly left another goal") + kernel = lean.kernel(try_guard["state"]["sid"]) + success = kernel.get("ok") is True and kernel.get("axioms") == [] + if not success: + raise ValueError("Lean closed without clean kernel certificate") + return { + "action": tactic, + "public_state_sha256": digest(visible), + "menu": list(menu), "raw_guards": list(guards), + "numeric_features": [list(v) for v in vectors], + "root_status": "accepted_nonterminal", + "guard_status": "kernel_closed" if success else "rfl_rejected", + "guard_goal_sha256": digest(after), + "kernel_ok": success, + "native_tactic_calls": 2, + "script": [tactic, "rfl"] if success else [tactic], + } + + +def collect_pair(lean: LeanRepl, pair: GuardPair): + """Both candidate outcomes are checked *before* source examples are fitted.""" + items = [] + for bit in (0, 1): + world = pair.world(bit) + outcomes = [proof_attempt(lean, world, action) + for action in ("apply r0", "apply r1")] + labels = [int(x["kernel_ok"]) for x in outcomes] + if (labels.count(1) != 1 or + outcomes[0]["numeric_features"] != outcomes[1]["numeric_features"] or + outcomes[0]["raw_guards"] != outcomes[1]["raw_guards"]): + raise ValueError("native verdict, inputs, or source label mismatch") + if ("apply r" + str(labels.index(1))) != world.reference_action(): + raise ValueError("native proof disagrees with source registration") + items.append({ + "root": digest(world.statement()), "pair_id": world.pair_id, + "split": pair.split, "world": bit, + "statement": world.statement(), + "source": outcomes[0]["public_state_sha256"], + "menu": outcomes[0]["menu"], + "raw_guards": outcomes[0]["raw_guards"], + "features": outcomes[0]["numeric_features"], + "labels": labels, "attempts": outcomes, + "reference_proof": outcomes[labels.index(1)]["script"], + "tactic_budget": 2, + }) + if items[0]["root"] == items[1]["root"]: + raise ValueError("pair worlds became identical") + return tuple(items) + + +def certified_standalone(rows: list[dict], out: Path): + """Independent Lean compiler for the narrow apply-r0/r1 + rfl grammar.""" + lines = ["namespace OLRGuardNative"] + names = [] + for index, row in enumerate(rows): + script = row["reference_proof"] + if (len(script) != 2 or not VALID_TACTIC.fullmatch(script[0]) + or script[1] != "rfl"): + raise ValueError("unsafe native proof script") + # All parameters are frozen integers and generated from our closed grammar. + name = f"g_{index}" + stmt = row["statement"] + if not re.fullmatch(r"∀ \(P : Prop\) \(r0 : \(\d+ \+ \d+ = \d+\) → P\) \(r1 : \(\d+ \+ \d+ = \d+\) → P\), P",stmt): + raise ValueError("unsafe source declaration") + # Standalone theorem statement includes a closed binder list. + binders = stmt[2:-3] # remove leading '∀ ' and trailing ', P' + lines.extend([f"theorem {name} {binders} : P := by", + f" {script[0]}", " rfl"]) + names.append(name) + lines.append("end OLRGuardNative") + lines.extend(f"#print axioms OLRGuardNative.{name}" for name in names) + source = "\n".join(lines) + "\n" + out.write_text(source, encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "OLRGuard.lean" + path.write_text(source, encoding="utf-8") + result = subprocess.run([str(config.LEAN_EXE), str(path)], env=config.lean_env(), + capture_output=True, text=True, encoding="utf-8", + timeout=180, check=False) + text = result.stdout + result.stderr + clean = sum(f"'OLRGuardNative.{name}' does not depend on any axioms" in text + for name in names) + if result.returncode != 0 or clean != len(names): + raise ValueError(f"standalone guard proofs rejected: rc={result.returncode}, clean={clean}/{len(names)}; {text[-1000:]}") + return {"compiled":len(names),"clean_axioms":clean,"source_sha256":sha256_file(out)} + + +def freeze(seed: int, train: int, dev: int, out: Path, *, ood: int = 0): + """Freeze a complete source/held-out verifier bank with separate lineages.""" + if out.exists(): + raise ValueError("output directory must be fresh") + train_pairs = generate_pairs("train", seed, train, low=0, high=8) + dev_pairs = generate_pairs("dev", seed+7, dev, low=0, high=8) + ood_pairs = generate_pairs("ood", seed+13, ood, low=9, high=16) if ood else () + # Scope together all raw arithmetic shapes, regardless of name/order. + all_pairs = (*train_pairs,*dev_pairs,*ood_pairs) + seen = [(p.a,p.b,p.delta) for p in all_pairs] + if len(set(seen)) != len(seen): + raise ValueError("source and evaluation arithmetic lineages overlap") + rows: dict[str,list] = {"train":[],"dev":[],"ood":[]} + with LeanRepl(timeout=60) as lean: + if not str(lean.version).startswith("4.19.0"): + raise ValueError("pinned native Lean 4.19.0 required") + version = lean.version + for pair in all_pairs: + rows[pair.split].extend(collect_pair(lean,pair)) + out.mkdir(parents=True) + for split, shard in rows.items(): + (out/f"{split}.jsonl").write_text( + "".join(canonical(r)+"\n" for r in shard),encoding="utf-8") + compiled = certified_standalone([row for s in rows.values() for row in s], + out/"standalone.lean") + manifest = { + "schema":SCHEMA, "seed":seed, "lean_version":version, + "lean_exe_sha256":sha256_file(config.LEAN_EXE), + "repl_exe_sha256":sha256_file(config.REPL_EXE), + "source_not_heldout":True, "model_training_uses_train_split_only":True, + "independent_certificates":compiled, + "splits":{s:{"pairs":len(shard)//2, "worlds":len(shard), + "sha256":sha256_file(out/f"{s}.jsonl")} for s,shard in rows.items()}, + "learning_status":"untrained_native_bank", + "scientific_scope":"arithmetic_guard_smoke_not_external_mathlib", + } + (out/"manifest.json").write_text(canonical(manifest)+"\n",encoding="utf-8") + return manifest + + +def main(argv=None): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument("--seed",type=int,default=20261123) + p.add_argument("--train",type=int,default=12) + p.add_argument("--dev",type=int,default=4) + p.add_argument("--ood",type=int,default=0) + p.add_argument("--out",type=Path,required=True) + x=p.parse_args(argv) + print(canonical(freeze(x.seed,x.train,x.dev,x.out,ood=x.ood))) + + +if __name__=="__main__": + main() From d17709a0fe676b691b6c30df5e226b9ea944ce43 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:38:07 +0800 Subject: [PATCH 14/51] test(olr): guard pair swaps and native-public numeral feature custody --- .../ppt_gym/tests/test_olr_guards.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_guards.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_guards.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_guards.py new file mode 100644 index 000000000..ea3a6b566 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_guards.py @@ -0,0 +1,50 @@ +"""OLR-01C computational guard: source custody and public-feature unit tests.""" +import unittest +from ppt_gym.olr_guards import ( + generate_pairs, read_raw_guards, numeric_features, GuardPair, RAW_SUM, +) + + +class OLRGuardUnitTests(unittest.TestCase): + def test_pair_swaps_the_legal_root_action(self): + p = generate_pairs("train", 20261123, 4, low=0, high=8) + self.assertEqual(len({x.pair_id for x in p}), 4) + for item in p: + a, b = item.world(0), item.world(1) + self.assertNotEqual(a.statement(), b.statement()) + self.assertEqual(a.reference_action(), "apply r0") + self.assertEqual(b.reference_action(), "apply r1") + self.assertEqual(a.targets, b.targets[::-1]) + self.assertEqual(item.true_sum, item.a + item.b) + self.assertNotEqual(item.true_sum, item.false_sum) + + def test_numeric_features_take_only_uncomputed_public_operands(self): + self.assertEqual(numeric_features("3 + 4 = 7"), (3/40,4/40,7/80)) + self.assertEqual(numeric_features("(3 + 4 = 7)"), (3/40,4/40,7/80)) + self.assertIsNone(RAW_SUM.fullmatch("True")) + self.assertIsNone(RAW_SUM.fullmatch("3 * 4 = 12")) + with self.assertRaises(ValueError): + numeric_features("3 + 4 = 999") + + def test_native_public_json_required_and_no_reference_feature(self): + goal = {"target": {"a": "P"}, "hypotheses": [ + {"name":"r0","type":{"imp":[{"raw":"3 + 4 = 7"},{"a":"P"}]}}, + {"name":"r1","type":{"imp":[{"raw":"3 + 4 = 8"},{"a":"P"}]}}, + ]} + self.assertEqual(read_raw_guards({"goals":[goal]},("apply r0","apply r1")), + ("3 + 4 = 7","3 + 4 = 8")) + goal["hypotheses"][0]["type"]={"imp":[{"true":None},{"a":"P"}]} + with self.assertRaises(ValueError): + read_raw_guards({"goals":[goal]},("apply r0","apply r1")) + + def test_generation_fails_for_unbounded_request(self): + with self.assertRaises(ValueError): + generate_pairs("train", 1, 0, low=0, high=8) + with self.assertRaises(ValueError): + generate_pairs("train", 1, 1, low=0, high=100) + with self.assertRaises(ValueError): + GuardPair("train","x",1,1,2,3,1).world(2) + + +if __name__ == "__main__": + unittest.main() From ef264857db62bb0a0348ec774b0df8c0d04ade8b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:38:18 +0800 Subject: [PATCH 15/51] ci(olr): require native arithmetic-guard candidate outcomes and axiom-free certificates --- .github/workflows/ppt-g03-live-lean.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index 42fb9a187..64ed815d7 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -123,6 +123,18 @@ jobs: assert m["architecture_promotion_eligible"] is False print("OLR-01B real Lean paired proof and replay preflight", m["scorecard"]) PY + - name: OLR-01C arithmetic-guard native bank + working-directory: research/lean_cgrt_hrm400 + run: | + python -m ppt_gym.olr_guards --seed 20261123 --train 3 --dev 2 --out runs/olr-01c-native + python - <<'PY' + import json + m=json.load(open("runs/olr-01c-native/manifest.json",encoding="utf-8")) + assert m["independent_certificates"]["compiled"]==10, m + assert m["independent_certificates"]["clean_axioms"]==10, m + assert m["splits"]["train"]["worlds"]==6 and m["splits"]["dev"]["worlds"]==4, m + print("OLR native arithmetic-guard source bank certified",m["independent_certificates"]) + PY - name: Fresh generated Lean suite and model smoke working-directory: research/lean_cgrt_hrm400 env: From 99e5a2591c31d38cc9740e557662680cbf4381c3 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:39:19 +0800 Subject: [PATCH 16/51] feat(olr): add tied recurrent guard scorer with isolated and direct controls --- .../ppt_gym/olr_guard_model.py | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/olr_guard_model.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_guard_model.py b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_model.py new file mode 100644 index 000000000..5deee92a5 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_model.py @@ -0,0 +1,91 @@ +"""Tiny trainable OLR guard-scoring reference and equally informed controls. + +This is a developmental two-candidate policy for native Lean arithmetic guards. +A learned score never certifies a guard; Lean is still the sole proof authority. +""" +from __future__ import annotations + +import torch +from torch import nn +from torch.nn import functional as F + + +class GuardScorer(nn.Module): + """Tied message-passing scorer over two candidate obligations. + + Input: (B, 2, 3) with separately visible numerals [lhs_a,lhs_b,rhs]. + No arithmetic relation, winning action, verifier label, or reference script + is precomputed for the learned feature channel. + + mode=cross: previous-pass opposite candidate message is available; + mode=isolated: message input is zeroed but *same parameters* are used. + mode=direct: no recurrence (diagnostic lower-compute control). + + The evidence readout is initialized to 'unknown' at a new proof root. + Status updates from a live verifier are a future separate experiment. + """ + + def __init__(self, width: int = 32, *, mode: str = "cross"): + super().__init__() + if width < 8 or width > 128 or mode not in ("cross", "isolated", "direct"): + raise ValueError("invalid guard architecture") + self.width, self.mode = width, mode + self.embed = nn.Sequential(nn.Linear(3, width), nn.GELU(), + nn.Linear(width, width), nn.LayerNorm(width)) + self.role = nn.Parameter(torch.zeros(1, 2, width)) + self.unknown_evidence = nn.Parameter(torch.zeros(1, 1, width)) + self.core = nn.Sequential(nn.Linear(4*width, 2*width), nn.Tanh(), + nn.Linear(2*width, width)) + self.gate = nn.Linear(4*width, width) + self.norm = nn.LayerNorm(width) + self.head = nn.Sequential(nn.Linear(2*width, width), nn.GELU(), + nn.Linear(width, 1)) + + def forward(self, x: torch.Tensor, *, depth: int = 3, + return_states: bool = False): + if x.ndim != 3 or x.shape[1:] != (2, 3) or not 1 <= depth <= 16: + raise ValueError("features must be B x 2 x 3 and depth 1..16") + context = self.embed(x) + slots = context + self.role + states = [] + for _ in range(depth if self.mode != "direct" else 0): + other = slots.flip(1) if self.mode == "cross" else torch.zeros_like(slots) + evidence = self.unknown_evidence.expand_as(slots) + packets = torch.cat((context, slots, other, evidence), -1) + proposal = self.core(packets) + gate = torch.sigmoid(self.gate(packets)) + slots = self.norm(slots + .25 * gate * proposal) + states.append(slots) + logits = self.head(torch.cat((context, slots), -1)).squeeze(-1) + return (logits, states) if return_states else logits + + def parameter_count(self) -> int: + return sum(p.numel() for p in self.parameters()) + + +def ranking_loss(logits: torch.Tensor, labels: torch.Tensor): + if logits.ndim != 2 or logits.shape[-1] != 2 or labels.shape != logits.shape: + raise ValueError("malformed paired tactic ranking batch") + if not bool((labels.sum(-1) == 1).all()): + raise ValueError("native training pairs must contain exactly one completed proof") + return F.cross_entropy(logits, labels.argmax(-1)) + + +def choose(model: GuardScorer, features, *, depth: int = 3) -> int: + """Only a public feature packet, never a target label, is model-visible.""" + with torch.no_grad(): + batch = torch.as_tensor(features, dtype=torch.float32).reshape(1, 2, 3) + return int(model(batch, depth=depth)[0].argmax().item()) + + +def exact_arithmetic_reference(features) -> int: + """Explicit host arithmetic oracle for a strict best-possible comparator. + + This control deliberately has access to the exact '+' semantics. It must + never be presented as an OLR learned effect. + """ + for i, row in enumerate(features): + a, b, target = row + if abs(40*a + 40*b - 80*target) < 1e-5: + return i + raise ValueError("no provable candidate in the exact arithmetic reference") From 60e13c13737fab6018a541c04cc913053111b750 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:40:10 +0800 Subject: [PATCH 17/51] fix(olr): exclude source arithmetic lineages from dev sampling --- research/lean_cgrt_hrm400/ppt_gym/olr_guards.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_guards.py b/research/lean_cgrt_hrm400/ppt_gym/olr_guards.py index 0e477bf5c..ad1aaace6 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/olr_guards.py +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_guards.py @@ -64,7 +64,8 @@ def reference_action(self): return "apply r0" if self.world == 0 else "apply r1" -def generate_pairs(split: str, seed: int, count: int, *, low: int, high: int): +def generate_pairs(split: str, seed: int, count: int, *, low: int, high: int, + exclude: frozenset[tuple[int, int, int]] = frozenset()): """Create unique arithmetic lineages in a declared operand range.""" if not (0 <= low <= high <= 40 and 1 <= count <= 1024): raise ValueError("invalid bounded arithmetic sample") @@ -76,7 +77,7 @@ def generate_pairs(split: str, seed: int, count: int, *, low: int, high: int): for attempt in range(500): a, b = rng.randint(low, high), rng.randint(low, high) delta = rng.choice((-3, -2, -1, 1, 2, 3)) - if a+b+delta < 0 or (a, b, delta) in used: + if a+b+delta < 0 or (a, b, delta) in used or (a, b, delta) in exclude: continue used.add((a,b,delta)) break @@ -242,7 +243,8 @@ def freeze(seed: int, train: int, dev: int, out: Path, *, ood: int = 0): if out.exists(): raise ValueError("output directory must be fresh") train_pairs = generate_pairs("train", seed, train, low=0, high=8) - dev_pairs = generate_pairs("dev", seed+7, dev, low=0, high=8) + seen_train = frozenset((p.a, p.b, p.delta) for p in train_pairs) + dev_pairs = generate_pairs("dev", seed+7, dev, low=0, high=8, exclude=seen_train) ood_pairs = generate_pairs("ood", seed+13, ood, low=9, high=16) if ood else () # Scope together all raw arithmetic shapes, regardless of name/order. all_pairs = (*train_pairs,*dev_pairs,*ood_pairs) From 268b410165d1726652da05d992bf83e9c2ca9483 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:41:17 +0800 Subject: [PATCH 18/51] feat(olr): train tied/isolated/direct guard scorers on native source receipts and evaluate fresh Lean proofs --- .../lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py | 278 ++++++++++++++++++ 1 file changed, 278 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py new file mode 100644 index 000000000..301512e2f --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py @@ -0,0 +1,278 @@ +"""OLR-01C: train/evaluate tiny guard scorers on native Lean source labels. + +This is an exploratory source-only training pilot. Same-structure paired worlds +share a root lineage. Only source ('train') outcomes may update model weights; +all development and OOD predictions are made before their native replay. +""" +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import random +import re +import time +from pathlib import Path + +import torch + +from lcgrt.lean_repl import LeanRepl +from .data import canonical, digest, sha256_file +from .olr_guards import SCHEMA as SOURCE_SCHEMA, GuardWorld, certified_standalone, proof_attempt +from .olr_guard_model import GuardScorer, ranking_loss, choose, exact_arithmetic_reference + +SCHEMA = "ppt.olr-guard-fit.v1" +SEED_ROSTER = (17, 29, 43) +ARMS = ("cross", "isolated", "direct", "frozen_cross") +CONTROLS = ("fixed_r0", "exact_arithmetic") +STMT = re.compile( + r"^∀ \(P : Prop\) \(r0 : \((\d+) \+ (\d+) = (\d+)\) → P\) " + r"\(r1 : \((\d+) \+ (\d+) = (\d+)\) → P\), P$" +) + + +def load_bank(directory: Path): + manifest=json.loads((directory/"manifest.json").read_text(encoding="utf-8")) + if manifest.get("schema") != SOURCE_SCHEMA or manifest.get("model_training_uses_train_split_only") is not True: + raise ValueError("not a verifier-grounded OLR source bank") + shards = {} + for split in ("train", "dev", "ood"): + info=manifest["splits"][split] + path=directory/(split+".jsonl") + if sha256_file(path)!=info["sha256"]: + raise ValueError("tampered native source shard") + rows=[json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + if len(rows) != info["worlds"]: + raise ValueError("native bank lost a world") + shards[split]=rows + source = {r["pair_id"] for r in shards["train"]} + if any(r["pair_id"] in source for split in ("dev", "ood") for r in shards[split]): + raise ValueError("source lineage leaked into evaluation") + ids = [r["root"] for rows in shards.values() for r in rows] + if len(ids) != len(set(ids)): + raise ValueError("duplicate theorem root across splits") + for split,rows in shards.items(): + grouped=defaultdict(list) + for r in rows: + grouped[r["pair_id"]].append(r) + if (r["split"] != split or len(r["menu"]) != 2 or + r["menu"] != ["apply r0","apply r1"] or + len(r["features"]) != 2 or r["labels"] not in ([1,0],[0,1])): + raise ValueError("invalid source root / candidate label") + if len(r["attempts"]) != 2 or sum(a["kernel_ok"] for a in r["attempts"]) != 1: + raise ValueError("missing native proof receipts") + if any(sorted(r["world"] for r in group) != [0,1] + for group in grouped.values()): + raise ValueError("unpaired worlds in registered root family") + return manifest,shards + + +def reconstruct(row: dict): + """Reconstruction for native theorem execution, outside model input.""" + match=STMT.fullmatch(row["statement"]) + if match is None: + raise ValueError("unrecognized bounded guard statement") + a,b,c,d,e,f=map(int,match.groups()) + if (a,b)!=(d,e): + raise ValueError("root guard operands disagree") + return GuardWorld(row["split"],row["pair_id"],row["world"],a,b,(c,f)) + + +def tensors(rows): + x=torch.tensor([r["features"] for r in rows],dtype=torch.float32) + y=torch.tensor([r["labels"] for r in rows],dtype=torch.float32) + if x.shape!=(len(rows),2,3) or y.shape!=(len(rows),2): + raise ValueError("invalid source candidate tensor") + return x,y + + +def fit(rows: list[dict], *, seed: int, arm: str, + steps: int, depth: int, width: int): + if arm not in ARMS or not 1 <= steps <= 5000: + raise ValueError("unsupported fitted arm or step count") + torch.manual_seed(seed) + mode = "cross" if arm == "frozen_cross" else arm + model=GuardScorer(width=width, mode=mode) + if arm == "frozen_cross": + # Source encoder and readout train; the tied recurrence itself stays + # at its seed-initialized values. A stronger readout-only control. + for name,param in model.named_parameters(): + if name.startswith(("core.","gate.","norm.","unknown_evidence")): + param.requires_grad_(False) + model.train() + optimizer=torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), + lr=.003,weight_decay=.005) + x,y=tensors(rows) + # Same minibatch stream, seed and source ordering across all arms. + rng=torch.Generator().manual_seed(seed+7000) + batches=torch.randint(len(rows),(steps,min(32,len(rows))),generator=rng) + first_loss=last_loss=0. + for t,ind in enumerate(batches): + pred=model(x[ind],depth=depth) + loss=ranking_loss(pred,y[ind]) + if not torch.isfinite(loss): + raise FloatingPointError("nonfinite OLR reward-model loss") + if t==0: + first_loss=float(loss.detach()) + optimizer.zero_grad() + loss.backward() + torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad], + 1.,error_if_nonfinite=True) + optimizer.step() + last_loss=float(loss.detach()) + model.eval() + train_correct=0 + with torch.no_grad(): + for row in rows: + train_correct+=choose(model,row["features"],depth=depth)==row["labels"].index(1) + return model, { + "seed":seed,"arm":arm,"mode":mode, + "steps":steps,"depth":depth,"width":width, + "parameters":model.parameter_count(), + "trained_parameters":sum(p.numel() for p in model.parameters() if p.requires_grad), + "first_loss":first_loss,"last_loss":last_loss, + "source_correct":train_correct,"source_worlds":len(rows), + } + + +def evaluate(lean: LeanRepl, rows: list[dict], models: dict[tuple,int], + *, depth: int, split: str): + """Choose without labels and execute each selected tactic on a new Lean root.""" + output=[] + for row in rows: + world=reconstruct(row) + controls={ + "fixed_r0":0, + "exact_arithmetic":exact_arithmetic_reference(row["features"]), + } + actions={} + for (seed,arm),model in models.items(): + actions[(seed,arm)]=choose(model,row["features"],depth=depth) + for arm,index in controls.items(): + actions[(0,arm)]=index + # Deduplicate *identical native action requests* within a root to + # make CI cheaper. Every selected action has a new live Lean witness; + # artifact records retain which policy reused that checked outcome. + native = {} + for index in set(actions.values()): + outcome=proof_attempt(lean,world,"apply r"+str(index)) + if (outcome["numeric_features"]!=row["features"] or + outcome["public_state_sha256"]!=row["source"] or + int(outcome["kernel_ok"])!=row["labels"][index]): + raise ValueError("evaluation tactic outcomes or public inputs drifted") + native[index]=outcome + for (seed,arm),index in actions.items(): + outcome=native[index] + output.append({ + "seed":seed,"arm":arm,"split":split,"root":row["root"], + "pair_id":row["pair_id"],"world":row["world"], + "action":"apply r"+str(index),"kernel_closed":outcome["kernel_ok"], + "native_tactic_calls":outcome["native_tactic_calls"], + "native_result_sha256":digest(outcome), + }) + return output + + +def scores(records): + groups=defaultdict(list) + for r in records: + groups[(r["split"],r["seed"],r["arm"])].append(r) + report={} + for (split,seed,arm),rows in groups.items(): + bypair=defaultdict(list) + for r in rows: + bypair[r["pair_id"]].append(r) + if any(len(v)!=2 or sorted(x["world"] for x in v)!=[0,1] + for v in bypair.values()): + raise ValueError("paired evaluation lost a root") + key=f"{split}:{seed}:{arm}" + report[key]={ + "worlds":len(rows), "pairs":len(bypair), + "proofs":sum(int(x["kernel_closed"]) for x in rows), + "complete_pairs":sum(all(x["kernel_closed"] for x in v) + for v in bypair.values()), + "native_tactic_calls":sum(x["native_tactic_calls"] for x in rows), + } + return report + + +def run(bank: Path, out: Path, *, steps: int, depth: int, + width: int, seeds: tuple[int,...], max_seconds: float = 900.): + if out.exists() or not seeds or len(set(seeds)) != len(seeds): + raise ValueError("fresh output and unique model seeds required") + if not 1 <= depth <= 16 or not 8 <= width <= 128: + raise ValueError("invalid bounded recurrent architecture") + torch.set_num_threads(1) + start=time.perf_counter() + source,shards=load_bank(bank) + train=shards["train"] + models={} + training={} + for seed in seeds: + for arm in ARMS: + model,receipt=fit(train,seed=seed,arm=arm,steps=steps,depth=depth,width=width) + models[(seed,arm)]=model + training[f"{seed}:{arm}"]=receipt + if time.perf_counter()-start>max_seconds: + raise TimeoutError("bounded CPU training budget exhausted") + # All query labels are source-file data used solely for postchoice checks. + scores_by_shard={} + records=[] + with LeanRepl(timeout=60) as lean: + for split in ("dev","ood"): + rows=shards[split] + if not rows: + continue + records.extend(evaluate(lean,rows,models,depth=depth,split=split)) + score=scores(records) + # Recompile exactly those distinct query declarations which some policy + # closed. The generator's reference proof is excluded from model input. + passed = {(r["root"],r["action"]) for r in records if r["kernel_closed"]} + certified=[] + for split in ("dev","ood"): + for row in shards[split]: + for action in ("apply r0","apply r1"): + if (row["root"],action) in passed: + certified.append({**row,"reference_proof":[action,"rfl"]}) + out.mkdir(parents=True) + proof_receipt=certified_standalone(certified,out/"standalone.lean") + with (out/"models.pt").open("xb") as stream: + torch.save({f"{s}:{arm}":model.state_dict() + for (s,arm),model in models.items()},stream) + (out/"decisions.jsonl").write_text( + "".join(canonical(r)+"\n" for r in records),encoding="utf-8") + receipt={ + "schema":SCHEMA,"source_manifest_sha256":sha256_file(bank/"manifest.json"), + "source_lean_sha256":source["lean_exe_sha256"], + "seed_roster":list(seeds),"training":training,"evaluation":score, + "new_native_query_choices":len(records), + "native_query_replays":sum(len({r["action"] for r in records if r["root"]==x["root"]}) + for x in shards["dev"]+shards["ood"]), + "independent_query_certificates":proof_receipt, + "architecture_promotion_eligible":False, + "training_classification":"native-source-labelled_CPU_research_pilot", + "runtime_seconds":round(time.perf_counter()-start,3), + "model_causal_evidence":"none; next-stage comparison requires prospective matched compute and sham", + } + receipt["artifacts"]={name:sha256_file(out/name) + for name in ("models.pt","decisions.jsonl","standalone.lean")} + (out/"manifest.json").write_text(canonical(receipt)+"\n",encoding="utf-8") + return receipt + + +def main(argv=None): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument("--bank",type=Path,required=True) + p.add_argument("--out",type=Path,required=True) + p.add_argument("--steps",type=int,default=100) + p.add_argument("--depth",type=int,default=3) + p.add_argument("--width",type=int,default=32) + p.add_argument("--seeds",type=int,nargs="+",default=list(SEED_ROSTER)) + p.add_argument("--max-seconds",type=float,default=900.) + a=p.parse_args(argv) + print(canonical(run(a.bank,a.out,steps=a.steps,depth=a.depth, + width=a.width,seeds=tuple(a.seeds),max_seconds=a.max_seconds))) + + +if __name__=="__main__": + main() From 1053ed3e3a1f0774de04c861788a080c0d19eb28 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:42:11 +0800 Subject: [PATCH 19/51] test(olr): exercise recurrent gradients, shared-seed controls and native-label guards --- .../ppt_gym/tests/test_olr_guard_model.py | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_guard_model.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_guard_model.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_guard_model.py new file mode 100644 index 000000000..b63df8215 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_guard_model.py @@ -0,0 +1,72 @@ +"""OLR-01C trainable recurrence and matched-message controls.""" +import unittest + +import torch + +from ppt_gym.olr_guard_model import ( + GuardScorer, ranking_loss, choose, exact_arithmetic_reference, +) +from ppt_gym.olr_guard_fit import fit + + +class OLRGuardLearningTests(unittest.TestCase): + def setUp(self): + torch.manual_seed(42) + torch.set_num_threads(1) + # Public operands: 2+3=5 vs 2+3=6, then opposite order. + self.features = [ + [[2/40,3/40,5/80],[2/40,3/40,6/80]], + [[2/40,3/40,6/80],[2/40,3/40,5/80]], + ] + self.rows = [ + {"features":self.features[0],"labels":[1,0]}, + {"features":self.features[1],"labels":[0,1]}, + ] + + def test_exact_arithmetic_oracle_and_pair_flip(self): + self.assertEqual(exact_arithmetic_reference(self.features[0]),0) + self.assertEqual(exact_arithmetic_reference(self.features[1]),1) + with self.assertRaises(ValueError): + exact_arithmetic_reference([[0,0,1],[0,0,2]]) + + def test_recurrence_is_differentiable_at_all_message_depths(self): + x = torch.tensor(self.features,dtype=torch.float32) + labels=torch.tensor([[1.,0.],[0.,1.]]) + for mode in ("cross","isolated","direct"): + model=GuardScorer(width=16,mode=mode) + logits,states=model(x,depth=4,return_states=True) + self.assertEqual(tuple(logits.shape),(2,2)) + self.assertEqual(len(states),0 if mode=="direct" else 4) + loss=ranking_loss(logits,labels) + loss.backward() + self.assertIsNotNone(model.embed[0].weight.grad) + self.assertTrue(torch.isfinite(model.embed[0].weight.grad).all()) + with self.assertRaises(ValueError): + GuardScorer(mode="unrecognized") + + def test_label_custody_rejects_ambiguous_feedback(self): + model=GuardScorer(width=16) + logits=model(torch.tensor(self.features,dtype=torch.float32)) + with self.assertRaises(ValueError): + ranking_loss(logits,torch.tensor([[1.,1.],[0.,1.]])) + with self.assertRaises(ValueError): + model(torch.ones(1,4,3)) + + def test_source_training_is_deterministic_and_frozen_body_stays_frozen(self): + model, receipt=fit(self.rows,seed=17,arm="cross",steps=8,depth=2,width=16) + self.assertEqual(receipt["source_worlds"],2) + self.assertEqual(receipt["seed"],17) + self.assertTrue(0 <= receipt["source_correct"] <= 2) + self.assertGreater(receipt["parameters"],0) + self.assertEqual(model(torch.tensor(self.features,dtype=torch.float32)).shape,(2,2)) + model2,receipt2=fit(self.rows,seed=17,arm="cross",steps=8,depth=2,width=16) + self.assertEqual(receipt["last_loss"],receipt2["last_loss"]) + self.assertEqual(choose(model,self.features[0],depth=2), + choose(model2,self.features[0],depth=2)) + frozen, frozen_receipt=fit(self.rows,seed=17,arm="frozen_cross",steps=8,depth=2,width=16) + self.assertLess(frozen_receipt["trained_parameters"],frozen_receipt["parameters"]) + self.assertFalse(frozen.core[0].weight.requires_grad) + + +if __name__=="__main__": + unittest.main() From 1a532f4e96988412def5792e81145c9361ef0a42 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:42:40 +0800 Subject: [PATCH 20/51] ci(olr): fit 3-seed recurrent guard pilot on fresh native Lean receipts and archive evidence --- .github/workflows/ppt-g03-live-lean.yml | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index 64ed815d7..f59aa6112 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -135,6 +135,37 @@ jobs: assert m["splits"]["train"]["worlds"]==6 and m["splits"]["dev"]["worlds"]==4, m print("OLR native arithmetic-guard source bank certified",m["independent_certificates"]) PY + - name: OLR-01C trainable guard comparison + working-directory: research/lean_cgrt_hrm400 + env: + OMP_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + run: | + python -m ppt_gym.olr_guards --seed 20261124 --train 32 --dev 12 --ood 8 --out runs/olr-01c-bank + python -m ppt_gym.olr_guard_fit --bank runs/olr-01c-bank --out runs/olr-01c-fit --steps 80 --depth 3 --width 32 --seeds 17 29 43 --max-seconds 600 + python - <<'PY' + import json + r=json.load(open("runs/olr-01c-fit/manifest.json",encoding="utf-8")) + s=r["evaluation"] + assert r["schema"]=="ppt.olr-guard-fit.v1" and len(r["seed_roster"])==3, r + assert len(r["training"])==12 and len(s)==(3*4+2)*2, (len(s),s) + assert all(x["worlds"]==24 if key.startswith("dev:") else x["worlds"]==16 + for key,x in s.items()), s + assert s["dev:0:exact_arithmetic"]["proofs"]==24, s + assert s["ood:0:exact_arithmetic"]["proofs"]==16, s + assert r["independent_query_certificates"]["clean_axioms"]==40, r + assert r["architecture_promotion_eligible"] is False + print("OLR-01C trainable paired guard pilot scorecard",json.dumps(s,sort_keys=True)) + PY + - name: Upload OLR-01C verified experiment receipts + if: always() + uses: actions/upload-artifact@v4 + with: + name: olr-01c-native-guard-pilot + path: | + research/lean_cgrt_hrm400/runs/olr-01c-bank + research/lean_cgrt_hrm400/runs/olr-01c-fit + if-no-files-found: ignore - name: Fresh generated Lean suite and model smoke working-directory: research/lean_cgrt_hrm400 env: From b2adfd4b5b0d389f6f27100d0e65ed4c141c42e1 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:44:01 +0800 Subject: [PATCH 21/51] research(olr): prerecord trainable arithmetic-guard pilot and matched controls --- .../OLR_01C_GUARD_LEARNING.md | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_01C_GUARD_LEARNING.md diff --git a/research/lean_cgrt_hrm400/OLR_01C_GUARD_LEARNING.md b/research/lean_cgrt_hrm400/OLR_01C_GUARD_LEARNING.md new file mode 100644 index 000000000..28fc32914 --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_01C_GUARD_LEARNING.md @@ -0,0 +1,60 @@ +# OLR-01C: native arithmetic-guard learning pilot + +**Date:** 2026-11-23 +**Status:** Protocol and executable development pilot. Model outcome must be read from a completed native Lean CI run before any success claim. +**Parent:** [OLR proposal](OLR_01_OBLIGATION_LEDGER_RECURRENCE.md), [OLR-01B structural result](OLR_01B_NATIVE_PREFLIGHT.md). + +## Research question + +Can a compact, weight-tied two-obligation recurrent model learn to choose between native Lean tactics whose propositional shape is identical while their computational guard differs? The ordinary Horn graph has two equal-arity rules and no way to decide which numerical equality Lean will close. A model must extract information from the public guard expression, then spend its two-check allowance on the correct rule and `rfl`. + +The first pilot uses a closed arithmetic grammar: a candidate `rN : (a + b = c) → P`, where the two choices share `a,b` and one has `c=a+b`. Both worlds in a pair exchange the guard assignments between r0 and r1. The exact arithmetic oracle is a strong reference; a neural win against a fixed lexical tie is weak evidence unless it also beats direct or isolated readers. This grammar can teach the network to approximate a hand-coded arithmetic test and makes no general Lean claim. + +## Source custody and native execution + +[ppt_gym/olr_guards.py](ppt_gym/olr_guards.py) generates deterministic paired roots. Each of the two root tactics is physically tested through the pinned Lean 4.19 REPL. A successful root first advances to an arithmetic subgoal; Lean's `rfl` must close it and `kernel` must accept the full theorem. An unsuccessful route earns a *two-tactic menu failure* label; the `rfl` failure is not interpreted as a proof that the guard proposition is false. + +A separate whitelist-only compiler accepts only a generated closed theorem statement and the pair `apply r0|r1; rfl`. It reports independent, axiom-free compilations. Candidate labels are defined by native outcomes and the original reference winner is used only for auditing. The ranker receives public normalized numerals `a/40, b/40, c/80` parsed from Lean's `raw` guard JSON, with no computed sum, equality bit, source verdict, or proof script. + +The source bank uses 32 distinct source pairs and a new 12-pair development cohort, with another eight pairs from an operand range unseen in training. Both worlds of each pair remain together in their split. The generator excludes duplicate arithmetic lineages across train and dev. The main 20261124 seed, splits, and model seeds were set in CI before model scoring. + +## Trainable architecture and controls + +[ppt_gym/olr_guard_model.py](ppt_gym/olr_guard_model.py) embeds each candidate's three public operands, initializes two obligation slots, and updates them through a **shared/tied recurrent cell**. Each cell sees immutable encoded context, its previous slot, a message from the other candidate, and an unknown-evidence embedding. It fits a gate and produces one tactic score per slot. Repeated recurrence is the algorithm clock; native feedback only arrives after an actual action. + +Four independently trained arms share source data, seed, minibatch indices, loss, optimizer and number of updates: + +| Arm | Architectural change | +| --- | --- | +| cross | Tied recurrent cell exchanges cross-candidate messages | +| isolated | Same trainable parameters and compute path, cross message set to zero | +| direct | Same source encoder and output head, bypasses recurrence; lower-compute control | +| frozen_cross | Tied recurrence initialized identically but frozen, source embed and readout trained | + +The direct and frozen-body controls have different *effective trainable* parameter counts. Retain exact counts from the source-fit receipt and compare per-decision actual compute in a follow-up. This pilot does not establish a strict FLOP-matched architecture winner by itself. + +Loss is paired 2-class cross entropy over the unique native-verified completion. Learning reads **train source only**; dev and OOD labels are used only for consistency checks *after* each policy decides. Three model seeds (17,29,43), 80 updates, width 32 and recurrent depth 3 form the initial smoke. All model outcomes on query roots are executed again by Lean. Identical selections can share a native replay within a root while all model decisions are separately logged. + +An independent numeric oracle using exact host addition and an r0-fixed guess make the ceiling and lexical tie explicit. All arms receive the same public numerals; model feature engineering itself is a simplifying computational prior. + +## Primary measurements + +Report individual kernel proof completions out of 24 development worlds and 16 out-of-range worlds, plus both-world pair completions, native tactic calls, source accuracy and parameter count. Both proof worlds in a pair count as **one independent lineage** in uncertainty analysis. The exact oracle should close every world with the fixed two-call budget. A useful learned recurrence signal requires complete-pair gains over isolated/direct/frozen controls across seeds, with fixed query samples, and more than an exact-information or runtime advantage. No sealed cohort has yet been opened for scientific confirmation. + +A mechanism experiment must further patch the cross-candidate message direction while matching its logit-margin perturbation to a sham. The structural hypergraph control from OLR-01B remains an upper bound for fully known Horn dependencies; OLR-01C has unknown computational guards and tests only their *initial action selection*. + +## Execution + +From `research/lean_cgrt_hrm400`, with the native Lean 4.19 REPL built and CPU PyTorch installed: + +~~~sh +python -m unittest discover -s ppt_gym/tests -v +python -m ppt_gym.olr_guards --seed 20261124 --train 32 --dev 12 --ood 8 --out runs/olr-01c-bank +python -m ppt_gym.olr_guard_fit --bank runs/olr-01c-bank --out runs/olr-01c-fit --steps 80 --depth 3 --width 32 --seeds 17 29 43 --max-seconds 600 +~~~ + +The runner writes source and query native JSONL, immutable hashes, source-fitted model states, paired policy decisions, standalone compiled source, and kernel receipts. GitHub Actions uploads the complete bank and result directory under **olr-01c-native-guard-pilot** for audit. The CI step asserts source/eval custody, a full exact-oracle ceiling, the expected sample/seed counts, independent query certificates and that the result is *not architecture-promotion eligible*. + +## Exit gates + +The next phase should train on ground numerical/computational judgments with more than two candidate moves, multi-goal pending proofs, resource-constrained rollback and public raw/unknown guard statuses. It must compare with a direct supervised guard reader and exact host fold under equal data and compute, then register a fresh confirmation cohort following the EvalMath FSI-01 mechanism/sham audit. A reproducible neural gain beyond an equivalent direct reader would justify replacing the tiny independent guard scorer with a full graph-aware obligation ledger. From 525ff0d218f218eb7fd78a167b37d0679ca82425 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:45:56 +0800 Subject: [PATCH 22/51] research(olr): archive three-seed native guard transfer and seed-sensitive negative controls --- research/lean_cgrt_hrm400/OLR_01C_RESULTS.md | 64 ++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_01C_RESULTS.md diff --git a/research/lean_cgrt_hrm400/OLR_01C_RESULTS.md b/research/lean_cgrt_hrm400/OLR_01C_RESULTS.md new file mode 100644 index 000000000..24bef0fc4 --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_01C_RESULTS.md @@ -0,0 +1,64 @@ +# OLR-01C: first native arithmetic-guard learning results + +**Date:** 2026-11-23 +**Status:** Successful CI and native verifier integration; **exploratory neural pilot, no confirmed mechanism gain**. +**Protocol:** [OLR_01C_GUARD_LEARNING.md](OLR_01C_GUARD_LEARNING.md) +**GitHub Actions:** [PPT G03 native run 45167635953](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45167635953) (success), [CPU regression run 45167635782](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45167635782) (success). +**Exact source and model receipts:** [olr-01c-native-guard-pilot.zip, artifact 14815601193](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45167635953/artifacts/14815601193). Uploaded artifact archive SHA-256: `aec24abdb47bee2477874244a30b98f339841e711afc8dfa24bc4b299fc07bbe`. + +## Executed protocol + +- Registered native source seed 20261124: **32 train pairs (64 worlds), 12 dev pairs (24 worlds), eight OOD pairs (16 worlds)**. Within each pair, the winning guard swaps from r0 to r1, preserving both candidate costs and their public grammar. +- The training sampler uses three model seeds **17, 29, 43**, 80 AdamW updates each, depth 3, width 32 and learning rate 0.003. The same source rows and minibatch indices are used across independently fitted arms. +- Each scorer has **17,985 stored parameters**. Cross and isolated recurrence train 17,985; frozen recurrent body trains 3,425. The direct model bypasses the cell and therefore uses less active computation. Strict matched-FLOP attribution is a later gate. +- The predecision model receives three separately normalized public operands per candidate. It receives neither Python's computed equality result nor the source winner. All training labels come from native Lean's `apply rN; rfl` and independent certificate checks. +- The exact host-arithmetic policy closes all 24 dev and 16 OOD worlds. The frozen r0-only policy closes 12 and eight respectively; both-world pair score is zero by construction. The proof menu is complete and the two-call budget is feasible. +- All **104 source and evaluation witness scripts** were independently compiled and axiom-audited before learning. At evaluation, the scorer selects the first tactic; Lean executes it and its guard step from a fresh proof root, matching the source's native verdict. The runner records 560 policy decisions and 80 native reruns of distinct selected root/action combinations. The **40 distinct evaluable winning scripts** compiled independently, axiom-free. + +## Outcome: completed pairs (both worlds certified) + +The same theorem pairs are re-used across model seeds. These are repeated seeded evaluations, **not independent samples**. Pair successes are a stricter measure of whether the policy can reverse its root choice when the guard positions change. + +| Arm | Dev seed 17 / 12 | Dev seed 29 / 12 | Dev seed 43 / 12 | Dev sum / 36 | OOD seed 17 / 8 | OOD seed 29 / 8 | OOD seed 43 / 8 | OOD sum / 24 | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| Cross-message tied loop | 5 | 3 | 9 | **17** | 3 | 3 | 8 | **14** | +| Isolated tied loop | 4 | 2 | 11 | **17** | 0 | 3 | 4 | **7** | +| Direct reader | 4 | 3 | 10 | **17** | 0 | 3 | 4 | **7** | +| Frozen recurrent body | 5 | 5 | 10 | **20** | 2 | 3 | 3 | **8** | + +Development gives **no complete-pair advantage** for learned cross-message recurrence over the simpler direct or isolated scorers. Frozen-body calibration is strongest there. The OOD panel shows a +7/24 descriptive complete-pair advantage for cross over both isolated and direct, and +6/24 over the frozen recurrent body. However, the seed-specific OOD cross-versus-isolated differences are +3, zero and +4 pairs from the **same eight roots**. The seed-43 score saturates at 8/8 while seed-17 and seed-29 close only 3/8. This is too unstable and small for a mechanism claim, especially because OOD was already an expected diagnostic split in the original CI protocol. + +## Individual native Lean completions + +| Arm | Development proofs by seed (out of 24 each) | OOD proofs by seed (out of 16 each) | +| --- | --- | --- | +| Cross-message tied loop | 10, 6, 18 | 7, 6, 16 | +| Isolated tied loop | 9, 4, 22 | 4, 6, 8 | +| Direct reader | 16, 6, 20 | 4, 6, 8 | +| Frozen recurrent body | 10, 10, 20 | 6, 6, 6 | +| Exact arithmetic oracle | 24 on every evaluation | 16 on every evaluation | +| Fixed r0 | 12 on every evaluation | 8 on every evaluation | + +Every policy spent exactly two native tactic calls per evaluated world. The **first-action selection** is therefore the operative difference; there is no learned tool-query or stopping benefit in this experiment. + +## Training and optimization diagnostic + +The cross-message model's source accuracy varies across seeds: 39/64, 42/64 and 54/64 training worlds. Its final minibatch losses were 0.8686, 0.5864 and 0.5226. Seed 17 ended with a loss above its initial 0.6936, suggesting unstable optimization or atypical final-batch composition at this short schedule. Direct and isolated source fits vary comparably, with seed 43 much stronger than the other two. The fitted models share a frozen source bank and have no separate optimized stopping head. + +Because initial root guards in this experiment have a single equality premise, this pilot tests **semantic guard scoring in two recurrent slots**, rather than transport of general AND-OR hypergraph obligations through many Lean goal transitions. The full OLR hypothesis remains untested. + +## Verification receipts + +- Native Lean 4.19.0; `lean` binary SHA-256: `92c3d35b5bfaa5e0fea413a775d504cf46cd95e1345df61c2274f76779e7e023`. +- Source manifest SHA-256: `ca3d4f2be451d6c49656f8e063f5130e75e35673a2432ebdba8a8d88eb6e6019`. +- Source bank native scripts: 104 compiled, 104 axiom-clean. +- Evaluation independent scripts: 40 compiled, 40 axiom-clean. +- Model state `models.pt` SHA-256: `23a702fa7a634cff50b407588aa78d4022bea700587fdc60cc15cce33a56b1e9`. +- Evaluation `decisions.jsonl` SHA-256: `ce16aca83de77822c3a71fded96b7c85e1f2a1f42ea0064cd4af9657b8dd7c42`. +- Runner-reported source+evaluation execution time for the trainable stage: approximately four seconds of Python/Lean work on the GitHub worker, excluding environment installation and native bank generation. + +## Follow-up decision + +**Keep OLR at research status.** The out-of-range paired improvement is useful as a *diagnostic hunch*. The source sample is small; a fixed exact host arithmetic procedure dominates every neural arm. Scaling this two-slot numeric equality learner would mainly spend parameters rediscovering arithmetic with strong prior knowledge already available. + +A more decisive OLR experiment should provide genuine multi-step obligations and evidence-driven branching, with a meaningful gap between a structural graph solver and a direct semantic reader. Candidate families include arithmetic guards whose premise is unfolded after a tactic, dependent witness reuse, and budgets where choosing or restoring a branch early matters. Pre-register the source-shift, root lineage, stronger matched baselines and causal sham before opening new evidence. Only promote an OLR checkpoint if more roots complete at matched Lean checks and matched inference compute, with a direction-specific effect beyond the sham envelope. From 3b04f10b5b4a362045c131955e3681c196a23e92 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:46:52 +0800 Subject: [PATCH 23/51] research(olr): add frozen cross-message removal and matched-margin sham to native scoring --- .../lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py index 301512e2f..d0d930e0e 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py @@ -146,8 +146,34 @@ def evaluate(lean: LeanRepl, rows: list[dict], models: dict[tuple,int], "exact_arithmetic":exact_arithmetic_reference(row["features"]), } actions={} + diagnostics={} for (seed,arm),model in models.items(): actions[(seed,arm)]=choose(model,row["features"],depth=depth) + if arm == "cross": + # The checkpoint and source fit are frozen. Patch only the + # cross-message input at inference, without changing logits + # through a trained alternative. The sham changes the action + # margin at the same absolute dose with an independent sign. + x=torch.tensor([row["features"]],dtype=torch.float32) + with torch.no_grad(): + normal=model(x,depth=depth)[0] + model.mode="isolated" + try: + no_message=model(x,depth=depth)[0] + finally: + model.mode="cross" + margin=float(normal[0]-normal[1]) + removed_margin=float(no_message[0]-no_message[1]) + delta=abs(margin-removed_margin) + sign=1 if int(digest([row["root"],seed,"margin-sham-v1"])[:8],16)%2 else -1 + actions[(seed,"cross_zero_message")]=int(no_message.argmax().item()) + actions[(seed,"cross_margin_sham")]=0 if margin+sign*delta >= 0 else 1 + diagnostics[seed]={ + "natural_margin":round(margin,7), + "zero_message_margin":round(removed_margin,7), + "matched_margin_sham_dose":round(delta,7), + "sham_sign":sign, + } for arm,index in controls.items(): actions[(0,arm)]=index # Deduplicate *identical native action requests* within a root to @@ -169,6 +195,8 @@ def evaluate(lean: LeanRepl, rows: list[dict], models: dict[tuple,int], "action":"apply r"+str(index),"kernel_closed":outcome["kernel_ok"], "native_tactic_calls":outcome["native_tactic_calls"], "native_result_sha256":digest(outcome), + "intervention":diagnostics.get(seed) if arm in ( + "cross","cross_zero_message","cross_margin_sham") else None, }) return output From 41d732ecc9af86e46e376f0c94b6860ddef9b902 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:47:04 +0800 Subject: [PATCH 24/51] ci(olr): assert matched-message interventions in frozen model replay --- .github/workflows/ppt-g03-live-lean.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index f59aa6112..5047d6cc4 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -148,13 +148,16 @@ jobs: r=json.load(open("runs/olr-01c-fit/manifest.json",encoding="utf-8")) s=r["evaluation"] assert r["schema"]=="ppt.olr-guard-fit.v1" and len(r["seed_roster"])==3, r - assert len(r["training"])==12 and len(s)==(3*4+2)*2, (len(s),s) + assert len(r["training"])==12 and len(s)==(3*6+2)*2, (len(s),s) assert all(x["worlds"]==24 if key.startswith("dev:") else x["worlds"]==16 for key,x in s.items()), s assert s["dev:0:exact_arithmetic"]["proofs"]==24, s assert s["ood:0:exact_arithmetic"]["proofs"]==16, s assert r["independent_query_certificates"]["clean_axioms"]==40, r assert r["architecture_promotion_eligible"] is False + assert all(f"dev:{seed}:cross_zero_message" in s and + f"ood:{seed}:cross_margin_sham" in s + for seed in (17,29,43)) print("OLR-01C trainable paired guard pilot scorecard",json.dumps(s,sort_keys=True)) PY - name: Upload OLR-01C verified experiment receipts From 286318591284b4e39bf8962c0c86620caee1de2d Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:47:32 +0800 Subject: [PATCH 25/51] docs(olr): index three-seed arithmetic-guard model results in research README --- research/lean_cgrt_hrm400/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/research/lean_cgrt_hrm400/README.md b/research/lean_cgrt_hrm400/README.md index db327c7fc..130d89607 100644 --- a/research/lean_cgrt_hrm400/README.md +++ b/research/lean_cgrt_hrm400/README.md @@ -11,7 +11,8 @@ Start with these documents: - [PPT gyms: runnable Plan A/B, DataGoblin importer, DRAM accretion and replay](PPT_GYM_RUNBOOK.md): CPU PyTorch reference implementation, checked-data custody, support/query controls, synthetic smoke tests and CI. - [PPT-G03 live Lean search and verifier-checked data accretion](PPT_G03_RUNBOOK.md): native Lean 4.19 stepper, frozen theorem suites, independent compiled certificates, train-support DRAM updates and replay-gated export. - [PPT-G03B bounded backtracking gym](PPT_G03B_BACKTRACKING.md): saved Lean-state rollback on unprovable branches, separate tactic and host-cost accounting, and exact independent replay. -- [OLR-01 obligation ledger architecture](OLR_01_OBLIGATION_LEDGER_RECURRENCE.md), [novelty investigation](OLR_01_INVESTIGATION.md) and [native Lean paired-proof preflight](OLR_01B_NATIVE_PREFLIGHT.md): exact AND-OR structural baseline, 8/8 kernel closures on 4 paired toy graphs, and the proposed computational-guard learning gate. Prototype is not trained. +- [OLR-01 architecture](OLR_01_OBLIGATION_LEDGER_RECURRENCE.md), [investigation](OLR_01_INVESTIGATION.md) and [native Horn preflight](OLR_01B_NATIVE_PREFLIGHT.md): explicit AND-OR structural baseline and eight independently certified toy proofs. +- [OLR-01C native arithmetic-guard learning protocol](OLR_01C_GUARD_LEARNING.md) and [three-seed results](OLR_01C_RESULTS.md): trained ~18k parameter two-slot recurrence, direct/frozen/isolated controls, fresh native Lean arithmetic proofs and strong seed variance; no confirmed recurrent mechanism gain. - [`LOCAL_SCALING_RESULTS.md`](LOCAL_SCALING_RESULTS.md): campaign c1, Lean-certified results; - [`SILICO_400M_HANDOFF.md`](SILICO_400M_HANDOFF.md): decision and ready-to-run 400M specs. - [`RLT_ABLATION_MATRIX.md`](RLT_ABLATION_MATRIX.md): RLT-01 feedback controls and Q5 transfer caveats; [completed two-lane pilot results](results/rlt01/RLT-comparison.md) found no RLT-specific Lean completion gain. From 54b0b73e59d4819eddaaa71229a0b37491f71b0c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:51:26 +0800 Subject: [PATCH 26/51] audit(olr): require same-worker bit-exact model replay and record deterministic CPU environment --- .../lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py index d0d930e0e..699f8ac26 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py @@ -12,6 +12,7 @@ import random import re import time +import platform from pathlib import Path import torch @@ -231,6 +232,8 @@ def run(bank: Path, out: Path, *, steps: int, depth: int, if not 1 <= depth <= 16 or not 8 <= width <= 128: raise ValueError("invalid bounded recurrent architecture") torch.set_num_threads(1) + torch.backends.mkldnn.enabled=False + torch.use_deterministic_algorithms(True) start=time.perf_counter() source,shards=load_bank(bank) train=shards["train"] @@ -240,6 +243,17 @@ def run(bank: Path, out: Path, *, steps: int, depth: int, for arm in ARMS: model,receipt=fit(train,seed=seed,arm=arm,steps=steps,depth=depth,width=width) models[(seed,arm)]=model + # Same-worker exact replay distinguishes stochastic code from + # CPU-hardware-dependent cross-run numerical drift. + if seed==seeds[0] and arm in ("cross","direct"): + replay_model,_=fit(train,seed=seed,arm=arm,steps=steps, + depth=depth,width=width) + if not all(torch.equal(a,b) for + (ka,a),(kb,b) in zip(model.state_dict().items(), + replay_model.state_dict().items()) + if ka==kb): + raise ValueError("same-worker seeded training replay changed weights") + receipt["same_worker_bit_exact_replay"]=True training[f"{seed}:{arm}"]=receipt if time.perf_counter()-start>max_seconds: raise TimeoutError("bounded CPU training budget exhausted") @@ -279,6 +293,15 @@ def run(bank: Path, out: Path, *, steps: int, depth: int, "independent_query_certificates":proof_receipt, "architecture_promotion_eligible":False, "training_classification":"native-source-labelled_CPU_research_pilot", + "cpu_environment":{ + "torch":torch.__version__, + "platform":platform.platform(), + "machine":platform.machine(), + "cpu_count":__import__("os").cpu_count(), + "threads":torch.get_num_threads(), + "mkldnn":torch.backends.mkldnn.enabled, + "deterministic_algorithms":torch.are_deterministic_algorithms_enabled(), + }, "runtime_seconds":round(time.perf_counter()-start,3), "model_causal_evidence":"none; next-stage comparison requires prospective matched compute and sham", } From 102e54922ba11cd63ebd40c545aa43afa3980401 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:51:37 +0800 Subject: [PATCH 27/51] ci(olr): enforce deterministic in-worker source fit for tied and direct controls --- .github/workflows/ppt-g03-live-lean.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index 5047d6cc4..09fe10019 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -155,6 +155,9 @@ jobs: assert s["ood:0:exact_arithmetic"]["proofs"]==16, s assert r["independent_query_certificates"]["clean_axioms"]==40, r assert r["architecture_promotion_eligible"] is False + assert r["training"]["17:cross"]["same_worker_bit_exact_replay"] + assert r["training"]["17:direct"]["same_worker_bit_exact_replay"] + assert r["cpu_environment"]["deterministic_algorithms"] is True assert all(f"dev:{seed}:cross_zero_message" in s and f"ood:{seed}:cross_margin_sham" in s for seed in (17,29,43)) From fe68bfc18b1ca279df3716a428807e1f4420f1a8 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:53:20 +0800 Subject: [PATCH 28/51] research(olr): add equal-information one-pass cross-reader control --- research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py index 699f8ac26..45622508d 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_guard_fit.py @@ -24,7 +24,7 @@ SCHEMA = "ppt.olr-guard-fit.v1" SEED_ROSTER = (17, 29, 43) -ARMS = ("cross", "isolated", "direct", "frozen_cross") +ARMS = ("cross", "isolated", "direct", "frozen_cross", "cross_onepass") CONTROLS = ("fixed_r0", "exact_arithmetic") STMT = re.compile( r"^∀ \(P : Prop\) \(r0 : \((\d+) \+ (\d+) = (\d+)\) → P\) " @@ -92,7 +92,7 @@ def fit(rows: list[dict], *, seed: int, arm: str, if arm not in ARMS or not 1 <= steps <= 5000: raise ValueError("unsupported fitted arm or step count") torch.manual_seed(seed) - mode = "cross" if arm == "frozen_cross" else arm + mode = "cross" if arm in ("frozen_cross", "cross_onepass") else arm model=GuardScorer(width=width, mode=mode) if arm == "frozen_cross": # Source encoder and readout train; the tied recurrence itself stays @@ -104,12 +104,13 @@ def fit(rows: list[dict], *, seed: int, arm: str, optimizer=torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=.003,weight_decay=.005) x,y=tensors(rows) + effective_depth = 1 if arm == "cross_onepass" else depth # Same minibatch stream, seed and source ordering across all arms. rng=torch.Generator().manual_seed(seed+7000) batches=torch.randint(len(rows),(steps,min(32,len(rows))),generator=rng) first_loss=last_loss=0. for t,ind in enumerate(batches): - pred=model(x[ind],depth=depth) + pred=model(x[ind],depth=effective_depth) loss=ranking_loss(pred,y[ind]) if not torch.isfinite(loss): raise FloatingPointError("nonfinite OLR reward-model loss") @@ -125,10 +126,10 @@ def fit(rows: list[dict], *, seed: int, arm: str, train_correct=0 with torch.no_grad(): for row in rows: - train_correct+=choose(model,row["features"],depth=depth)==row["labels"].index(1) + train_correct+=choose(model,row["features"],depth=effective_depth)==row["labels"].index(1) return model, { "seed":seed,"arm":arm,"mode":mode, - "steps":steps,"depth":depth,"width":width, + "steps":steps,"depth":effective_depth,"width":width, "parameters":model.parameter_count(), "trained_parameters":sum(p.numel() for p in model.parameters() if p.requires_grad), "first_loss":first_loss,"last_loss":last_loss, @@ -149,7 +150,7 @@ def evaluate(lean: LeanRepl, rows: list[dict], models: dict[tuple,int], actions={} diagnostics={} for (seed,arm),model in models.items(): - actions[(seed,arm)]=choose(model,row["features"],depth=depth) + actions[(seed,arm)]=choose(model,row["features"],depth=(1 if arm=="cross_onepass" else depth)) if arm == "cross": # The checkpoint and source fit are frozen. Patch only the # cross-message input at inference, without changing logits From 06b74a82c1bf456f1de308fca8a8ce0de632048a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:53:34 +0800 Subject: [PATCH 29/51] ci(olr): require one-pass equal-information comparator on native proof panels --- .github/workflows/ppt-g03-live-lean.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index 09fe10019..60d944358 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -148,7 +148,7 @@ jobs: r=json.load(open("runs/olr-01c-fit/manifest.json",encoding="utf-8")) s=r["evaluation"] assert r["schema"]=="ppt.olr-guard-fit.v1" and len(r["seed_roster"])==3, r - assert len(r["training"])==12 and len(s)==(3*6+2)*2, (len(s),s) + assert len(r["training"])==15 and len(s)==(3*7+2)*2, (len(s),s) assert all(x["worlds"]==24 if key.startswith("dev:") else x["worlds"]==16 for key,x in s.items()), s assert s["dev:0:exact_arithmetic"]["proofs"]==24, s @@ -159,7 +159,8 @@ jobs: assert r["training"]["17:direct"]["same_worker_bit_exact_replay"] assert r["cpu_environment"]["deterministic_algorithms"] is True assert all(f"dev:{seed}:cross_zero_message" in s and - f"ood:{seed}:cross_margin_sham" in s + f"ood:{seed}:cross_margin_sham" in s and + f"ood:{seed}:cross_onepass" in s for seed in (17,29,43)) print("OLR-01C trainable paired guard pilot scorecard",json.dumps(s,sort_keys=True)) PY From fc9b10006e376fa72006bf73f17b18582626208a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:57:45 +0800 Subject: [PATCH 30/51] research(olr): report one-pass matched-information controls and cross-run bit-exact audit --- .../OLR_01C_COMPUTE_ABLATION.md | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_01C_COMPUTE_ABLATION.md diff --git a/research/lean_cgrt_hrm400/OLR_01C_COMPUTE_ABLATION.md b/research/lean_cgrt_hrm400/OLR_01C_COMPUTE_ABLATION.md new file mode 100644 index 000000000..dfbf824e3 --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_01C_COMPUTE_ABLATION.md @@ -0,0 +1,68 @@ +# OLR-01C: compute-depth, cross-message, and reproducibility audit + +**Date:** 2026-11-23 +**Status:** Completed native Lean exploratory audit. No architecture promotion or direction-specific mechanism claim. +**Parent:** [OLR-01C protocol](OLR_01C_GUARD_LEARNING.md), [initial result](OLR_01C_RESULTS.md). +**Reproducibility run:** [45168959420](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45168959420). +**One-pass and message audit:** [45169236940](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45169236940). +**Latest audited ZIP:** [olr-01c-native-guard-pilot.zip (artifact 14815748042)](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45169236940/artifacts/14815748042). Both CI workflows passed. + +## Why this extension was required + +The original 3-pass recurrent cross-message arm saw *both* candidate guards at each iteration; the direct and isolated arms read candidates independently. An OOD gain against them could come from the extra **candidate-pair information** rather than from performing more recurrent steps. + +Added `cross_onepass`: one cross-candidate update, using exactly the same public numeric features and **17,985 stored parameters** as the 3-pass cross arm. Its training data, minibatch sequence, model seeds and 80-step optimizer schedule match the primary. It computes fewer model passes. The comparison isolates whether three visits appear useful beyond a one-pass cross reader on this developmental grammar. It does not match model FLOPs or training-stage compute. + +Also added inference-time interventions on each *frozen* 3-pass cross checkpoint: +- `cross_zero_message`: replace the opposite-candidate signal with zeros in the same tied block, without retraining or modifying source evidence. +- `cross_margin_sham`: preserve the natural checkpoint, perturb its selected-action logit margin at the **same absolute dose** as message removal, and assign an independently hashed random sign per root and seed. This is a margin-magnitude control, not a universal causal-sham certificate. + +Each policy selection is replayed on a native Lean 4.19 proof root under the same two-tactic limit, with independent standalone proof compilation. No query label enters the model scorer. + +## Results: complete paired worlds + +Both worlds must close under Lean to count one complete pair. The 12 development root pairs and eight OOD root pairs are re-used for all model seeds, so seed totals are descriptive repeated observations. + +| Policy | Development, seeds 17/29/43 (of 12 each) | Sum dev (of 36) | OOD, seeds 17/29/43 (of 8 each) | Sum OOD (of 24) | +| --- | --- | ---: | --- | ---: | +| **3-pass cross recurrence** | **5 / 3 / 11** | **19** | **3 / 1 / 8** | **12** | +| **1-pass cross reader** | 2 / 9 / 12 | **23** | 0 / 3 / 3 | **6** | +| Cross checkpoint, messages zeroed | 5 / 2 / 12 | 19 | 3 / 1 / 5 | 9 | +| Cross checkpoint, matched-margin sham | 5 / 2 / 10 | 17 | 3 / 1 / 7 | 11 | +| Independently trained isolated recurrence | 4 / 2 / 11 | 17 | 0 / 3 / 3 | 6 | +| Direct per-candidate reader | 4 / 3 / 11 | 18 | 0 / 3 / 4 | 7 | +| Frozen recurrent body, fitted embed/readout | 5 / 5 / 10 | 20 | 2 / 3 / 3 | 8 | +| Exact host arithmetic oracle | 12 / 12 / 12 | 36 | 8 / 8 / 8 | 24 | + +On development roots, the single-pass cross reader completes four more pairs across seeded evaluations than the 3-pass recurrent model. The 3-pass checkpoint completes six more pairs across seeded evaluations on the out-of-range panel. This sign change reveals distribution-sensitive depth effects and is **insufficient evidence that added recurrence is broadly useful**. + +The OOD cross-vs-one-pass paired differences across seeds are **+3, -2 and +5** of eight; the seed-29 one-pass reader beats the longer loop. The effect across three seeds therefore has substantial variance. These seed outcomes share the same eight source-independent OOD graph roots, and their observed range precludes a reliable mechanism claim. + +In the OOD panel, zeroing the frozen message loses **three** complete pairs across seed observations, while the matched-margin sham loses **one**. The seed-43 checkpoint is responsible for those differences: natural 8/8, zeroed 5/8, sham 7/8. The seed-17 and seed-29 OOD pair counts are unchanged by message removal. This is a **seed-specific causal effect on policy choices** and supplies no prospective matched-sham improvement across model seeds. + +## Reproducibility audit + +The first two native CI runs used identical registered training/dev/OOD bytes, seeds, optimizer steps and model definition, yet produced differing fitted weights and some different development choices: + +- [45167635953](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45167635953): model archive SHA-256 `23a702fa7a634cff50b407588aa78d4022bea700587fdc60cc15cce33a56b1e9`. +- [45168290451](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45168290451): model archive SHA-256 `bd45278f4d1da3275e5166774585c1c7940a3cca7a0dc6f7c3d4b1d984b8b7b9`. + +The source shard digests agreed bit-for-bit in those runs. The exact numerical cause of the earlier drift has not been isolated. The follow-up enabled `torch.use_deterministic_algorithms(True)`, disabled CPU MKLDNN and fixed one CPU thread. Within a single runner, repeated source fitting at the same seed now gives identical tensors. + +**Cross-run verified checkpoint equality:** the source train/dev/OOD files are bit-identical across [45168959420](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45168959420) and [45169236940](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45169236940). All **12 common model state dictionaries** (`cross`, `isolated`, `direct` and `frozen_cross` at seeds 17/29/43) were independently downloaded from their artifact ZIPs and compared tensor by tensor. **Every tensor is bit-for-bit equal.** The latter run adds three distinct one-pass checkpoints, so comparing whole ZIP or `models.pt` file hashes would be misleading. + +Runner environment in the deterministic audit: Python with PyTorch `2.5.1+cpu`, x86_64 Linux, single CPU thread, MKLDNN disabled, deterministic algorithms enabled. The native Lean 4.19 verifier, exact arithmetic source bank and independent axiom-free certifier were unchanged. + +## What this suggests about OLR + +The current neural model learns to rank **two simple numeric equality guards**. It carries two recurrent slots with trainable cross-candidate messages but does not yet maintain a full proof hypergraph across live tactic steps, plan on multiple simultaneous obligations, or learn a new tool-feedback update rule. A fixed integer-adder oracle already solves every target in two Lean calls. + +The experiment supports the following narrow observations: + +- The pinned native data pipeline, source/query split checks, independent certificate compiler, and deterministic model checkpoint protocol operate end-to-end. +- Three recurrent visits can affect out-of-range policy choices even with the same input and parameterization as a one-pass reader, but this advantage lacks stability across seeds and flips direction on development. +- A single checkpoint can depend causally on its cross-message input, while a magnitude-matched logit sham can reproduce some of the same outcome changes. + +The next research gate should **move away from static equality classification** toward a multi-step, shared-premise Lean proof where exactly exposed symbolic structure is insufficient and native feedback changes the proper action. Register fresh root families, all verifier-call and FLOP constraints, matched direct/one-pass controls, an independent structural planner, the message intervention, and an EvalMath FSI-01 sham/power floor before model scoring. + +Do not promote this pilot as a learned novel-recurrence success or scale to 5M/20M parameters based on the current data. From b9940ffa358eb0fd2f4852938b5ea194b0886114 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:58:00 +0800 Subject: [PATCH 31/51] docs(olr): link first-run findings to reproducibility and compute-depth follow-up --- research/lean_cgrt_hrm400/OLR_01C_RESULTS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/research/lean_cgrt_hrm400/OLR_01C_RESULTS.md b/research/lean_cgrt_hrm400/OLR_01C_RESULTS.md index 24bef0fc4..4bd914a10 100644 --- a/research/lean_cgrt_hrm400/OLR_01C_RESULTS.md +++ b/research/lean_cgrt_hrm400/OLR_01C_RESULTS.md @@ -1,5 +1,7 @@ # OLR-01C: first native arithmetic-guard learning results +**Follow-up:** The [one-pass/matched-sham and deterministic-checkpoint audit](OLR_01C_COMPUTE_ABLATION.md) supersedes this first exploratory scorecard for scientific interpretation. The first two hosted runs exhibited checkpoint drift across workers; the later controlled runs are bit-identical for all common model tensors. This page retains the initial run exactly as observed. + **Date:** 2026-11-23 **Status:** Successful CI and native verifier integration; **exploratory neural pilot, no confirmed mechanism gain**. **Protocol:** [OLR_01C_GUARD_LEARNING.md](OLR_01C_GUARD_LEARNING.md) From f78f11b52446b2c24c0fb224a2070800befc1cb4 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 19:58:12 +0800 Subject: [PATCH 32/51] docs(olr): index compute-depth and reproducibility findings --- research/lean_cgrt_hrm400/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/research/lean_cgrt_hrm400/README.md b/research/lean_cgrt_hrm400/README.md index 130d89607..bda454b91 100644 --- a/research/lean_cgrt_hrm400/README.md +++ b/research/lean_cgrt_hrm400/README.md @@ -13,6 +13,7 @@ Start with these documents: - [PPT-G03B bounded backtracking gym](PPT_G03B_BACKTRACKING.md): saved Lean-state rollback on unprovable branches, separate tactic and host-cost accounting, and exact independent replay. - [OLR-01 architecture](OLR_01_OBLIGATION_LEDGER_RECURRENCE.md), [investigation](OLR_01_INVESTIGATION.md) and [native Horn preflight](OLR_01B_NATIVE_PREFLIGHT.md): explicit AND-OR structural baseline and eight independently certified toy proofs. - [OLR-01C native arithmetic-guard learning protocol](OLR_01C_GUARD_LEARNING.md) and [three-seed results](OLR_01C_RESULTS.md): trained ~18k parameter two-slot recurrence, direct/frozen/isolated controls, fresh native Lean arithmetic proofs and strong seed variance; no confirmed recurrent mechanism gain. +- [OLR-01C compute-depth and reproducibility audit](OLR_01C_COMPUTE_ABLATION.md): equal-information one-pass reader, cross-message shams, bit-exact seeded checkpoints across two hosted runs, and mixed development/OOD transfer. - [`LOCAL_SCALING_RESULTS.md`](LOCAL_SCALING_RESULTS.md): campaign c1, Lean-certified results; - [`SILICO_400M_HANDOFF.md`](SILICO_400M_HANDOFF.md): decision and ready-to-run 400M specs. - [`RLT_ABLATION_MATRIX.md`](RLT_ABLATION_MATRIX.md): RLT-01 feedback controls and Q5 transfer caveats; [completed two-lane pilot results](results/rlt01/RLT-comparison.md) found no RLT-specific Lean completion gain. From be4c6b5a97aa673492b8fd76736bffbe85d84181 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 20:56:32 +0800 Subject: [PATCH 33/51] research(olr): pre-register delayed-feedback multi-goal Lean budget experiment --- .../lean_cgrt_hrm400/OLR_01D_REGISTRATION.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_01D_REGISTRATION.md diff --git a/research/lean_cgrt_hrm400/OLR_01D_REGISTRATION.md b/research/lean_cgrt_hrm400/OLR_01D_REGISTRATION.md new file mode 100644 index 000000000..0eca63b6e --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_01D_REGISTRATION.md @@ -0,0 +1,33 @@ +# OLR-01D registration: delayed guard feedback with pending Lean obligations + +**Date:** 2026-11-23 +**Status:** registered before the new native scorer or its outcomes are evaluated +**Lineage:** [OLR-01C](OLR_01C_COMPUTE_ABLATION.md) used source seed 20261124 and model seeds 17/29/43. + +## Claim under test + +Can the OLR experiment stack use a *public Lean goal state* to maintain two simultaneous pending proof obligations, make a reversible branch choice, and spend a diagnostic check early enough to recover a certified proof within a tight budget? The exact arithmetic guard remains visible, so a host arithmetic solver can settle every root without a probe. This gate establishes real native control semantics and cost accounting. The frozen OLR-01C learner is an exploratory ranking control, with **no online learned feedback update** in this gate. + +## Frozen design + +- **New cohort:** 8 root pairs, both worlds, generated with `olr-guard-v1` seed **20261127** and operand range **9..16**. Exclude every (a,b,delta) tuple from the 20261124 OLR-01C source, dev, and OOD bank. This source freeze is performed before scoring any OLR-01D model. +- **New theorem:** `∀ (P Q R : Prop) (h0 : P) (h1 : Q) (r0 : (a+b=c0) → P → Q → R) (r1 : (a+b=c1) → P → Q → R), R`. Across pair worlds, c0 and c1 swap. Lean must expose *three active goals* after the first `apply rN`: a computational equality followed by P and Q. +- **Budget:** compare 4 and 6 **tactic calls**, with one allowed host rollback; count host `focus` separately. Each candidate path needs exactly four tactics to close. +- **Schedule:** `probe_early` checks the arithmetic guard with native `rfl` before solving P and Q; `probe_late` solves both open propositional obligations first (with `focus`) and tests the guard last. The early schedule can recover from a wrong initial branch within six calls, while the late schedule has already spent four calls before discovering the mistake. +- **Root policies:** frozen OLR-01C `cross`, `cross_onepass`, `direct`, `isolated`, `frozen_cross` at each of seeds **17, 29, 43**; host exact-addition oracle; deterministic `r0` tie. Keep weights frozen and report every seed. All policies consume only the raw Lean predecision guard expressions. +- **Learning evidence:** the previous OLR-01C source bank and model archive stay fixed. No OLR-01D proof, verdict or test-set data may be used for training or model selection. +- **Controls:** rerun both schedules under both budgets; native verifier feedback alone determines rollback, without a hindsight proof label in the action selection. The immediate oracle and fixed-tie reference bound success and repair cost. The OLR-01C matched-margin sham is retained as an earlier caveat, not claimed anew on this distribution. + +## Required verifications before reporting + +1. Register and hash all world statements, pair membership, toolchain hashes and source-bank checksum before model scoring. Verify menus exactly `apply r0`, `apply r1`. +2. Force each root branch and validate in fresh native Lean that it creates three simultaneous goals, one `rfl` pass and one rejection per pair world. A rejected `rfl` is a failed tactic attempt, not proof that the equality is mathematically false. +3. In successful trajectories call Lean's `kernel`, require an empty axiom list, replay the full tactic/focus/rollback ledger in a fresh server state, and compile every distinct successful proof independently against its **full original theorem**. +4. Score only fully paired roots; report native closures, mean calls, host focus and rollback counts, cost utilities separately, and exact reachable coverage. Group roots by pair and retain every model seed. +5. Keep the registry and live native results in a downloadable CI artifact with exact SHA-256 content hashes. Classify any result as **engineering / exploratory** under FSI-01 until an independent mechanism-sham and power design exists. + +## What counts as progress + +A verified early-probe rollback must recover at least one wrong-branch proof within six native checks while the matched late probe cannot. The exact arithmetic oracle should close both worlds under four checks and is a higher-value baseline than a neural guard classifier on this grammar. An OLR-specific benefit requires future fresh pair families in which native feedback changes the right action under partially observable semantics, a learned adaptive budget controller outperforms exact and direct-reader baselines at equal inference cost, and message removal has a direction-specific effect beyond the matched-sham floor. + +**This protocol registers the live search/custody gate. It does not assert that the current recurrent classifier possesses verified obligation-tracking ability.** From 1efe6bd2de5308a55bc695dcaeb6c4bee790eeab Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 20:59:12 +0800 Subject: [PATCH 34/51] feat(olr): native multi-goal probe/rollback with event replay and standalone scripts --- .../lean_cgrt_hrm400/ppt_gym/olr_delayed.py | 332 ++++++++++++++++++ 1 file changed, 332 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/olr_delayed.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_delayed.py b/research/lean_cgrt_hrm400/ppt_gym/olr_delayed.py new file mode 100644 index 000000000..b227e802a --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_delayed.py @@ -0,0 +1,332 @@ +"""OLR-01D: real Lean multi-goal guard probe, rollback and exact replay. + +The model chooses only the initial root rule. Lean supplies all subsequent +tactic/verifier outcomes. The two proof schedules are deterministic reference +controllers, not learned recurrence or online adaptation. +""" +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +import re +import subprocess +import tempfile + +from lcgrt import config +from lcgrt.lean_repl import LeanRepl +from .data import digest, sha256_file +from .live_lean import candidate_menu, public_state +from .olr_guards import numeric_features + +ARMS = ("probe_early", "probe_late") +ROOT_MENU = ("apply r0", "apply r1") +NATIVE_ACTION = re.compile(r"^(apply r[01]|apply h[01]|rfl)$") +STMT = re.compile( + r"^∀ \(P Q R : Prop\) \(h0 : P\) \(h1 : Q\) " + r"\(r0 : \((\d+) \+ (\d+) = (\d+)\) → P → Q → R\) " + r"\(r1 : \((\d+) \+ (\d+) = (\d+)\) → P → Q → R\), R$" +) + + +@dataclass(frozen=True) +class DelayedWorld: + pair: str + world: int + a: int + b: int + targets: tuple[int, int] + + def statement(self) -> str: + x, y = self.targets + return ("∀ (P Q R : Prop) (h0 : P) (h1 : Q) " + f"(r0 : ({self.a} + {self.b} = {x}) → P → Q → R) " + f"(r1 : ({self.a} + {self.b} = {y}) → P → Q → R), R") + + @classmethod + def from_row(cls, row: dict) -> "DelayedWorld": + m = STMT.fullmatch(row["statement"]) + if not m: + raise ValueError("OLR-01D statement outside registered safe grammar") + a, b, x, c, d, y = (int(v) for v in m.groups()) + if a != c or b != d: + raise ValueError("two candidate guards changed shared operands") + if digest(row["statement"]) != row["root"]: + raise ValueError("registered native theorem changed") + return cls(row["pair"], row["world"], a, b, (x, y)) + + +def raw_root_features(visible: dict, menu: tuple[str, ...]) -> tuple[tuple[float, ...], ...]: + """Read raw arithmetic operands from Lean. No equality calculation or label.""" + goals = visible.get("goals") + if not isinstance(goals, list) or len(goals) != 1 or goals[0].get("target") != {"a":"R"}: + raise ValueError("not a single public root goal R") + if menu != ROOT_MENU: + raise ValueError("public root menu changed") + hyps = goals[0].get("hypotheses") + if not isinstance(hyps,list): + raise ValueError("missing Lean root hypotheses") + types = {h.get("name"):h.get("type") for h in hyps if isinstance(h,dict)} + if types.get("h0") != {"a":"P"} or types.get("h1") != {"a":"Q"}: + raise ValueError("pending proof hypotheses changed") + vectors=[] + for rule in ("r0","r1"): + node=types.get(rule) + for premise in range(3): + if not isinstance(node,dict) or set(node) != {"imp"}: + raise ValueError("root candidate lost an implication") + two=node["imp"] + if not isinstance(two,list) or len(two)!=2: + raise ValueError("root implication malformed") + first,node=two + if premise==0: + if not isinstance(first,dict) or not isinstance(first.get("raw"),str): + raise ValueError("computational guard not reported as raw") + vectors.append(numeric_features(first["raw"])) + elif first != {"a":"P"} if premise==1 else first != {"a":"Q"}: + raise ValueError("pending premise identity changed") + if node != {"a":"R"}: + raise ValueError("candidate consequent changed") + return tuple(vectors) + + +def observe_root(lean: LeanRepl, world: DelayedWorld) -> dict: + lean.reset() + state=lean.init(world.statement(),pp=True) + visible=public_state(lean,state) + menu=candidate_menu(lean,state) + features=raw_root_features(visible,menu) + return { + "source_sha256":digest(visible), + "root":digest(world.statement()), + "menu":list(menu), + "features":[list(x) for x in features], + } + + +def run_path(lean: LeanRepl, world: DelayedWorld, initial: int, schedule: str, + budget: int) -> dict: + """Execute one policy branch with a saved native root state for rollback.""" + if schedule not in ARMS or initial not in (0,1) or budget not in (4,6): + raise ValueError("registered action/schedule/check budget mismatch") + lean.reset() + root=lean.init(world.statement(),pp=True) + state=root + original=public_state(lean,root) + root_menu=candidate_menu(lean,root) + features=raw_root_features(original,root_menu) + events=[] + script=[] + calls=focus_count=rollback_count=0 + closed=False + + def tactic(action: str) -> bool: + nonlocal calls,state + if not NATIVE_ACTION.fullmatch(action) or calls>=budget: + raise ValueError("illegal native tactic or over budget") + before=digest(public_state(lean,state)) + result=lean.run(state["sid"],action) + if type(result.get("ok")) is not bool: + raise ValueError("malformed Lean tactic outcome") + calls+=1 + if result["ok"]: + state=result["state"] + after=digest(public_state(lean,state)) + script.append(action) + else: + after=before + events.append({"kind":"tactic","action":action,"ok":result["ok"], + "before":before,"after":after,"calls":calls}) + return result["ok"] + + def focus(index: int) -> None: + nonlocal focus_count,state + if index != 1: + raise ValueError("only registered focus index 1 is allowed") + before=digest(public_state(lean,state)) + output=lean.focus(state["sid"],index) + if output.get("ok") is not True: + raise ValueError("native pending-goal focus rejected") + state=output["state"] + after=digest(public_state(lean,state)) + focus_count+=1 + script.append("rotate_left 1") # exact Lean tactic for the host permutation + events.append({"kind":"focus","index":index,"before":before,"after":after}) + + def rollback() -> None: + nonlocal state,rollback_count,script + if rollback_count>=1: + raise ValueError("rollback cap exceeded") + before=digest(public_state(lean,state)) + state=root + script=[] + rollback_count+=1 + events.append({"kind":"rollback","before":before,"after":digest(original)}) + + def active() -> list: + return public_state(lean,state)["goals"] + + def attempt(choice: int) -> str: + nonlocal closed + if not tactic(f"apply r{choice}"): + raise ValueError("registered native opening rejected") + if len(active())!=3: + raise ValueError("root must expose guard + two pending goals") + if schedule=="probe_late": + focus(1) + if not tactic("apply h0") or len(active())!=2: + raise ValueError("failed to discharge the first pending goal") + focus(1) + if not tactic("apply h1") or len(active())!=1: + raise ValueError("failed to discharge the second pending goal") + if not tactic("rfl"): + return "guard_rejected" + if schedule=="probe_early": + if len(active())!=2: + raise ValueError("guard success must retain two pending goals") + if not tactic("apply h0") or len(active())!=1: + raise ValueError("first post-guard goal did not close") + if not tactic("apply h1") or active(): + raise ValueError("second post-guard goal did not close") + if active(): + raise ValueError("native proof retained goals after terminal action") + cert=lean.kernel(state["sid"]) + if cert.get("ok") is not True or cert.get("axioms")!=[]: + raise ValueError("native Lean kernel rejected a closed multi-goal proof") + events.append({"kind":"kernel","ok":True,"axioms":[],"before":digest(public_state(lean,state))}) + closed=True + return "kernel_closed" + + status=attempt(initial) + if status=="guard_rejected": + rollback() + if budget-calls >= 4: + status=attempt(1-initial) + if status!="kernel_closed": + raise ValueError("the complementary registered branch did not close") + else: + status="insufficient_budget_after_probe" + if not closed and status=="kernel_closed": + raise ValueError("bad terminal state") + if closed and calls>budget: + raise ValueError("native cost cap breached") + return { + "root":digest(world.statement()), "pair":world.pair, "world":world.world, + "initial_action":f"apply r{initial}", "schedule":schedule, "budget":budget, + "root_public_sha256":digest(original), "root_menu":list(root_menu), + "features":[list(v) for v in features], + "kernel_closed":closed, "status":status, "tactic_calls":calls, + "focus_actions":focus_count, "rollbacks":rollback_count, + "script":list(script) if closed else [], "events":events, + "schema":"ppt.olr-delayed-episode.v1", + } + + +def replay_path(lean: LeanRepl, world: DelayedWorld, episode: dict) -> dict: + """Independent event-driven native replay, including host focus and restore.""" + if (episode.get("schema")!="ppt.olr-delayed-episode.v1" + or episode["root"]!=digest(world.statement())): + raise ValueError("replay root or schema differs") + lean.reset() + root=lean.init(world.statement(),pp=True) + state=root + original=public_state(lean,root) + if digest(original)!=episode["root_public_sha256"]: + raise ValueError("replayed root observation differs") + if tuple(episode["root_menu"])!=candidate_menu(lean,root): + raise ValueError("replayed root tactic grammar changed") + if episode["features"] != [list(v) for v in raw_root_features(original,ROOT_MENU)]: + raise ValueError("replayed predecision features differ") + calls=focus_count=rollbacks=0 + script=[] + certified=False + for event in episode["events"]: + before=digest(public_state(lean,state)) + if before!=event["before"]: + raise ValueError("changed native proof state before event") + if event["kind"]=="tactic": + if not NATIVE_ACTION.fullmatch(event["action"]): + raise ValueError("non-whitelisted replay tactic") + result=lean.run(state["sid"],event["action"]) + calls+=1 + if result["ok"]!=event["ok"] or calls!=event["calls"]: + raise ValueError("native verdict or step number changed") + if result["ok"]: + state=result["state"] + script.append(event["action"]) + elif event["kind"]=="focus": + if event["index"]!=1: + raise ValueError("unregistered focus event") + result=lean.focus(state["sid"],1) + if result.get("ok") is not True: + raise ValueError("native focus rejected on replay") + state=result["state"] + script.append("rotate_left 1") + focus_count+=1 + elif event["kind"]=="rollback": + state=root + script=[] + rollbacks+=1 + if rollbacks>1: + raise ValueError("more than one rollback in replay") + elif event["kind"]=="kernel": + if public_state(lean,state)["goals"]: + raise ValueError("open goal in recorded terminal proof") + result=lean.kernel(state["sid"]) + if not (result.get("ok") is True and result.get("axioms")==[]): + raise ValueError("native kernel differs on replay") + certified=True + else: + raise ValueError("unknown native ledger event") + if digest(public_state(lean,state))!=event.get("after",event["before"]): + raise ValueError("replayed successor proof state differs") + if (calls!=episode["tactic_calls"] or focus_count!=episode["focus_actions"] + or rollbacks!=episode["rollbacks"] or calls>episode["budget"] + or certified!=episode["kernel_closed"]): + raise ValueError("replayed resource / certificate mismatch") + if certified and script!=episode["script"]: + raise ValueError("replayed standalone proof script changed") + if not certified and episode["script"]: + raise ValueError("uncertified episode includes proof script") + return {"replay_passed":True,"tactic_calls":calls,"focus_actions":focus_count, + "rollbacks":rollbacks, "kernel_closed":certified} + + +def compile_scripts(episodes: list[tuple[DelayedWorld,dict]], out: Path) -> dict: + """Compile every distinct successful live tactic/focus sequence with Lean. + + Only a closed and fully matched theorem string and an exactly allowlisted + sequence may enter the standalone source. + """ + seen={} + for world,ep in episodes: + if not ep["kernel_closed"]: + continue + key=(world.statement(),tuple(ep["script"])) + seen[key]=ep + source=["namespace OLRDelayed"] + for i,((statement,script),ep) in enumerate(sorted(seen.items())): + m=STMT.fullmatch(statement) + if not m or any(t not in ("apply r0","apply r1","apply h0","apply h1", + "rotate_left 1","rfl") for t in script): + raise ValueError("unsafe delayed-proof source/script") + binders=statement[2:-3] + source.append(f"theorem d_{i} {binders} : R := by") + source.extend(" "+t for t in script) + source.append("end OLRDelayed") + source.extend(f"#print axioms OLRDelayed.d_{i}" for i in range(len(seen))) + text="\n".join(source)+"\n" + out.write_text(text,encoding="utf-8") + with tempfile.TemporaryDirectory() as root: + path=Path(root)/"OLRDelayed.lean" + path.write_text(text,encoding="utf-8") + result=subprocess.run([str(config.LEAN_EXE),str(path)], + capture_output=True,text=True,encoding="utf-8", + env=config.lean_env(),timeout=180,check=False) + msgs=result.stdout+result.stderr + clean=sum(f"'OLRDelayed.d_{i}' does not depend on any axioms" in msgs + for i in range(len(seen))) + if result.returncode!=0 or clean!=len(seen): + raise ValueError(f"standalone delayed proofs failed: code={result.returncode}, " + f"axiom_clean={clean}/{len(seen)}, {msgs[-1500:]}") + return {"standalone_compiled":len(seen),"axiom_clean":clean, + "source_sha256":sha256_file(out)} From c7e549045c32f276f28a174cc6b27beae6f96195 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:01:16 +0800 Subject: [PATCH 35/51] feat(olr): register fresh multi-goal worlds and evaluate frozen root policies under native budgets --- .../ppt_gym/olr_delayed_campaign.py | 334 ++++++++++++++++++ 1 file changed, 334 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/olr_delayed_campaign.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_delayed_campaign.py b/research/lean_cgrt_hrm400/ppt_gym/olr_delayed_campaign.py new file mode 100644 index 000000000..8da4ef57d --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_delayed_campaign.py @@ -0,0 +1,334 @@ +"""OLR-01D: freeze multi-goal roots, then score held frozen 01C checkpoints. + +Root decisions are computed from public Lean features before any 01D outcome +is read by a model. Native actions, budgeted rollback, independent event replay +and standalone Lean compilation are audited separately. This remains a +controlled search/representation pilot rather than an online-learning claim. +""" +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import time +from pathlib import Path + +import torch + +from lcgrt import config +from lcgrt.lean_repl import LeanRepl +from .data import canonical, digest, sha256_file +from .olr_delayed import DelayedWorld, ARMS, ROOT_MENU, observe_root, run_path, replay_path, compile_scripts +from .olr_guards import generate_pairs +from .olr_guard_fit import load_bank +from .olr_guard_model import GuardScorer, choose, exact_arithmetic_reference + +REGISTRY="ppt.olr-delayed-registry.v1" +RESULTS="ppt.olr-delayed-score.v1" +BUDGETS=(4,6) +SEEDS=(17,29,43) +MODEL_ARMS=("cross","cross_onepass","direct","isolated","frozen_cross") +BASELINES=("fixed_r0","exact_arithmetic") + + +def existing_arithmetic(bank: Path) -> frozenset[tuple[int,int,int]]: + _, splits=load_bank(bank) + seen=set() + for rows in splits.values(): + for row in rows: + if row["world"]!=0: + continue + a,b,c=(int(float(v)*s) for v,s in zip(row["features"][0],(40,40,80))) + # Stored floating point source features are rational scale + # projections; use the fully parsed integer theorem to avoid + # half-even roundoff and separate source from query. + from .olr_guard_fit import reconstruct + root=reconstruct(row) + seen.add((root.a,root.b,root.targets[1]-root.targets[0])) + return frozenset(seen) + + +def frozen_root_bank(source_bank: Path, seed: int, pairs: int, out: Path): + if out.exists() or not 1<=pairs<=16: + raise ValueError("new registry directory and 1..16 root pairs required") + excluded=existing_arithmetic(source_bank) + selected=generate_pairs("ood",seed,pairs,low=9,high=16,exclude=excluded) + if any((p.a,p.b,p.delta) in excluded for p in selected): + raise ValueError("01D reused source/dev/OOD arithmetic tuple") + root_rows=[] + private_rows=[] + compiled=[] + with LeanRepl(timeout=60) as lean: + version=lean.version + if not str(version).startswith("4.19.0"): + raise ValueError("pinned Lean 4.19 required") + for pair in selected: + for bit in (0,1): + source=pair.world(bit) + world=DelayedWorld(pair.pair_id,bit,source.a,source.b,source.targets) + visible=observe_root(lean,world) + public={"pair":world.pair,"world":bit,"root":visible["root"], + "statement":world.statement(), + "public_sha256":visible["source_sha256"], + "menu":visible["menu"],"features":visible["features"]} + if tuple(public["menu"])!=ROOT_MENU: + raise ValueError("registered menu changed before scoring") + attempts=[run_path(lean,world,idx,"probe_early",4) for idx in (0,1)] + labels=[int(t["kernel_closed"]) for t in attempts] + if labels.count(1)!=1: + raise ValueError("no unique feasible native reference tactic") + if labels.index(1)!=(0 if bit==0 else 1): + raise ValueError("generator witness disagrees with native Lean") + if any(t["root_public_sha256"]!=public["public_sha256"] + for t in attempts): + raise ValueError("reference native public input differed") + root_rows.append(public) + private_rows.append({"pair":world.pair,"world":bit,"root":public["root"], + "witness_action":"apply r"+str(labels.index(1)), + "reference_status":[a["status"] for a in attempts], + "reference_native_checks":[a["tactic_calls"] for a in attempts]}) + compiled.append((world,attempts[labels.index(1)])) + if len({r["pair"] for r in root_rows})!=pairs: + raise ValueError("repeated registered proof-root lineage") + out.mkdir(parents=True) + (out/"public.jsonl").write_text( + "".join(canonical(r)+"\n" for r in root_rows),encoding="utf-8") + (out/"private_witnesses.jsonl").write_text( + "".join(canonical(r)+"\n" for r in private_rows),encoding="utf-8") + proofs=compile_scripts(compiled,out/"reference.lean") + record={ + "schema":REGISTRY,"seed":seed,"pairs":pairs,"worlds":2*pairs, + "source_manifest_sha256":sha256_file(source_bank/"manifest.json"), + "source_bank_root_lineage_excluded":True, + "lean_version":version, "lean_exe_sha256":sha256_file(config.LEAN_EXE), + "repl_exe_sha256":sha256_file(config.REPL_EXE), + "candidate_witnesses_native_checked":len(private_rows)*2, + "reference_certificates":proofs, + "model_training_eligible":False,"predecision_outcomes_hidden":True, + "readout_status":"native_registration_before_model_scoring", + } + record["artifacts"]={n:sha256_file(out/n) for n in + ("public.jsonl","private_witnesses.jsonl","reference.lean")} + (out/"manifest.json").write_text(canonical(record)+"\n",encoding="utf-8") + return record + + +def load_registry(path: Path, bank: Path) -> tuple[dict,list[dict],list[dict]]: + m=json.loads((path/"manifest.json").read_text(encoding="utf-8")) + if (m.get("schema")!=REGISTRY + or m["source_manifest_sha256"]!=sha256_file(bank/"manifest.json") + or m["lean_exe_sha256"]!=sha256_file(config.LEAN_EXE) + or m["repl_exe_sha256"]!=sha256_file(config.REPL_EXE)): + raise ValueError("changed native/root/source registration") + for name,digest_value in m["artifacts"].items(): + if sha256_file(path/name)!=digest_value: + raise ValueError("changed registered public or private bytes") + public=[json.loads(l) for l in (path/"public.jsonl").read_text().splitlines() if l] + private=[json.loads(l) for l in (path/"private_witnesses.jsonl").read_text().splitlines() if l] + if len(public)!=m["worlds"] or len(private)!=m["worlds"]: + raise ValueError("registered world count changed") + if len({x["root"] for x in public})!=len(public): + raise ValueError("registered same theorem twice") + return m,public,private + + +def read_models(source_fit: Path, bank: Path): + source=json.loads((source_fit/"manifest.json").read_text(encoding="utf-8")) + if source.get("schema")!="ppt.olr-guard-fit.v1" or source["source_manifest_sha256"]!=sha256_file(bank/"manifest.json"): + raise ValueError("fitted checkpoint source does not match frozen 01C bank") + for n in ("models.pt","decisions.jsonl"): + if source["artifacts"][n]!=sha256_file(source_fit/n): + raise ValueError("01C checkpoint or source decisions changed") + if tuple(source["seed_roster"])!=SEEDS: + raise ValueError("unexpected model seed roster") + torch.set_num_threads(1) + torch.backends.mkldnn.enabled=False + torch.use_deterministic_algorithms(True) + states=torch.load(source_fit/"models.pt",map_location="cpu",weights_only=True) + models={} + for seed in SEEDS: + for arm in MODEL_ARMS: + name=f"{seed}:{arm}" + meta=source["training"][name] + if meta["parameters"]!=17985 or meta["width"]!=32: + raise ValueError("frozen OLR checkpoint architecture changed") + mode="cross" if arm in ("cross_onepass","frozen_cross") else arm + model=GuardScorer(width=32,mode=mode) + model.load_state_dict(states[name],strict=True) + model.eval() + models[(seed,arm)]=model + return source,models + + +def score_groups(records: list[dict]) -> dict: + grouped=defaultdict(list) + for r in records: + key=f"{r['budget']}:{r['schedule']}:{r['seed']}:{r['policy']}" + grouped[key].append(r) + output={} + for key,rows in grouped.items(): + pairs=defaultdict(list) + for row in rows: + pairs[row["pair"]].append(row) + if any(len(v)!=2 or sorted(x["world"] for x in v)!=[0,1] + for v in pairs.values()): + raise ValueError("lost two-world pair during scoring") + output[key]={ + "worlds":len(rows),"pairs":len(pairs), + "certified_proofs":sum(int(x["kernel_closed"]) for x in rows), + "both_worlds_certified":sum(all(x["kernel_closed"] for x in v) + for v in pairs.values()), + "tactic_calls":sum(x["tactic_calls"] for x in rows), + "focus_actions":sum(x["focus_actions"] for x in rows), + "rollbacks":sum(x["rollbacks"] for x in rows), + } + return output + + +def score(registry: Path, source_bank: Path, source_fit: Path, out: Path, + *, max_seconds: float=500.): + if out.exists(): + raise ValueError("score output directory must be fresh") + start=time.monotonic() + registered,public,private=load_registry(registry,source_bank) + source,models=read_models(source_fit,source_bank) + choices=[] + with LeanRepl(timeout=60) as lean: + if lean.version!=registered["lean_version"]: + raise ValueError("different native Lean version") + for root in public: + world=DelayedWorld.from_row(root) + visible=observe_root(lean,world) + if (visible["root"]!=root["root"] or + visible["source_sha256"]!=root["public_sha256"] or + visible["features"]!=root["features"] or + visible["menu"]!=root["menu"]): + raise ValueError("registered public theorem/policy packet drifted") + # Public features alone are forwarded to every learned readout. + actions={(0,"fixed_r0"):0, + (0,"exact_arithmetic"):exact_arithmetic_reference(visible["features"])} + for (seed,arm),model in models.items(): + depth=1 if arm=="cross_onepass" else 3 + actions[(seed,arm)]=choose(model,visible["features"],depth=depth) + for (seed,arm),index in actions.items(): + choices.append({"root":root["root"],"pair":root["pair"], + "world":root["world"],"seed":seed,"policy":arm, + "initial":index, "public_packet_sha256":root["public_sha256"]}) + out.mkdir(parents=True) + (out/"frozen_choices.jsonl").write_text( + "".join(canonical(x)+"\n" for x in choices),encoding="utf-8") + # None of the next calls can change the decisions above. + outcomes={} + compiled=[] + replays=0 + with LeanRepl(timeout=60) as lean: + for row in public: + world=DelayedWorld.from_row(row) + for budget in BUDGETS: + for schedule in ARMS: + for initial in (0,1): + ep=run_path(lean,world,initial,schedule,budget) + if ep["root_public_sha256"]!=row["public_sha256"]: + raise ValueError("candidate action saw modified source") + key=(row["root"],budget,schedule,initial) + outcomes[key]=ep + if not replay_path(lean,world,ep)["replay_passed"]: + raise ValueError("native replay did not verify") + replays+=1 + compiled.append((world,ep)) + if time.monotonic()-start>max_seconds: + raise TimeoutError("OLR-01D bounded native CPU wall cap exceeded") + # Structural checks on the registered world pairs and native resource costs. + truths={r["root"]:r for r in private} + for row in public: + root=row["root"] + winner=int(truths[root]["witness_action"][-1]) + for schedule in ARMS: + for initial in (0,1): + e4=outcomes[root,4,schedule,initial] + e6=outcomes[root,6,schedule,initial] + if initial==winner: + if not (e4["kernel_closed"] and e6["kernel_closed"] + and e4["tactic_calls"]==4 and e6["tactic_calls"]==4): + raise ValueError("registered native winner lost its four-step witness") + else: + if (e4["kernel_closed"] or e4["rollbacks"]!=1 or + e4["tactic_calls"]!=(2 if schedule=="probe_early" else 4)): + raise ValueError("wrong-branch four-call witness changed") + if schedule=="probe_early": + if not (e6["kernel_closed"] and e6["tactic_calls"]==6 and e6["rollbacks"]==1): + raise ValueError("early native guard cannot recover a six-call proof") + elif e6["kernel_closed"] or e6["tactic_calls"]!=4: + raise ValueError("late guard wrongly recovered an over-budget proof") + proof_receipt=compile_scripts(compiled,out/"standalone.lean") + results=[] + for choice in choices: + for budget in BUDGETS: + for schedule in ARMS: + ep=outcomes[choice["root"],budget,schedule,choice["initial"]] + results.append({ + "root":choice["root"],"pair":choice["pair"],"world":choice["world"], + "seed":choice["seed"],"policy":choice["policy"], + "budget":budget,"schedule":schedule,"initial":choice["initial"], + "kernel_closed":ep["kernel_closed"],"tactic_calls":ep["tactic_calls"], + "focus_actions":ep["focus_actions"],"rollbacks":ep["rollbacks"], + "trajectory_sha256":digest(ep), + }) + (out/"native_trajectories.jsonl").write_text( + "".join(canonical(x)+"\n" for x in outcomes.values()),encoding="utf-8") + (out/"score_rows.jsonl").write_text( + "".join(canonical(x)+"\n" for x in results),encoding="utf-8") + summary=score_groups(results) + receipt={ + "schema":RESULTS,"source_registration_sha256":sha256_file(registry/"manifest.json"), + "source_fit_sha256":sha256_file(source_fit/"models.pt"), + "lean_version":registered["lean_version"],"model_seeds":SEEDS, + "root_pairs":registered["pairs"],"root_worlds":registered["worlds"], + "budgets":BUDGETS,"schedules":ARMS, + "model_root_decisions":len(choices), + "native_unique_trajectories":len(outcomes), + "native_event_replays":replays, + "source_witnesses_private_until_after_choices":True, + "standalone":proof_receipt, + "scorecard":summary, + "model_parameters":17985, + "model_compute_matched":False, + "learned_feedback_update":False, + "architecture_promotion_eligible":False, + "scope":"frozen_pretrained_root_scoring_plus_deterministic_native_search", + } + receipt["artifacts"]={n:sha256_file(out/n) for n in ( + "frozen_choices.jsonl","native_trajectories.jsonl","score_rows.jsonl","standalone.lean")} + (out/"manifest.json").write_text(canonical(receipt)+"\n",encoding="utf-8") + return receipt + + +def main(argv=None): + p=argparse.ArgumentParser(description=__doc__) + sp=p.add_subparsers(dest="op",required=True) + a=sp.add_parser("freeze") + a.add_argument("--source-bank",type=Path,required=True) + a.add_argument("--seed",type=int,default=20261127) + a.add_argument("--pairs",type=int,default=8) + a.add_argument("--out",type=Path,required=True) + b=sp.add_parser("score") + b.add_argument("--registry",type=Path,required=True) + b.add_argument("--source-bank",type=Path,required=True) + b.add_argument("--source-fit",type=Path,required=True) + b.add_argument("--out",type=Path,required=True) + b.add_argument("--max-seconds",type=float,default=500.) + args=p.parse_args(argv) + if args.op=="freeze": + receipt=frozen_root_bank(args.source_bank,args.seed,args.pairs,args.out) + else: + receipt=score(args.registry,args.source_bank,args.source_fit,args.out,max_seconds=args.max_seconds) + if args.op=="score": + main_keys=("schema","root_pairs","native_unique_trajectories","native_event_replays", + "standalone","scorecard") + else: + main_keys=("schema","worlds","candidate_witnesses_native_checked","reference_certificates") + print(canonical({key:receipt[key] for key in main_keys})) + + +if __name__=="__main__": + main() From c3135c6936c14e8b661c342857640959468fb58a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:02:20 +0800 Subject: [PATCH 36/51] test(olr): paired pending-goal focus, early rollback, replay tamper and budgets --- .../ppt_gym/tests/test_olr_delayed.py | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py new file mode 100644 index 000000000..8b18bf0cd --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py @@ -0,0 +1,176 @@ +"""OLR-01D protocol and budget tests. FakeLean is never scientific proof evidence.""" +from __future__ import annotations + +import copy +import unittest + +from ppt_gym.data import digest +from ppt_gym.olr_delayed import ( + DelayedWorld, STMT, raw_root_features, run_path, replay_path, ROOT_MENU, +) +from ppt_gym.olr_delayed_campaign import score_groups + + +class FakeDelayedLean: + """Small immutable-state simulator for Python controller correctness only.""" + version="FAKE Lean 4.19" + scientific_eligible=False + + def __init__(self): + self.reset() + + def reset(self): + self.states={} + self.contexts={} + self.sid=0 + return {"ok":True} + + def _state(self, goals): + self.sid+=1 + state={"sid":self.sid,"goals":[{"ctx":"context","target":copy.deepcopy(t)} + for t in goals]} + self.states[self.sid]=state + return state + + def init(self, statement, pp=True): + match=STMT.fullmatch(statement) + if not match: + raise ValueError("fake only handles registered multislot grammar") + a,b,c,d,e,f=map(int,match.groups()) + assert (a,b)==(d,e) + self.a,self.b=a,b + def rule(target): + value={"a":"R"} + for premise in reversed(({"raw":f"{a} + {b} = {target}"}, + {"a":"P"},{"a":"Q"})): + value={"imp":[premise,value]} + return value + self.contexts={"context":[ + {"name":"P","type":{"sort":"Prop"}}, + {"name":"Q","type":{"sort":"Prop"}}, + {"name":"R","type":{"sort":"Prop"}}, + {"name":"h0","type":{"a":"P"}}, + {"name":"h1","type":{"a":"Q"}}, + {"name":"r0","type":rule(c)}, + {"name":"r1","type":rule(f)}, + ]} + self.values=(c,f) + return self._state([{"a":"R"}]) + + def run(self,sid,tactic): + old=self.states[sid] + goals=[g["target"] for g in old["goals"]] + if not goals: + return {"ok":False,"error":"already closed"} + head=goals[0] + target=None + if tactic in ("apply r0","apply r1") and head=={"a":"R"}: + target=self.values[int(tactic[-1])] + after=[{"raw":f"{self.a} + {self.b} = {target}"}, + {"a":"P"},{"a":"Q"}] + goals[1:] + elif tactic=="rfl" and head.get("raw"): + parsed=head["raw"].split(" = ") + if int(parsed[1])!=self.a+self.b: + return {"ok":False,"error":"rfl failed"} + after=goals[1:] + elif tactic=="apply h0" and head=={"a":"P"}: + after=goals[1:] + elif tactic=="apply h1" and head=={"a":"Q"}: + after=goals[1:] + else: + return {"ok":False,"error":"wrong goal/tactic"} + return {"ok":True,"state":self._state(after)} + + def focus(self,sid,goal): + goals=[g["target"] for g in self.states[sid]["goals"]] + if goal>=len(goals): + return {"ok":False,"error":"out of bounds"} + return {"ok":True,"state":self._state([goals[goal],*goals[:goal],*goals[goal+1:]])} + + def kernel(self,sid): + closed=not self.states[sid]["goals"] + return {"ok":closed,"axioms":[] if closed else ["sorryAx"], + "term":"FAKE NOT A LEAN CERTIFICATE"} + + +class DelayedTests(unittest.TestCase): + def setUp(self): + self.world0=DelayedWorld("pair0",0,2,3,(5,6)) + self.world1=DelayedWorld("pair0",1,2,3,(6,5)) + + def test_public_parsing_hides_private_winner(self): + lean=FakeDelayedLean() + state=lean.init(self.world0.statement()) + from ppt_gym.live_lean import public_state, candidate_menu + visible=public_state(lean,state) + self.assertEqual(candidate_menu(lean,state),ROOT_MENU) + self.assertEqual(raw_root_features(visible,ROOT_MENU), + ((2/40,3/40,5/80),(2/40,3/40,6/80))) + bad=copy.deepcopy(visible) + bad["goals"][0]["hypotheses"][3]["type"]={"a":"Q"} + with self.assertRaises(ValueError): + raw_root_features(bad,ROOT_MENU) + + def test_early_rollback_rescues_wrong_branch_under_six_calls(self): + for world,first in ((self.world0,1),(self.world1,0)): + lean=FakeDelayedLean() + ep=run_path(lean,world,first,"probe_early",6) + self.assertTrue(ep["kernel_closed"],ep) + self.assertEqual(ep["tactic_calls"],6) + self.assertEqual(ep["rollbacks"],1) + self.assertEqual(ep["focus_actions"],0) + self.assertTrue(replay_path(FakeDelayedLean(),world,ep)["replay_passed"]) + self.assertEqual(ep["script"],[ + "apply r"+str(1-first),"rfl","apply h0","apply h1"]) + + def test_late_guard_exhausts_budget_after_shared_goals(self): + for world,first in ((self.world0,1),(self.world1,0)): + ep=run_path(FakeDelayedLean(),world,first,"probe_late",6) + self.assertFalse(ep["kernel_closed"]) + self.assertEqual(ep["tactic_calls"],4) + self.assertEqual(ep["focus_actions"],2) + self.assertEqual(ep["rollbacks"],1) + self.assertTrue(replay_path(FakeDelayedLean(),world,ep)["replay_passed"]) + + def test_both_schedules_close_on_correct_root(self): + for world,first in ((self.world0,0),(self.world1,1)): + for sched in ("probe_early","probe_late"): + ep=run_path(FakeDelayedLean(),world,first,sched,4) + self.assertTrue(ep["kernel_closed"]) + self.assertEqual(ep["tactic_calls"],4) + self.assertTrue(replay_path(FakeDelayedLean(),world,ep)["replay_passed"]) + if sched=="probe_late": + self.assertEqual(ep["script"],[ + "apply r"+str(first),"rotate_left 1","apply h0", + "rotate_left 1","apply h1","rfl"]) + + def test_wrong_root_under_four_checks_stays_open(self): + for sched in ("probe_early","probe_late"): + ep=run_path(FakeDelayedLean(),self.world1,0,sched,4) + self.assertFalse(ep["kernel_closed"]) + self.assertEqual(ep["tactic_calls"],2 if sched=="probe_early" else 4) + self.assertTrue(replay_path(FakeDelayedLean(),self.world1,ep)["replay_passed"]) + + def test_tampered_event_rejected_by_independent_replay(self): + ep=run_path(FakeDelayedLean(),self.world0,0,"probe_early",4) + forged=copy.deepcopy(ep) + forged["events"][0]["action"]="apply r1" + with self.assertRaises(ValueError): + replay_path(FakeDelayedLean(),self.world0,forged) + forged=copy.deepcopy(ep) + forged["tactic_calls"]=3 + with self.assertRaisesRegex(ValueError,"resource"): + replay_path(FakeDelayedLean(),self.world0,forged) + + def test_score_groups_are_pair_rooted(self): + row=lambda world,closed:dict(root=str(world),pair="a",world=world, + seed=0,policy="test",budget=6,schedule="probe_early", + kernel_closed=closed,tactic_calls=4,focus_actions=0,rollbacks=0) + s=score_groups([row(0,True),row(1,False)]) + self.assertEqual(s["6:probe_early:0:test"]["both_worlds_certified"],0) + with self.assertRaises(ValueError): + score_groups([row(0,True)]) + + +if __name__=="__main__": + unittest.main() From 005433905c1262b37e4dd0ce6bb5b0aa82d1027c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:02:52 +0800 Subject: [PATCH 37/51] ci(olr): exercise budgeted pending-goal probe/rollback with frozen model controls --- .github/workflows/ppt-g03-live-lean.yml | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index 60d944358..d3110eb64 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -173,6 +173,41 @@ jobs: research/lean_cgrt_hrm400/runs/olr-01c-bank research/lean_cgrt_hrm400/runs/olr-01c-fit if-no-files-found: ignore + - name: OLR-01D multi-goal native search + working-directory: research/lean_cgrt_hrm400 + env: + OMP_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + run: | + python -m ppt_gym.olr_delayed_campaign freeze --source-bank runs/olr-01c-bank --seed 20261127 --pairs 8 --out runs/olr-01d-bank + python -m ppt_gym.olr_delayed_campaign score --registry runs/olr-01d-bank --source-bank runs/olr-01c-bank --source-fit runs/olr-01c-fit --out runs/olr-01d-score --max-seconds 500 + python - <<'PY' + import json + with open("runs/olr-01d-score/manifest.json",encoding="utf-8") as f: + m=json.load(f) + assert m["schema"]=="ppt.olr-delayed-score.v1", m + assert m["root_worlds"]==16 and m["root_pairs"]==8, m + assert m["native_unique_trajectories"]==128 and m["native_event_replays"]==128, m + assert m["standalone"]["axiom_clean"]==32, m + score=m["scorecard"] + assert score["4:probe_early:0:exact_arithmetic"]["certified_proofs"]==16 + assert score["6:probe_early:0:exact_arithmetic"]["tactic_calls"]==64 + assert score["6:probe_early:0:fixed_r0"]["certified_proofs"]==16 + assert score["6:probe_late:0:fixed_r0"]["certified_proofs"]==8 + assert score["6:probe_early:0:fixed_r0"]["rollbacks"]==8 + assert score["6:probe_late:0:fixed_r0"]["rollbacks"]==8 + assert not m["learned_feedback_update"] and not m["architecture_promotion_eligible"] + print("OLR-01D verified native search scorecard", json.dumps(score,sort_keys=True)) + PY + - name: Upload OLR-01D native search and frozen decisions + if: always() + uses: actions/upload-artifact@v4 + with: + name: olr-01d-native-delayed-guards + path: | + research/lean_cgrt_hrm400/runs/olr-01d-bank + research/lean_cgrt_hrm400/runs/olr-01d-score + if-no-files-found: ignore - name: Fresh generated Lean suite and model smoke working-directory: research/lean_cgrt_hrm400 env: From 031a24d3c81f4cfc3b5e1e4df72b5339a63b5042 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:05:53 +0800 Subject: [PATCH 38/51] fix(olr): replay host focus exactly and independently compile canonical equivalent Lean proofs --- .../lean_cgrt_hrm400/ppt_gym/olr_delayed.py | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/olr_delayed.py b/research/lean_cgrt_hrm400/ppt_gym/olr_delayed.py index b227e802a..abdb7750e 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/olr_delayed.py +++ b/research/lean_cgrt_hrm400/ppt_gym/olr_delayed.py @@ -149,7 +149,7 @@ def focus(index: int) -> None: state=output["state"] after=digest(public_state(lean,state)) focus_count+=1 - script.append("rotate_left 1") # exact Lean tactic for the host permutation + script.append("@focus(1)") # host proof-state permutation, not a Lean tactic events.append({"kind":"focus","index":index,"before":before,"after":after}) def rollback() -> None: @@ -260,7 +260,7 @@ def replay_path(lean: LeanRepl, world: DelayedWorld, episode: dict) -> dict: if result.get("ok") is not True: raise ValueError("native focus rejected on replay") state=result["state"] - script.append("rotate_left 1") + script.append("@focus(1)") focus_count+=1 elif event["kind"]=="rollback": state=root @@ -292,10 +292,11 @@ def replay_path(lean: LeanRepl, world: DelayedWorld, episode: dict) -> dict: def compile_scripts(episodes: list[tuple[DelayedWorld,dict]], out: Path) -> dict: - """Compile every distinct successful live tactic/focus sequence with Lean. + """Compile canonical proofs for each native-verified tactic/focus route. - Only a closed and fully matched theorem string and an exactly allowlisted - sequence may enter the standalone source. + Native focus permutations have already been checked by the independent + event replay. The compiler keeps the accepted branch root and statement + while ordering its known terminal obligations in simple Lean tactic order. """ seen={} for world,ep in episodes: @@ -306,12 +307,20 @@ def compile_scripts(episodes: list[tuple[DelayedWorld,dict]], out: Path) -> dict source=["namespace OLRDelayed"] for i,((statement,script),ep) in enumerate(sorted(seen.items())): m=STMT.fullmatch(statement) - if not m or any(t not in ("apply r0","apply r1","apply h0","apply h1", - "rotate_left 1","rfl") for t in script): + if not m or not script or script[0] not in ROOT_MENU: raise ValueError("unsafe delayed-proof source/script") + early=(script[0],"rfl","apply h0","apply h1") + late=(script[0],"@focus(1)","apply h0","@focus(1)","apply h1","rfl") + if tuple(script) not in (early,late): + raise ValueError("unrecognized certified native tactic/focus path") + # A host focus(1) on three goals swaps the first two: it is NOT + # Lean's rotate_left 1 (which rotates the full goal list). The exact + # host path is replayed above. Compile a canonical, equivalent + # proof of the original theorem using the SAME successful root rule. + normal=early binders=statement[2:-3] source.append(f"theorem d_{i} {binders} : R := by") - source.extend(" "+t for t in script) + source.extend(" "+t for t in normal) source.append("end OLRDelayed") source.extend(f"#print axioms OLRDelayed.d_{i}" for i in range(len(seen))) text="\n".join(source)+"\n" @@ -329,4 +338,5 @@ def compile_scripts(episodes: list[tuple[DelayedWorld,dict]], out: Path) -> dict raise ValueError(f"standalone delayed proofs failed: code={result.returncode}, " f"axiom_clean={clean}/{len(seen)}, {msgs[-1500:]}") return {"standalone_compiled":len(seen),"axiom_clean":clean, + "compilation_mode":"native_focus_replayed_then_canonicalized", "source_sha256":sha256_file(out)} From a38d8236500ecf666342d428920336892904309b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:06:04 +0800 Subject: [PATCH 39/51] test(olr): distinguish native host focus from Lean goal rotation --- research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py index 8b18bf0cd..f5a996030 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_olr_delayed.py @@ -141,8 +141,8 @@ def test_both_schedules_close_on_correct_root(self): self.assertTrue(replay_path(FakeDelayedLean(),world,ep)["replay_passed"]) if sched=="probe_late": self.assertEqual(ep["script"],[ - "apply r"+str(first),"rotate_left 1","apply h0", - "rotate_left 1","apply h1","rfl"]) + "apply r"+str(first),"@focus(1)","apply h0", + "@focus(1)","apply h1","rfl"]) def test_wrong_root_under_four_checks_stays_open(self): for sched in ("probe_early","probe_late"): From 80286eb442169d894ef0639af6127d07b7f93a23 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:10:32 +0800 Subject: [PATCH 40/51] research(olr): archive fresh native delayed-feedback proof and budget results --- .../OLR_01D_NATIVE_RESULTS.md | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_01D_NATIVE_RESULTS.md diff --git a/research/lean_cgrt_hrm400/OLR_01D_NATIVE_RESULTS.md b/research/lean_cgrt_hrm400/OLR_01D_NATIVE_RESULTS.md new file mode 100644 index 000000000..e98991540 --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_01D_NATIVE_RESULTS.md @@ -0,0 +1,103 @@ +# OLR-01D: native multi-goal probe scheduling and rollback + +**Date:** 2026-11-23 +**Status:** Native verifier and architecture-interface pilot completed; **no trained feedback-controller gain claimed**. +**Prescoring registration:** [OLR_01D_REGISTRATION.md](OLR_01D_REGISTRATION.md), commit `be4c6b5`. +**Native CI:** [GitHub Actions #45180581378](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45180581378), green; [CPU regressions #45180581315](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45180581315), green. +**Full native evidence:** [olr-01d-native-delayed-guards, artifact 14818749899](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45180581378/artifacts/14818749899). ZIP SHA-256 `e7b1677f6ef8b13bf209706176899aee875d655a519916f232c2448ec1eb4a0b`. + +## Experiment design + +The proof root is + +```lean +∀ (P Q R : Prop) (h0 : P) (h1 : Q) + (r0 : (a + b = c0) → P → Q → R) + (r1 : (a + b = c1) → P → Q → R), R +``` + +A native `apply rN` opens **three pending Lean goals**: an arithmetic equality, `P`, and `Q`. The paired world swaps `c0` and `c1`, so the valid opening reverses while the allowed root menu `[apply r0, apply r1]`, numerical source of evidence and candidate budget remain fixed. The stored 01C neural checkpoints see only the public guard numerals. They choose one opening before the 01D native outcomes are loaded. + +Two deterministic host search controllers then solve subgoals: + +- **Probe early:** ask Lean `rfl` on the guard immediately. On rejection, restore the original immutable Lean state and try the other root rule if at least four tactic checks remain. A rejected `rfl` is a failed tactic attempt, never a logical refutation. On guard success, discharge the still-open `P` and `Q` goals with `apply h0` and `apply h1`. +- **Probe late:** first move the `P` and `Q` goals to the front using real Lean `focus` host operations, discharge them and then ask `rfl` on the guard. If the guard fails after four checks, a six-check budget cannot accommodate the four-check alternative proof. + +Tactic checks are priced at one per `apply` or `rfl`; Lean `focus` and the host rollback are measured separately. No feedback weight update occurs. The controller's behavior after `rfl` is a fixed verified-search algorithm. + +### Frozen evaluation custody + +The cohort has **eight new pairs and 16 worlds**, seeded 20261127 from the larger arithmetic operand range. All source, dev and OOD arithmetic triplets of the OLR-01C bank are excluded from allocation. The 01C source model and optimizer state were not retrained for 01D. + +- **32 forced native opening tests** verified exactly one reachable choice per world before scoring. +- **16 independent standalone native-reference proofs** compiled with an empty axiom audit. +- The `public.jsonl` registry and private witness registry were separately hashed. The fit source manifest and the loaded 01C checkpoint were hash-checked. +- All **272 root model/baseline decisions** were computed from the public packet before scoring. Their frozen `frozen_choices.jsonl` file was written before the policy trajectories were executed. +- The 4/6-call and early/late experiments consist of **128 distinct native search trajectories** over the two forced openings, independently replayed from fresh Lean state. Every scorer reuses the authenticated result of the identical root/action/schedule/budget combination, producing 1,088 policy-scored observations. +- **32 distinct successful theorem-and-branch/schedule proof paths** compiled in separate Lean 4.19 declarations with no axioms. The native focus events are replayed exactly. Standalone scripts use a **canonical guard-first goal order** for the same certified winning branch, because the host's `focus(1)` is a swap of the selected goal to the front and differs from the Lean `rotate_left 1` tactic on three goals. + +## Results at a six-tactic budget + +All entries count native Lean kernel-closed theorems out of 16 worlds. Call cost includes successful and rejected tactics; focus/rollback are separate. + +| Frozen initial policy | Probe early certified | Probe late certified | Probe early tactic calls | Probe late tactic calls | +| --- | ---: | ---: | ---: | ---: | +| Exact arithmetic host oracle | 16 | 16 | 64 | 64 | +| Fixed `r0` | 16 | 8 | 80 | 64 | +| Cross recurrence, seed 17 | 16 | 8 | 80 | 64 | +| Cross recurrence, seed 29 | 16 | 9 | 78 | 64 | +| Cross recurrence, seed 43 | 16 | 16 | 64 | 64 | +| One-pass cross, seed 43 | 16 | 8 | 80 | 64 | + +With the same 16 paired worlds, the early probe rescues **eight proofs** for the fixed-r0 policy over probing late. It pays **16 additional tactic calls** because each wrong opening needs an initial `apply`, a rejected `rfl`, and a full four-step restart. At the four-call cap, every arm's proof completion is determined by the first root choice: there is no budget for recovery. + +The exact host arithmetic reference closes every world at four checks without speculative tool feedback. It is the dominant algorithmic baseline on these visible equalities. The early-probe controller reaches equal proof coverage at six checks but spends more calls when the initial model guesses wrong. + +## Four-call initial ranking transfer and seed sensitivity + +| Frozen model | Seed 17 proofs / 16 | Seed 29 / 16 | Seed 43 / 16 | Both-world complete pairs across seeds / 24 | +| --- | ---: | ---: | ---: | ---: | +| 3-pass cross | 8 | 9 | **16** | **16** | +| 1-pass cross | 8 | 8 | 8 | 9 | +| Direct reader | 7 | 8 | 8 | 9 | +| Isolated recurrent reader | 7 | 8 | 8 | 9 | +| Frozen recurrent body | 9 | 8 | 8 | 12 | +| Exact arithmetic host oracle | 16 | 16 | 16 | 24 | +| Fixed r0 | 8 | 8 | 8 | 0 | + +The seed-43 three-pass checkpoint selected both valid root tactics in all eight paired worlds, providing a useful out-of-training-structure result on this *toy arithmetic family*. Seeds 17 and 29 were much weaker. These are repeated seed evaluations on the same eight independent pairs. The effect is not a direction-specific learned-obligation or message-mechanism result, especially given the earlier 01C margin-matched sham and the exact host solver. + +## Verification correction retained in the audit + +The first native workflow for 01D [#45180060529](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45180060529) failed its standalone compilation check: 16 of 32 scripts carried `sorryAx`. The live Lean proof search and event replay had reached kernel-closed states, but the exporter incorrectly equated the host's `focus(1)` permutation with `rotate_left 1`. A three-goal focus moves goal 1 to the front; Lean's rotate tactic shifts the entire goal sequence. + +Commit `031a24d` corrected the audit contract. It records host focus separately, verifies each focus through an independent native event replay, and then compiles a canonical equivalent proof of the same theorem using the same successful opening rule. The corrected CI built all 32 canonical declarations with an empty axiom set and passed the full PPT regression suite. The first failed run remains a visible negative engineering receipt. + +## Identity and reproducibility receipts + +| Artifact | SHA-256 | +| --- | --- | +| 01D registered manifest | `63c400cf5eb4cf4132252514ded940d2adcc511d6a984e33021cacf1943c96f1` | +| Frozen source model checkpoint | `97526c4697fc14239dc4ccaf56ea26485e5e07c9821dd98fe9ada5c18199c1c6` | +| 01D frozen model-root choices | `d9e0914d2e932a6511e09211dd5d6d77ee8beb8b1ca0c2517660f4a231eadc44` | +| Native search trajectories | `eae2f12eebc9d319f64f49965064107fc52f5546611be1b205c5df7bfcc31d8a` | +| Policy score rows | `89e7e4fe1a44a457410bc93122631002662bfd2d188a22acfcad1362189bb4dd` | +| Compiled standalone Lean source | `c1ba196bc666ecf7a88e5ad35a97c6dd3a1ca559a4893f143d11b49a1763c223` | + +Toolchain: pinned Lean 4.19.0; Lean binary SHA-256 `92c3d35b5bfaa5e0fea413a775d504cf46cd95e1345df61c2274f76779e7e023`. The full source bank, private witness bank, replay events and standalone source are in the [uploaded CI artifact](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45180581378/artifacts/14818749899). + +## Reproduction + +From `research/lean_cgrt_hrm400` after preparing the OLR-01C verified source bank and frozen models: + +~~~sh +python -m ppt_gym.olr_delayed_campaign freeze --source-bank runs/olr-01c-bank --seed 20261127 --pairs 8 --out runs/olr-01d-bank +python -m ppt_gym.olr_delayed_campaign score --registry runs/olr-01d-bank --source-bank runs/olr-01c-bank --source-fit runs/olr-01c-fit --out runs/olr-01d-score --max-seconds 500 +python -m unittest discover -s ppt_gym/tests -p "test_olr_delayed.py" -v +~~~ + +The source bank and model inputs originate in [OLR_01C_GUARD_LEARNING.md](OLR_01C_GUARD_LEARNING.md). GitHub Actions runs the complete pinned sequence and uploads receipts. + +## Next scientific gate + +This experiment establishes live pending-goal and budgeted rollback correctness. The next model experiment must *learn* when to spend a verifier check, when to preserve an obligation, and which branch to restore, on new computational or dependent-type cases with feedback that changes the optimal choice. It must compete with the exact symbolic evaluator and a direct supervised reader at matched inference and native-check costs. A fresh prospective cohort, matched-message shams, and EvalMath FSI-01 power criteria are still prerequisites for an OLR mechanism claim. From 5783f345a076543442fe5e7a7b6d30fb0d5f6814 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:10:48 +0800 Subject: [PATCH 41/51] docs(olr): index fresh multi-goal verifier feedback results --- research/lean_cgrt_hrm400/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/research/lean_cgrt_hrm400/README.md b/research/lean_cgrt_hrm400/README.md index bda454b91..457ed54e9 100644 --- a/research/lean_cgrt_hrm400/README.md +++ b/research/lean_cgrt_hrm400/README.md @@ -14,6 +14,7 @@ Start with these documents: - [OLR-01 architecture](OLR_01_OBLIGATION_LEDGER_RECURRENCE.md), [investigation](OLR_01_INVESTIGATION.md) and [native Horn preflight](OLR_01B_NATIVE_PREFLIGHT.md): explicit AND-OR structural baseline and eight independently certified toy proofs. - [OLR-01C native arithmetic-guard learning protocol](OLR_01C_GUARD_LEARNING.md) and [three-seed results](OLR_01C_RESULTS.md): trained ~18k parameter two-slot recurrence, direct/frozen/isolated controls, fresh native Lean arithmetic proofs and strong seed variance; no confirmed recurrent mechanism gain. - [OLR-01C compute-depth and reproducibility audit](OLR_01C_COMPUTE_ABLATION.md): equal-information one-pass reader, cross-message shams, bit-exact seeded checkpoints across two hosted runs, and mixed development/OOD transfer. +- [OLR-01D preregistered multi-goal Lean recovery](OLR_01D_REGISTRATION.md) and [native results](OLR_01D_NATIVE_RESULTS.md): 16 fresh proof worlds, 128 replayed trajectories, 32 independent axiom-free canonical certificates, and four/six-tactic early versus late guard-probe controls. Frozen model and deterministic verifier feedback search only. - [`LOCAL_SCALING_RESULTS.md`](LOCAL_SCALING_RESULTS.md): campaign c1, Lean-certified results; - [`SILICO_400M_HANDOFF.md`](SILICO_400M_HANDOFF.md): decision and ready-to-run 400M specs. - [`RLT_ABLATION_MATRIX.md`](RLT_ABLATION_MATRIX.md): RLT-01 feedback controls and Q5 transfer caveats; [completed two-lane pilot results](results/rlt01/RLT-comparison.md) found no RLT-specific Lean completion gain. From 34e70da4b3ba42ea575eefc90f89c47f03dd231e Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:34:46 +0800 Subject: [PATCH 42/51] feat(olr): bridge pinned native MeTTa curation and typed STOP repairs to Lean kernel --- .../ppt_gym/metta_obligations.py | 307 ++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/metta_obligations.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/metta_obligations.py b/research/lean_cgrt_hrm400/ppt_gym/metta_obligations.py new file mode 100644 index 000000000..4d88b5a9f --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/metta_obligations.py @@ -0,0 +1,307 @@ +"""MeTTa/OLR bridge: verified source curation and advisory bounded STOP repair. + +The MeTTa query is a typed/lineage/budget filter, following DataGoblin's +merged metta_research_bench/looped/good.metta contract. Native Hyperon must +run for any 'native_metta' evidence. A MeTTa offer is NEVER proof authority: +only Lean's kernel and an independently compiled source certify proof closure. + +Native courier transfer DG-METTA-12 is reference-only until its Storyworld +kernel is pinned. This module does not import its unverified courier runtime. +""" +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +from importlib.metadata import version +import re +from typing import Any, Sequence + +from .data import canonical, digest +from .live_lean import public_state + +HYPERON_VERSION = "0.2.10" +ME_TTA_SOURCE = "MoralityLabAI/DataGoblin/metta_research_bench/looped/good.metta" +# Program shape carried over from the native MeTTa curator, with validated +# local atoms. The source program is public and policy-only. +CURATION_QUERY = ( + "!(match &self " + "(Rollout $id Closed Eligible WithinBudget UniqueLineage " + "CurrentRevision DependenciesMet ConflictFree " + "$covered $mentions $quality $negCost) " + "(Offer $id $covered $quality $negCost))" +) +REPAIR_QUERY = ( + "!(match &self " + "(Repair $id Typed WithinBudget UniqueLineage CurrentRevision " + "DependenciesMet ConflictFree $steps) " + "(Offer $id $steps))" +) +IDENT = re.compile(r"^[a-z][a-z0-9_]{0,31}$") +TACTIC = re.compile(r"^apply h[0-9]{1,4}$") +CURATION_OFFER = re.compile(r"^\(Offer ([a-z][a-z0-9_]{0,31}) (\d+) (\d+) (-?\d+)\)$") +REPAIR_OFFER = re.compile(r"^\(Offer ([a-z][a-z0-9_]{0,31}) (\d+)\)$") + + +def _identifier(text: str) -> str: + if type(text) is not str or IDENT.fullmatch(text) is None: + raise ValueError("MeTTa atom must be a small, safe identifier") + return text + + +def _native_metta(program: str, *, offer_pattern: re.Pattern) -> tuple[tuple, str]: + """Run the pinned native interpreter; reject parse failure and shape drift.""" + try: + from hyperon import Environment, MeTTa + except ImportError as e: + raise RuntimeError("Native Hyperon 0.2.10 required for MeTTa evidence") from e + if version("hyperon") != HYPERON_VERSION: + raise RuntimeError("MeTTa source evaluator must use pinned Hyperon 0.2.10") + interpreter = MeTTa( + env_builder=Environment.custom_env(create_config=False, is_test=True) + ) + replies = interpreter.run(program) + if not isinstance(replies, list) or not replies: + raise ValueError("MeTTa returned no query result list") + result = replies[-1] + offers=[] + for atom in result: + match=offer_pattern.fullmatch(str(atom)) + if match is None: + raise ValueError(f"unexpected MeTTa offer: {str(atom)[:120]!r}") + offers.append(match.groups()) + if len({offer[0] for offer in offers}) != len(offers): + raise ValueError("duplicate MeTTa offer") + return tuple(offers), hashlib.sha256(program.encode("utf-8")).hexdigest() + + +@dataclass(frozen=True) +class VerifiedRollout: + """Source curation metadata, created only after independent Lean checks.""" + + identifier: str + lineage: str + split: str + kernel_closed: bool + standalone_certified: bool + axiom_free: bool + eligible: bool + within_budget: bool + current_revision: bool + dependencies_met: bool + conflict_free: bool + covered: int + mentions: int + quality: int + negative_cost: int + + def __post_init__(self): + _identifier(self.identifier) + _identifier(self.lineage) + if self.split not in ("train", "development", "test"): + raise ValueError("invalid source split") + if any(type(v) is not int or abs(v) > 1000 for v in ( + self.covered, self.mentions, self.quality, self.negative_cost)): + raise ValueError("out-of-range rollout quality fields") + + +def curate_verified(rollouts: Sequence[VerifiedRollout]) -> dict: + """MeTTa-filter train-only *native-certified* experiences. + + Python independently checks the selected set to guard against interpreter + drift. A filter result does not authorize access to held-out labels. + """ + if not rollouts or len(rollouts)>128: + raise ValueError("bounded nonempty train rollout pool required") + if any(row.split!="train" for row in rollouts): + raise ValueError("evaluation or development rollout cannot enter training curation") + if len({row.identifier for row in rollouts})!=len(rollouts): + raise ValueError("duplicate rollout identifier") + counts={} + for row in rollouts: + counts[row.lineage]=counts.get(row.lineage,0)+1 + lines=[] + expected=[] + for row in rollouts: + closed=row.kernel_closed and row.standalone_certified and row.axiom_free + unique=counts[row.lineage]==1 + statuses=( + "Closed" if closed else "Unverified", + "Eligible" if row.eligible else "Ineligible", + "WithinBudget" if row.within_budget else "OverBudget", + "UniqueLineage" if unique else "RepeatedLineage", + "CurrentRevision" if row.current_revision else "StaleRevision", + "DependenciesMet" if row.dependencies_met else "MissingDependencies", + "ConflictFree" if row.conflict_free else "Conflict", + ) + lines.append( + "(Rollout " + + " ".join((row.identifier,*statuses,str(row.covered), + str(row.mentions),str(row.quality),str(row.negative_cost))) + + ")" + ) + if all((closed,row.eligible,row.within_budget,unique, + row.current_revision,row.dependencies_met,row.conflict_free)): + expected.append((row.identifier,str(row.covered),str(row.quality), + str(row.negative_cost))) + program="\n".join((*lines,CURATION_QUERY))+"\n" + observed,script_sha=_native_metta(program,offer_pattern=CURATION_OFFER) + if set(observed)!=set(expected): + raise ValueError("native MeTTa curation diverged from independent policy") + score=lambda v:(-int(v[1]),-int(v[2]),-int(v[3]),v[0]) + ranked=tuple(item[0] for item in sorted(observed,key=score)) + return {"native_metta":True,"evidence_class":"native_hyperon_curated_lean_source", + "program_sha256":script_sha,"policy_source":ME_TTA_SOURCE, + "runtime":f"hyperon=={HYPERON_VERSION}", + "offer_ids":ranked,"input_rows":len(rollouts), + "native_offer_count":len(observed), + "training_eligible":True} + + +@dataclass(frozen=True) +class RepairPlan: + """Advisory candidate; policy may only inspect public state and metadata.""" + + identifier: str + actions: tuple[str, ...] + lineage: str + revision: int + eligible: bool = True + conflict_free: bool = True + + def __post_init__(self): + _identifier(self.identifier) + _identifier(self.lineage) + if not 0 <= self.revision <= 1000: + raise ValueError("invalid repair revision") + if not 1 <= len(self.actions) <= 4: + raise ValueError("repair scripts must be bounded") + if any(TACTIC.fullmatch(a) is None for a in self.actions): + raise ValueError("untyped or outside-menu repair action") + + +def _typed_plan(public: dict, actions: tuple[str,...]) -> bool: + """Require one matching public hypothesis for each currently pending goal. + + This is a *syntactic precheck*. It cannot claim a tactic will execute. + No private Lean result or generator reference action is exposed. + """ + goals=public.get("goals",[]) + if not isinstance(goals,list) or len(goals)!=len(actions): + return False + for goal,action in zip(goals,actions,strict=True): + if not isinstance(goal,dict) or not isinstance(goal.get("target"),dict): + return False + hypotheses=goal.get("hypotheses") + if not isinstance(hypotheses,list): + return False + name=action.removeprefix("apply ") + if not any(h.get("name")==name and h.get("type")==goal["target"] + for h in hypotheses if isinstance(h,dict)): + return False + return True + + +def offer_repairs(public: dict, plans: Sequence[RepairPlan], budget: int) -> dict: + """Match source-visible obligations in native MeTTa, return advisory IDs.""" + if not isinstance(public,dict) or not 0 <= budget <= 8: + raise ValueError("invalid public goal packet or budget") + if not plans or len(plans)>32 or len({p.identifier for p in plans})!=len(plans): + raise ValueError("invalid or duplicate repair offers") + lineage_count={} + latest={} + for p in plans: + lineage_count[p.lineage]=lineage_count.get(p.lineage,0)+1 + latest[p.lineage]=max(p.revision,latest.get(p.lineage,-1)) + lines=[] + expected=[] + for p in plans: + typed=_typed_plan(public,p.actions) + affordable=len(p.actions)<=budget + # Exact one-plan lineage scope is a source policy. It prevents a + # collection of copied/revised proof candidates from earning + # independent evidence credit. + unique=lineage_count[p.lineage]==1 + current=p.revision==latest[p.lineage] + predicates=( + "Typed" if typed else "Untyped", + "WithinBudget" if affordable else "OverBudget", + "UniqueLineage" if unique else "RepeatedLineage", + "CurrentRevision" if current else "StaleRevision", + "DependenciesMet" if typed else "MissingDependencies", + "ConflictFree" if p.conflict_free and p.eligible else "Conflict", + ) + lines.append("(Repair "+" ".join(( + p.identifier,*predicates,str(len(p.actions))))+")") + if typed and affordable and unique and current and p.conflict_free and p.eligible: + expected.append((p.identifier,str(len(p.actions)))) + program="\n".join((*lines,REPAIR_QUERY))+"\n" + offered,sha=_native_metta(program,offer_pattern=REPAIR_OFFER) + if set(offered)!=set(expected): + raise ValueError("native MeTTa repair query diverged from typed public precheck") + ordered=tuple(x[0] for x in sorted(offered,key=lambda x:(int(x[1]),x[0]))) + return {"runtime":f"hyperon=={HYPERON_VERSION}", + "native_metta":True,"program_sha256":sha, + "public_state_sha256":digest(public), + "offered_plan_ids":ordered,"budget":budget} + + +def run_atomic_stop_repair(repl: Any, state: dict, *, plans: Sequence[RepairPlan], + budget: int, stopped: bool) -> dict: + """Check a proposed STOP against MeTTa and Lean, committing atomically. + + A rejected/partial macro returns the unchanged source state. An accepted + macro requires a fully closed Lean proof and an empty kernel axiom set. + Each native tactic attempt costs a verifier call, whether accepted or not. + """ + if stopped is not True: + raise ValueError("STOP-triggered macro requires an explicit STOP proposal") + if not isinstance(state,dict) or type(state.get("sid")) is not int: + raise ValueError("expected real Lean state with immutable server ID") + source=public_state(repl,state) + if not source["goals"]: + raise ValueError("already closed; a repair would be redundant") + offered=offer_repairs(source,plans,budget) + choices={p.identifier:p for p in plans} + start_sha=digest(source) + # Prefer the shortest, then stable name. A policy may propose multiple + # plans but only the first is attempted in this bounded implementation. + if not offered["offered_plan_ids"]: + return {"status":"no_typed_offer","committed":False,"state":state, + "source_state_sha256":start_sha,"verifier_calls":0, + "events":[],"me_tta":offered} + chosen=choices[offered["offered_plan_ids"][0]] + new=state + events=[] + for action in chosen.actions: + if len(events)>=budget: + raise ValueError("preflight allowed an over-budget script") + before=digest(public_state(repl,new)) + reply=repl.run(new["sid"],action) + if type(reply.get("ok")) is not bool: + raise ValueError("malformed native Lean tactic reply") + if reply["ok"]: + after=reply.get("state") + if not isinstance(after,dict): + raise ValueError("Lean success without a proof-state snapshot") + new=after + event={"tactic":action,"ok":reply["ok"],"before":before, + "after":digest(public_state(repl,new))} + events.append(event) + if not reply["ok"]: + return {"status":"native_tactic_rejected","committed":False, + "state":state,"source_state_sha256":start_sha, + "verifier_calls":len(events),"events":events,"me_tta":offered} + if public_state(repl,new)["goals"]: + return {"status":"pending_goals_after_macro","committed":False, + "state":state,"source_state_sha256":start_sha, + "verifier_calls":len(events),"events":events,"me_tta":offered} + receipt=repl.kernel(new["sid"]) + if receipt.get("ok") is not True or receipt.get("axioms")!=[]: + return {"status":"kernel_rejected","committed":False, + "state":state,"source_state_sha256":start_sha, + "verifier_calls":len(events),"events":events,"me_tta":offered} + return {"status":"kernel_closed","committed":True,"state":new, + "chosen_plan":chosen.identifier,"source_state_sha256":start_sha, + "end_state_sha256":digest(public_state(repl,new)), + "verifier_calls":len(events),"events":events,"me_tta":offered, + "kernel":{"ok":True,"axioms":[]}} From 49ceabe650d503e09adf1083ee757ea7e53726f6 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:35:26 +0800 Subject: [PATCH 43/51] feat(olr): add verified optimal action-set loss with canonical and SHA-256 singleton controls --- .../ppt_gym/metta_action_sets.py | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/metta_action_sets.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/metta_action_sets.py b/research/lean_cgrt_hrm400/ppt_gym/metta_action_sets.py new file mode 100644 index 000000000..e0455f85e --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/metta_action_sets.py @@ -0,0 +1,133 @@ +"""DG-METTA-12-compatible action-set supervision for verified OLR transitions. + +A verified state may have several equally good next actions. Normalize over +the *full legal action menu* and credit the total probability mass of all +min-cost, verifier-certified successors. Controls select either the canonical +first action or a stable hashed singleton of the same valid set. + +This is a training objective, not an executable MeTTa proof certifier. +Source: MoralityLabAI/DataGoblin draft PR #57 at 88c910993b3a86438c6de85d7efa039dcdb68cac. +""" +from __future__ import annotations + +import hashlib +import math +from collections.abc import Sequence + +import torch +from torch.nn import functional as F + + +def normalized_action_set( + legal_actions: Sequence[str], optimal_actions: Sequence[str] +) -> tuple[int, ...]: + """Reject malformed or non-legal action labels and return sorted indices.""" + if (not legal_actions or len(legal_actions)>128 + or len(set(legal_actions))!=len(legal_actions)): + raise ValueError("legal action menu must be bounded and unique") + if not optimal_actions or len(set(optimal_actions))!=len(optimal_actions): + raise ValueError("nonempty unique optimal action set required") + indexes={act:i for i,act in enumerate(legal_actions)} + if not set(optimal_actions).issubset(indexes): + raise ValueError("optimal action outside publicly legal menu") + return tuple(sorted(indexes[a] for a in optimal_actions)) + + +def choose_hashed_singleton( + *, root_id: str, state_sha256: str, model_seed: int, + legal_actions: Sequence[str], optimal_actions: Sequence[str] +) -> str: + """A stable tie-breaking comparator independent of PYTHONHASHSEED.""" + if not root_id or not state_sha256 or type(model_seed) is not int: + raise ValueError("hash control requires root, state and model seed") + normalized_action_set(legal_actions,optimal_actions) + ordered=tuple(sorted(optimal_actions)) + # Matches DG-METTA-12's public root/seed/state/tied-action SHA256 recipe. + key="|".join((root_id,str(model_seed),state_sha256,*ordered)).encode("utf-8") + j=int.from_bytes(hashlib.sha256(key).digest()[:8],"big")%len(ordered) + return ordered[j] + + +def objective( + logits: torch.Tensor, legal_actions: Sequence[str], + optimal_actions: Sequence[str], *, mode: str, + root_id: str, state_sha256: str, model_seed: int, +) -> torch.Tensor: + """Return a differentiable single-state loss for the declared control. + + 'set' = -log sum_{a in A*} softmax_legal(logits)[a] + 'canonical' and 'hashed' are matched singleton baselines. + """ + if logits.ndim!=1 or len(logits)!=len(legal_actions) or not logits.is_floating_point(): + raise ValueError("one float score per legal action required") + if not torch.isfinite(logits).all(): + raise ValueError("nonfinite action logits") + allowed=normalized_action_set(legal_actions,optimal_actions) + if mode=="set": + return torch.logsumexp(logits,dim=0)-torch.logsumexp(logits[list(allowed)],dim=0) + if mode=="canonical": + idx=legal_actions.index(min(optimal_actions)) + elif mode=="hashed": + selected=choose_hashed_singleton(root_id=root_id,state_sha256=state_sha256, + model_seed=model_seed,legal_actions=legal_actions,optimal_actions=optimal_actions) + idx=legal_actions.index(selected) + else: + raise ValueError("unknown action-set control") + return F.cross_entropy(logits.reshape(1,-1), + torch.tensor([idx],device=logits.device,dtype=torch.long)) + + +def teacher_actions_from_verified_graph( + legal_actions: Sequence[str], transitions: dict[str,dict], + *, remaining_calls: int, goal_is_kernel_closed: bool, +) -> tuple[str, ...]: + """Build a local source-only action set from an independently checked DAG. + + Transitions must contain exact native/standalone proof verification and + nonnegative *total remaining call cost* (including this action). + The verifier's source receipt is intentionally separate from any model + input. A STOP is eligible only when Lean has already certified the goal. + """ + if not 0<=remaining_calls<=32: + raise ValueError("invalid source action budget") + if not legal_actions or len(set(legal_actions))!=len(legal_actions): + raise ValueError("invalid observed legal action menu") + if set(transitions)!=set(legal_actions): + raise ValueError("missing independent receipt for candidate") + eligible=[] + for action in legal_actions: + rec=transitions[action] + if not isinstance(rec,dict): + raise ValueError("malformed native transition receipt") + if action=="STOP": + if goal_is_kernel_closed and rec.get("status")=="kernel_closed": + eligible.append((0,"STOP")) + continue + # Only full kernel and independently checked standalone proofs may be + # used as positive action targets. Nonterminal alone is insufficient. + cost=rec.get("total_tactic_calls") + if (type(cost) is int and 1<=cost<=remaining_calls + and rec.get("status")=="kernel_closed" + and rec.get("native_kernel") is True + and rec.get("standalone_verified") is True + and rec.get("axioms")==[]): + eligible.append((cost,action)) + if not eligible: + return () + best=min(cost for cost,_ in eligible) + return tuple(sorted(action for cost,action in eligible if cost==best)) + + +def batch_objective(logits: torch.Tensor, rows: Sequence[dict], *, + mode: str, model_seed: int) -> torch.Tensor: + """One target state per presentation, regardless of tie count.""" + if logits.ndim!=2 or len(rows)!=len(logits) or not len(rows): + raise ValueError("expected B x action logits and aligned receipts") + terms=[] + for scores,row in zip(logits,rows,strict=True): + if set(row)!=set(("root_id","state_sha256","legal","optimal")): + raise ValueError("teacher row missing provenance or source-only action set") + terms.append(objective(scores,row["legal"],row["optimal"], + mode=mode,root_id=row["root_id"],state_sha256=row["state_sha256"], + model_seed=model_seed)) + return torch.stack(terms).mean() From 6595397d7a7ea20855a31c31721df737489d536c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:37:27 +0800 Subject: [PATCH 44/51] feat(olr): run native MeTTa curation and atomic Lean STOP repair with independent certificates --- .../lean_cgrt_hrm400/ppt_gym/metta_olr_cli.py | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/metta_olr_cli.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/metta_olr_cli.py b/research/lean_cgrt_hrm400/ppt_gym/metta_olr_cli.py new file mode 100644 index 000000000..70a1483c9 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/metta_olr_cli.py @@ -0,0 +1,171 @@ +"""OLR-METTA-01 native Hyperon + Lean STOP repair and source curation smoke. + +Runs *real* MeTTa 0.2.10 policy queries and a real Lean 4.19 proof server. +Provenance split: Hyperon checks advisory typed/lineage filters, Lean alone +checks tactic outcomes and proof closure. This is a plumbing/verifier test. +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from lcgrt import config +from lcgrt.lean_repl import LeanRepl +from .data import canonical, digest, sha256_file +from .live_lean import public_state +from .metta_action_sets import objective, teacher_actions_from_verified_graph +from .metta_obligations import ( + RepairPlan, VerifiedRollout, curate_verified, offer_repairs, + run_atomic_stop_repair, HYPERON_VERSION, +) +from .olr_delayed import DelayedWorld, compile_scripts + +SCHEMA="ppt.olr-metta-native-bridge.v1" + + +def demonstration(out: Path, *, a: int=5, b: int=7) -> dict: + """Create-only native test; input numerals do not come from a trained model.""" + if out.exists() or not 0<=a<=15 or not 0<=b<=15: + raise ValueError("fresh output directory and bounded integers required") + world=DelayedWorld("metta_smoke_source",0,a,b,(a+b,a+b+1)) + plans=( + RepairPlan("good",("apply h0","apply h1"),"good_source",1), + RepairPlan("wrong_order",("apply h1","apply h0"),"wrong_source",1), + RepairPlan("incomplete",("apply h0",),"short_source",1), + RepairPlan("conflicted",("apply h0","apply h1"),"conflict_source",1, + conflict_free=False), + ) + with LeanRepl(timeout=60) as lean: + version=lean.version + if not str(version).startswith("4.19.0"): + raise ValueError("pinned Lean runtime required") + lean.reset() + root=lean.init(world.statement(),pp=True) + initial=public_state(lean,root) + if len(initial["goals"])!=1: + raise ValueError("unexpected Lean root") + open_rule=lean.run(root["sid"],"apply r0") + if open_rule.get("ok") is not True: + raise ValueError("native rule did not open expected obligations") + subgoals=public_state(lean,open_rule["state"]) + if len(subgoals["goals"])!=3: + raise ValueError("expected guard plus two pending obligations") + guard=lean.run(open_rule["state"]["sid"],"rfl") + if guard.get("ok") is not True: + raise ValueError("native equality guard did not close") + pending=guard["state"] + public=public_state(lean,pending) + if [goal["target"] for goal in public["goals"]] != [{"a":"P"},{"a":"Q"}]: + raise ValueError("native pending goal order drifted") + + stop_untouched_state=digest(public) + # A standalone STOP on a proof with open goals cannot be certified. + direct_stop_closed=not public["goals"] + if direct_stop_closed: + raise ValueError("STOP baseline prematurely reported closure") + + # A one-call macro must be refused by MeTTa's public budget test. + short=run_atomic_stop_repair(lean,pending,plans=plans,budget=1,stopped=True) + if short["committed"] or short["verifier_calls"]!=0: + raise ValueError("insufficient-budget typed repair was admitted") + + # Permit a maximum of two native tactic checks; certify them before + # committing the end state to the caller. + repaired=run_atomic_stop_repair(lean,pending,plans=plans,budget=2,stopped=True) + if (repaired["status"]!="kernel_closed" or not repaired["committed"] + or repaired["chosen_plan"]!="good" or repaired["verifier_calls"]!=2): + raise ValueError("native MeTTa offer did not close exactly two obligations") + if digest(public_state(lean,pending))!=stop_untouched_state: + raise ValueError("immutable Lean source state was mutated") + + # The same source branch must independently compile at full theorem + # statement scope. MeTTa's offer itself earns no certificate credit. + out.mkdir(parents=True,exist_ok=False) + script=["apply r0","rfl",*plans[0].actions] + compiled=compile_scripts( + [(world,{"kernel_closed":True,"script":script})], + out/"standalone.lean") + if compiled["axiom_clean"]!=1: + raise ValueError("independent source script verification failed") + + # Native-program curation applies exclusively to TRAIN source. The + # accepted rollout has a clean Lean+standalone receipt. A copied + # lineage, incomplete attempt, or stale revision fails the query. + curation=curate_verified([ + VerifiedRollout("goodproof","verified_source","train",True,True,True, + True,True,True,True,True,2,2,1,-2), + VerifiedRollout("unverified","unverified_source","train",False,False,False, + True,True,True,True,True,10,10,3,-1), + VerifiedRollout("stale","stale_source","train",True,True,True, + True,True,False,True,True,5,5,2,-3), + VerifiedRollout("dupone","shared_source","train",True,True,True, + True,True,True,True,True,4,4,2,-2), + VerifiedRollout("duptwo","shared_source","train",True,True,True, + True,True,True,True,True,4,4,2,-2), + ]) + if curation["offer_ids"]!=("goodproof",): + raise ValueError("native MeTTa source curation selected invalid evidence") + + # Minimal action-set custody example from the exact Lean-certified + # rule. A different multi-witness bank is needed to test tie benefits. + verified_root=teacher_actions_from_verified_graph( + ["apply r0","apply r1"], + {"apply r0":{"status":"kernel_closed","native_kernel":True, + "standalone_verified":True,"axioms":[], + "total_tactic_calls":4}, + "apply r1":{"status":"rfl_rejected","native_kernel":False, + "standalone_verified":False,"axioms":[], + "total_tactic_calls":2}}, + remaining_calls=4,goal_is_kernel_closed=False) + if verified_root!=("apply r0",): + raise ValueError("source-only action set leaked uncertified branch") + + return_report={ + "schema":SCHEMA,"evidence":"real_hyperon_and_real_lean_engineering_smoke", + "scientific_eligible":False, + "lean_version":version,"lean_sha256":sha256_file(config.LEAN_EXE), + "lean_repl_sha256":sha256_file(config.REPL_EXE), + "metta_runtime":f"hyperon=={HYPERON_VERSION}", + "parent_public_sha256":digest(initial), + "stopped_public_sha256":stop_untouched_state, + "standalone":compiled, + "source_train_curator":curation, + "repairs":{ + "stop_only_verified_closed":False, + "short_budget_committed":short["committed"], + "short_budget_checks":short["verifier_calls"], + "native_macro_committed":repaired["committed"], + "native_macro_checks":repaired["verifier_calls"], + "native_macro_plan":repaired["chosen_plan"], + "native_macro_actions":[e["tactic"] for e in repaired["events"]], + "native_macro_metta_sha256":repaired["me_tta"]["program_sha256"], + "native_tactic_receipts":repaired["events"], + }, + "action_set":{ + "source_optimal_actions":list(verified_root), + "training_schema":"DG_METTA12_optimal_action_set_v1", + "tie_training_evidence":"not_tested_in_single_success_world", + }, + } + (out/"manifest.json").write_text(canonical(return_report)+"\n",encoding="utf-8") + return_report["artifact_sha256"]={ + name:sha256_file(out/name) for name in ("manifest.json","standalone.lean") + } + return return_report + + +def main(argv=None): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument("--out",type=Path,required=True) + p.add_argument("--a",type=int,default=5) + p.add_argument("--b",type=int,default=7) + args=p.parse_args(argv) + report=demonstration(args.out,a=args.a,b=args.b) + print(canonical({ + key:report[key] for key in ("schema","scientific_eligible","standalone","repairs","action_set") + })) + + +if __name__=="__main__": + main() From d86fa0dab18e5525f6ebc180ecb1759d551a4d59 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:38:23 +0800 Subject: [PATCH 45/51] test(olr): verify MeTTa source lineage, STOP atomicity, and full optimal-set gradient controls --- .../ppt_gym/tests/test_metta_olr_bridge.py | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_metta_olr_bridge.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_metta_olr_bridge.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_metta_olr_bridge.py new file mode 100644 index 000000000..c58f76bd8 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_metta_olr_bridge.py @@ -0,0 +1,192 @@ +"""OLR MeTTa bridge protocol, action sets and atomicity. + +Fake native backends in these Python tests are protocol fixtures, NEVER +evidence of native MeTTa execution or Lean proof completion. +""" +from __future__ import annotations + +from unittest import TestCase +from unittest.mock import patch + +import torch + +from ppt_gym import metta_obligations as bridge +from ppt_gym.data import digest +from ppt_gym.live_lean import public_state +from ppt_gym.metta_action_sets import ( + batch_objective, choose_hashed_singleton, normalized_action_set, + objective, teacher_actions_from_verified_graph, +) +from ppt_gym.metta_obligations import ( + RepairPlan, VerifiedRollout, curate_verified, offer_repairs, + run_atomic_stop_repair, +) +from ppt_gym.tests.test_olr_delayed import FakeDelayedLean +from ppt_gym.olr_delayed import DelayedWorld + + +class MeTTaBridgeProtocolTests(TestCase): + def setUp(self): + self.world=DelayedWorld("fixture",0,2,3,(5,6)) + self.lean=FakeDelayedLean() + root=self.lean.init(self.world.statement()) + opened=self.lean.run(root["sid"],"apply r0") + self.assertTrue(opened["ok"]) + checked=self.lean.run(opened["state"]["sid"],"rfl") + self.assertTrue(checked["ok"]) + self.pending=checked["state"] + self.public=public_state(self.lean,self.pending) + self.good=RepairPlan("good",("apply h0","apply h1"),"fresh",1) + self.bad=RepairPlan("bad",("apply h1","apply h0"),"badsource",1) + + @staticmethod + def _fake_native(program, *, offer_pattern): + # Simplified protocol fixture models only the two safe offered atoms. + # It is deliberately distinct from Hyperon and never scientific data. + if "(Repair " in program: + value=(("good","2"),) if "(Repair good Typed WithinBudget UniqueLineage CurrentRevision DependenciesMet ConflictFree 2)" in program else () + else: + value=(("goodproof","2","1","-2"),) if "(Rollout goodproof Closed Eligible WithinBudget UniqueLineage CurrentRevision DependenciesMet ConflictFree 2 2 1 -2)" in program else () + return value,digest(program) + + def test_curation_requires_verified_train_lineage(self): + rows=[ + VerifiedRollout("goodproof","fresh_lineage","train", + True,True,True,True,True,True,True,True,2,2,1,-2), + VerifiedRollout("badproof","bad_lineage","train", + True,False,True,True,True,True,True,True,6,6,4,-1), + ] + with patch.object(bridge,"_native_metta",side_effect=self._fake_native): + report=curate_verified(rows) + self.assertEqual(report["offer_ids"],("goodproof",)) + self.assertTrue(report["training_eligible"]) + with self.assertRaises(ValueError): + curate_verified([VerifiedRollout("held","evalid","test", + True,True,True,True,True,True,True,True,2,2,1,-1)]) + + def test_metta_filter_rejects_untyped_and_unaffordable(self): + with patch.object(bridge,"_native_metta",side_effect=self._fake_native): + result=offer_repairs(self.public,(self.good,self.bad),2) + self.assertEqual(result["offered_plan_ids"],("good",)) + one=offer_repairs(self.public,(self.good,self.bad),1) + self.assertEqual(one["offered_plan_ids"],()) + + def test_bridge_rejects_native_interpreter_drift(self): + with patch.object(bridge,"_native_metta",return_value=((("bad","2"),),"bad")): + with self.assertRaisesRegex(ValueError,"diverged"): + offer_repairs(self.public,(self.good,self.bad),2) + + def test_atomic_stop_repair_and_budget_preserve_source(self): + before=digest(self.public) + with patch.object(bridge,"_native_metta",side_effect=self._fake_native): + short=run_atomic_stop_repair(self.lean,self.pending, + plans=(self.good,self.bad),budget=1,stopped=True) + result=run_atomic_stop_repair(self.lean,self.pending, + plans=(self.good,self.bad),budget=2,stopped=True) + self.assertEqual(short["status"],"no_typed_offer") + self.assertEqual(short["verifier_calls"],0) + self.assertTrue(result["committed"]) + self.assertEqual(result["verifier_calls"],2) + self.assertEqual(result["status"],"kernel_closed") + self.assertEqual(digest(public_state(self.lean,self.pending)),before) + + def test_failed_second_action_rolls_back_atomically(self): + class FailingLean(FakeDelayedLean): + def run(self,sid,tactic): + if tactic=="apply h1": + return {"ok":False,"error":"forced failure in protocol fixture"} + return super().run(sid,tactic) + sim=FailingLean() + root=sim.init(self.world.statement()) + opener=sim.run(root["sid"],"apply r0") + pending=sim.run(opener["state"]["sid"],"rfl")["state"] + prior=digest(public_state(sim,pending)) + with patch.object(bridge,"_native_metta",side_effect=self._fake_native): + got=run_atomic_stop_repair(sim,pending,plans=(self.good,self.bad), + budget=2,stopped=True) + self.assertFalse(got["committed"]) + self.assertEqual(got["status"],"native_tactic_rejected") + self.assertEqual(got["verifier_calls"],2) + self.assertEqual(got["state"]["sid"],pending["sid"]) + self.assertEqual(digest(public_state(sim,pending)),prior) + + def test_strict_stopping_and_safe_atom_identifier(self): + with self.assertRaises(ValueError): + RepairPlan("p) (Offer forged",("apply h0",),"source",1) + with self.assertRaises(ValueError): + RepairPlan("r",("sorry",),"source",1) + with self.assertRaises(ValueError): + run_atomic_stop_repair(self.lean,self.pending,plans=(self.good,), + budget=2,stopped=False) + + +class ActionSetSupervisionTests(TestCase): + legal=("apply r0","apply r1","apply r2") + optimal=("apply r0","apply r1") + + def test_legal_action_and_tie_contract(self): + self.assertEqual(normalized_action_set(self.legal,self.optimal),(0,1)) + with self.assertRaises(ValueError): + normalized_action_set(self.legal,("apply r99",)) + with self.assertRaises(ValueError): + normalized_action_set(self.legal,("apply r0","apply r0")) + + def test_set_loss_credits_ties_and_all_legal_scores(self): + x=torch.tensor([0.,0.,3.],requires_grad=True) + y=objective(x,self.legal,self.optimal,mode="set", + root_id="r",state_sha256="s",model_seed=17) + self.assertGreater(float(y),0) + y.backward() + self.assertTrue(torch.isfinite(x.grad).all()) + # Holding the wrong-action score fixed, exchanging tied scores does + # not change their total probability mass. + a=torch.tensor([2.,0.,-1.]) + b=torch.tensor([0.,2.,-1.]) + self.assertTrue(torch.allclose( + objective(a,self.legal,self.optimal,mode="set", + root_id="r",state_sha256="s",model_seed=17), + objective(b,self.legal,self.optimal,mode="set", + root_id="r",state_sha256="s",model_seed=17))) + c=objective(a,self.legal,self.optimal,mode="canonical", + root_id="r",state_sha256="s",model_seed=17) + self.assertGreater(float(c),0) + + def test_hashed_control_is_order_independent(self): + h=choose_hashed_singleton(root_id="r",state_sha256="hash",model_seed=103, + legal_actions=self.legal,optimal_actions=self.optimal) + h2=choose_hashed_singleton(root_id="r",state_sha256="hash",model_seed=103, + legal_actions=self.legal[::-1],optimal_actions=self.optimal[::-1]) + self.assertEqual(h,h2) + self.assertIn(h,self.optimal) + + def test_verified_graph_requires_full_proof_certificates(self): + graph={ + "apply r0":{"status":"kernel_closed","native_kernel":True, + "standalone_verified":True,"axioms":[],"total_tactic_calls":4}, + "apply r1":{"status":"kernel_closed","native_kernel":True, + "standalone_verified":True,"axioms":[],"total_tactic_calls":4}, + "apply r2":{"status":"rfl_rejected","native_kernel":False, + "standalone_verified":False,"axioms":[],"total_tactic_calls":2}, + } + self.assertEqual(teacher_actions_from_verified_graph( + self.legal,graph,remaining_calls=4,goal_is_kernel_closed=False), + self.optimal) + self.assertEqual(teacher_actions_from_verified_graph( + self.legal,graph,remaining_calls=3,goal_is_kernel_closed=False),()) + with self.assertRaises(ValueError): + teacher_actions_from_verified_graph(self.legal,{"apply r0":graph["apply r0"]}, + remaining_calls=4,goal_is_kernel_closed=False) + + def test_batch_tie_is_one_presentation(self): + rows=[{"root_id":"r","state_sha256":"s", + "legal":self.legal,"optimal":self.optimal}] + logits=torch.tensor([[0.,0.,0.]],requires_grad=True) + value=batch_objective(logits,rows,mode="set",model_seed=17) + self.assertGreater(float(value),0) + value.backward() + self.assertEqual(tuple(logits.grad.shape),(1,3)) + + +if __name__=="__main__": + import unittest + unittest.main() From 6c93b54aa527fcb116e7d8f578f9193b868bbca1 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:38:47 +0800 Subject: [PATCH 46/51] ci(olr): execute pinned Hyperon 0.2.10 curation and atomic Lean STOP repair --- .github/workflows/ppt-g03-live-lean.yml | 30 +++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index d3110eb64..356308c01 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -208,6 +208,36 @@ jobs: research/lean_cgrt_hrm400/runs/olr-01d-bank research/lean_cgrt_hrm400/runs/olr-01d-score if-no-files-found: ignore + - name: Native MeTTa source curation and Lean STOP exchange + working-directory: research/lean_cgrt_hrm400 + env: + OMP_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + run: | + python -m pip install "hyperon==0.2.10" + python -m ppt_gym.metta_olr_cli --out runs/olr-metta-native-01 + python - <<'PY' + import json + with open("runs/olr-metta-native-01/manifest.json",encoding="utf-8") as f: + r=json.load(f) + assert r["scientific_eligible"] is False, r + assert r["metta_runtime"]=="hyperon==0.2.10", r + assert r["source_train_curator"]["offer_ids"]==["goodproof"], r + assert r["repairs"]["native_macro_committed"] is True, r + assert r["repairs"]["native_macro_checks"]==2, r + assert r["repairs"]["short_budget_checks"]==0, r + assert r["standalone"]["axiom_clean"]==1, r + assert r["action_set"]["source_optimal_actions"]==["apply r0"], r + print("Verified native Hyperon-to-Lean STOP repair and source curation", + r["repairs"]["native_macro_metta_sha256"]) + PY + - name: Upload OLR native MeTTa/Lean bridge receipts + if: always() + uses: actions/upload-artifact@v4 + with: + name: olr-metta-01-native-hyperon-lean + path: research/lean_cgrt_hrm400/runs/olr-metta-native-01 + if-no-files-found: ignore - name: Fresh generated Lean suite and model smoke working-directory: research/lean_cgrt_hrm400 env: From aa02c395ad7c277e40e3b477d78a3137ec67d90f Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:42:27 +0800 Subject: [PATCH 47/51] feat(olr): train matched action-set/canonical/hashed heads on native Lean multi-witness roots --- .../ppt_gym/metta_actionset_native.py | 349 ++++++++++++++++++ 1 file changed, 349 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/metta_actionset_native.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/metta_actionset_native.py b/research/lean_cgrt_hrm400/ppt_gym/metta_actionset_native.py new file mode 100644 index 000000000..c445980ec --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/metta_actionset_native.py @@ -0,0 +1,349 @@ +"""OLR-METTA-02 native multi-witness proof-tactic learning. + +Integrates DataGoblin's DG-METTA-12 A/B/C controls with a lightweight OLR +tied recurrent scorer and independently certified Lean proof actions. +Native Hyperon curates TRAIN source roots. Held roots are scored only after +fitted policy decisions are frozen; every successful script compiles in Lean. +This CPU study is a reference pilot, not native courier transfer. +""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import hashlib +import json +from pathlib import Path +import random +import subprocess +import tempfile + +import torch +from torch import nn + +from lcgrt import config +from lcgrt.lean_repl import LeanRepl +from .data import canonical, digest, sha256_file +from .live_lean import candidate_menu, public_state +from .metta_action_sets import objective, teacher_actions_from_verified_graph +from .metta_obligations import VerifiedRollout, curate_verified + +SCHEMA = "ppt.olr-metta-multi-witness.v1" +ACTIONS=("apply r0","apply r1","apply r2") +TRAIN_MODES=("canonical","hashed","set") +SEEDS=(17,29,43) + + +@dataclass(frozen=True) +class Root: + split: str + index: int + a: int + b: int + targets: tuple[int,int,int] + mode: str + + @property + def root_id(self): + return digest([SCHEMA,self.split,self.index,self.a,self.b, + self.targets,self.mode]) + + def statement(self): + a,b=self.a,self.b + parts=" ".join( + f"(r{i} : ({a} + {b} = {value}) → P → Q → R)" + for i,value in enumerate(self.targets) + ) + return f"∀ (P Q R : Prop) (h0 : P) (h1 : Q) {parts}, R" + + +def generate_roots(split:str,count:int,seed:int): + if split not in ("train","development") or not 1<=count<=64: + raise ValueError("invalid root generation request") + rng=random.Random(f"olr-metta-02/{seed}/{split}") + seen=set() + result=[] + for i in range(count): + mode=("tie","r0","r1","r2")[i%4] + for retry in range(500): + a,b=rng.randint(1,18),rng.randint(1,18) + bad=[a+b+1,a+b+2,a+b+3] + true=[a+b if mode=="tie" and n in (0,1) or mode==f"r{n}" + else bad[n] for n in range(3)] + key=(a,b,tuple(true)) + if key not in seen: + seen.add(key) + result.append(Root(split,i,a,b,tuple(true),mode)) + break + else: + raise ValueError("root generator exhausted unique operands") + return tuple(result) + + +def _one_action(lean:LeanRepl,root:Root,action:str): + if action not in ACTIONS: + raise ValueError("outside allowed proof tactic menu") + lean.reset() + state=lean.init(root.statement(),pp=True) + visible=public_state(lean,state) + menu=candidate_menu(lean,state) + if menu!=ACTIONS: + raise ValueError(f"native root candidate menu differs: {menu}") + source_sha=digest(visible) + first=lean.run(state["sid"],action) + if first.get("ok") is not True: + raise ValueError("native rule opening rejected") + current=first["state"] + if len(public_state(lean,current)["goals"])!=3: + raise ValueError("native applied rule has wrong obligation count") + guard=lean.run(current["sid"],"rfl") + if guard.get("ok") is not True: + return {"status":"guard_rejected","native_kernel":False, + "standalone_verified":False,"axioms":[], + "total_tactic_calls":2,"state_sha256":source_sha} + current=guard["state"] + for tactic in ("apply h0","apply h1"): + result=lean.run(current["sid"],tactic) + if result.get("ok") is not True: + raise ValueError("native true guard failed deterministic proof tail") + current=result["state"] + if public_state(lean,current)["goals"]: + raise ValueError("expected proof to be closed after two fact applications") + checker=lean.kernel(current["sid"]) + if checker.get("ok") is not True or checker.get("axioms")!=[]: + raise ValueError("native kernel rejected a proof tail") + return {"status":"kernel_closed","native_kernel":True, + "standalone_verified":True,"axioms":[], + "total_tactic_calls":4,"state_sha256":source_sha} + + +def verify_root(lean:LeanRepl,root:Root): + checks={action:_one_action(lean,root,action) for action in ACTIONS} + hashes={item["state_sha256"] for item in checks.values()} + if len(hashes)!=1: + raise ValueError("independent native actions did not see the same root") + gold=teacher_actions_from_verified_graph( + ACTIONS,checks,remaining_calls=4,goal_is_kernel_closed=False) + count=2 if root.mode=="tie" else 1 + if len(gold)!=count: + raise ValueError("native theorem did not have registered witness count") + # The full source is generated from known bounded typed public numerals. + # The binary equality test is a private audit only, never a model feature. + features=[[root.a/40.,root.b/40.,target/80.] for target in root.targets] + return {"root_id":root.root_id,"statement":root.statement(), + "state_sha256":next(iter(hashes)), "legal":ACTIONS, + "optimal":gold,"features":features,"receipts":checks, + "split":root.split,"mode":root.mode,"index":root.index} + + +def compile_proofs(rows:list[tuple[Root,str]], out:Path): + """Compile each native-verified source root/action as a full Lean theorem.""" + source=["namespace OLRMeTTaTies"] + for i,(root,action) in enumerate(rows): + if action not in ACTIONS or any(x<0 or x>100 for x in (root.a,root.b,*root.targets)): + raise ValueError("outside bounded independently checked statement grammar") + source.append(f"theorem p{i} {root.statement()[2:-3]} : R := by") + source.extend((" "+action," rfl"," apply h0"," apply h1")) + source.append("end OLRMeTTaTies") + source.extend(f"#print axioms OLRMeTTaTies.p{i}" for i in range(len(rows))) + text="\n".join(source)+"\n" + out.write_text(text,encoding="utf-8") + with tempfile.TemporaryDirectory() as d: + file=Path(d)/"NativeTies.lean" + file.write_text(text,encoding="utf-8") + process=subprocess.run([str(config.LEAN_EXE),str(file)],check=False, + env=config.lean_env(),capture_output=True,text=True, + encoding="utf-8",timeout=120) + data=process.stdout+process.stderr + clean=sum(f"'OLRMeTTaTies.p{i}' does not depend on any axioms" in data + for i in range(len(rows))) + if process.returncode!=0 or clean!=len(rows): + raise ValueError(f"native multi-witness standalone certifier failed: " + f"rc={process.returncode}; clean={clean}/{len(rows)}; {data[-1500:]}") + return {"independent_proofs":len(rows),"axiom_free":clean, + "sha256":sha256_file(out)} + + +class TiedSetScorer(nn.Module): + """Tied 3-slot recurrent score cell; same architecture for all label arms.""" + def __init__(self,width:int=24): + super().__init__() + self.embedding=nn.Sequential(nn.Linear(3,width),nn.GELU(),nn.LayerNorm(width)) + self.role=nn.Parameter(torch.zeros(1,3,width)) + self.message=nn.Sequential(nn.Linear(3*width,2*width),nn.Tanh(), + nn.Linear(2*width,width)) + self.gate=nn.Linear(3*width,width) + self.norm=nn.LayerNorm(width) + self.head=nn.Linear(width,1) + + def forward(self,public:torch.Tensor,depth:int=3): + if public.ndim!=3 or public.shape[1:]!=(3,3) or not 1<=depth<=8: + raise ValueError("expected Bx3x3 public numeric action features") + original=self.embedding(public)+self.role + state=original + for _ in range(depth): + shared=state.mean(1,keepdim=True).expand_as(state) + packet=torch.cat((original,state,shared),dim=-1) + proposal=self.message(packet) + gate=self.gate(packet).sigmoid() + state=self.norm(state+0.25*gate*proposal) + return self.head(state).squeeze(-1) + + +def fit(roots:list[dict],seed:int,mode:str,steps:int=40): + if mode not in TRAIN_MODES or not roots or not 1<=steps<=200: + raise ValueError("unsupported model training request") + torch.manual_seed(seed) + model=TiedSetScorer() + # Same seed initialization and sampled roots for all loss arms. + initialization=digest([(k,v.detach().tolist()) for k,v in model.state_dict().items()]) + optimizer=torch.optim.AdamW(model.parameters(),lr=.003) + rng=torch.Generator().manual_seed(seed+3000) + choices=torch.randint(len(roots),(steps, min(len(roots),12)),generator=rng) + losses=[] + for indices in choices: + optimizer.zero_grad() + loss=0. + for j in indices.tolist(): + row=roots[j] + features=torch.tensor([row["features"]],dtype=torch.float32) + logits=model(features)[0] + loss=loss+objective(logits,row["legal"],row["optimal"], + mode=mode,root_id=row["root_id"], + state_sha256=row["state_sha256"],model_seed=seed) + loss=loss/len(indices) + loss.backward() + nn.utils.clip_grad_norm_(model.parameters(),1.) + optimizer.step() + losses.append(float(loss.detach())) + model.eval() + return model,{"seed":seed,"objective":mode,"initial_sha256":initialization, + "steps":steps,"training_root_count":len(roots), + "parameter_count":sum(p.numel() for p in model.parameters()), + "final_loss":losses[-1]} + + +def run(out:Path, *, seed:int=20261128,train_roots:int=12, + development_roots:int=8,steps:int=40): + if out.exists(): + raise ValueError("out must be a new directory") + torch.set_num_threads(1) + torch.use_deterministic_algorithms(True) + torch.backends.mkldnn.enabled=False + trains=generate_roots("train",train_roots,seed) + developments=generate_roots("development",development_roots,seed+31) + seen={(r.a,r.b,r.targets) for r in trains} + if any((r.a,r.b,r.targets) in seen for r in developments): + raise ValueError("train/development source overlap") + with LeanRepl(timeout=60) as lean: + if not str(lean.version).startswith("4.19.0"): + raise ValueError("pinned native Lean 4.19.0 required") + version=lean.version + train=[verify_root(lean,r) for r in trains] + dev=[verify_root(lean,r) for r in developments] + root_objects={r.root_id:r for r in (*trains,*developments)} + verified=[(root_objects[row["root_id"]],action) for row in (*train,*dev) + for action in row["optimal"]] + out.mkdir(parents=True) + cert=compile_proofs(verified,out/"standalone.lean") + # Native MeTTa admission runs once for each TRAIN source root. A rooted + # action set with 2 equal successes stays one supervised presentation. + offerings=[ + VerifiedRollout(f"root{i}",f"lineage{i}","train",True,True,True, + True,True,True,True,True,len(row["optimal"]), + len(ACTIONS),1,-4) + for i,row in enumerate(train) + ] + selected=curate_verified(offerings) + if len(selected["offer_ids"])!=len(trains): + raise ValueError("native MeTTa curator unexpectedly dropped a certified root") + byid={f"root{i}":r for i,r in enumerate(train)} + curated=[byid[x] for x in selected["offer_ids"]] + models={} + model_data={} + for model_seed in SEEDS: + initial=None + for mode in TRAIN_MODES: + model,meta=fit(curated,model_seed,mode,steps) + models[model_seed,mode]=model + model_data[f"{model_seed}:{mode}"]=meta + if initial is None: + initial=meta["initial_sha256"] + elif initial!=meta["initial_sha256"]: + raise ValueError("unequal initialization in matched label-control arms") + records=[] + with LeanRepl(timeout=60) as lean: + for row in dev: + r=root_objects[row["root_id"]] + for model_seed in SEEDS: + for mode in TRAIN_MODES: + with torch.no_grad(): + scores=models[model_seed,mode]( + torch.tensor([row["features"]],dtype=torch.float32))[0] + action=ACTIONS[int(scores.argmax().item())] + # Query outcome is checked by a fresh native Lean session. + result=_one_action(lean,r,action) + if (result["status"]!=row["receipts"][action]["status"] + or result["state_sha256"]!=row["state_sha256"]): + raise ValueError("frozen model's new native verdict drifted") + records.append({"root_id":row["root_id"],"mode":mode, + "model_seed":model_seed,"action":action, + "kernel_closed":result["native_kernel"], + "tie":len(row["optimal"])>1,"checks":result["total_tactic_calls"]}) + scoreboard={} + for mode in TRAIN_MODES: + matched=[x for x in records if x["mode"]==mode] + scoreboard[mode]={ + "trials":len(matched), + "certified":sum(x["kernel_closed"] for x in matched), + "tied_state_trials":sum(x["tie"] for x in matched), + "tied_state_certified":sum(x["kernel_closed"] and x["tie"] for x in matched), + "tactic_calls":sum(x["checks"] for x in matched), + } + root_manifest={"schema":SCHEMA,"root_seed":seed, + "train_roots":len(trains),"development_roots":len(developments), + "tied_train_roots":sum(len(r["optimal"])>1 for r in train), + "tied_development_roots":sum(len(r["optimal"])>1 for r in dev), + "lean_version":version, + "lean_sha256":sha256_file(config.LEAN_EXE), + "native_source_certificates":cert, + "native_metta_curation":selected, + "fitted_arms":model_data,"evaluation":scoreboard, + "native_query_trials":len(records), + "source_only_model_training":True, + "checkpoint_promotion_eligible":False, + "evidence_class":"native_lean_source_and_hyperon_curation_cpu_training_pilot"} + (out/"train.jsonl").write_text( + "".join(canonical(r)+"\n" for r in train),encoding="utf-8") + (out/"development.jsonl").write_text( + "".join(canonical(r)+"\n" for r in dev),encoding="utf-8") + (out/"decisions.jsonl").write_text( + "".join(canonical(r)+"\n" for r in records),encoding="utf-8") + with (out/"models.pt").open("xb") as handle: + torch.save({f"{seed}:{mode}":model.state_dict() + for (seed,mode),model in models.items()},handle) + root_manifest["artifacts"]={ + name:sha256_file(out/name) for name in ( + "standalone.lean","train.jsonl","development.jsonl","decisions.jsonl","models.pt")} + (out/"manifest.json").write_text(canonical(root_manifest)+"\n",encoding="utf-8") + return root_manifest + + +def main(argv=None): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument("--out",type=Path,required=True) + p.add_argument("--seed",type=int,default=20261128) + p.add_argument("--train",type=int,default=12) + p.add_argument("--development",type=int,default=8) + p.add_argument("--steps",type=int,default=40) + a=p.parse_args(argv) + result=run(a.out,seed=a.seed,train_roots=a.train, + development_roots=a.development,steps=a.steps) + print(canonical({ + k:result[k] for k in ("schema","train_roots","development_roots", + "tied_train_roots","tied_development_roots", + "native_source_certificates","evaluation") + })) + + +if __name__=="__main__": + main() From 30e9941cc930406027542a1acfbbb8ac061e6e05 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:43:10 +0800 Subject: [PATCH 48/51] test(olr): cover native tied-action generator, shared scorer gradients and matched label budgets --- .../tests/test_metta_actionset_native.py | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_metta_actionset_native.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_metta_actionset_native.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_metta_actionset_native.py new file mode 100644 index 000000000..a5431f78e --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_metta_actionset_native.py @@ -0,0 +1,65 @@ +"""CPU shape and source-only controls for OLR MeTTa native multi-witness gym.""" +import unittest + +import torch + +from ppt_gym.metta_actionset_native import ( + ACTIONS, generate_roots, TiedSetScorer, fit, +) +from ppt_gym.metta_action_sets import normalized_action_set + + +class NativeTieContractTests(unittest.TestCase): + def setUp(self): + torch.set_num_threads(1) + + def test_generator_has_ties_and_unique_source_roots(self): + roots=generate_roots("train",12,20261128) + self.assertEqual(len(roots),12) + self.assertEqual(len({r.root_id for r in roots}),12) + self.assertEqual(sum(r.mode=="tie" for r in roots),3) + for root in roots: + self.assertTrue(root.statement().endswith(", R")) + good=[f"apply r{i}" for i,v in enumerate(root.targets) + if v==root.a+root.b] + self.assertEqual(len(good),2 if root.mode=="tie" else 1) + self.assertEqual(normalized_action_set(ACTIONS,good), + tuple(ACTIONS.index(x) for x in good)) + with self.assertRaises(ValueError): + generate_roots("sealed",4,1) + + def test_recurrent_scorer_backpropagates_from_action_set_targets(self): + model=TiedSetScorer() + x=torch.tensor([[[.1,.2,.3],[.1,.2,.3],[.1,.2,.4]]],dtype=torch.float32) + y=model(x,depth=3) + self.assertEqual(tuple(y.shape),(1,3)) + from ppt_gym.metta_action_sets import objective + loss=objective(y[0],ACTIONS,ACTIONS[:2], + mode="set",root_id="test",state_sha256="public",model_seed=17) + loss.backward() + self.assertIsNotNone(model.embedding[0].weight.grad) + self.assertTrue(torch.isfinite(model.embedding[0].weight.grad).all()) + with self.assertRaises(ValueError): + model(x[:,:,:2]) + + def test_matched_arms_start_from_identical_weights(self): + roots=generate_roots("train",4,20261128) + rows=[] + for root in roots: + optimal=[f"apply r{i}" for i,v in enumerate(root.targets) + if v==root.a+root.b] + rows.append({"root_id":root.root_id,"state_sha256":root.root_id, + "legal":ACTIONS,"optimal":optimal, + "features":[[root.a/40,root.b/40,v/80] for v in root.targets]}) + a,ma=fit(rows,17,"canonical",steps=2) + b,mb=fit(rows,17,"hashed",steps=2) + c,mc=fit(rows,17,"set",steps=2) + self.assertEqual(len({ma["initial_sha256"],mb["initial_sha256"],mc["initial_sha256"]}),1) + self.assertEqual(ma["parameter_count"],mb["parameter_count"]) + self.assertEqual(ma["parameter_count"],mc["parameter_count"]) + self.assertEqual(ma["steps"],2) + self.assertEqual(c(torch.tensor([rows[0]["features"]])).shape,(1,3)) + + +if __name__=="__main__": + unittest.main() From bdca595bc1c87d3a63a161281e85cab4fcb1db7d Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:43:35 +0800 Subject: [PATCH 49/51] ci(olr): compare canonical, hashed and full optimal sets on native Lean multi-witness roots --- .github/workflows/ppt-g03-live-lean.yml | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/.github/workflows/ppt-g03-live-lean.yml b/.github/workflows/ppt-g03-live-lean.yml index 356308c01..06159d174 100644 --- a/.github/workflows/ppt-g03-live-lean.yml +++ b/.github/workflows/ppt-g03-live-lean.yml @@ -238,6 +238,35 @@ jobs: name: olr-metta-01-native-hyperon-lean path: research/lean_cgrt_hrm400/runs/olr-metta-native-01 if-no-files-found: ignore + - name: OLR MeTTa native multi-witness action-set pilot + working-directory: research/lean_cgrt_hrm400 + env: + OMP_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + run: | + python -m ppt_gym.metta_actionset_native --out runs/olr-metta-02-ties --seed 20261128 --train 12 --development 8 --steps 40 + python - <<'PY' + import json + with open("runs/olr-metta-02-ties/manifest.json",encoding="utf-8") as f: + r=json.load(f) + assert r["schema"]=="ppt.olr-metta-multi-witness.v1", r + assert r["train_roots"]==12 and r["development_roots"]==8, r + assert r["tied_train_roots"]==3 and r["tied_development_roots"]==2, r + assert r["native_source_certificates"]["axiom_free"]==25, r + assert r["native_metta_curation"]["native_offer_count"]==12, r + assert r["native_query_trials"]==72, r + assert r["checkpoint_promotion_eligible"] is False, r + assert set(r["evaluation"])=={"canonical","hashed","set"} + assert all(x["trials"]==24 for x in r["evaluation"].values()), r + print("OLR native MeTTa optimal-action-set pilot",r["evaluation"]) + PY + - name: Upload OLR native MeTTa action-set pilot + if: always() + uses: actions/upload-artifact@v4 + with: + name: olr-metta-02-native-action-sets + path: research/lean_cgrt_hrm400/runs/olr-metta-02-ties + if-no-files-found: ignore - name: Fresh generated Lean suite and model smoke working-directory: research/lean_cgrt_hrm400 env: From bd5bafd77e6fd5648789894ce4fe066529f91352 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:47:52 +0800 Subject: [PATCH 50/51] research(olr): record native MeTTa curation, STOP exchange and multi-witness training results --- research/lean_cgrt_hrm400/OLR_METTA_BRIDGE.md | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 research/lean_cgrt_hrm400/OLR_METTA_BRIDGE.md diff --git a/research/lean_cgrt_hrm400/OLR_METTA_BRIDGE.md b/research/lean_cgrt_hrm400/OLR_METTA_BRIDGE.md new file mode 100644 index 000000000..0add26447 --- /dev/null +++ b/research/lean_cgrt_hrm400/OLR_METTA_BRIDGE.md @@ -0,0 +1,67 @@ +# OLR-METTA: native MeTTa curation, STOP repair, and action-set supervision + +**Date:** 2026-11-23 +**Status:** Implemented and tested on native Hyperon and native Lean; engineering and development evidence only. +**Parent:** [OLR-01D](OLR_01D_NATIVE_RESULTS.md) +**CI:** [Lean/Hyperon #45186782600](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45186782600), [CPU regression #45186782625](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45186782625): green. + +## Recent DataGoblin evidence and source boundary + +[DataGoblin PR #46](https://github.com/MoralityLabAI/DataGoblin/pull/46) established a gain from stringent native MeTTa curation: 190/600 vs 147/600 verified completions on the original fresh primary roots (+7.17 percentage points). [PR #47](https://github.com/MoralityLabAI/DataGoblin/pull/47) later reported 178/600 vs 117/600 (+10.17 points) on another cohort. The native policy filters closed, eligible, within-budget, unique-lineage, current-revision, dependency-satisfied and conflict-free training rollouts. See DataGoblin/metta_research_bench/looped/good.metta. + +[DG-METTA-12 draft PR #57](https://github.com/MoralityLabAI/DataGoblin/pull/57), exact head 88c910993b3a86438c6de85d7efa039dcdb68cac, proposes full-set supervision for all tied optimal next actions, a stable hashed-singleton control and certified two-step STOP exchange. The claimed local courier Storyworld dependency was unavailable remotely, so native courier transfer remains blocked. OLR integrates the verified *methods* on its own Lean gym, without importing or claiming courier results. + +## Components + +- [metta_obligations.py](ppt_gym/metta_obligations.py): runs pinned Hyperon 0.2.10 queries over source-only, independently verified rollout metadata; filters public typed repair candidates and enforces source lineage and remaining verifier budgets. +- [metta_olr_cli.py](ppt_gym/metta_olr_cli.py): native MeTTa proposes a two-tactic repair after a premature STOP, while immutable saved Lean states protect against partial commit. Lean executes each action and independently certifies the original complete theorem. +- [metta_action_sets.py](ppt_gym/metta_action_sets.py): full legal-menu log-sum-exp action-set loss, canonical first-action labels, and stable SHA-256 hashed singleton controls. Only native-kernel and standalone-certified minimum-cost source actions can earn positive proof labels. +- [metta_actionset_native.py](ppt_gym/metta_actionset_native.py): fresh three-option Lean roots with one or two equally short successful actions. Native MeTTa curates source lineages; the same small tied recurrent model is trained from matched initialization on three label objectives. +- [test_metta_olr_bridge.py](ppt_gym/tests/test_metta_olr_bridge.py) and [test_metta_actionset_native.py](ppt_gym/tests/test_metta_actionset_native.py): atomic rollback, malformed MeTTa reply, budgets, curriculum split and differentiable tie controls. + +A MeTTa match result is an *advisory policy offer*, never a Lean proof. The Lean 4.19 kernel and standalone source compiler supply proof authority. A failed macro leaves the original immutable state available. Each attempted action consumes one native tactic check. No held-out proof label or oracle continuation is passed to the recurrent model before its choice. + +The hashed-singleton control follows DG-METTA-12 conceptually, but OLR hashes a public *state SHA-256* rather than DG's full canonical state serialization. Tie selection can therefore differ between the two implementations. All OLR arms have the same deterministic hash control, model architecture, root allocation, training steps and minibatch schedule. + +## OLR-METTA-01: native STOP repair + +From a real Lean proof root, a correct arithmetic guard is closed by Lean, leaving goals P and Q. The deliberately proposed STOP leaves these goals unfinished. Native Hyperon inspects public typed repair candidates and offers the two-step script applying h0 and h1; a reversed script, incomplete script or conflicted source fails preflight. + +The accepted plan was executed by native Lean and the resulting full proof independently compiled with no axioms. It consumed exactly two tactic calls. With one available call, the MeTTa policy offered nothing, spent zero tactic calls and left the source state unchanged. + +**Evidence:** one certified successful source proof and an actual Hyperon 0.2.10 rule query; source curation admitted the independently verified TRAIN trace, excluding unverified, stale and duplicate-lineage examples. This is a manually injected STOP, not learned STOP scheduling or a neural proof gain. + +[Verified OLR-METTA-01 native receipt #14823257263](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45186000256/artifacts/14823257263). + +## OLR-METTA-02: multiple equally optimal Lean actions + +The native three-option Lean family has public candidate rules r0, r1 and r2. Each target has either a single four-tactic certifiable action or two equally short certifiable actions. Native Lean separately evaluates every candidate and independently compiles every successful complete theorem. Unsuccessful actions remain in the public normalization denominator and receive no positive target. + +The experiment froze 12 training roots (three tied) and eight distinct development roots (two tied). Native MeTTa admitted all 12 verified TRAIN roots; ties remained *one training state presentation* each. There were 25 independently compiled successful scripts across source and development. Three paired model seeds (17, 29, 43), 40 source optimizer updates per arm, and the same small tied three-slot recurrent scorer were used for all label variants. + +| Objective | Native-certified development choices / 24 | Certified tied-root choices / 6 | Native tactic calls | +| --- | ---: | ---: | ---: | +| A: canonical singleton | 21 | 6 | 90 | +| B: hashed singleton from optimum set | 24 | 6 | 96 | +| C: all-optimal action-set supervision | 24 | 6 | 96 | + +The experiment contains eight independent development roots shared across three model seeds. All three objectives completed every repeated tied-root trial. B and C tied on overall verified completion, so this pilot **does not establish** a gain from full action-set supervision over hashed singleton. The difference over A is a small development observation and no sealed result. The exact environment guard remains solvable by direct arithmetic. + +[Verified OLR-METTA-02 native data and checkpoints #14824166743](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/45186782600/artifacts/14824166743). + +## Reproduce + +From research/lean_cgrt_hrm400 with the pinned Lean 4.19 server and CPU PyTorch installed: + +~~~sh +python -m pip install "hyperon==0.2.10" +python -m unittest discover -s ppt_gym/tests -v +python -m ppt_gym.metta_olr_cli --out runs/olr-metta-01 +python -m ppt_gym.metta_actionset_native --out runs/olr-metta-02 --seed 20261128 --train 12 --development 8 --steps 40 +~~~ + +These output directories must be new. The hosted native CI workflow runs the same gates and uploads full proof receipts, native source states, model weights, training metadata and selected development actions. This code does not require a GPU. + +## Next OLR-METTA experiment + +The missing experiment is a *learned* obligation controller that decides when to pay for guard evidence or spend its two-call STOP repair allowance, rather than inheriting a deterministic branch schedule. Build fresh computational/dependent proof families where a direct arithmetic solver cannot simply close everything. Compare full optimal-set labels against hashed singleton, then compare the exact same checkpoint with and without MeTTa-backed atomic repair. Match actual Lean calls, model FLOPs, candidate menus and causal shams; obtain an EvalMath FSI-01 sample/power gate before any mechanism claim. From 31f1693aab3eb7afde7a574ed37e8e4850f2ddd4 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:48:20 +0800 Subject: [PATCH 51/51] docs(olr): index native MeTTa and action-set learning experiments --- research/lean_cgrt_hrm400/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/research/lean_cgrt_hrm400/README.md b/research/lean_cgrt_hrm400/README.md index 457ed54e9..81edad2e8 100644 --- a/research/lean_cgrt_hrm400/README.md +++ b/research/lean_cgrt_hrm400/README.md @@ -15,6 +15,7 @@ Start with these documents: - [OLR-01C native arithmetic-guard learning protocol](OLR_01C_GUARD_LEARNING.md) and [three-seed results](OLR_01C_RESULTS.md): trained ~18k parameter two-slot recurrence, direct/frozen/isolated controls, fresh native Lean arithmetic proofs and strong seed variance; no confirmed recurrent mechanism gain. - [OLR-01C compute-depth and reproducibility audit](OLR_01C_COMPUTE_ABLATION.md): equal-information one-pass reader, cross-message shams, bit-exact seeded checkpoints across two hosted runs, and mixed development/OOD transfer. - [OLR-01D preregistered multi-goal Lean recovery](OLR_01D_REGISTRATION.md) and [native results](OLR_01D_NATIVE_RESULTS.md): 16 fresh proof worlds, 128 replayed trajectories, 32 independent axiom-free canonical certificates, and four/six-tactic early versus late guard-probe controls. Frozen model and deterministic verifier feedback search only. +- [OLR-MeTTa integration](OLR_METTA_BRIDGE.md): native Hyperon 0.2.10 source curation, a typed two-check STOP repair accepted only by Lean's kernel, and native multiple-optimal-action training with canonical, hashed and full-set losses. CPU and native CI receipts are recorded in the report. - [`LOCAL_SCALING_RESULTS.md`](LOCAL_SCALING_RESULTS.md): campaign c1, Lean-certified results; - [`SILICO_400M_HANDOFF.md`](SILICO_400M_HANDOFF.md): decision and ready-to-run 400M specs. - [`RLT_ABLATION_MATRIX.md`](RLT_ABLATION_MATRIX.md): RLT-01 feedback controls and Q5 transfer caveats; [completed two-lane pilot results](results/rlt01/RLT-comparison.md) found no RLT-specific Lean completion gain.