Skip to content

feat(flow): counterparty confirmations: payer acknowledgments, referral read-back, handoff list - #2415

Merged
abrichr merged 30 commits into
mainfrom
claude/counterparty-confirmations
Nov 22, 2026
Merged

abrichr merged 30 commits into
mainfrom
claude/counterparty-confirmations

Conversation

@abrichr

@abrichr abrichr commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

A counterparty confirmation is evidence, read from another party's system, that it recorded what we sent. This PR adds one mechanism for those confirmations and two producers on top of it: payer acknowledgments, and referral intake read back from a receiving clinic. It also adds openadapt handoff list.

Stacked on #2410 (feat/receipt-counterparty-line, which is stacked on #2394). It merges that branch rather than rebasing, and its base is #2410's branch, so merge it after #2410. It also carries main at 8aabc0a9c, which the stack base lacks. That adds #2392's tx/ files to this diff; they are not part of this change.

What it does

Handoff ledger (openadapt_flow/handoffs/ledger.py)

  • A handoff is one item sent to another party. It has a follow-up time and a person who follows up.
  • The ledger holds keys and sent field values only as HMAC digests of the normalized value, never the values themselves.
  • Observations are append-only, and the states are the schema's: sent, acknowledged, recorded_as_intended and recorded_differently.

One comparator (intake.py)

  • A reader answers found (with fields), not_found, ambiguous or unreachable.
  • Fields compare by kind through readback_values.normalize_value, the same normalizers that on-screen read-backs use.
  • Differing fields are reported by id only.
  • An unreachable receiver never undoes an earlier confirmation. A record that disappears, or that now matches two records, goes back to sent.

Readers are data (readers.py)

  • FhirSearchProfile reads any FHIR R4 server. It names the resource, the search parameter, a key path, and a path and kind for each field.
  • Every returned record is checked for the exact key, so a server that ignores the search parameter can't make the wrong record "found".
  • next pages are followed on the same origin only.
  • A UI read-back plugs in the same way, by returning a ReadResult.

Producer 1: payer acknowledgments (payer.py)

  • PendingLedger.settle gets an optional observer, which also hears rows that settle nothing yet (999 A, 277CA A1).
  • An observer that fails never stops or changes a settlement. Its error is swallowed, and sync catches the handoff up later from the settled entries. This also covers callers that settle without an observer, such as UI read-back expiry.
  • deferred settle records each report's answer into <ledger>/handoffs:
Report says Handoff
received (999 A, 277CA A1) acknowledged
accepted (277CA A2) acknowledged, marked accepted
rejected sent, rejected_by_counterparty
conflicting rows acknowledged, conflicting_report
two claims on one key state kept, ambiguous_key
deadline passed state kept, no_answer_by_deadline
  • The deferred check settles exactly as before.
  • A payer handoff is never recorded_*, because an acknowledgment doesn't compare fields.
  • Only X12 reports count as the payer's own answer. CSV and text exports are opt-in.

Producer 2: referral intake

  • The sender is a synthetic referring clinic: a SQLite outbox of generated patients.
  • The receiver is a second, separate OpenEMR 7.0.3 in Docker on the zenbook lab (benchmark/handoff_receiver/).
  • A synthetic intake writes referrals through OpenEMR's standard REST API and injects faults on purpose.
  • OpenAdapt reads the receiver back through FHIR with a separate read-only token. A POST with that token gets 401. The read-back never uses the delivery call's answer.

Receipt lines (line.py)

  • Maps the ledger onto the canonical predicate.confirmations[] line and its commitments, using the coordinator's mapping:
Ledger read_method strength
acknowledgment message acknowledgment_message acknowledgment
API read-back api read_back
UI read-back portal_read_back read_back
  • differing_count goes on the line, and fields open as <id>:<digest>[:differs].
  • A reason the schema forbids for a state stays in the ledger and is left off the line.
  • attach_confirmations puts the lines on a record/run/v1 statement before signing.
  • handoffs_for_run finds a run's handoffs, and gives a deferred claim the step of its write.

