Skip to content

feat(receipt): one receipt for each learning update, with a Nickel contract (E0-09) - #1161

Merged
hyperpolymath merged 4 commits into
mainfrom
feat/e0-09-receipt-emitter
Nov 15, 2026
Merged

hyperpolymath merged 4 commits into
mainfrom
feat/e0-09-receipt-emitter

Conversation

@hyperpolymath

@hyperpolymath hyperpolymath commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

What

Work order E0-09. Hypatia writes one receipt for each learning update, in the form that the ruled design of E0-08 defines, and a Nickel contract refuses a receipt that claims more than its evidence.

  • lib/hypatia/receipt.ex: build, canonical encoding, append, replay check, repair, orphan report.
  • lib/hypatia/event_id.ex: an Elixir implementation of the ADR-008 profile T layout (owner ruling R5-A). No System.cmd.
  • schema/receipt.ncl: the contract.
  • Two call sites (owner ruling D2): OutcomeTracker.persist_outcome/6 (every local and imported row) and the neural call of FleetDispatcher.

Why

Issue 984, step 10 and acceptance A7, and the rulings of 2026-11-15 recorded in docs/design/e0-receipt.adoc (RULED, section 9a).

How it works (the rules that matter)

  • A receipt is a pure function of the stored row, so a missing one can be rewritten identically. It names the row by event_id and by the SHA-256 of the exact evidence bytes, never a count.
  • Order of writes (design 5.3): the row is the commit; the receipt is written next, into the store that the row was written into; then the derived updates. A receipt is never written for a row that is not in the log ({:error, :row_not_in_log}).
  • A failed receipt write returns {:ok, record} to the caller (R3), logs receipt_pending event_id=..., and update_recipe_confidence/1 writes the missing receipts the next time the recipe is recomputed.
  • A caller cannot choose event_id or any context field: the public entry strips them, and only the trusted fleet import may bring a producer's id. Receipts are deduplicated by event_id, so a chosen duplicate would have silenced a real receipt.
  • Audit rows get a receipt with verdict audit_only (R1). verdict is derived from the gate by the contract.
  • The canonical form is the profile of scripts/proof-ledger.sh: a number is a decimal string; text outside printable ASCII is written %XX (and % as %25) so the receipt stays ASCII and decodable.

