core/tests/test_deduction_serve_license.py
Claude 71bf04fb44
feat(provenance,teaching): close the lateral gaps the assessment actually found
Squashes the arc's work into one commit; the workflow-file edit it originally
carried is excluded (see the end of this message).

## Lane 1 — Workbench recorded a proved answer as ungrounded

With deduction_serving_enabled ratified ON (ADR-0256), workbench/api.py's live
chat route builds a bare ChatRuntime(), so the deduction composer decides
Workbench turns and stamps grounding_source="deduction" — but
_coerce_grounding_source carried a hand-copied whitelist of the six pre-arc
labels and silently rewrote anything else to "none". The runtime comment
reasoned this was inert because "REPL turns do not flow through Workbench's
CognitivePipelineRecord path". True, and irrelevant: the traffic flows the
other way. Stale since 2026-07-24.

Scope is one field. workbench/api.py:818 prefers TurnEvent.epistemic_state,
which read epistemic_state_needed — honest. So the UNregistered path degraded
honestly while the hand-copied whitelist asserted a falsehood; a second copy of
a closed enum was worse than no copy. Hence registration AND derivation:
GROUNDING_SOURCES exposes the Literal's members, and the coercion reads it.
workbench-ui badges/tokens/snapshot follow; enumCoverage.test.ts forces atomicity.

## Lane 2 — the ratification ceremony

The discovery loop was instrumented but not closed. teaching/ratification.py
turns a reviewed decision into a chain record, a corpus commit, and a receipt.

Its design turns on one observation: _ratified_rows DROPS unadmissible rows
silently — correct when serving, a trap when ratifying, because the file grows,
the commit lands, and the band count does not move. So the ceremony refuses to
call an append a ratification until it has re-read the curriculum through the
real loader and seen the chain arrive; a non-admitted append is rolled back.
Validation is a pre-flight courtesy, admission is the proof.

Arena queue entry and ledger reseal are deliberately NOT performed (bridge rule
1); the receipt names them. Front door: `core proposal-queue ratify`, a sibling
of `review` rather than a flag on it.

## Lane 3 — structural closures

- ADR-0263 gains rule 5: absence policy is DECLARED in CAPABILITY_LEDGERS, not
  passed at the call site. An AST-matched test fails if a serving path passes
  missing_ok again.
- Deductive suite added WHOLE to the pre-push gate: 285 tests in 29s against
  smoke's 216 in 62s, so no coverage trade was needed.
- Smoke/CI parity assertion made bidirectional. It was one-directional, and had
  drifted.
- test_prior_surface_deduction_binding.py pins correction binding on the
  deduction path. The review's diagnosis did NOT reproduce — hash_surface moves
  in lockstep — so it pins what is there. Mutation-checked.
- Domain-keyed ADR index over 312 flat-numbered files, explicitly partial.
- Arc-close brief template, plus this arc's own brief filled in against it.

## Lanes 4 and 5 — two premises falsified by measurement, one of them mine

Math 4.2: baseline reproduced (correct=5 wrong=0 refused=495); all four named
cases traced to one seam with each gap isolated by one-variable probes. Then the
number that changes the recommendation: the gap blocking case 0000 affects 1
case in 500, the 'than' gap blocking 0001 affects 2. ADR-0251's prohibition on
per-case growth now rests on a count. No reader change made.

CGA: versor_condition is 0.22% of a turn, not the "~10x proof latency" I claimed
— that multiplied an isolated microbenchmark by a call count and compared it to
a single verdict's latency. The real cost is geometric_product at 33,986
calls/turn (~73%) via cga_inner in search paths. The obvious closed form is NOT
bit-exact (954/4000 in f32); backend.vault_recall's serial fold IS (3000/3000,
worst-rel 0) and is the correct target. cargo test could not run —
static.crates.io is denied by the sandbox network policy — so the Rust parity
question stays open and the typestate lane is carried forward, not shipped
uncompiled.

## Not landed: three lines owed to .github/workflows/smoke.yml

The CI smoke gate is narrower than the local one —
test_pack_draft_serve_boundary.py (ADR-0253 INV-33) has been local-only, unseen
because the parity pin checked one direction. The edit was authored and rejected
at push for lacking the `workflow` OAuth scope, so it is recorded as a named,
dated PENDING_IN_CI exception rather than dropped: the assertion still fires on
any new divergence, and a second guard fires once the three land.

[Verification]: pre-push gates all green — smoke 236 passed, warmed_session 10
passed, deductive 285 passed. Ratification 14, ADR index 5, CLI suites 10.
Grounding/epistemic sweep 741 passed 1 skipped. workbench-ui 598 passed across
73 files, tsc -b clean. capability index 11 passed, digest unchanged. Math
holdout correct=5 wrong=0 refused=495. Committed chain corpora byte-unchanged
after the tests that write to them.
Environment caveat: the repo pins requires-python ==3.12.13, which uv cannot
fetch for linux-x86_64, so `uv sync --locked` fails. All Python runs used a
scratch venv on 3.12.11 with declared deps — not the locked universe, not the
full ~12k suite. The pin was left untouched. Re-run on a 3.12.13 host before
treating this as merge evidence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FduW6Krm3PPQv3P5iwBYtx
2026-07-25 04:51:15 +00:00

160 lines
6 KiB
Python

