Skip to content

Deliver a comment once when Escape interrupts a tool boundary - #3857

Closed
max-sixty wants to merge 2 commits into
mainfrom
grind/s-double-delivery
Closed

max-sixty wants to merge 2 commits into
mainfrom
grind/s-double-delivery

Conversation

@max-sixty

@max-sixty max-sixty commented Oct 25, 2026 •

Copy link
Copy Markdown
Owner

Since #3591, Claude Code's prompt and tool-boundary hooks both left their handover unconfirmed until the turn's next hook. If the turn ended first, Leaf offered the update again. That is right for the prompt hook: Escape while Claude Code still runs prompt hooks drops the prompt, and Leaf's context with it. It is wrong at a tool boundary. Escape while another PostToolBatch hook runs keeps Leaf's context in the conversation, so the server's nudge delivered the comment a second time.

What changes

  • A Claude Code tool boundary records its receipt itself, as every Pi hook already does. Harness.commits_hook_context (a bool per harness) becomes Harness.drops_hook_context, the set of hook events whose context the harness may still drop after Leaf's hook returns. For Claude Code that set is {"UserPromptSubmit", "Stop"}. Stop stays in it because whether Escape drops a Stop hook's output is unmeasured, and Stop hands input over only under plain --print. Every other harness's set is empty, which matches its earlier True.
  • The receipt follows the printed context, and the hook process ends at once. receive_held now records only the opened pickup. After carry_turn prints an inline delivery for an event outside drops_hook_context, it calls delivery.confirm_turn(sid, deadline=...). confirm_turn takes the hook's deadline, and a page whose locks are still held at that deadline keeps its handover for the turn's next hook. hooks.main then flushes stdout and stderr and calls os._exit(0), skipping interpreter teardown. A harness reads a hook's output only once the process exits, so a hook stopped before its receipt leaves the handover to be offered again. The only window left where an update reads received but its context could still be dropped is the exit itself.
  • Only a prompt hook's handover can be offered again. Its re-offer path is unchanged (deliverable, awaiting_receipt, handed_into_turn, confirm_turn at the turn's next hook). It stays covered by test_a_handover_its_turn_never_confirmed_is_offered_again and the journey's dropped and withdrawn steps.
  • After Escape, a comment the tool boundary handed over is treated like any other received input. It waits for the user's next prompt, and that prompt's hook names what is still owed. The server no longer nudges the session for it. This is how Pi already behaves after an interrupt, and how Claude Code already behaved for input a later hook had confirmed.
  • The docstrings, the "Delivered" row in docs/how-it-works.html, and the TODO entry now describe this. The TODO entry keeps only the open decision. test_a_hook_in_a_session_holding_no_page_imports_no_page_reading_or_server runs several hooks in one interpreter, so it now stubs os._exit.

Why there is no reminder nudge, and no protocol bump

The brief asked for a nudge after an interrupted tool boundary that reminds the agent of what it owes. Without a protocol bump, the log can't target that nudge. Once a tool boundary writes its receipt, its handover looks the same in the log as a prompt handover that a later hook confirmed: an opened pickup followed by a receipt. A nudge that reminds the agent about every received, unanswered update in the interrupted turn would also fire in the commonest Escape case: a wake turn whose prompt delivered a comment, and the user pressed Escape while the agent was answering it. Leaf would start the agent again right after the user stopped it. To limit the reminder to tool-boundary handovers, the pickup has to record which hook handed it over. pickup is additionalProperties: false, so that needs a protocol bump. That choice is left to Max as the narrowed TODO entry.

A call Max may reverse. Before this change, a comment handed over at a tool boundary just before Escape was answered without the user doing anything, and the agent received it twice. Now it is delivered once, and it waits for the next prompt. The same applies to any turn that ends without its Stop hooks after a tool boundary handed something over, not only Escape: an API error or a usage-limit error ends the turn the same way. A background job may never get a next prompt, so its comment stays unanswered, and the page shows it as overdue.

Evidence

