Skip to content

feat(hooks): check a coding agent's writes to declared systems of record - #2411

Merged
abrichr merged 14 commits into
mainfrom
claude/agent-hooks-pack
Nov 21, 2026
Merged

abrichr merged 14 commits into
mainfrom
claude/agent-hooks-pack

Conversation

@abrichr

@abrichr abrichr commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Stacked on #2394. The base is feat/seal-page-app, because the record/run/v1 receipt types (openadapt_types.receipt) and the Flow writer (receipt_record.py) are only there. This PR retargets to main once #2394 merges.

What this does

openadapt hooks install --agent claude-code (or codex) writes project-local hook settings. Each tool call that writes to a system declared in openadapt.systems.yaml (a database URL, an HTTP API base, a CLI such as sqlite3/psql/curl reaching it, or an MCP server's tools) gets three steps:

  1. Pre-check. The call is matched against the system's declared writes. Its approval mode (allow, ask, block) decides what happens. A write to a declared system that no entry covers is blocked, or asked about if unknown_write: ask. Before an allowed write, the store is read, so the read-back can tell new rows from old.
  2. Read-back. After the call, the write's openadapt.verify/v1 contract is checked through openadapt_flow.verifier's file-based pair: capture, a saved Snapshot, then verify_write. It's the same judge that verify-run, guarded saves and openadapt verify use. No new checker. A failed read-back, or one that never ran, is UNCERTAIN, never a pass, and the same write (the declared write with the same values, however the call is worded) is held until a person runs openadapt hooks approve <id>.
  3. Receipt. Every outcome gets .openadapt/hooks/runs/<id>/report.json and a signed record/run/v1 receipt.json, written by receipt_record.write_receipt_record. The receipt holds no value, path or URL from the call.

Also: openadapt hooks status, openadapt hooks uninstall (removes only OpenAdapt's entries; keeps the user's) and openadapt hooks approve.

Verified hook facts (2026-11-21, primary docs)

Claude Code (code.claude.com/docs/en/hooks)

  • Hooks live in .claude/settings.json or .claude/settings.local.json, under hooks.<Event>[].{matcher, hooks[].{type, command, timeout}}. A matcher with regex characters is an unanchored regular expression. MCP tools are named mcp__<server>__<tool>.
  • Input: session_id, transcript_path, cwd, permission_mode, hook_event_name. PreToolUse adds tool_name, tool_input and tool_use_id. PostToolUse adds tool_response. Stop adds stop_hook_active.
  • PreToolUse output is hookSpecificOutput.permissionDecision (allow/deny/ask/defer) with permissionDecisionReason. allow skips the user's prompt, and settings deny/ask rules still apply. The top-level decision field is deprecated for this event. PostToolUse and Stop use decision: "block" and reason.
  • Exit 2 blocks. Any other non-zero exit is non-blocking, so the tool runs.

Codex (learn.chatgpt.com/docs/hooks): Codex has hooks.

  • They live in .codex/hooks.json or [hooks] in config.toml, with the same structure. Project hooks run only once trusted (/hooks), and the trust is hash-bound.
  • Shell calls match as Bash, patches as apply_patch (both tool_input.command), and MCP tools by name. Hosted tools aren't covered.
  • PreToolUse supports deny and allow. ask is parsed but unsupported, and the tool runs. Errors, timeouts and malformed output also let the tool run.

Failing closed

  • Because both agents run the tool on any hook failure except exit 2, install writes a launcher (.openadapt/hooks/run-hook) that exits 2 before a tool call if the hook can't start or crashes. The launcher can't catch a timeout, so Claude Code's PreToolUse entry also sets onFailure: "block" (Claude Code 2.1.295 and later). On older Claude Code and on Codex, a hook timeout lets the call run.
  • A missing or invalid systems file denies every hooked call.
  • OpenAdapt never sends ask to Codex. A write that needs a person is denied with an approval id. The person runs openadapt hooks approve <id> in their own terminal, and the identical call is allowed once.
  • Anything that names a declared system and isn't provably a read is a write: a script, a redirect, ;, $(...), a body read from a file. The curl, psql, sqlite3 and mysql parsers read an allow-list of flags, so an unknown flag or an attached short value (-d'...', -XPOST, --config=, --file=, --init-command=) is a write. SQL that holds a comment, an escape or dollar quoting is never a read.
  • The agent can't widen its own scope. Edits to the systems file, the contracts, .openadapt/hooks and the agents' hook settings are blocked, and so is openadapt hooks approve|install|uninstall run from the agent's shell.
  • In-scope allow writes send no decision, so Claude Code's own permission prompt still applies. auto_approve: true opts in to skipping it.

Honesty and limits

  • Advisory. Hooks see tool calls, not the network. An agent with its own credentials and a shell can reach a system in ways no hook sees. HOOKS.md says so at the top.
  • --strict is refused. It needs a credential broker. openadapt wrap -- COMMAND (feat(wrap): openadapt wrap --example, and compiled browser tools that run over MCP #2406, feat(wrap): openadapt wrap -- COMMAND wraps any agent process #2407) is a browser-MCP harness, not a broker for databases, HTTP APIs or MCP servers. So --strict refuses rather than installing advisory hooks under a strict name. Nothing here duplicates wrap.
  • Values come from the call. The read-back confirms that the call did what it said and that nothing else in the read set changed. The declared scope and approvals are what limit which values the agent may choose.
  • Not the uncertain-write ledger. The begin/verify ledger lease lives in one process, and each hook event is its own process, so the hooks keep their own hold on a REFUTED or UNCERTAIN call.
  • A declined Claude Code ask is UNCERTAIN. It never gets PostToolUse, so the Stop hook reads it back and reports it UNCERTAIN, because "not sent" can't be told from "not landed".
  • The receipt schema fits imperfectly. record/run/v1 is built for OpenAdapt's own runs. model_calls is 0: it counts OpenAdapt's check, not the agent. A declared write whose read-back didn't settle is a line with approved_unverified, because the schema has no read-back-failed code. The hooks feed receipt_record.write_receipt_record a synthetic report.json, and the end-to-end test asserts the signed lines and checks, so a change in that builder fails loudly.
  • Live sessions: one run. Real headless claude -p (Claude Code 2.1.305) and codex exec (Codex CLI 0.144.4) sessions ran against a temporary synthetic project (benchmark/hooks_live/). Declared writes came out VERIFIED with receipts that verify; an out-of-scope delete was blocked with the database unchanged; a broken read-back was UNCERTAIN; a Python heredoc naming the file was blocked. A Python write that builds the path at run time was not seen, and its row landed unchecked: the advisory limit. Cost: USD 0.125 for Claude Code, plus about 96,000 input tokens for Codex.

Tests

  • tests/test_hooks.py: the systems file schema; shell, file, MCP and WebFetch classification, with fail-closed cases (SQL hidden behind comments, attached curl values, unknown CLI flags); write keys that ignore wording; hook input parsing; PreToolUse, PostToolUse and Stop output for each agent, including Codex ask becoming deny; engine refusals (no systems file, missing contract values, unreadable store, unknown-write policy); install merging, idempotence and uninstall that keeps the user's entries; refusal of --strict, the home folder and a broken settings file.
  • tests/test_hooks_e2e.py: the harness runs the real launcher as a subprocess with HOME and the receipt key in temp dirs.
    • Claude Code: an allowed SQLite write is read back VERIFIED, and its receipt verifies (verify_run_receipt, signer "Signed by this computer"). An out-of-scope DELETE is blocked, the database is unchanged, and the receipt says STOPPED. An HTTP write whose read-back fails is UNCERTAIN (receipt UNKNOWN), and its retry is refused. Stop summarizes the session.
    • Codex: ask is denied until approved, then allowed once, then VERIFIED.
    • A retry of the UNCERTAIN write with a reworded description is still refused.
    • A call with no PostToolUse is read back at Stop.
    • A launcher whose Python is missing exits 2.

Docs: packages/flow/docs/HOOKS.md, the hooks command doc and command map, a CAPABILITIES row (Experimental, synthetic), a README mention, and llms-full.txt.

Not run locally: mypy, test_import_layers (its environment lacks hypothesis), the link and anchor check, and the wheel-content tests. CI covers them.

openadapt hooks install --agent claude-code|codex writes project-local hook
settings. Each tool call that writes to a database, HTTP API or MCP tool
declared in openadapt.systems.yaml is pre-checked against its declared scope
and approval mode, read back with its openadapt.verify/v1 contract through the
verifier, and given a signed record/run/v1 receipt. An undeclared write to a
declared system is blocked or asked about; a failed read-back is UNCERTAIN and
the same call is held until a person releases it. Codex can't ask from a hook,
so ask is a deny until openadapt hooks approve. --strict is refused until a
credential broker exists for these systems. The hooks are advisory.
…he write not the wording

curl, psql, sqlite3 and mysql flags are read from an allow-list; any other
flag, an attached short value or SQL with a comment, escape or dollar quote
makes the call an unknown write. Holds and approvals are keyed on the declared
write and its values (or the call without its free-text description), so a
reworded retry of an UNCERTAIN write is refused. Claude Code's PreToolUse entry
sets onFailure: block, the launcher runs from the hooks folder, agent-facing
errors name the exception type only, and an unsettled declared write's
receipt line says approved_unverified.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Grok
Reviewed-Head: f32cdce

First review of this PR, stacked on #2394. Author is GitHub abrichr, not Grok. The PR is a draft. I will not merge. I am not re-litigating #2394's open safeHref finding here.

Classification does not fail open on the paths I tried

A call that names a declared system and is not one clear read is a write or unknown_write. curl flags outside the allow-list, a pipeline with two system names, or a non-single curl are unknown writes. SQL with comments, /* */, \, #, or $$ is never a read (_one_statement returns None → unknown write). _WRITE_WORDS includes into, copy, pragma, and the usual mutation verbs, so SELECT … INTO is not a read. WebFetch is treated as GET-only; I did not find a POST path through that tool name in this PR.

Holds and Codex approvals key the write, not the wording

write_key for a declared write is (system, write, params). For any other write it is the call minus inert fields (description, timeout, run_in_background). A reworded description or a new tool-use id is the same key. After a non-VERIFIED settlement, _settle writes held/ under that key, and pre refuses a retry until a person releases it. A granted Codex approval is unlinked after one use of the same key, so it does not cover a later call.

Receipt honesty

_run_folder builds a synthetic report with model_calls: 0, execution_outcome from _RUN_OUTCOME (VERIFIED / FAILED / RECONCILIATION_REQUIRED / HALTED), and no raw tool arguments or command text in the signed fields. receipt_record.write_receipt_record does not upgrade a non-VERIFIED outcome. Tool input is not copied into the statement.

Leftovers, not blockers

  • Mapping a declared write whose read-back did not settle to not_checked: approved_unverified is a schema squeeze, as you noted. I would rather see a dedicated code than reuse approved_unverified, but I am not blocking this draft on it. model_calls: 0 is honest if it means OpenAdapt's check, not the agent's.
  • An UNCERTAIN receipt raised from _finish when PostToolUse runs with no pre-check does not write a hold. The main _settle path does.

Review only; I am not merging.

One run against a temporary synthetic project: declared writes VERIFIED with
receipts that verify, an out-of-scope delete blocked with the database
unchanged, a broken read-back UNCERTAIN, a Python heredoc naming the file
blocked, and a Python write that builds the path at run time not seen (the
advisory limit). Reports, receipts, the signing key and key transcript lines
are in benchmark/hooks_live.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Grok
Reviewed-Head: 075417f

Delta re-review after my APPROVE at f32cdceb615d22a6e3156a93fef3ce445e6c7366. Author is still GitHub abrichr, not Grok. The PR is still a draft. I will not merge.

The only unique commit is evidence: packages/flow/benchmark/hooks_live/ (transcripts, eight run folders, a public verifying key, README), plus HOOKS.md / CAPABILITIES.md / public-artifacts.json. No hook code changed.

The eight reports match the claimed matrix: two VERIFIED clinic-db add-note receipts, two UNCERTAIN notes-api add-note receipts (indeterminate read-back), and four BLOCKED clinic-db receipts (compound command or SQL that is not one statement). Receipts are presented against a public seal-ed25519-… key, not a private key. The transcripts are synthetic clinic notes on localhost; I did not find secrets, credentials, or personal contact data. Task 4b is stated as an advisory limit and was not run.

Review only; I am not merging.

…sts in .gitleaksignore

Secret Scan flagged hold_key in the live run's report.json files as a generic
API key. Each is a SHA-256 digest of a declared write and its values, not a
credential. The reports stay byte-identical (signed receipts cover them), so
their eight findings are pinned by exact commit:file:rule:line fingerprint;
new reports use hold_sha256, which the rule doesn't match.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Grok
Reviewed-Head: 7640ac2

Delta re-review of my APPROVE at 075417ff50b15d443f31be4fc591ec07be9ced49. The #211 request named the Secret Scan fix at d1ae3c7493c36ffa9b62f4819b725d83ae241359; the current head also merges current #2394 (feat/seal-page-app). Author is still GitHub abrichr, not Grok. Review only; I am not merging. Still a draft.

The Secret Scan change is sound. The eight report.json files are byte-identical to 075417ff (receipts still cover them). Each hold_key is a 64-character SHA-256 digest on the exact line named in .gitleaksignore. Those reports were introduced in 075417ff, so the fingerprints 075417ff50…:path:generic-api-key:line are exact; no pattern or rule is relaxed. New engine records use hold_sha256, which gitleaks does not treat as a key name. The live-run README records the rename.

The merge of current #2394 brings in _write via open_binary and the current safeHref. The still-open userinfo-after-colon finding remains a #2394 issue; I am not changing this PR's unique hooks verdict for it.

The Windows descriptor contract refuses raw os.open next to os.write: on
Windows it gives a text-mode descriptor that translates newlines. The hook
state, log and report files now open through private_file.open_binary and
loop until every byte is written, as receipt_record does.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Grok
Reviewed-Head: eadebdc

Delta review of the Secret Scan / hooks work, at the current head named in #211 (7060178263, d1ae3c74 → eadebdcb). Author is GitHub abrichr, not Grok. Still a draft. Review only; I am not merging.

My previous verdict on this PR (7060107423) was APPROVE at 7640ac2d, which already included the merge of #2394 5a70434b. The unique new commit is eadebdcb (hooks/engine.py only).

_write_json and _log now open through private_file.open_binary (O_BINARY, refuse O_TEXT) and write with a _write_all short-write loop, the same pattern #2394 added for receipt files. Temporary JSON files are still created with O_EXCL and replaced into place. Every report / state / receipt / approval write I found still goes through _write_json; the append-only log goes through the same helper. That closes the Windows raw-descriptor failure the request describes, where engine.py called os.open next to os.write.

Inherited from the already-merged #2394 tree, and not unique to this hooks change: safeFileHref still accepts a userinfo-after-colon URL (https://openadapt.ai:@evil.example). That remains a #2394 issue and does not flip this unique verdict.

…istry

benchmark/hooks_live/signing-key.json held only a public Ed25519 entry, but
its name is key-material shaped, so check_evidence_keys refused it. It is
now seal-key.json, a one-entry registry like the other evidence folders, and
listed in PUBLIC_REGISTRIES, where it still has to pass the closed schema.
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Re-review request; your APPROVE was at eadebdcb. New head: 275e86553020910c7c2b25905f642c53585fe585.

Delta:

  • 4b9cdf28: check_evidence_keys.py refused benchmark/hooks_live/signing-key.json (a public Ed25519 entry with a key-material-shaped name). It is now seal-key.json, stored as a one-entry registry like the other evidence folders, and listed in PUBLIC_REGISTRIES, where it still has to pass the closed public-registry schema. The README and public-artifacts.json are updated to match.
  • A merge of feat/seal-page-app at 99dcc782 (Receipts: one signed record per run (replaces Seals) #2394's round-1 to 3 fixes).
    Tests: test_evidence_key_exclusion.py 131 passed; test_hooks*.py 59 passed.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Codex
Reviewed-Head: 275e865

I reviewed the registry conversion in 4b9cdf28 against Grok’s approved head. The other commit merges the current #2394 parent.

The new registry contains one active public verification entry. I compared its three fields with the earlier entry. All three values are identical. The checker adds one repository-relative path and still applies its existing Ed25519 registry validator. Sibling paths retain the existing policy. The README and public artifact manifest reference the new name.

All eight reports and eight receipts have the same Git blobs as the approved head. The manifest lists all sixteen files. This preserves the earlier evidence for declared writes, blocked calls and uncertain read-back. The documented unchecked write still has no receipt. I checked the committed files and mapping without rerunning the agent sessions or signature checks.

The change introduces no app-specific engine code. It uses the same validator as the other public evidence registries. Held-out evidence remains the previously recorded synthetic runs.

This PR is a draft stacked on open #2394 at 99dcc782. At review time, source CI and the protected evaluator were queued. Secret Scan was skipped.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

From: Gemini (integration)

Added "hooks": "setup hooks" to FLOW_NAMES in packages/flow/openadapt_flow/cli_tasks.py and openadapt/cli_tasks.py at f73f96bb6, preserving all existing handlers, help behavior, and parity assertions.

Verified locally: packages/flow/tests/test_cli_tasks.py (54 passed) and tests/test_cli_tasks.py (130 passed).

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Codex
Reviewed-Head: f73f96b

The delta from the approved head adds hooks → setup hooks to both the launcher and Flow task registries. These are the only two changed lines. The existing parser-parity tests now have a mapping for the registered hooks command.

I checked both registries on this exact head and exercised the live parser without invoking a hook. The launcher translated setup hooks --help to the Flow hooks command, Flow displayed its help, and the legacy and task spellings both selected cmd_hooks with the same arguments. The public key registry, eight reports, eight receipts, and their validator are unchanged from the approved head.

The task mapping applies across agents; this check covers CLI compatibility. The author reports 54 Flow and 130 launcher CLI tests passed locally. Hosted CI stopped at the draft-state check. The PR is still stacked on #2394.

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

From: Gemini
Reviewed-Head: 9eb3452

CI-only fix: added allow_abbrev=False to all 5 hooks child parsers in packages/flow/openadapt_flow/hooks/cli.py so test_cli_no_abbreviations.py passes (8 passed, ruff check/format green).

@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Codex
Reviewed-Head: 9eb3452

All five hooks subcommands now require full option names. I exercised the registered parser for install, status, uninstall, approve and run. Each accepted the documented option, selected the existing handler and rejected a shortened option with exit 2 before dispatch. This is the entire change since the previous approval. Both task registries, the public verification key registry, the eight report/receipt pairs and their validator have identical Git blobs at both heads.

The current #2394 tip af70c507 and this head merge cleanly in a dry Git merge. #2411 remains a draft. Hosted CI failed at the draft check and skipped package tests. The author separately reports eight local CLI tests passed. Hosted draft check

Base automatically changed from feat/seal-page-app to main November 21, 2026 21:44
@abrichr
abrichr marked this pull request as ready for review November 21, 2026 21:44
@abrichr

abrichr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Codex
Reviewed-Head: 6eb1185

The only changes since the approved head are the Literal import and the annotation on mode. Its three values exactly match Write.approval's Approval type. The configuration for unknown writes still accepts only ask or block and defaults to block.

The prior Mypy job inferred that narrower unknown-write type for the whole variable. It then rejected two valid assignments: the declared write's approval at line 248 and "allow" after consuming a one-call approval at line 270. The annotation covers both assignments. The grant check, consumption and runtime decisions are unchanged. Prior diagnostics

#2411 now targets main and is marked ready for review. Hosted CI for this head is pending. Current run

@abrichr
abrichr merged commit 877722f into main Nov 21, 2026
57 of 58 checks passed
@abrichr
abrichr deleted the claude/agent-hooks-pack branch November 21, 2026 23:00
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