"""Deduction-serve arc, Phase 3 (ADR-0256) — earned SERVE license tests.
Pins:
- the shared shape-band classifier is deterministic + exhaustive;
- the synthetic practice corpus is sound against the INDEPENDENT oracle
(a mis-stated gold can never seal the ledger) and earns SERVE per band
at the θ_SERVE=0.99 Wilson floor with wrong=0;
- the committed sealed ledger's content_sha256 verifies on load (tamper-
evidence), and a tampered ledger is rejected;
- the serving composer serves AUTHORITATIVELY only for earned bands and
DISCLOSES (hedges) an unearned band — the gate genuinely governs the
serving posture, so the capability is earned, not merely flagged.
"""
from __future__ import annotations
import json
import pytest
from chat.deduction_serve_license import (
RatifiedLedgerError,
deduction_serve_license,
load_ratified_ledger,
)
from chat.deduction_surface import (
_UNVERIFIED_SHAPE_DISCLOSURE,
deduction_grounded_surface,
)
from core.reliability_gate import Action, Ceilings, license_for
from generate.proof_chain.shape import (
ALL_SHAPE_BANDS,
ATOMIC,
CONDITIONAL_CHAIN,
CONDITIONAL_SINGLE,
DISJUNCTIVE,
SHAPE_BANDS,
classify_deduction_shape,
)
# ---------------------------------------------------------------------------
# Shape classifier
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("premises,query,expected", [
(("p implies q", "p"), "q", CONDITIONAL_SINGLE),
(("p implies q", "q implies r", "p"), "r", CONDITIONAL_CHAIN),
(("p or q", "not p"), "q", DISJUNCTIVE),
(("p",), "p", ATOMIC),
(("not p",), "p", ATOMIC),
])
def test_classify_deduction_shape(premises, query, expected) -> None:
assert classify_deduction_shape(premises, query) == expected
def test_shape_bands_are_exhaustive_for_the_projector() -> None:
"""Every band the classifier can emit is a declared SHAPE_BAND (so the
ledger's key space and the serving key space cannot drift)."""
for premises, query in [
(("a or b", "not a"), "b"),
(("a implies b", "b implies c"), "a implies c"),
(("a implies b", "a"), "b"),
(("a",), "a"),
]:
assert classify_deduction_shape(premises, query) in SHAPE_BANDS
# ---------------------------------------------------------------------------
# Practice corpus + arena ledger
# ---------------------------------------------------------------------------
def test_corpus_is_sound_against_independent_oracle() -> None:
from evals.deduction_serve.practice.gold import assert_corpus_sound
assert_corpus_sound() # raises AssertionError on any mis-stated gold
def test_every_band_earns_serve_wrong_zero() -> None:
from evals.deduction_serve.practice.runner import run
report = run()
assert report["wrong_is_zero"] is True
assert report["all_bands_serve_licensed"] is True
assert set(report["classes"]) == set(ALL_SHAPE_BANDS)
for band, c in report["classes"].items():
assert c["wrong"] == 0, band
assert c["serve_licensed"] is True, band
assert c["reliability"] >= 0.99, (band, c["reliability"])
# ---------------------------------------------------------------------------
# Committed sealed ledger — tamper-evidence
# ---------------------------------------------------------------------------
def test_committed_ledger_verifies_and_earns_serve() -> None:
ledger = load_ratified_ledger()
assert set(ledger) == set(ALL_SHAPE_BANDS)
ceilings = Ceilings.default()
for band, tally in ledger.items():
assert tally.wrong == 0, band
assert license_for(tally, Action.SERVE, ceilings).licensed is True, band
def test_serve_license_returns_none_for_unknown_band() -> None:
assert deduction_serve_license("nonexistent_band") is None
def test_tampered_ledger_is_rejected(tmp_path, monkeypatch) -> None:
"""A hand-edited ledger (counts inflated, sha not recomputed) must be
rejected on load — only the sealed-practice output is trusted."""
import chat.deduction_serve_license as mod
from dataclasses import replace
from core.ratified_ledger import CAPABILITY_LEDGERS
original = json.loads(mod._LEDGER_PATH.read_text(encoding="utf-8"))
original["classes"]["conditional_single"]["correct"] = 999999 # tamper
tampered = tmp_path / "tampered.json"
tampered.write_text(json.dumps(original), encoding="utf-8")
# Redirect at the manifest, which owns the path since ADR-0263 rule 5 —
# patching the module constant would no longer reach the load.
monkeypatch.setitem(
CAPABILITY_LEDGERS,
mod._LEDGER_CAPABILITY,
replace(CAPABILITY_LEDGERS[mod._LEDGER_CAPABILITY], path=tampered),
)
load_ratified_ledger.cache_clear()
with pytest.raises(RatifiedLedgerError):
load_ratified_ledger()
load_ratified_ledger.cache_clear() # restore cache for other tests
# ---------------------------------------------------------------------------
# Serving composer — the gate genuinely governs posture
# ---------------------------------------------------------------------------
def test_earned_band_serves_authoritatively() -> None:
"""With the committed (earned) ledger, an in-band argument is served
plainly — no hedge (Phase 1 behavior preserved)."""
surface = deduction_grounded_surface("If p then q. p. Therefore q.")
assert surface is not None
assert surface.startswith("Given:")
assert _UNVERIFIED_SHAPE_DISCLOSURE not in surface
def test_unearned_band_is_disclosed_not_committed() -> None:
"""Strip the ledger (inject an empty lookup) and the SAME sound answer is
served DISCLOSED — proving the capability is earned, not merely flagged."""
surface = deduction_grounded_surface(
"If p then q. p. Therefore q.", license_lookup=lambda band: None,
)
assert surface is not None
assert surface.startswith(_UNVERIFIED_SHAPE_DISCLOSURE)
assert "Your premises entail: q" in surface # the sound answer still served