Evidence

  • Head commit: 2bf46b95
  • Tests first, as far as I did it. schema/receipt.ncl, Receipt and EventId were written before their own tests (I wrote the contract and the module together). The integration tests of test/receipt_test.exs (29 tests) were written before the call sites were wired, and with the three call sites set aside they gave:
    1) test the Nickel contract every receipt that the integration tests below write satisfies the contract 
    2) test one receipt for each learning update a verified update on the local rescan path 
    3) test one receipt for each learning update a verified update on the fleet import path (through the scheduler) 
    4) test one receipt for each learning update a verified update on the neural path 
    5) test one receipt for each learning update a qualified failure on the local rescan path (a caller's own failed claim) 
    6) test one receipt for each learning update a qualified failure on the fleet import path 
    7) test one receipt for each learning update a qualified failure on the neural path 
    8) test one receipt for each learning update an audit row (owner ruling R1) writes a receipt with verdict audit_only 
    9) test the identity of an event a row carries the event_id that its receipt names 
   10) test the identity of an event a caller cannot choose an event_id or any field of the receipt context 
   11) test the identity of an event two events with identical content have different ids and two receipts 
   12) test replay a replay of the same event writes no second receipt 
   13) test replay writing the receipt of a row twice writes one 
   14) test the store of the row a receipt goes into the store of its row, also after the data root changes 
   15) test the failure rule the receipt write fails: the caller still gets {:ok, record}, the log says receipt_pending, and the next cycle writes it 
   16) test the failure rule the derived update fails: the row and its receipt exist, the next cycle repeats the update, and the receipt stays one 
   17) test the failure rule after the next run each row has exactly one receipt and no receipt is without its row 
  29 tests, 17 failures
  • With the call sites wired: mix test test/receipt_test.exs gave 29 tests, 0 failures; mix test test/event_id_test.exs 7 tests, 0 failures; mix test (LANG=C.UTF-8) gave 3713 tests, 0 failures, 246 excluded.
  • The acceptance lines, by test: a verified update and a qualified failure on each of the 3 paths write 1 receipt each (6 tests: local rescan, fleet import through the scheduler, neural); an audit row writes audit_only; a replay writes no second receipt (the scheduler three times, and Receipt.write twice); the receipt goes to the store of its row when the data root changes; the 3 failure points (row write fails: no receipt and nothing else; receipt write fails: {:ok, record}, receipt_pending, repaired by the next recompute, exactly once; derived update fails: the receipt stays one); no receipt before its row, and an orphan is reported; nothing is back-filled for a row with no event_id.
  • Canonical form: the encoded line equals the committed fixture test/fixtures/receipt/e0-receipt-line.jsonl byte for byte, and jq -cS . fixture prints the same bytes (tested).
  • The contract was run, not assumed. Nickel 1.11.0 (the version escript-soundness.yml pins), SHA-256 d40cd32b... verified, run by test/receipt_test.exs: the emitter's receipts satisfy it (the fixture, and the 3 that the integration test writes), and 8 changes are each refused: a verdict that is not the gate's answer, verified with no observations, missing_evidence not exact, a qualification outside the closed set, a malformed digest, a number where a string belongs, a wrong chain version, an event id that is not version 8.
  • Mutation checks (each on the code or the schema, restored after), each caught:
  # M1: the receipt is never written by persist_outcome
    1) test the Nickel contract every receipt that the integration tests below write satisfies the contract 
    2) test one receipt for each learning update a verified update on the local rescan path 
    3) test one receipt for each learning update a verified update on the fleet import path (through the scheduler) 
    4) test one receipt for each learning update a qualified failure on the local rescan path (a caller's own failed claim) 
    5) test one receipt for each learning update a qualified failure on the fleet import path 
    6) test one receipt for each learning update an audit row (owner ruling R1) writes a receipt with verdict audit_only 
  # M3: a replay writes a second receipt (no check for an existing one)
    1) test replay writing the receipt of a row twice writes one 
  29 tests, 1 failure
  # M4: repair is not run when the recipe is recomputed
    1) test the failure rule the receipt write fails: the caller still gets {:ok, record}, the log says receipt_pending, and the next cycle writes it 
  29 tests, 1 failure
  # M5: the contract no longer checks the derived verdict
    1) test the Nickel contract the contract refuses a receipt that claims more than its evidence 
  29 tests, 1 failure
  # M2: a caller can choose the event_id and the receipt context
  # M2: a caller can choose the event_id and the receipt context
    1) test the identity of an event a caller cannot choose an event_id or any field of the receipt context 
  29 tests, 1 failure

Mutation M2 first survived: my test passed with the stripping removed, because event_id is overwritten anyway for a local row. The stripping is what keeps a caller's made-up source_line, source_row_sha256 and source_bot out of stored rows, so I added that assertion and M2 now fails as shown.

  • mix format --check-formatted: exit 0 for the 3 changed lib/ files (formatted on main), the 2 new modules and the 2 new test files. mix escript.build && ./hypatia scan . --format json: 17 findings in total, 0 on the changed files. ls ~/Documents after the suite: nothing written there.
  • CI: not run yet.