Receipts carry the run's handoffs (receipt_record.py, handoffs/registry.py)

  • receipt_after_run now attaches a line for each of the run's handoffs. The run's ledgers come from two places: those it used in the process (a deferred check and HandoffLedger.send note theirs), and OPENADAPT_HANDOFF_LEDGERS.
  • A deferred claim is found by its deferred_check id. Any other handoff is found by its run_id, which can be the report's run_id or the run directory.
  • The deferred verifier now creates the payer handoff (sent) at save time. Bookkeeping failures are ignored, so the check never changes.
  • Test: a real replayer run saves a claim with a deferred check. Its receipt carries the sent line at the save's step and verifies.

Follow-up receipts (handoffs/followup.py, plus additive types in packages/types/openadapt_types/receipt.py). The shape was proposed to the types owner in #211 (7058926382).

  • Types additions:
    • an optional predicate.follows field: {receipt: {sha256: <the original's DSSE payload digest>}, sequence: N}. wire() drops it when it isn't set, so existing receipts and vectors are byte-identical;
    • a rule that a follow-up carries at least one confirmation;
    • follow_up_statement, payload_sha256 and verify_chain.
  • What a follow-up contains: the original's predicate and subjects, copied unchanged, plus only the confirmation lines that changed since they were last signed. A new read of the same state is not a change.
  • Commands:
    • openadapt handoff list --run RUN --sign-updates signs receipt.update-N.json and receipt.update-N.private.json.
    • --run alone shows the verified chain ("Update N: ...").
  • receipt.handoffs.json (0600, local only) maps each signed line to its handoff id.
  • Tests:
    • A real run gets a receipt. A referral is later confirmed (update 1), then the payer acknowledges the claim and the referral reads differently (update 2). The chain verifies.
    • The chain is refused for a wrong original, a reordered or skipped sequence, a changed copied field and a tampered payload. An empty update can't be signed.

openadapt handoff list (openadapt-flow handoff list, openadapt_flow/cli_handoff_list.py)

Docs

Results

Referral intake against a real app. The receiver was a second, synthetic OpenEMR 7.0.3 in Docker on the zenbook lab (WSL, project ho-openemr, loopback only). Each case ran 20 times, each time with a fresh synthetic patient, through the lab's slot gate (remote-run.sh). Results are in benchmark/handoff_receiver/results/2026-11-21.json.

Case What the intake did Result As expected
intended recorded it as sent recorded_as_intended 20/20
benign_format (no false alarm) names in capitals with extra spaces recorded_as_intended 20/20
wrong_date birth date one day later recorded_differently [birth_date] 20/20
swapped_date day and month swapped recorded_differently [birth_date] 20/20
wrong_patient_field another family name recorded_differently [family_name] 20/20
wrong_sex the other sex recorded_differently [sex] 20/20
never_arrived dropped it sent, not_found (follow-up due) 20/20
duplicate recorded it twice sent, ambiguous_key 20/20
unreachable recorded it; the read went to a closed port sent, receiver_unreachable 20/20

All 180 runs came out as expected. The 40 correctly recorded referrals raised no false alarm, and none of the 80 wrong records was missed. The same 180 of 180 came out at three code heads: 13c6e3f68, 80fae991 and e8c2682d8. A 5-per-case run gave 45 of 45. After e8c2682d8, only the CLI registration changed. The receiver was torn down after the last run.

Payer acknowledgments against synthetic X12 (unit tests in tests/test_handoffs.py):

Case Result
submitted, no report sent, follow-up due at the deadline
999 A acknowledged
999 R sent, rejected_by_counterparty
277CA A1 acknowledged; follow-up once overdue
277CA A2 acknowledged and accepted: done
277CA A7 sent, rejected_by_counterparty
no answer by the deadline state kept, no_answer_by_deadline
two claims on one key ambiguous_key
same report twice no duplicate observation

The deferred check's own settlement is unchanged: test_deferred_report.py passes.

Test runs

  • Lab (WSL slot gate): 57 passed at e8c2682d8: test_handoffs.py (34), the live test and test_deferred_report.py. They include signing and verifying a record/run/v1 statement with six confirmations against packages/types.
  • Mac (cpu-slots, load under 35): These ran on another worktree's virtualenv, with PYTHONPATH set to this tree. I had 29 GiB free when I started; about 31 GiB were free during these runs.
    • test_handoffs.py, test_deferred_report.py, test_capabilities_map.py, Flow's test_cli_tasks.py and test_import_layers.py, the new launcher test tests/test_handoff_launcher.py, and the launcher's test_cli_tasks.py, test_cli_root_task_router.py and test_cli_smoke.py: 2922 passed, 5 failed and 5 skipped. None of the five failures touches this change:
      • a Hypothesis FlakyFailure in test_import_layers.py;
      • agent serve --help, which needs the agent package installed;
      • three test_cli_smoke.py checks of installed package metadata, which belongs to the borrowed virtualenv.
    • mypy on openadapt_flow/handoffs and cli_handoff_list.py reports no errors in those modules. The one error it reports is in reward/worker.py, against the borrowed environment's installed types.
    • Ruff --fix and format ran outside the gate. They took under a second.
  • CI on this PR is running.

Delta tests (Mac cpu-slots):

  • Flow: test_handoff_receipts.py, test_handoffs.py, test_deferred_report.py, test_capabilities_map.py, tests/test_handoff_launcher.py and tests/test_receipt_verify.py: 95 passed.
  • packages/types/tests, including the new test_receipt_follow_up.py: 828 passed. The existing vectors are unchanged.
  • mypy reports no errors in the new code. The two errors it does report are in reward/worker.py and in an unchanged line of receipt_record.py from the stack.
  • git merge-tree against Agent-to-agent handoffs with receipts: MCP, HTTP, files and the A2A protocol #2414 (feat/a2a-serve) still shows no conflicts.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: 2753093

First review of this PR, stacked on an earlier #2410 head (this tree does not contain 49da9cdd). Author is GitHub abrichr, not Grok. I will not merge. I am not re-litigating #2410's open _approval finding here.

A 31-field cap can emit an inconsistent confirmation line

handoffs/line.py to_line walks sorted(handoff.fields)[:31] when recording field commitments. differing_count is counted only over those 31 keys, but state still comes from judge(), which compares every field.

If a handoff has more than 31 fields and a differing field falls after that slice, the line can have state="recorded_differently" and differing_count=0. That contradicts the record/run/v1 rule that recorded_differently and differing_count > 0 must agree, and a later verifier would refuse the receipt as inconsistent. Raising differing_count to the true total would also fail (differing_count must not exceed the committed field openings). Fail closed instead: do not emit a line (or do not cap away a differing field) when any compared field would not fit.

I also checked the other places I was asked to attack:

  • Carry-over. A confirmed record that later comes back not_found or ambiguous returns to sent with strength none. An unreachable receiver leaves a confirmed state unchanged. That matches the module docstring.
  • Readers. Every search hit is re-checked against key_path. A next link off the same origin, a non-Bundle body, a resource-type mismatch, or more than 20 pages is unreachable, never not_found.
  • Reasons. A reason the schema does not allow for the state is dropped from the line and left in the ledger. Strength and read-method map onto the closed record/run/v1 vocabulary (field_readback → read_back, api_readback → api).
  • Observer. The payer observer is invoked from PendingLedger.settle while the ledger lock is held; I did not find it performing network I/O on that path.

Review only; I am not merging.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: 6bf5c4a

Re-review after my REQUEST CHANGES at 2753093c65d2c1ac42f7212397e3d79fcc310d26. Author is still GitHub abrichr, not Grok. I will not merge.

New since that head: list now registers into the shared handoff_group; a failing settle observer is swallowed in _notify and payer.sync can catch up missed settlements; refused-claim wording is "sent; they refused it"; a launcher test covers openadapt handoff list; and the branch has merged current #2410 including report.canonical. Those deltas are aimed correctly.

The blocking 31-field finding is still unfixed. handoffs/line.py to_line still walks sorted(handoff.fields)[:31] and still counts differing_count only over that slice, while judge() still compares every field. A differing field past the slice can still yield state="recorded_differently" with differing_count=0. Fail closed when a compared field would not fit.

Review only; I am not merging.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: fb5cc35

Delta review after my REQUEST CHANGES at 6bf5c4a828e9f8c1031d524c63351b7266a25c73. Author is GitHub abrichr, not Grok. Review only; I am not merging.

The 31-field finding is still unfixed. to_line still walks sorted(handoff.fields)[:31] and still counts differing_count only over that slice, while judge() still compares every field. A differing field past the slice can still yield state="recorded_differently" with differing_count=0. Fail closed when a compared field would not fit.

New issues in this delta:

  1. handoffs_for_run now treats a handoff as belonging to the run when handoff.run_id equals the report's run_id, the run directory path, or the directory's name. The name is too loose: two runs that share a folder name (or a handoff whose run_id happens to be that name) will have their lines attached to this receipt. Match the report's run_id and, if you also accept a path, only the resolved directory path, never Path(run_dir).name.

  2. verify_chain accepts a follow-up signed by any key in the receiver's registry. A different pinned key (including a customer_key or a Cloud key) can append recorded_as_intended (or recorded_differently) lines to someone else's run. Require that every follow-up be signed by a key that already signed the original receipt. sign_updates should also verify the original envelope before copying its statement.

FOLLOW_UP_COPIED and the changed_original / out_of_sequence / wrong_original checks look right: subjects and the copied predicate fields must stay equal, sequence is 1, 2, 3, and wire() still drops follows when unset. _signature ignoring observed_at is the right change criterion. receipt.handoffs.json is a local index, not a proof; the signed chain does not depend on it for verification, which is correct.

This head also contains #2394 84a3c7ab and #2410 f95f7c98, so the open safeHref userinfo-after-colon bypass and _approval ignoring block.decision are still in the tree.

I am not merging.

to_line refuses a handoff with more than 31 compared fields, or whose
differing field ids aren't among them, so differing_count always matches
judge(); the ledger model caps fields at 31. handoffs_for_run matches the
report's run_id or the run directory's resolved path, never its bare folder
name. sign_updates verifies the run's receipt against the signing key
before copying it. write_receipt_record reports an unplaceable handoff as a
receipt error.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: dc07e1f

The head moved from fb5cc35a to dc07e1fe before this review, so this review covers the new head. This PR is protected and Claude wrote it, so a second vendor reviewed it. Codex could not start because its local config failed to load. Gemini (gemini-3.1-pro-preview) reviewed the diff against feat/receipt-counterparty-line, along with the full head versions of handoffs/*.py and receipt_record.py. It looked for correctness and safety blockers only.

Status of Grok's earlier blockers at this head:

  1. 31-field cap (line.py to_line): fixed. to_line now raises when a handoff has more fields than a line can hold, or when a differing field is not one of the compared fields. It no longer drops fields from the line.
  2. handoffs_for_run matching by folder name: fixed. A handoff now matches on the report's run_id, or on an absolute path that resolves to the run directory. A bare folder name no longer matches.
  3. Follow-ups signed by any registry key: fixed. sign_updates checks the original receipt against its own key before it copies the statement. In the base branch, openadapt_types.receipt.verify_chain refuses an update with different_signer when its signers are not a subset of the original receipt's signers.
  4. Inherited _approval ignoring block.decision: fixed in the base this PR merges. _approval now requires decision == "approved".

What Gemini checked against the PR body:

  • The ledger keeps only HMAC digests.
  • judge handles found, not_found, ambiguous and unreachable. An unreachable receiver leaves a confirmation in place. A record that disappears or becomes ambiguous goes back to sent.
  • The FHIR reader checks the exact key on every record and refuses next links to another origin.
  • The settle observer catches its own errors and never changes a settlement.
  • Payer handoffs are only ever acknowledged or sent.
  • By default, only X12 999 and 277CA reports count as the payer's answer.
  • read_method and strength map as the PR body's table says.
  • A reason the schema does not allow for a state is left off the line.

Gemini found nothing that fails open and no removed safety check.

No blockers.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: dc07e1f

The 31-field limit now applies at admission and when building a confirmation. Run matching accepts the report ID or resolved absolute directory and drops the basename fallback. This head also includes #2410 at 941afc5a, where every verified follow-up signer must have signed the original. Two issues remain in the handoff path.

  1. Bind the report used to select handoffs to the signed receipt. sign_updates checks the original envelope with the local signing key, then uses a separate read of report.json to choose the run ID and deferred-check IDs. It never checks those report bytes against the signed subjects. A stale report in a reused directory can therefore attach another run’s confirmations to a valid original. Read the report once, check the signed subject against that same input, and refuse before writing any update if it does not match. Cover the normal match and a mismatched report with the original envelope intact. Follow-up writer · Existing subject check
  2. Refuse an incomplete on-disk history before reading or extending it. updates() stops at the first missing number, even when later signed update files exist. The CLI can mark the resulting prefix verified. The writer uses the same prefix length to allocate its next number. Discover the numbered public envelopes first and require a contiguous sequence before reporting verified history or writing another update. The existing out-of-order test calls the lower-level verifier directly. Cover a gap through verify_history and sign_updates as well. Sequence discovery · History reader

The fixes belong in the shared receipt and history paths used by both payer acknowledgments and referral read-backs. I inspected their synthetic regression tests and the CLI call sites. This was a source review, with no new test run or held-out application run. Separate base findings remain with #2410 and #2394.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: dc07e1f

Codex (codex exec --sandbox read-only) review of the PR diff at this head, posted as Codex returned it apart from shortening local file links to repo paths.

  1. followup.py:132: sign_updates verifies only the original receipt, not the existing update chain, before signing the next update. A tampered, wrong-signer, or out-of-sequence update can therefore be extended with a new valid signature. The CLI verifies only afterward and still exits successfully (cli_handoff_list.py:269, cli_handoff_list.py:250). Verify the complete existing chain before writing anything, and fail nonzero if verification fails.

The three previous blockers are otherwise fixed: receipt lines now fail closed on excess/unknown differing fields; run matching uses report ID or resolved absolute path; and verify_chain enforces original-signer membership.

Tests could not run because the environment has no usable temporary directory.

sign_updates verifies the receipt and every update already written, against
the signing key alone, before it signs the next one. handoff list exits 1
when the run's signed history does not verify.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Re-review request for Codex's REQUEST CHANGES at dc07e1fe. New head: 754add8fa7c1aae9e8e76c816accfd669d24522a.

What changed (commit 754add8f):

  • sign_updates (packages/flow/openadapt_flow/handoffs/followup.py) now runs verify_history over the receipt and every update already written, with a registry holding only the signing key, and refuses (ValueError, nothing written) unless the whole chain verifies. A tampered, wrong-signer or out-of-sequence update is never extended.
  • handoff list --run (packages/flow/openadapt_flow/cli_handoff_list.py) exits 1 when the run's signed history does not verify, in text and --json output and with no handoffs listed; a refused --sign-updates still exits 2.
  • Tests: a tampered update-2 blocks signing update 3; the CLI returns 1 for an unsigned update-1 and 2 when asked to sign on top of it, with no update-2 written.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 754add8

The new check rejects an invalid update in the sequence it reads, and the CLI returns a failure status when that verification fails. The two findings from my previous review remain.

  1. The report used to select handoffs still needs a signed subject match. After verifying the receipt and updates, sign_updates separately reads report.json and uses its run ID and deferred-check IDs. Neither that function nor verify_history checks those exact report bytes against the original receipt’s signed subjects. A valid receipt and a stale report can thus produce a signed update for the wrong run. Check the exact input used for selection and refuse before writing when it does not match. Follow-up writer · Existing report-subject comparison
  2. A gap in the numbered files still passes as the end of history. updates() stops at the first missing number, so a later envelope never reaches verify_history. Both verification and allocation of the next update use that same incomplete list. Discover the public update envelopes and refuse a gap before reporting a verified history or signing another update. File discovery · Append · History reader

This one-commit delta retains #2410 at 941afc5a. I inspected the source and the new synthetic cases for a damaged update already in the sequence. The shared writer and reader serve both payer and referral handoffs. The mismatched-report and missing-middle-file cases still need regression coverage. This review included no new test execution or held-out application run.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 754add8

Codex (codex exec --sandbox read-only) review of the PR diff at this head, posted as Codex returned it apart from shortening local file links to repo paths.

  1. packages/flow/openadapt_flow/handoffs/followup.py:101 — updates() stops at the first missing sequence number. Thus receipt.update-2.json is ignored when update 1 is absent. verify_history() can report the history verified, and sign_updates() may write a new update despite an existing tampered/out-of-sequence file. Discover all update files and fail closed on gaps or unexpected names.

The other previously reported blockers appear fixed, including the CLI’s nonzero exit after verification failure.

updates() lists every receipt.update-N.json and fails closed on a gap in
the numbering, an unexpected update file name, or a private update with no
update beside it.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Re-review request for Codex's REQUEST CHANGES at 754add8f. New head: cdbc61150ec4d69f57fc47f982863c165a421a7f.

What changed (one commit): updates() in packages/flow/openadapt_flow/handoffs/followup.py now lists every receipt.update-*.json in the run and raises on a gap in the numbering, a name that isn't receipt.update-<N>.json (or .private.json) with N from 1, or a private update with no update beside it. verify_history and sign_updates both go through it, so an update past a gap fails the history instead of being ignored. Tests in test_sign_updates_refuses_a_receipt_it_cannot_verify_or_did_not_sign.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: cdbc611

Codex (codex exec --sandbox read-only) review of the PR diff at this head, posted as Codex returned it apart from shortening local file links to repo paths.

  1. followup.py:165 — The report-binding blocker remains. sign_updates() selects handoffs using report.json without matching those bytes to the original receipt’s signed subject. A stale report can attach another run’s confirmations to a chain that verifies. Check the exact report used for selection before signing.

  2. followup.py:96 — If the final update and its openings disappear together, verification accepts the shorter history. The sidecar still counts the missing update as signed, so --sign-updates can report no change while the last surviving receipt says the opposite. Reconcile sidecar records with verified envelopes.

  3. cli_handoff_list.py:266 — handoff list --run exits successfully when receipt.json is missing but signed updates remain. Check for orphan updates before treating the run as unsigned.

  4. followup.py:174 — Concurrent signers can verify the same history, allocate the same sequence, and overwrite each other’s signed update or private openings. Hold a per-run lock from verification through publication and refuse to replace an existing sequence.

  5. followup.py:169 — Only the latest observation is compared. If a confirmed handoff reads differently and then matches again between signing calls, neither transition enters the signed history. Track the last signed observation and process subsequent changes in order.

  6. readers.py:182 — The FHIR reader discards error OperationOutcome entries and ignores Bundle.total. A partial search returning one matching record can therefore produce recorded_as_intended despite an unresolved duplicate. Apply the existing search-outcome and coverage checks before accepting a match.

  7. ledger.py:322 — A completed handoff’s key can be reused. If the second delivery never arrives, the first delivery’s matching record can still confirm it. Require a per-delivery identifier or evidence that distinguishes the two deliveries.

  8. intake.py:82 — Receiver values use the sender’s date order even when the receiver profile declares a different order. Identical text such as 03/04/2026 can represent two different dates and still produce recorded_as_intended.

At cdbc6115, 72 focused tests passed. The 31-field cap, basename exclusion, original-signer check, invalid-chain exit status, and missing-middle sequence fix are covered.

Instance fixes, named by class until the shared fail-open harness lands:
- wrong subject: sign_updates picks handoffs only from the report the
  receipt signed; a key names one delivery, never reused.
- missing evidence: a signed update missing from the run (or updates
  without their receipt) breaks the history; a FHIR search with an error
  OperationOutcome or a total it didn't return is unreachable.
- race: an update's sequence is claimed with O_EXCL, never overwritten.
- wrong reading: the receiver's values are read in the receiver's date
  order; with none declared, an ambiguous date counts as differing.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

How each item in Codex's round-3 review at cdbc6115 was handled. New head: a8e2098c1b570b98cd9d69ee981ade8aa5a721e6.

# Item Status
1 sign_updates picks handoffs from an unbound report.json Fixed: the report bytes must match the receipt's report.json subject.
2 A dropped last update shortens the history Fixed: verify_history requires the update files to match the sidecar's record of what was signed.
3 handoff list --run passes with orphan updates and no receipt.json Fixed: orphan updates or a sidecar without the receipt are a broken history (exit 2).
4 Concurrent signers overwrite a sequence Fixed: each update file is claimed with O_EXCL; the second signer fails and writes nothing.
5 Only the latest observation is compared Not fail-open; filed in #2475.
6 FHIR reader ignores error OperationOutcome and Bundle.total Fixed: an outcome issue that isn't information or warning, or a total that differs from the resources returned, is unreachable.
7 A completed handoff's key can be reused Fixed: a key names one delivery; a second handoff under it is refused.
8 Receiver values read in the sender's date order Fixed: ReadResult.date_orders carries the receiver profile's order. With none declared, an ambiguous date counts as differing.

handoff tests: 45 passed. Codex delta review requested in the review inbox.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: a8e2098

The signed-report finding (1) is fixed. The signer hashes the exact bytes it then parses to select handoffs. The reader reconciles stored update names with the sidecar, detecting a missing final update and its openings (2). The sender rejects a reused delivery key even after completion (7), and the receiver’s date order controls comparison (8). The page reader also rejects explicit error outcomes and a single inconsistent total. Report binding · History reconciliation

Three cases in the changed paths still affect correctness.

  • Missing receipt in the CLI (3). An orphan update reaches the history verifier. A remaining receipt.handoffs.json by itself does not. The CLI returns early for a read-only listing, reporting success even though the sidecar records signed history and the receipt is gone. Include the sidecar in that early check or let the verifier decide. CLI
  • Concurrent or interrupted publication (4). Exclusive creation prevents replacing the same sequence number. The changed-line decision and sequence count are still separate from that claim. Two calls that read the same prior state can allocate consecutive numbers for the same change and race on the shared sidecar. An interruption after the empty public file is created can also leave the next verification unable to proceed. Serialize verification, change detection and publication per run, and provide a recoverable commit point for the envelope, openings and sidecar. Append path · Sidecar update
  • Conflicting totals across FHIR pages (6). Each page overwrites declared_total. The reader compares only the last value with the number of resources received. An earlier page can declare more results than arrived, yet the reader can return found when the last total is lower. Refuse conflicting declared totals across pages before accepting a match. Page totals

I inspected the single commit since cdbc6115 and its synthetic regression assertions. The author reports 45 handoff tests passed. I did not rerun them or exercise a held-out receiver. Item 5 stays in #2475.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: cd47e7c

This merges the previously reviewed head a8e2098c with #2410 at 4ab5ce04. I compared the three affected source files and both handoff test files. All five have identical Git blob IDs before and after the merge. The prior findings still apply.

  • Item 3. With only the signed-history sidecar left, a read-only CLI listing returns before it checks for the missing receipt. Include the sidecar in orphan detection. CLI
  • Item 4. Exclusive file creation protects one sequence number. Two signers can still select the same change and append it under consecutive numbers, and publication can stop between the envelope, openings and sidecar writes. Serialize the append per run and make interrupted publication recoverable. Append path
  • Item 6. Each FHIR page replaces the previously declared total. A later, smaller total can hide an incomplete search. Refuse conflicting totals before returning a match. Reader

The report binding and the earlier fixes for items 2, 7 and 8 carry forward. Item 5 is tracked in #2475. I reused the existing source and synthetic evidence for this merge-only review.

…rphans, FHIR totals

Round-4 items, named by class:
- race: sign_updates holds an exclusive per-run lock from the history check
  through publication; a pending note written before any update file lets
  the next call complete or roll back an interrupted publication.
- missing evidence: a sidecar left without its receipt is a broken history
  in the read-only listing too; FHIR pages that disagree on the total are
  unreachable.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 01fe62f

Items 3 and 6 are fixed. A sidecar without the original receipt now reaches the history verifier and fails the CLI listing. The FHIR reader refuses a change in the declared total across pages and still checks the final resource count. CLI · FHIR totals

Item 4 remains open. The per-run lock serializes live signers. Two details prevent safe recovery from an interruption.

  1. The lock persists on disk if the signer process dies. Its file descriptor is already closed, and only the Python finally removes the file. The next sign_updates therefore stops before it reaches the pending publication. Use a process-owned lock that releases on exit, or an ownership check that safely reclaims an abandoned lock. The new test calls the recovery helper directly after manually removing the lock. Cover recovery through the normal signing entry point. Lock acquisition · Test
  2. Recovery can remove valid evidence before verifying that the retrying signer belongs to the original run. It reads filenames from the pending note and unlinks both when verification with the retrying key fails. A different local key after an interrupted append must leave the existing envelope and openings intact. Verify the original and authorize the signer before making changes, derive both filenames from the expected sequence in the run directory, and preserve existing evidence when validation is inconclusive. Recovery · Order of operations

I inspected the corrective source and its synthetic assertions. I did not rerun tests or contact a receiver. Item 5 remains in #2475.

Base automatically changed from feat/receipt-counterparty-line to main November 21, 2026 23:10
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: 01fe62f

Gemini run on 01fe62f (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it. Gemini returned only its verdict line, with no findings.

…doff receipts (permissive-default guarded)

Takes main's settled-run writer (#2412) and adds this branch's handoff
lines to it. A run whose transaction outcome is SAVED_AWAITING_CHECK still
refuses readback_pending unless every unverified write line is a declared
counterparty handoff still in the sent state, with no refuted line; that
receipt is signed with outcome UNKNOWN and reason awaiting_counterparty,
never VERIFIED, and follow-ups record the settlement. The CLI verifier and
the viewer say 'Awaiting counterparty confirmation'. The synthetic fixture
gains step_id and intent.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: a45b39b

Gemini run on a45b39b (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it. This is a delta after the main merge and the guarded pending-handoff receipt (permissive-default guarded).

The implementation of counterparty confirmations and follow-up receipts is solid. The _awaiting_counterparty guard strictly enforces the requirement that a SAVED_AWAITING_CHECK run is only signed if every unverified write line is a declared handoff still in the "sent" state, and it correctly forces the outcome to UNKNOWN with reason awaiting_counterparty.

The follow-up receipt chain securely links to the original receipt, verifies the sequence, and ensures that the report.json matches the one originally signed. The FHIR reader correctly fails closed to "unreachable" on any transport error, bad body, or partial search (e.g., OperationOutcome errors or mismatched totals). The ledger safely uses HMAC-SHA256 digests to compare fields without storing plaintext values.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: bbe9e7e

Gemini run on bbe9e7e (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it. This is a merge-only delta since a45b39b. The prompt held this PR's files as the main merge changed them. Gemini returned only its verdict line.

Main now carries #2426's receipt surfaces; the handoff confirmation lines
and the guarded awaiting-counterparty receipt attach after build_statement
with evidence lines, the card is written, then the handoff sidecar is
recorded. Viewer rebuilt.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: 503dd3d

Gemini run on 503dd3d (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it. This is a delta after the main merge that brought #2426's receipt surfaces into the same writer. The prompt held the resolved write path, build_statement and evidence_lines.

The resolved writer correctly prevents fail-open paths in the receipt generation process.

To answer the specific questions:

  1. Can an unverified evidence line slip past the awaiting guard? No. Unverified evidence lines are assigned check = "not_checked" and are added to the pending list. The guard any(line["step"] not in sent_steps for line in pending) ensures that unless the evidence line was explicitly matched as a declared handoff line (which would place its step into sent_steps), it will raise a readback_pending error and halt the signing process.
  2. Is the awaiting outcome ever VERIFIED? No. If the run is awaiting counterparty (awaiting = True), the _awaiting_counterparty function explicitly hardcodes the outcome to "UNKNOWN" and the reason to "awaiting_counterparty". There is no subsequent code that can override this back to "VERIFIED" before the envelope is signed.

Additionally, build_statement correctly tallies all not_checked and refuted lines (including the newly appended evidence lines) and downgrades the outcome to "UNKNOWN" if any are found, ensuring that runs with unverified evidence cannot be signed as "VERIFIED" even when not in the awaiting state.

…artifact inventory

After merging main: openadapt and flow cli_tasks listed 'handoff' twice
(ruff F601); the handoff_receiver benchmark parser sets allow_abbrev=False;
public-artifacts.json lists the handoff_receiver compose file and results.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: 94981d6

Gemini run on 94981d6 (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it. This is a delta since 503dd3d: a merge of main and one CI-fix commit. Gemini returned only its verdict line.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: d88fe0d

Gemini run on d88fe0d (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it. This is a delta for one annotation-only commit since 94981d6. A first prompt framed as a security review got a refusal from Gemini, so this is the rerun with plainer wording.

This commit only updates a type annotation for the fields dictionary and imports Literal from typing.

  1. Runtime behavior: Type annotations in Python are not enforced at runtime, and since the actual runtime values being assigned to this dictionary have not changed, the runtime behavior remains exactly the same.
  2. Type checking: Changing str to Literal["text"] actually strengthens the static type check by restricting the allowed values for the second element of the tuple to exactly the string "text", rather than any arbitrary string.

@abrichr
abrichr merged commit 5e51ea9 into main Nov 22, 2026
56 of 57 checks passed
@abrichr
abrichr deleted the claude/counterparty-confirmations branch November 22, 2026 09:20
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.

1 participant