uv run leaf-dev journey claude-code, on Claude Code 2.1.310:

  • Before, on main (f00911ed1), all steps passed. In the boundary step, the comment "Is the timezone bug a regression?" got two inline handovers. The log shows an opened pickup with refs from PostToolBatch at 03:28:13.597Z, Escape (onCancel) at 14.018Z while the other PostToolBatch hook slept, and a second opened pickup with refs from the nudged turn's prompt hook at 16.054Z. The debug log shows that Leaf's PostToolBatch hook provided additionalContext before the cancel.
  • After (first revision), all steps passed, with the boundary step now checking the new behavior. Ten seconds after Escape, no nudge row had appeared and the comment was still unanswered. The user's next prompt ("Carry on.") named the owed comment, and that turn answered both comments. The transcript holds exactly one inline delivery of the comment, the PostToolBatch one. This also confirms on 2.1.310 that Escape keeps a tool boundary's context in the conversation.
  • After (this revision), all steps passed again, including the new boundary checks. The comment got one opened pickup with refs at 03:59:41.813Z. Its receipt followed at 41.815Z, written after the hook printed.

The window between receipt and exit. I measured it with a scratch probe, not committed. It runs bin/leaf hook --harness claude-code eight times as a subprocess, each with a PostToolBatch payload against a claimed page holding one new comment. Each pair below is (last print to process exit, receipt to process exit). The 1-minute load was 30 to 33 for both runs.

last print → exit receipt → exit
receipt before print, normal teardown (the first revision of this PR) 24, 31, 35, 34, 35, 41, 37, 26 ms at least as long as print → exit
receipt after print, os._exit (this revision) 8, 11, 7, 8, 8, 8, 8, 8 ms 5, 8, 6, 6, 5, 7, 6, 6 ms

The receipt-to-exit figures include uv run's own exit and use the event's millisecond timestamp. An independent reviewer measured print to exit at 41 to 158 ms at a load near 40.

Tests

  • test_escape_keeps_a_tool_boundary_handover_and_nothing_delivers_it_again is the reproducer. A PostToolBatch hands over an owed comment and a resolve that owes nothing, and the turn then reads interrupted. Both are received, deliverable() is empty, the server nudges nobody, and the next prompt names the comment without delivering it inline. On main, the receipt assertion fails. With that assertion removed, it fails because deliverable() returns the comment again.
  • test_a_tool_boundary_hook_stopped_before_its_receipt_offers_its_handover_again stops the hook between its pickup and its receipt. The resolve, an update that owes nothing, is then offered again once the turn reads ended.
  • test_claude_codes_turn_confirms_what_its_hooks_hand_over now expects the boundary to confirm its own handover.

Checks

  • uv run pytest -n 4 over tests/model/test_hooks.py, test_delivery.py, test_hook_registration.py, test_wait.py, test_activity.py, test_claims.py, test_interact_layer.py, tests/process/test_hook_gate.py, test_interact_claude_code_module.py, test_read_state.py, test_bridge.py and dev/tests/model/test_journey.py: 418 passed.
  • The pre-commit hooks pass on every changed file.

Not verified

  • Whether Escape drops a Stop hook's context is unmeasured, so Stop keeps the deferred receipt.
  • The 5 to 8 ms between receipt and exit remains. If Claude Code stops Leaf's hook inside it, an owed comment is still named by the next prompt through its delivery pointer, but an update that owes nothing would be lost.

With pointer-handover

The local branch pointer-handover overlaps this PR in receive_held and in carry_turn's handover.

  • On this branch, a delivery with a refused batch goes as a pointer and its hook records no receipt. The batches it did record keep their opened pickups, and the turn's next hook confirms them even though the model read only a pointer. Main has the same defect, and that branch's 4fa6fc6 fixes it. Either PR can land first.
  • Merging. Keep that branch's receive_held, which returns the batches it recorded, without the confirm parameter, which this PR removes. Have hand_over append that list and return it. Call confirm_turn after the print when the list is non-empty. confirm_turn confirms what the hook recorded, which is what that branch hands over inline.

This was written by Claude Code on behalf of max-sixty

max-sixty and others added 2 commits October 24, 2026 20:37
Since #3591, Claude Code's prompt and tool-boundary hooks both left their handover unconfirmed until the turn's next hook. If the turn ended first, Leaf offered the update again. That is right for the prompt hook: Escape while Claude Code still runs prompt hooks drops the prompt, and Leaf's context with it. It is wrong at a tool boundary. Escape while another PostToolBatch hook runs keeps Leaf's context in the conversation, so the server's nudge delivered the comment a second time.

### What changes