Not done, and deviations you should see

  • The diff is wider than the work order's list. It touches lib/learning_scheduler.ex (one function and one call) as well as the two call sites. The fleet import is the only place that knows the source line, the digest of the exact source bytes and the producing bot, and the receipt needs them. Without it a fleet receipt would hash the stored row and not the evidence the producer wrote.
  • A fleet row gets an event_id minted by Hypatia (provenance.event_id_source is hypatia), because no fleet row carries a producer id yet. Replay is still safe: the row is deduplicated by fleet_import_id before it is written, so no second row and no second receipt. When E0-11 and E0-12 give rows a producer id, the import will pass it and the source becomes producer.
  • Repair runs when a recipe is recomputed (update_recipe_confidence/1), not on a schedule of its own. A recipe whose receipt is pending and that gets no new row and no confidence retry waits. A hook in the scheduler cycle would be a third call site; I did not add it. Say so if you want it.
  • Neural receipts cannot be repaired (there is no row to rebuild from). Today none is written in production, because no trusted verification reaches that path (E0-05).
  • The contract tests are skipped, loudly, where nickel is absent. The Integration Tests job has no Nickel, so the contract is not checked in CI by this change. Adding a Nickel step (pinned, with its SHA-256, as escript-soundness.yml does) is a workflow change that is outside this work order's paths; I have not made it.
  • Cost of the scans (design note R7): exists?/2 and repair/2 read the receipt and outcome logs; line of a local row is found by scanning for its event_id. Fine at today's volumes; a per-recipe high-water mark is the fix if it grows. Not measured.
  • pattern_id and match_kind are named in missing_evidence until E0-18 gives rows those fields. head_sha, subject_id, tool_version, scan_digest and test_digest are named as gaps, as the design says.
  • Every outcome row now carries event_id, event_id_source and source_kind (additive; the gate ignores them).
  • Not done: E0-10 (the Idris 2 model), E0-11 and E0-12 (producer ids). Not run: CI.
  • My local toolchain is Elixir 1.17.3 and main formats under 1.19.4 (chore(elixir): move to Elixir 1.19.4 and gate formatting in CI #1151); a difference in the formatter is possible on a file I wrote.
  • Estate-gates checklist read in part only.
  • Model: this work order names Sonnet at medium; the session ran on Opus 5.5 at high effort, above its tier.

Cost

  • Work order E0-09, cap $18. Cost unknown: the launch script was not run for real and I cannot see my own spend. Check the Console.

CI fix (commit 859995b)

The first CI run failed 4 checks, all caused by this change. Fixed in a second commit:

  • Validate Documentation (x2): readme-claims said lib/ had 170 files; this PR adds lib/hypatia/receipt.ex and lib/hypatia/event_id.ex, so 172. README corrected. Local: scripts/check-readme-claims.sh exit 0; tests/readme-claims-test.sh 7 passed, 0 failed (CI had 5 passed, 2 failed).
  • governance / UUID v8 and v7 conformance: check-uuid-v8.sh --strict (from metadatastician/standards, pinned 7641c7f) has no exemption mechanism and refused three deliberately wrong UUID literals in my tests. The tests now derive each wrong id from a v8 id by changing one nibble (and check that restoring the nibble gives the valid id). I did not touch the estate script. On a clean export, the gate fails on the old commit with exactly those 3 findings and passes on the new one.
  • Mutation checks (restored byte-identical): contract accepting v7, valid?/1 accepting v7, and valid?/1 accepting variant c each fail a test.
  • Full suite with nickel on PATH: 3713 tests, 0 failures, 246 excluded.

Observed, not mine: asciidoctor reports unterminated table block in verification/PROOF-STATUS.adoc (line 758 before #1160, 788 now). It is non-fatal and pre-existing. CodeRabbit is rate-limited, so no automated review happened.

…ntract (E0-09)

Hypatia now writes a receipt for each row that the gate reads (a qualified row
and an audit row) and for each qualified neural update, in the form that the
ruled design of E0-08 defines (docs/design/e0-receipt.adoc): canonical JSON
(sorted keys, ASCII, no numbers), receipts/YYYY-MM.jsonl under the data root of
the row, a receipt_sha256 over every other field, and a Nickel contract
(schema/receipt.ncl) that derives the verdict from the gate and refuses a
receipt that claims more than its evidence. Every row carries an event_id (an
Elixir implementation of ADR-008 profile T) that a caller cannot choose. The
row is the commit; a failed receipt write is logged as receipt_pending and
written when the recipe is next recomputed.

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

Summary

Summary by CodeRabbit

  • New Features
    • Recorded learning outcomes now receive unique event identifiers and provenance, with receipts capturing relevant outcome and source details.
    • Receipts are supported for local, fleet-imported and qualified neural learning outcomes. Fleet receipts include source-line and content-hash details.
    • Repeated writes avoid duplicate receipts, and missing receipts can be retried.
    • Receipt write failures are logged without changing the outcome result, and orphaned receipts can be identified.

The change adds UUIDv8 event IDs and an E0 receipt schema. It builds, stores, repairs, and reports receipts, then connects receipt writing to local, fleet, rescan, and qualified neural outcomes.

Changes: Receipt lifecycle

Layer / File(s) Summary
Event identity and receipt contract
lib/hypatia/event_id.ex, schema/receipt.ncl, test/event_id_test.exs
Adds UUIDv8 event ID generation, conversion, and validation. Defines receipt fields and validation rules, with tests for identifier format, ordering, uniqueness, and validation.
Receipt construction and storage
lib/hypatia/receipt.ex, test/fixtures/receipt/*, test/receipt_test.exs
Adds receipt construction, canonical encoding, monthly append-only storage, outcome-row lookup, repair, and orphan reporting. Tests cover encoding and schema validation.
Outcome recording and receipt lifecycle
lib/outcome_tracker.ex, lib/learning_scheduler.ex, lib/fleet_dispatcher.ex, test/receipt_test.exs, README.adoc
Assigns event identity and source metadata to recorded outcomes, writes receipts after outcome rows, and attempts repair during recipe-confidence updates. Fleet context includes source metadata; qualified neural outcomes also write receipts. Tests cover these paths, failures, replay, and repair. The README source-file count changes from 170 to 172.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant OutcomeTracker
  participant EventId
  participant OutcomeLog
  participant Receipt
  participant ReceiptStore
  participant DerivedUpdates
  OutcomeTracker->>EventId: Generate an event ID when needed
  OutcomeTracker->>OutcomeLog: Write the outcome row
  OutcomeTracker->>Receipt: Build and write a receipt
  Receipt->>ReceiptStore: Append the encoded receipt
  OutcomeTracker->>DerivedUpdates: Continue derived updates
Loading

Possibly related PRs

  • hyperpolymath/hypatia#1157: Defines the E0 receipt requirements that this change implements, including receipt generation, repair, failure handling, and local outcome receipts.
Merge Risk: Moderate · up to 54dfa

Receipts can be written that the receipt contract rejects, and fleet receipts that fail to write may never be repaired. Concurrent writes can also duplicate receipts. Resolve the verified-receipt and fleet-repair issues before merging, since the log is append-only and bad entries are hard to fix later.

- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

claude and others added 2 commits November 15, 2026 13:42
…09 branch

CI on the receipt emitter failed two checks, both caused by that change:

* readme-claims: lib/ holds 172 source files (the emitter adds
  lib/hypatia/receipt.ex and lib/hypatia/event_id.ex) and README.adoc said 170.
  The count is corrected; scripts/check-readme-claims.sh and its self-test
  (7 of 7) pass.
* governance / UUID v8 conformance (and its v7 alias): check-uuid-v8.sh --strict
  reads source text and has no exemption, and it refused three deliberately
  wrong UUID literals in the tests (a version 7 id, and a version 8 id with
  variant c). The tests now make each wrong id from a version 8 id by changing
  one nibble, and check that putting the nibble back gives the valid id again,
  so the nibble that valid?/1 and the Nickel contract refuse is the one that
  changed. The contract case now also re-seals the receipt and checks that the
  refusal names event_id.

Mutation checks (each restored byte-identical): the contract accepting version 7
fails the contract test; valid?/1 accepting version 7, and accepting variant c,
each fail the valid?/1 test.

Co-Authored-By: Claude <noreply@anthropic.com>
@hyperpolymath
hyperpolymath marked this pull request as ready for review November 15, 2026 13:47
@hyperpolymath
hyperpolymath enabled auto-merge (squash) November 15, 2026 13:47
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T13:54:00.988996Z 0ad4eb2 Draft marked ready
🔒 Security Review ✅ Completed 2026-11-15T13:53:35.943798Z 0ad4eb2 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@hyperpolymath
hyperpolymath enabled auto-merge (squash) November 15, 2026 13:52
@sonarqubecloud

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0ad4eb22d8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread lib/fleet_dispatcher.ex
Comment on lines 810 to +811
record_neural_outcome(finding, outcome_str, server)
write_neural_receipt(to_string(pattern), to_string(repo), outcome_str, verification)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Write the receipt only when neural queueing succeeds

When the coordinator is unavailable or returns an error, record_neural_outcome/3 converts that failure to {:error, ...}, but this return value is ignored and the next line still emits a receipt. In that scenario no update was queued, yet the receipt records a credited_success or credited_failure and therefore falsely claims that the event changed the learner; branch on :queued before writing it.

Useful? React with 👍 / 👎.

Comment thread lib/outcome_tracker.ex
Comment on lines +343 to +346
{:error, reason} ->
Logger.warning(
"receipt_pending event_id=#{Map.get(record, "event_id")} reason=#{inspect(reason)}"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ensure failed fleet receipts enter a repair path

If appending a receipt temporarily fails for a fleet-imported row, this branch only logs the failure. The source import is then acknowledged, while LearningScheduler.process_local_complete_lines/4 explicitly skips rows whose origin is gitbot-fleet (lines 686–690), so that recipe is never passed through the public update_recipe_confidence/1 call that invokes repair_receipts/1. The committed fleet row can therefore remain without a receipt permanently after a transient filesystem error.

Useful? React with 👍 / 👎.

Comment thread lib/fleet_dispatcher.ex
Comment on lines +735 to +738
else
{:error, reason} ->
Logger.warning("receipt_pending event_id=#{event_id} reason=#{inspect(reason)}")
end

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retain failed neural receipts for later repair

When neural queueing succeeds but the receipt append fails transiently, this handler records only a log message and discards the event ID and evidence. Unlike outcome-log rows, the neural event has no durable row that Receipt.repair/2 can discover, so no later cycle can ever create the missing receipt and the promised one-receipt-per-learning-update invariant is permanently broken.

Useful? React with 👍 / 👎.

Comment thread schema/receipt.ncl
Comment on lines +112 to +114
else if claimed == "false_positive"
&& std.array.elem qualification ["still_present", "verified", "rollback_requested"] then
"credited_false_positive"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require batch evidence before certifying a rollback

A receipt with claimed_outcome: "false_positive", qualification: "rollback_requested", and verdict: "credited_false_positive" satisfies this contract, but the actual gate in OutcomeTracker.qualified_outcome_counts/1 credits that qualification only when the row also has caused_by: "batch_rollback" and a nonempty batch_id (lines 762–769). Because the receipt schema neither carries nor checks those conditions, the contract can certify a rollback that the learning gate would ignore.

Useful? React with 👍 / 👎.

Comment thread lib/outcome_tracker.ex
Comment on lines +67 to +69
|> Map.drop(@receipt_context_keys),
true,
:local_caller

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve rescan provenance on still-present outcomes

When record_and_verify/5 detects :still_present, it writes both the claimed-success row and the credited false-positive row through record_outcome/5, so this forced kind labels them local_caller even though their qualification came from Hypatia's rescan. Receipt.observations/2 includes the rescan observation only for local_rescan, causing the resulting false-positive receipt to omit the observation that justified its credit and to misstate its source; those rescan-produced rows need the trusted rescan kind.

Useful? React with 👍 / 👎.

Comment thread lib/hypatia/receipt.ex
Comment on lines +310 to +315
with {:ok, event_id} <- fetch_event_id(row),
false <- exists?(data_root, event_id),
{:ok, ctx} <- context(data_root, row, opts),
receipt = build(row, ctx),
{:ok, line} <- encode(receipt) do
append(data_root, line)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize the receipt existence check and append

The replay guard is a check-then-append sequence with no lock or atomic uniqueness mechanism. If the immediate writer and a repair cycle, or any two replaying callers, process the same event concurrently, both can observe exists?/2 == false before either append and then write two receipt lines for one event_id; the sequential replay test does not cover this race, and it violates the exactly-one receipt invariant.

Useful? React with 👍 / 👎.

Comment thread lib/fleet_dispatcher.ex
Comment on lines +710 to +716
evidence = %{
"file" => ".",
"outcome" => outcome,
"recipe_id" => pattern,
"repo" => repo,
"verification" => verification
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Hash the complete neural training input

The coordinator trains MoE, LSM, and the sequence model from the entire finding map, including fields such as fix_type, confidence, and any other features, but this receipt hashes only pattern, repo, outcome, and verification. Two updates with different model inputs can therefore have the same row_sha256, and changes to the fields that actually influence training are invisible to the receipt, so it does not name the exact evidence on which the neural update rested.

Useful? React with 👍 / 👎.

Comment thread lib/hypatia/event_id.ex
Comment on lines +77 to +81
case :persistent_term.get(@key, nil) do
nil ->
ref = :atomics.new(1, signed: false)
:persistent_term.put(@key, ref)
:persistent_term.get(@key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Initialize the shared event counter atomically

On the first concurrent calls to generate/0, multiple processes can all observe a missing persistent term, create separate atomics references, and overwrite each other's reference. A process that generated its first ID from the displaced reference can then generate its next ID from the replacement counter starting at zero, so IDs within that process are no longer guaranteed to increase as the profile and module documentation require; the one-time initialization needs synchronization rather than an unconditional put.

Useful? React with 👍 / 👎.

Comment thread schema/receipt.ncl
assertion
| { claimed_outcome | claimed_outcome_c, file | ascii_c, recipe_id | ascii_c, repo | ascii_c },
chain_version | std.contract.Equal "e0-receipt/1",
event_id | event_id_c | optional,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject receipts without an event ID

Marking event_id optional allows a receipt with no stable identity to pass the contract as long as missing_evidence names event_id. The ruled design explicitly says that a legacy row without an ID gets no receipt at all, and receipt replay, repair, causality, and withdrawal all depend on that ID, so the schema currently accepts an object that cannot participate in the receipt protocol.

Useful? React with 👍 / 👎.

@hyperpolymath
hyperpolymath merged commit 682d671 into main Nov 15, 2026
95 checks passed
@hyperpolymath
hyperpolymath deleted the feat/e0-09-receipt-emitter branch November 15, 2026 13:54
hyperpolymath added a commit that referenced this pull request Nov 15, 2026
… test (E0-10) (#1164)

## What

An Idris2 model of the E0 receipt, `src/Hypatia/ABI/Receipt.idr`, that
states and
proves the five properties of `docs/design/e0-receipt.adoc` section 8.
The verdict
gate (`scripts/check-verdicts.sh`) checks it, with fixtures that it must
accept and
fixtures that it must refuse. A mirror test holds the emitter of E0-09
to the model.

Work order: E0-10. Depends on E0-09 (merged, #1161).

## Status of each property (machine register)

Kernel: Idris 2 0.7.0, `idris2 --build src/abi/hypatia-abi.ipkg` with
`--total` and
`%default total`. Holes: none. Axioms and postulates: none. A grep for
`believe_me`,
`assert_total`, `postulate`, `partial`, `covering` in the new files
finds nothing.

| Property | Model (kernel-checked) | Run time |
|---|---|---|
| P1 no two receipts share an `event_id` | VERIFIED:
`appendRefusesDuplicate`, `appendFresh`, `appendKeepsUnique` | TESTED by
the mirror test |
| P2 no claim beyond the evidence | VERIFIED: `verdictIsGate`,
`verifiedHasEvidence`, `noVerifiedWithoutObservations`,
`creditedSuccessIsEvidenced`, `withdrawnHasParent`,
`gateNeverWithdrawn`, `gateSuccessInverse` | TESTED, with one known
difference (below) |
| P3 a revision keeps the history | VERIFIED: `appendKeepsHistory`,
`reviseKeepsHistory`, `reviseKeepsClaim` | none: no run-time code builds
a revision yet (E0-07) |
| P4 a fill never overwrites | VERIFIED: `fillNeverOverwrites`,
`fillChangesOnlyGaps`, `fillValueIsFromExtra`, `reviseNeverOverwrites` |
none, as for P3 |
| P5 `missing_evidence` is exact | VERIFIED: `missingIff`,
`missingEmptyIff`, `receiptMissingExact` | TESTED over all 32
combinations of observations |

Trust base: the Idris 2 kernel, and `base` (`Data.List`,
`Data.List.Elem`,
`Data.Maybe`). The model uses no library `DecEq`: event ids are naturals
with a
structural equality written in the module (a first draft used `isElem`
and could not
be evaluated by the fixtures, so I replaced it). The Prelude's Nat
literal
elaboration contains an `assert_total`, visible in a compiler
diagnostic; it is
library trust, not a use by this module.

## What the model is not

* **Not the Elixir run time.** An `event_id`, a digest and a field value
are naturals.
The real values are ADR-008 strings. The ledger row of each property
says so.
* **Not retraction.** `Retraction.idr` retracts by position and the run
time by name.
This module has no retraction. A withdrawal is a revision (an appended
receipt with
verdict `Withdrawn` and a parent), by `event_id`. Neither the positional
nor the named
retraction is proved, and idempotence or order-independence of a
withdrawal is not
  claimed (the design says so too).
* **Not order or duplicates in `missing_evidence`.** The model proves
membership and
emptiness. Sortedness and absence of duplicates are checked by the
Nickel contract and
  the mirror test.
* **Nothing about confidence.** A withdrawal of a failure row raises it.

## Two differences between the model and the run time (please rule)

The stop rule of the work order says to report a property that does not
hold, and not
to weaken it. I have not weakened anything. Both are pinned as tests of
their own, so a
change is noticed.

1. **P1, "refused".** `Receipt.write/3` of an `event_id` that already
has a receipt writes
   nothing and returns `:ok` (an idempotent replay). The model answers
`Left DuplicateEventId`. The ledger is unchanged in both, which is the
property. If you
want a refusal to be an error at run time, that is a decision for
E0-07's replay rules.
2. **P2, `build/2` is not a smart constructor.** The model cannot build
a `verified`
receipt without a row digest and an observation, and the Nickel contract
refuses one.
But `Receipt.build/2` on a hand-made `verified` row with no hit counts
and no rescan
returns `observations == %{}`. **Counter-example at the run time:**
`build(row("verified",
"success"), ctx)`. No production entry point makes such a row: a fleet
row classifies as
`verified` only with `before_hits > 0` and `after_hits == 0` (the mirror
test runs 3 x 3 x
3 x 2 x 6 = 324 fleet records through `classify_fleet_record` and checks
every
`verified` one), a rescan-verified local row carries `rescan`,
`record_outcome/5` rewrites a
caller's `verified`, and the neural path's trusted verification is `nil`
today. But the
guarantee is held by the callers and by the contract, not by `build/2`
or `write/3`.
A guard in `write/3` (refuse, log `receipt_pending`) is about ten lines.
I did not add it:
E0-10 is the model, and what a refused receipt does to the repair loop
is your call.

## Evidence

* `bash scripts/check-verdicts.sh`: `PASS: ABI package, 11 positive
control(s), 21 expected
rejection(s)`. Before: 5 and 15, as the work order measured. Also run
from a clean
  `git archive` of the commit.
* Fixtures: 6 accepted, 6 refused; each property has at least one of
each.
`ReceiptP2GateTable` pins all 24 entries of the gate to `verdict_for` of
`schema/receipt.ncl`. Each refusal is a false claim about one property,
refused at its
  `invalid` declaration with a recorded diagnostic.
* `mix test`: 3487 tests, 0 failures (246 excluded).
`test/receipt_model_mirror_test.exs`:
  12 tests, in the run. Elixir 1.19.4 (see process notes).
* `scripts/proof-ledger.sh check`, `render --check` and `claims`: pass.
53 rows (6 new).
* `mix format --check-formatted` on the new test; `check-uuid-v8.sh
--strict` on a clean
export: exit 0; `scripts/check-readme-claims.sh`: pass; self-scan: the
same 15
  `structured_format` findings as `main`, none on a changed file.

### Mutation checks

Model (Idris), each restored byte-identical:

| Mutation | Result |
|---|---|
| fill prefers the new value | kernel refuses (`fillNeverOverwrites`) |
| a duplicate id is accepted | kernel refuses (`appendRefusesDuplicate`,
`appendKeepsUnique`) |
| a present field is named missing | kernel refuses (`elemGapIfKeeps`,
`gapIfElem`) |
| `verified` needs no observation | kernel refuses (`credit`,
`verifiedHasEvidence`) |
| a row of the gate table is changed | **kernel accepts the module**;
only the new `ReceiptP2GateTable` fixture catches it. I added that
fixture because of this result: the theorems hold of any table that
never answers `Withdrawn`, and the table itself was not pinned. |

Mirror test, each restored: an Idris gate row changed, a field dropped
from `allFields`,
the emitter no longer crediting false positives, the emitter no longer
naming
`tool_version`, and `write/3` no longer checking for an existing
receipt. All five fail a test.

## Not done / differences from the work order

* The work order's file list does not include `README.adoc`,
`AFFIRMATION.adoc` and
`EXPLAINME.adoc`. I changed only the census phrase in each (27 proven of
47 -> 33 of 53),
because `scripts/proof-ledger.sh claims` fails otherwise. No licence
file or SPDX header
  is touched.
* The Nickel contract tests need `nickel`, which CI does not install
(the receipt contract
  tests skip loudly there). Not changed here.
* The mirror test does not and cannot cover P3 and P4 (no run-time
counterpart). It says so.

## Process notes

* `scripts/api-agents/run-work-order.sh E0-10 --dry-run` exits 0 and
would run `--agent
e0-supervisor --model opus --effort high --max-budget-usd 25 --max-turns
250`, which is
  what this session is.
* Idris 2 0.7.0 was installed with `scripts/dev/install-toolchain.sh
--with-idris2`
(the pinned, checksum-verified source build). That script also moved the
local Elixir
from 1.17.3 to 1.19.4 (its current pin, which is CI's); the format gate
now matches CI.
* **Cost: unknown to me.** I cannot see spend. Please read it in the
Anthropic Console.
* Draft. Not merged, approved or marked ready by me.

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants