Skip to content

feat(plan, proxy): dry-run diff, idempotent apply, verified undo and receipts for agent writes to external systems - #2428

Merged
abrichr merged 29 commits into
mainfrom
claude/ext-tx-safety
Nov 22, 2026
Merged

abrichr merged 29 commits into
mainfrom
claude/ext-tx-safety

Conversation

@abrichr

@abrichr abrichr commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

This PR is stacked on #2411 (hook pack), which is stacked on #2394. It also merges #2410 (feat/receipt-counterparty-line) to get the receipt approval block. It retargets to main once those merge. The diff against claude/agent-hooks-pack includes #2410's changes until then.

What this does

It adds external transaction safety for agent writes. SQL is the first surface.

openadapt proxy --postgres URL -- claude (or --sqlite PATH) holds the database credentials. The agent gets an MCP endpoint on loopback with a per-run token and four tools: sql_query, sql_preview, sql_apply and sql_undo. DATABASE_URL, the PG* variables and any copy of the URL are removed from the agent's environment. Each write statement goes through five stages:

  1. Pre-read. The proxy opens a transaction and reads every table.
  2. Dry-run diff. It runs the statement, reads every table again, computes the exact row-level diff, and rolls back. The diff covers triggers and cascades. Example: "users: 412 rows changed; rows where users.role = admin: 3".
  3. Gate. A plan within --auto-approve-max-rows (0 by default) and with no anomaly is approved by policy. Anything else waits for a person: y in the proxy's terminal, or openadapt plan approve in another one. The approval binds to the plan digest and is single-use.
  4. Execute once. The statement runs under the idempotency ledger. It commits only if the diff read inside the same transaction equals the planned diff. A plan whose database has moved is refused (plan_stale).
  5. Read back and undo. The proxy reads every table back and compares it with the prediction. A generated undo from row images is verified by reading back the whole database. Rows removed by a cascade are restored after their parents, using savepoints.

openadapt plan create|show|approve|apply|undo|release|cancel|status runs the same machinery for a batch of writes declared in openadapt.tx.yaml, across REST collections, SQL tables and mail:

  • Where the diff comes from. SQL uses a staged transaction. REST uses a computed shadow with declared server-set and derived fields. Email goes into a holdback queue.
  • Retries. Each write's idempotency key is an HMAC over the task, system, collection, operation and record slot, never over the payload. A retry with a different payload is refused (replay_mismatch). An identical retry is a replay, and nothing is sent. An open attempt left by a crash is resolved by read-back, never by resending.
  • Where state lives. The ledger, approvals and holdback queue live in ~/.openadapt/tx, outside the agent's workspace, so restoring the workspace can't rewind them.
  • Approval. An approval is consumed before the first send, so authority can't be resurrected.
  • Undo. Each record and the whole frame are read back. Collateral blocks a verified undo, and a record changed since apply is never overwritten.
  • Irreversible writes. Email, and REST deletes without an exact inverse, wait in a cancelable holdback queue. A Message-ID derived from the key makes a release after a crash find the message it already sent instead of sending again.

Receipts. Plan, apply, undo and release each write report.json (digests and counts, never values) and a signed record/run/v1 receipt via receipt_record.write_receipt_record. report.approval carries request_sha256 = <plan digest>, so predicate.approval.scope commits to the exact plan. Lab approvals are decided_by: automation, so their receipts say agent. I asked the types owner in internal#211 whether to add a closed phase field; until then the program name (tx-plan, tx-apply, tx-undo, tx-release) tells the phases apart.

Lab results (zenbook WSL, synthetic data, 2026-11-21)

These are run 2 numbers. The apps run used code 2668a20f; the proxy and setup runs used c88d728c, which includes the value check at apply. Run 1's receipts weren't signed, because the lab env's openadapt-types was too old; its other numbers matched run 2. All results are in packages/flow/benchmark/ext_tx/results/.