- **A Claude Code tool boundary records its receipt as it hands the delivery over**, as every Pi hook already does. `Harness.commits_hook_context` (a bool per harness) becomes `Harness.drops_hook_context`, the set of hook events whose context the harness may still drop after Leaf's hook returns. For Claude Code that set is `{"UserPromptSubmit", "Stop"}`. Stop stays in it because whether Escape drops a Stop hook's output is unmeasured, and Stop hands input over only under plain `--print`. Every other harness's set is empty, which matches its earlier `True`.
- So only a prompt hook's handover can be offered again. Its re-offer path is unchanged (`deliverable`, `awaiting_receipt`, `handed_into_turn`, `confirm_turn`). The prompt-hook case stays covered by `test_a_handover_its_turn_never_confirmed_is_offered_again` and the journey's `dropped` and `withdrawn` steps.
- **After Escape, a comment the tool boundary handed over is treated like any other received input.** It waits for the user's next prompt, and that prompt's hook names what is still owed. The server no longer nudges the session for it. This is how Pi already behaves after an interrupt, and how Claude Code already behaved for input a later hook had confirmed.
- The docstrings, the "Delivered" row in `docs/how-it-works.html`, and the TODO entry now describe this. The TODO entry keeps only the open decision.

### Why there is no reminder nudge, and no protocol bump

The brief asked for a nudge after an interrupted tool boundary that reminds the agent of what it owes. Without a protocol bump, the log can't target that nudge. Once a tool boundary writes its receipt, its handover looks the same in the log as a prompt handover that a later hook confirmed: an opened pickup followed by a receipt. A nudge that reminds the agent about every received, unanswered update in the interrupted turn would also fire in the commonest Escape case: a wake turn whose prompt delivered a comment, and the user pressed Escape while the agent was answering it. Leaf would start the agent again right after the user stopped it. To limit the reminder to tool-boundary handovers, the pickup has to record which hook handed it over. `pickup` is `additionalProperties: false`, so that needs a protocol bump. That choice is left to Max as the narrowed TODO entry.

**A call Max may reverse.** Before this change, a comment handed over at a tool boundary just before Escape was answered without the user doing anything, and the agent received it twice. Now it is delivered once, and it waits for the user's next prompt.

### Evidence

`uv run leaf-dev journey claude-code`, on Claude Code 2.1.310:

- **Before, on main (`f00911ed1`), all steps passed.** In the `boundary` step, the comment "Is the timezone bug a regression?" got two inline handovers. The log shows an opened pickup with refs from PostToolBatch at 03:28:13.597Z, Escape (`onCancel`) at 14.018Z while the other PostToolBatch hook slept, and a second opened pickup with refs from the nudged turn's prompt hook at 16.054Z. The debug log shows that Leaf's PostToolBatch hook `provided additionalContext` before the cancel.
- **After, all steps passed, with the `boundary` step now checking the new behavior.** Ten seconds after Escape, no nudge row had appeared and the comment was still unanswered. The user's next prompt ("Carry on.") named the owed comment, and that turn answered both comments. The transcript holds exactly one inline delivery of the comment, the PostToolBatch one. This also confirms on 2.1.310 that Escape keeps a tool boundary's context in the conversation. The log shows one pickup with refs, then a receipt 5 ms later in the same transaction.

The new `test_a_tool_boundarys_handover_survives_escape_and_is_not_delivered_again` is the reproducer. On main it fails on the receipt. With that assertion removed, it fails because `deliverable()` returns the comment again after the interrupt. `test_claude_codes_turn_confirms_what_its_hooks_hand_over` now expects the boundary to confirm its own handover.

### Checks

- `uv run pytest tests/model/test_hooks.py tests/model/test_delivery.py tests/model/test_hook_registration.py tests/model/test_wait.py tests/process/test_hook_gate.py -n 4`: 131 passed.
- `uv run pytest tests/model/test_activity.py tests/model/test_claims.py tests/process/test_interact_claude_code_module.py tests/process/test_read_state.py -n 4`: 66 passed.
- `uv run pytest dev/tests/model/test_journey.py`: 19 passed.
- The pre-commit hooks pass on every changed file.

### Not verified

- What happens if Escape lands inside Leaf's own PostToolBatch hook, after its receipt but before it prints, is unmeasured. That window is a few milliseconds. An owed comment would still be named by the next prompt through its delivery pointer, but an update that owes nothing would be lost there. Pi accepts the same window.
- Whether Escape drops a Stop hook's context is unmeasured, so Stop keeps the deferred receipt.

### Merging with `pointer-handover`

The local branch `pointer-handover` ("Bound the pointer note's session lock by the hook's deadline") changes `receive_held` to return the batches it recorded and rewrites `carry_turn`'s `confirm=` lambda. This PR changes one argument inside that lambda, from `confirm=harness.commits_hook_context` to `confirm=event not in harness.drops_hook_context`. A merge keeps that branch's lambda and `receive_held` signature, with this argument substituted. Its docstring on `receive_held` should name `Harness.drops_hook_context` in place of `commits_hook_context`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…t once

A tool boundary's receipt was written before the hook printed its context. After
the print the interpreter still tore down: 24-41 ms on a loaded host here, and 41-158 ms
in an independent review's measurement. A hook stopped in that gap left an update
that reads received while Claude Code never read its context. An owed comment
survived only as the next prompt's pointer reminder, and an update that owes nothing
was lost.

`receive_held` now records only the opened pickup. `carry_turn` prints the context
and then confirms it with `confirm_turn`, which now takes the hook's deadline, for
an event outside `drops_hook_context`. A hook stopped before the receipt leaves the
handover to be offered again. `hooks.main` flushes and ends the process with
`os._exit(0)`, so the receipt now precedes the process exit by 5-8 ms, and the last
print precedes it by 7-11 ms. Both were measured over eight runs of `bin/leaf hook`
against a claimed page at a 1-minute load of about 30.

A new test stops the hook between its pickup and its receipt, and the resolve it
handed over is then offered again. The boundary test now also covers a resolve,
which is received with the comment. The import-guard test, which runs several hooks
in one interpreter, stubs `os._exit`. `drop()`'s journey docstring now says Escape
keeps a tool boundary's context. `leaf-dev journey claude-code` passed every step on
Claude Code 2.1.310.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@max-sixty

Copy link
Copy Markdown
Owner Author

Superseded by #3917 (merged), which fixes the same duplicate delivery after an interrupted tool boundary by reading receipt from Claude Code's transcript.

This was written by Claude Code on behalf of max-sixty

@max-sixty max-sixty closed this Oct 25, 2026
max-sixty added a commit that referenced this pull request Oct 27, 2026
…3884)

A hook on a claimed page imported `tinycss2` and `tree_sitter` (through
`revision_artifact`, `layer` and `styles`) and `watchfiles` (through
`file_changes`, reached by `presence` and `server`) without parsing CSS,
reading a script's imports or watching a file. Those are capture,
vendoring and watch work. Each import moves into the one function that
needs it; tree-sitter's parser and query are built once by
`_javascript_reader` on the first script read. No behavior changes.

The overnight note's headline does not hold: `jsonschema` (about 28 ms
warm) is not deferrable on this path. The claimed hook reads the page
and validates its stored events, and an instrumented run built three
schema validators, so the import is used. `jmespath` is likewise loaded
by registry validation (`registry/layer.py`) in the real hook, so it
stays.

Measured on a claimed scratch page with a PostToolBatch payload, warm
cache. Cumulative `leaf.hook_transport` from `python -X importtime -m
leaf hook --harness claude-code`: 102 ms before, 74-86 ms after. Wall
time of `.venv/bin/python -m leaf hook --harness claude-code` over 40
runs on a shared, noisy host: min 188 ms before, 156 ms after; medians
247 ms vs 199-229 ms. `import leaf.cli` and `import leaf.hooks` (the
no-page path, already guarded by
`test_a_hook_in_a_session_holding_no_page_imports_no_page_reading_or_server`)
are unchanged within noise.

Adds `test_a_claimed_hook_imports_no_css_script_or_watch_parser`,
holding `leaf.hook_transport`'s import free of the three.

Ran: tests/model/test_hook_registration.py, test_hooks.py,
tests/process/test_hook_gate.py, test_interact_layer.py,
test_native_watch.py, test_revision_delivery.py,
test_live_shell_artifact.py. Not run: the full suite or the claude-code
journey.

Only import placement changes, with no edits to `hooks.py` or
`bin/leaf`, so it merges with #3857 (`hooks.main` os._exit) and #3876
(launcher).

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
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