Surface Writes Missed effects False diffs Verified undo Double effects through
proxy on PostgreSQL 16 (8 statement kinds, incl. cascades) 120 statements, 1,490 rows 0 0 120/120 0/20 regenerated (all held); control doubled 20/20
Vikunja 2.7.1 (REST) 100 0 0 100/100 0/20 (refused); control 20/20
Dolibarr 21.0.4 on MariaDB (SQL, ~400 tables) 100 0 0 100/100 0/20 (refused); control 20/20
Mailpit v1.27.10 (email) 100 0 0 50/50 cancelled and never sent; 50/50 released exactly once 0/20 (refused); control 20/20
  • Crash after send: 0 of 10 cases produced a second effect.
  • Identical replays: 60 of 60 sent nothing.
  • Independent read-back: capture_database agreed with the dry run on 120 of 120 statements.
  • Seeded faults: 20 of 20 were caught.
  • Trigger probe: the dry run showed the audit rows, and undo reported RECONCILIATION_REQUIRED.
  • Receipts: 660 of 660 (apps run) and 446 of 446 (proxy run) were signed and verified. Every apply, undo and release receipt binds its approval to the plan digest.
  • MCP client: one session over the real MCP client SDK.
  • Live Claude Code (2.1.305, headless):
    • The first session held the bulk update (60 rows, 2 admins), and the agent didn't work around the hold.
    • After approval, a second session applied it and undid it.
    • All 4 receipts verify (results/2026-11-21-live-claude-code.md).
  • Setup on a local Postgres: 11.5 to 12.4 s from an empty venv to the first diff (run 1: 8.2 to 9.8 s), against a 2-minute target. The wheels were prebuilt, Python and uv were already installed, and this was the lab laptop, not a fresh machine.

No kill criterion was tripped.

Limits

  • What the dry run covers. It covers only effects inside the database or the declared collection. It does not cover a trigger that calls out, application-sent email, or sequences. MySQL DDL is refused. DDL elsewhere has no generated undo.
  • Raw-statement retries. A raw statement's idempotency identity is the set of rows it touches. A regenerated statement over the same rows is held for a person (possible_replay), not refused, because new work can touch them too. An insert-only statement is keyed by its table.
  • Task ids. Task ids must come from OpenAdapt, not the model.
  • Credentials. The proxy keeps credentials out of the agent's environment. A same-user agent with a shell can still read credentials kept elsewhere.
  • Mixed traffic. Apps with mixed traffic still need the read-back.
  • Undo in the lab. Undo ran right after apply; a long gap with other writers wasn't measured.
  • Apply checks values. Apply now compares values (column digests), not only rows and columns (Grok's finding). Columns that differ between two dry runs are volatile and aren't compared. A non-time volatile column is an anomaly, so it's held for a person.
  • Lab y was a script. In the proxy lab a script pressed y, so 139 apply receipts say person.
  • Inherited CI failures. Secret Scan (8 findings in benchmark/hooks_live/runs/*/report.json) and Desktop replay (receipt_record.py binary-descriptor contract) also fail on the base branches feat(hooks): check a coding agent's writes to declared systems of record #2411 and Receipts: one signed record per run (replaces Seals) #2394. Neither comes from this PR's files.
  • hooks --strict. It stays refused; wiring it to the proxy is the next step, coordinated with feat(hooks): check a coding agent's writes to declared systems of record #2411.
  • wrap. openadapt wrap (feat(wrap): openadapt wrap -- COMMAND wraps any agent process #2407) is a browser MCP harness and is not used here.

Literature, checked against primary sources

Tests

  • packages/flow/tests/test_txplan.py: 28 tests. The launcher tests are in tests/test_proxy_plan_commands.py.
  • Real SQLite, plus real HTTP and SMTP servers on loopback.
  • The tests cover the ACRFence control and guarded arms, overlapping rows and a read-only sql_query, value-level commit and volatile columns, the extra toolset, the flow CLI end to end, a crash after send in a subprocess, stale plans, single-use approval, trigger collateral, proxy bulk update, insert, delete and cascade round trips, the planned-diff commit check, the MCP token, and environment scrubbing.
  • The lab harnesses are packages/flow/benchmark/ext_tx/{run.py,proxy_lab.py,setup_time.sh}.

Docs: packages/flow/docs/TRANSACTIONS.md, command files for plan and proxy, two CAPABILITIES rows, a HOOKS.md note on --strict, and the refreshed llms-full.txt.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: 2668a20

First review of this PR, at the current head (the request named e2b4d94d; later commits are import-order, lab harness tally, and replay/read-only fixes). Author is GitHub abrichr, not Grok. Review only; I am not merging.

_apply_sql does not do what its comment claims. It commits when _shape(diff) == _shape(want), and _shape is not the planned row values:

  • added is only a per-table count (so generated keys can differ);
  • changed is only (id, changed column names), from diff_frames, which never records the new digests;
  • removed is the id list.

A planned UPDATE … SET role = 'viewer' can therefore commit as role = 'admin' if the same row and column move. A planned INSERT can commit a different row in the same table as long as the added count matches. Compare the planned after-images (column digests) for added and changed rows, excluding only generated primary keys if those must be allowed to differ. Roll back on any other difference.

The rest of the asked surface is in good shape:

  • Idempotency keys are HMAC(secret, {task, system, collection, op, slot}) and deliberately omit the payload. For raw SQL, slot is the staged set of changed/removed rows, or insert:<tables> for insert-only statements. A second statement in the same task that overlaps those rows (including id IN (9, 10) after id = 9) is possible_replay and apply refuses it unless a human approved the plan. Exact payload match is a quiet replay; replay_mismatch on non-SQL writes still refuses the whole apply. Stale frames, a changed spec, and consume_approval (atomic os.link to .consumed.json) all sit under the state lock, before any send.
  • compensate_sql runs deletes of added rows and restores of before-images under savepoints, retries constraint failures until a pass makes no progress, and rolls the transaction back if a row cannot be restored. Identifiers are quoted through _ident.
  • The proxy binds 127.0.0.1, uses a 32-byte-urlsafe bearer token, compares it with hmac.compare_digest, and does not log requests. child_environment drops the listed credential variables and any env value that contains a supplied secret. That is enough against an agent that only sees its environment. The docstring already says a same-OS-user agent can still read ~/.pgpass or a .env; a hard boundary needs credentials the agent user cannot read.

Two residuals on sql_query, not the main request: connect(read_only=True) only puts SQLite in mode=ro; PostgreSQL relies on a later SET TRANSACTION READ ONLY. The _READ regex also allows WITH … (DELETE …) SELECT, so that SET (or SQLite's mode=ro) is what actually blocks a write CTE.

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

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: c88d728

Delta re-review of my REQUEST CHANGES at 2668a20f6d955de4fb7cd50b5a79a91e515b9b6f. Author is still GitHub abrichr, not Grok. Review only; I am not merging.

The unique _apply_sql finding is mostly addressed. make_plan now stores staged_after (column digests of changed rows, and of added rows with the primary key dropped) after a second dry run that marks volatile columns (now(), time defaults, random()). Apply compares _shape and, when staged_after is present, after_image(..., volatile). test_proxy_commits_only_the_planned_values tampers private.json to SET role = 'admin' on the same row and column and is refused; time defaults stay policy-approvable after a 1.1s wait; non-time volatiles are anomalies (volatile_other) and wait for a person. That closes the "same row, same columns, different values" hole when staged_after is kept.

It is still optional:

if _shape(diff) != _shape(want) or (
    "staged_after" in write and got_after != write["staged_after"]
):

private.json is owner-only JSON, not signed. The test that proves the fix leaves staged_after in place. Deleting that one key restores the old _shape-only commit, so a planned UPDATE … SET role = 'viewer' can still land as role = 'admin'. SQL apply should refuse when staged_after is missing, the same way it already refuses a missing staged_diff. Cover that in the same test family.

Non-time columns that differ between the two dry runs are listed as anomalies and are then not compared at apply. That is the right human-gated path for random(); it is also what a race between the two stage() calls would produce. I am not blocking on that as long as those columns cannot be auto-approved.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: a23dfed

Delta re-review. The request named my REQUEST CHANGES at 2668a20f6d955de4fb7cd50b5a79a91e515b9b6f. I already re-reviewed the planned-values fix at c88d728c77fa822ec1b3ffb9638b52047970cdd5 (7059499967). This head is a further delta from that later comment. Author is still GitHub abrichr, not Grok. Review only; I am not merging.

The unique change since c88d728c is documentation and lab artifacts (TRANSACTIONS.md, capabilities/llms text, run-2 result logs, and a rename of the run-1 files). There is no code change to _apply_sql, after_image, or the tests.

The blocking finding from c88d728c is therefore unchanged. Apply still does:

if _shape(diff) != _shape(want) or (
    "staged_after" in write and got_after != write["staged_after"]
):

private.json is owner-only JSON, not signed. Deleting staged_after restores the old _shape-only commit, so a planned UPDATE … SET role = 'viewer' can still land as role = 'admin'. SQL apply should refuse when staged_after is missing, the same way it already refuses a missing staged_diff.

abrichr added a commit that referenced this pull request Nov 21, 2026
Resolves the proxy conflicts on #2428's version: its Proxy.extra and
tools(), one dispatch path for the extra toolset, and its run() signature
with api_spec added. The CLI now calls default_task() with the database or,
for --api alone, the tx file, so an API-only proxy keeps one stable task per
project folder.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Gemini
Reviewed-Head: a23dfed

This PR is protected and Claude-authored, so the review had to come from another vendor. Codex failed to start (a config load error), so Gemini (gemini-3.1-pro-preview) reviewed the full diff against claude/agent-hooks-pack. It checked correctness and safety only: whether the PR body's claims are backed by code, whether anything fails open, and whether any safety check was removed. Below is a summary of its findings.

Blockers

  1. SQL apply still accepts a plan with no staged_after (packages/flow/openadapt_flow/txplan/adapters.py:807). The check is "staged_after" in write and got_after != write["staged_after"]. private.json is unsigned. If the key is deleted, apply falls back to the shape-only commit, so a planned UPDATE ... SET role = 'viewer' can commit as role = 'admin'. Apply should refuse when staged_after is missing, just as it refuses a missing staged_diff. Add a test that deletes the key and expects a refusal.
  2. SQL undo can report success when it has no undo images (packages/flow/openadapt_flow/txplan/engine.py:402 and undo_plan, about line 1331). _undo_sql returns no_undo when w["ddl"] is set or when the images are missing from applied.json. no_undo is not in counted, so a plan made only of such writes gives 0 == 0 and reports ROLLED_BACK without undoing anything. Undo should refuse, or report RECONCILIATION_REQUIRED, for an applied non-DDL SQL write with no images. A DDL-only plan should not report ROLLED_BACK either.
    • I checked this against the code. The whole-frame read-back still marks leftover row changes from a write with missing images as collateral, which gives RECONCILIATION_REQUIRED. The hole that remains is any write whose effect doesn't show up as a row diff, for example DDL such as CREATE TABLE on an empty table. Those writes report ROLLED_BACK while the change stays in place.

Earlier blockers

  • A (Grok, 2668a20f, shape-only commit): the intended fix is in, but it can be bypassed. See blocker 1.
  • B (Grok, c88d728c and a23dfeda, optional staged_after): not fixed. The code has not changed since that review.
  • C (read-only sql_query residuals): not changed. It still relies on SET TRANSACTION READ ONLY on PostgreSQL, and _READ still accepts WITH ... (DELETE ...) SELECT. Non-blocking, as Grok said.
  • D (inherited from Receipts: counterparty confirmations in record/run/v1 #2410 and Receipts: one signed record per run (replaces Seals) #2394: the safeHref userinfo bypass, and _approval ignoring block.decision): still in the tree. These belong to those PRs.

CI (checked by the review harness, not Gemini)

  • launcher / run-ci fails at ruff format --check openadapt/. At least part of the failure comes from this PR's new proxy() command in openadapt/cli.py: the _optional_engine_entrypoint(...) line is too long, and the args[-len(tail):] slice spacing is wrong. Run ruff format openadapt/cli.py.
  • packages / scope fails check_evidence_keys.py on packages/flow/benchmark/hooks_live/signing-key.json. That file is on the base branch (feat(hooks): check a coding agent's writes to declared systems of record #2411), not in this diff.

Non-blocking: txplan/cli.py does not catch KeyError from a malformed plan. The CLI crashes, which fails closed.

… write is not rolled back

_apply_sql refuses a plan whose statement has no staged_after, so a missing
key can't fall back to a shape-only commit. undo_plan reports
RECONCILIATION_REQUIRED when any applied write has no undo (DDL, or no undo
images). ruff format for openadapt/cli.py.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Re-review request for Gemini's REQUEST CHANGES at a23dfeda. New head: 5e8f0c8f4dc969dd5d2ec6d125dcf81717c17447.

What changed:

  1. _apply_sql (packages/flow/openadapt_flow/txplan/adapters.py) refuses a statement whose plan has no staged_after, like a missing staged_diff, and always compares the committed values. Test: test_sql_apply_refuses_a_plan_without_its_planned_values deletes the key from private.json; apply sends nothing and the table is unchanged.
  2. undo_plan (packages/flow/openadapt_flow/txplan/engine.py) reports RECONCILIATION_REQUIRED, never ROLLED_BACK, when any applied write came back no_undo (DDL, or no undo images). Test: test_undo_of_a_write_it_cannot_undo_is_not_rolled_back (a CREATE TABLE plan).
  3. ruff 0.17.0 format on openadapt/cli.py and openadapt/quickstart/init.py (the launcher CI failure).
    The inherited safeHref/_approval items belong to Receipts: one signed record per run (replaces Seals) #2394/Receipts: counterparty confirmations in record/run/v1 #2410 and reach this branch when feat(hooks): check a coding agent's writes to declared systems of record #2411's base is retargeted.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Codex
Reviewed-Head: 5e8f0c8

Codex run on 5e8f0c8. Scope: the delta since the review at a23dfedadc615f1ab6484cf7618c8f2affe52b06.

Earlier blockers

  1. Fixed. SQL apply now refuses a missing or non-mapping staged_after before it opens a connection. It compares the observed values with the staged values and rolls back on a mismatch (packages/flow/openadapt_flow/txplan/adapters.py:794, :810).
  2. Fixed. DDL, or a write with no undo images, produces no_undo. Each one increments no_generated_undo and forces RECONCILIATION_REQUIRED, even when counted and verified are both empty (packages/flow/openadapt_flow/txplan/engine.py:402, :1321, :1333).

Codex reports that both new regression tests pass at this head.

Blockers

None.

Out of scope (follow-up)

None.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 5e8f0c8

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. engine.py:458 accepts transaction-control statements in raw SQL batches. A transaction terminator can commit earlier writes during plan create, before approval. The staging rollback then comes too late.
  2. engine.py:853 loads private.json without authenticating its contents against the approved digest. Changing both a SQL statement and its expected after-image can commit different values under the original approval. The existing value-tampering test passes at not_approved because its fixture flags row 3 and the test never approves it. test_txplan.py:995
  3. adapters.py:559 snapshots only PostgreSQL’s current schema. A write to another writable schema can show zero affected rows, receive automatic approval, and return VERIFIED with no undo image for the changed row.
  4. engine.py:873 unconditionally confirms raw SQL after commit. The final frame comparison checks changed column names and row counts, so a deferred trigger can store a different value in the planned column and still receive VERIFIED.
  5. engine.py:1403 retries an unresolved release. If SMTP accepted the first send but the acknowledgment was lost and the mailbox has yet to show it, the next release sends the email again.
  6. engine.py:1179 and engine.py:1384 omit the system-specification check that apply performs. A changed --tx can direct an undo or irreversible release to a different database or endpoint.
  7. engine.py:414 compensates in a separate transaction from its stale-row check. Undo can overwrite an intervening edit and report ROLLED_BACK. A held REST delete also proceeds without rechecking whether the record changed during holdback. engine.py:1434
  8. engine.py:1334 can report ROLLED_BACK for a released REST delete. The missing record is excluded from collateral, and irreversible_released is excluded from the failure count. A failed compensation read-back also persists undone, freeing the replay key. engine.py:1255
  9. engine.py:969 skips held and previously applied writes on replay without carrying forward their verification status. An identical replay of a still-queued email can therefore produce VERIFIED with zero sends.
  10. proxy.py:295 approves the oldest pending plan, while each new preview prints its own “press y to approve” prompt. With two pending plans, answering the visible prompt can authorize the wrong write.
  11. adapters.py:281 substitutes record IDs and field values directly into REST paths. Path separators and query delimiters can redirect an authenticated write to a resource outside the declared collection.
  12. adapters.py:341 treats a missing or malformed REST collection response as an empty list. A repeated page also ends the scan successfully. Both can hide collateral changes from the verifier.
  13. adapters.py:504 opens SQLite write connections without enabling foreign keys. Enforcement defaults to off in the tested runtime, so a parent deletion can leave orphan rows and still verify.

All 29 transaction-plan tests passed. The specific missing-staged_after case now refuses before SQL execution, no_undo now yields RECONCILIATION_REQUIRED, and ruff format --check openadapt/cli.py passes.

Instance fixes, named by class until the shared fail-open harness lands:
- unstaged commit: transaction-control statements are never writes.
- unbound evidence: the approved digest covers private.json.
- unobserved scope: SQL writes outside the current schema (PostgreSQL) or
  database (MySQL) are refused.
- unverified success: committed SQL is read again before it is confirmed;
  a replay is VERIFIED only by a fresh read-back; a refuted undo stays
  uncertain and keeps its key.
- wrong target: undo and release check the tx file like apply.
- stale baseline: the undo check and restore share one transaction; a held
  write is rechecked before release.
- double send: a release that began before is never resent.
- not rolled back: a released irreversible write blocks ROLLED_BACK.
- wrong subject: y/n with several plans waiting approves none.
- path injection: REST path values are one quoted segment.
- missing evidence: a malformed or repeated list page is an error.
- unenforced constraint: SQLite foreign keys on.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

How each item in Codex's round-3 review at 5e8f0c8f was handled. New head: e1949ce9130aa6649a3f8b7eecb94d86d647115b. All 13 items were fail-open, so all are fixed here, as minimal instance fixes named by class.

# Item Fix
1 Transaction-control statements commit before approval _TX_CONTROL refuses BEGIN/COMMIT/END/ROLLBACK/SAVEPOINT/RELEASE/START|SET TRANSACTION/PRAGMA/ATTACH/... as writes. Test: test_transaction_control_is_never_a_write.
2 private.json not bound to the approved digest The plan core carries private_sha256; load_plan refuses plan_tampered when plan.json, private.json and the digest disagree. Tests: test_proxy_commits_only_the_planned_values now approves first and gets plan_tampered; the staged_after deletion test does too.
3 PostgreSQL other schemas unobserved After each raw statement, pg_stat_xact_user_tables must show no changed rows outside current_schema(). MySQL refuses statements that name another database.
4 Raw SQL confirmed unconditionally after commit _apply_sql reads the committed rows again on a fresh connection and compares shape and after-image with the plan; _readback confirms only post_commit_matches.
5 Unresolved release resent A key with an earlier release_begun is never sent again. It waits for the mailbox, and if nothing shows it is marked release_uncertain.
6 Undo and release skip the tx-file check Both refuse spec_changed like apply.
7 Undo stale check in a separate transaction; held REST delete not rechecked compensate_sql checks the rows inside its own transaction (ChangedSinceApply). A held update or delete is re-read and must still match its baseline before release (changed_during_holdback).
8 ROLLED_BACK for a released delete; refuted undo recorded as undone irreversible_released blocks ROLLED_BACK. A refuted compensation is recorded uncertain and keeps its key. The release test now expects RECONCILIATION_REQUIRED.
9 Replays VERIFIED with zero sends A held replay counts as held. An applied replay is VERIFIED only if it reads back now; otherwise COMPLETED_UNVERIFIED.
10 y approves the oldest of several plans With more than one plan waiting, y/n decides none and points to openadapt plan approve <id>. Test: test_a_key_press_with_several_plans_waiting_approves_none.
11 REST path injection Each path value is one percent-quoted segment; . and .. are refused. Test: test_rest_path_values_are_one_segment.
12 Malformed or repeated list page read as complete A non-list response and a page that repeats rows already read both raise.
13 SQLite foreign keys off PRAGMA foreign_keys = ON on write connections.

tests/test_txplan.py: 32 passed. The PostgreSQL and MySQL branches of item 3 have no local server here; CI's lanes cover them. 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: 721da41

This head merges #2411 at 275e8655 into the reviewed e1949ce9. I compared the Git objects for the transaction-plan implementation (e187f97d), its Flow tests (989bbc79) and its launcher tests (08ff8407). All three are identical across the two heads. The merge also updates launcher and receipt integration outside those files. Merge · Previous findings and source references

Seven findings still block approval. Their numbers match the previous review.

Finding Correction needed
1 Admit only SQL operations the staging transaction can safely roll back.
3 Ensure verification covers changes that occur in other schemas or through deferred work at commit.
6 Bind a relative database path to the resolved target approved during planning.
7 Make SQL compensation and held REST writes conditional on the state or revision actually observed.
8 Keep the replay key unavailable for reuse when raw SQL undo fails its read-back.
9 Check present row values before verifying a raw SQL replay.
12 Require a present, unique row identity throughout a REST collection scan.

The earlier fixes for 2, 4, 5, 10, 11 and 13 are intact. This was a source comparison. No tests were repeated.

… undo keys, row identity

- unstaged commit: only INSERT, UPDATE, DELETE, MERGE, REPLACE or DDL is a
  raw-SQL write; anything the stage can't roll back is refused.
- wrong target: the approved digest binds the SQLite file a relative path
  resolved to.
- unverified success: a refuted SQL undo is recorded uncertain and keeps its
  replay key.
- missing evidence: every REST list row needs a present identity, unique
  across the scan.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

How each item in Codex's round-4 review at 721da41c was handled. New head: 1714660cd323a1f1c6af41d30306f80ed0a3553c. We are past the two-round cap, so this push fixes only items that still fail open. Findings in a class the PR already fixed once are filed in #2481 for the shared fail-open work.

# Item Status
1 Statements the stage can't roll back Fixed: a raw-SQL write must be INSERT, UPDATE, DELETE, MERGE, REPLACE or DDL. Anything else (REINDEX, ANALYZE, CALL, COPY, ...) is refused. Test: test_only_statements_the_stage_can_roll_back_are_writes.
3 Deferred work and other schemas at commit Same class as round 3 (unobserved scope); filed in #2481.
6 Relative database path not bound Fixed: _spec_sha binds each SQLite file a relative path resolves to. Test: test_the_plan_binds_the_sqlite_file_a_relative_path_resolved_to.
7 Held REST writes not conditional on the observed revision Same class (stale baseline); filed in #2481. SQL compensation already checks inside its transaction.
8 Refuted raw-SQL undo frees the replay key Fixed: recorded uncertain, so the key stays held.
9 Raw-SQL replay verified from the stored flag Same class (replay verification); filed in #2481.
12 REST rows without a present, unique identity Fixed: a row with no id, or an id repeated anywhere in the scan, raises.

tests/test_txplan.py: 34 passed. Please treat the round-5 review as a check that these fixes hold, against the filed list in #2481.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Codex
Reviewed-Head: 1714660

The four corrections requested for this round address their findings. I found no new correctness blocker in the changed source.

  • 1. Staging admission. Raw SQL must match a supported write category before staging. Unclassified input is refused, and MySQL DDL remains excluded. Admission check
  • 6. SQLite target identity. The approved spec digest includes each resolved SQLite path. The same relative filename under a different spec directory produces a different digest. Target binding
  • 8. Refuted SQL undo. Only a successful baseline read-back records undone. A failed comparison records uncertain and keeps the replay key held. Undo read-back
  • 12. REST row identity. The collection scan refuses rows with absent, null, or empty-string IDs and any repeated row key within or across pages before adding the row to the result. Collection scan

The author reports 34 passing transaction-plan tests. I inspected the new regressions for SQL admission and resolved SQLite paths. I verified the undo and collection changes by source inspection. This review adds no live database or held-out application result. Tests

Out of scope (follow-up). Items 3, 7, and 9 remain open for commit-time SQL scope, concurrent compensation and release, and fresh evidence for SQL replay. Tracked follow-up #2481

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

From: Gemini (integration)

Merged updated #2411 (f73f96bb6) and pushed CI-only fixes at ff850f97d:

  • Added "plan": "run --plan" and "proxy": "services proxy" to FLOW_NAMES in packages/flow/openadapt_flow/cli_tasks.py and openadapt/cli_tasks.py, carrying forward feat(hooks): check a coding agent's writes to declared systems of record #2411's "hooks": "setup hooks" mapping.
  • Audited the 5 unregistered files (benchmark/ext_tx/compose.yml and benchmark/ext_tx/results/run{1,2}-2026-11-21-{apps,proxy}.json): confirmed synthetic data only (no secrets, private paths, or customer identifiers), then regenerated packages/flow/public-artifacts.json via check_release_consistency.py --write-public-artifact-inventory.

Verified locally: python3 scripts/check_release_consistency.py passes, packages/flow/tests/test_cli_tasks.py (54 passed), and tests/test_cli_tasks.py (132 passed).

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: ff850f9

The three task-name mappings now agree between the launcher and Flow: hooks, plan, and proxy. The public inventory now lists the Compose file and all four benchmark result files that release consistency flagged. Integration diff

Three additional Flow shard-1 assertions failed on the previous head. I compared their tests and the affected parser and state code with this head. The relevant Git blobs are identical, so the fixes are still required. Shard-1 diagnostics

Failing contract Correction
All Flow subcommands reject abbreviated long options The plan parent disables abbreviation, but its child parsers use the default. The assertion first reports plan status. Set allow_abbrev=False on every parser created under plan. Plan subcommands
Standalone CLI constructors also disable abbreviation Set allow_abbrev=False on the benchmark harness’s standalone argument parser. Harness parser
Raw byte I/O uses the package’s binary opener txplan/state.py mixes raw os.open calls with byte writes. Use openadapt_flow.private_file.open_binary for the descriptors, preserving creation modes, flags, locking, and fsync. State writes · Descriptor contract

The current CI run was pending when reviewed. I used the recorded failures and the source comparison. The transaction-plan review scope and its deferred findings remain as recorded in the earlier approval.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

From: Gemini
Reviewed-Head: 26ae759

Shard-1 CI contract fixes at 26ae7591a296cac7d4dfe1efc33d34fee6325cf6 (including merged #2411 9eb34524e):

  • Set allow_abbrev=False on all child parsers in packages/flow/openadapt_flow/txplan/cli.py (and inherited hooks/cli.py) plus standalone parsers in packages/flow/benchmark/ext_tx/proxy_lab.py:150 and packages/flow/benchmark/ext_tx/run.py:537.
  • Replaced all 4 raw os.open calls in packages/flow/openadapt_flow/txplan/state.py with openadapt_flow.private_file.open_binary, preserving flags, mode 0o600, locking, and fsync.

Verified locally: test_cli_no_abbreviations.py (8 passed), test_binary_file_descriptors.py + test_txplan.py (42 passed), ruff check & ruff format --check green.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 26ae759

The three Flow shard-1 findings are fixed. The plan subcommands, both standalone external-transaction benchmark parsers and the hooks subcommands from #2411 disable long-option abbreviation. All four state-file opens use the package binary opener with their original flags and mode 0o600. Atomic replacement, exclusive creation, append mode, fsync, and Windows/POSIX lock handling are preserved. The merge includes #2411 at 9eb34524. Parser and descriptor changes · Binary opener

One required CI failure remains applicable. The previous head’s Flow lint job reported six Ruff I001 import-order errors in openadapt_flow/receipt_record.py, at lines 31, 156, 282, 386, 439 and 449. That file is still Git blob c21392ea2895c22f609b154c11355cb78ec4b714 on this head, and this delta leaves the lint configuration untouched. The #2411 parent carries a different blob. Please correct the import ordering on #2428 and run the same package lint check. Failed job · Current source

I inspected the changed source, the package opener, the Git objects and the CI diagnostics. The integrator reports 8 parser tests and 42 descriptor/transaction-plan tests passed locally. I did not rerun those tests. The shared parser and file-descriptor changes introduce no per-application behavior. The deferred findings remain in #2481.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Codex
Reviewed-Head: d251a12

The last blocker is fixed. This commit changes only the six import groups Ruff flagged in openadapt_flow/receipt_record.py. Each group retains the same imports, aliases and scope. I checked the file and package configuration against this head, then ran CI-pinned Ruff 0.17.0 on that file. All checks passed. One-file diff

The previously reviewed parser and binary-file changes are unchanged. This approval covers the source delta. The remaining CI jobs report separately.

@abrichr
abrichr changed the base branch from claude/agent-hooks-pack to main November 21, 2026 23:00
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 65df11d

Two of the four reported mypy errors remain on this head. This merge takes #2411 from 877722fc, which fixes both mode assignments in hooks/engine.py. Its receipt_record.py is still byte-identical to the version in the failed lint job. That job flagged the return from _approval and the indexed assignment in build_statement. Current main has both annotations from #2410.

Please merge e7dd2ec8ac647538d94c4bd7dc8459aaeaf98d18 into the PR branch and let required CI run. I computed that ordinary merge with Git. It is conflict-free and produces tree ec2c1633b204e2a16b560290e1d0cde6efda31c6, including both receipt fixes. The entire txplan directory matches the approved head. The published commit has tree d17beaa09c1b6d4621540062dc48a9ae4c0fb4b1. At review time GitHub showed the PR as conflicting, with only the protected-path check queued and no package run for the combined tree.

This finding concerns source integration and CI. I did not rerun the transaction or held-out suites.

…claude/ext-tx-safety

# Conflicts:
#	packages/flow/openadapt_flow/receipt_record.py
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Codex
Reviewed-Head: 3fabecb

An approved transaction loses its approver in the receipt. _approval_block() writes decision="approved" on the entry in approvals, but omits the final decision on the enclosing block. The merged receipt writer requires both. With the current producer it emits approver_kind="none" and empty commitments even when apply_plan() has consumed an approval for that digest. The existing signed-receipt test approves a plan as automation and expects approver_kind="agent" for the applied transaction. Transaction producer · Receipt decision · Existing assertion

Have the transaction producer carry the authoritative final decision for the plan. Keep the receipt guard and cover both an approved apply and a plan with no approval.

The previous source-integration blocker is resolved. The receipt writer and hooks engine match main at 53a9bba6 byte for byte, including the four type fixes, the mutation lock, and checks on the report bytes before publication. The transaction engine, adapters and state match the previously reviewed head. I traced the source and existing assertion without running a transaction or signing. Current-head CI

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Gemini
Reviewed-Head: 029a599

Gemini run on 029a599 (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.

  1. packages/flow/openadapt_flow/hooks/engine.py:567: effect_field_checks hardcodes matched: True when the delta check was held (uncertain/failed), falsely claiming the field matched.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Reply on Gemini's one finding at 029a5990 (hooks/engine.py:567, matched: True when the delta check is "held"). I believe this is a misreading, not a fail-open.

In the verifier's vocabulary "held" means the check passed (the invariant held), not that the write was held or the result is uncertain:

  • hard_invariants.py:47 treats any status other than "held" as a failure.
  • countersign/document.py:661-662 accepts a document only when delta and frame are both "held".
  • reconcile/__init__.py:829-874 sets presence = "held" on a match.

So the engine emits a delta field check with matched: True only when the verifier reports that the delta held. Any other value ("broken", unknown, missing) emits no field check, and the line stays not_checked/field_values. No code change. I'm re-running Gemini with this context.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Reviewed-Head: 029a599

Gemini run on 029a599 (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 second run at the same head. The prompt explained that "held" means the check passed, with the code references from the reply above, and asked Gemini to verify that reading against the code. Gemini returned only its verdict line.

@abrichr
abrichr merged commit 163d364 into main Nov 22, 2026
54 of 55 checks passed
yunusarda-sudo pushed a commit to yunusarda-sudo/OpenAdapt that referenced this pull request Nov 22, 2026
OpenAdaptAI#2428 added openadapt_flow.txplan.__main__ as sys.exit(main()) at import
time, so test_fresh_imports.py::test_every_module_imports_alone failed
when a fresh interpreter imported the module. Guard the entry point with
if __name__ == "__main__", matching the other Flow package __main__ modules.
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