Skip to content

Do one tool call's PreToolUse work once, in its first hook run - #3876

Merged
max-sixty merged 9 commits into
mainfrom
grind/g-hook-cost
Oct 27, 2026
Merged

max-sixty merged 9 commits into
mainfrom
grind/g-hook-cost

Conversation

@max-sixty

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

Copy link
Copy Markdown
Owner

Claude Code runs Leaf's PreToolUse registration once for each if rule a Bash command matches, all at once (hooks/hooks.json has three rules). A command it cannot read, such as one with a $VAR, matches all three. Each run escaped the sandbox (bridge.ensure) and, in a session holding a page, confirmed receipts from the transcript, so the same work ran three times in parallel.

Now the first run for a tool_use_id records it (leases.first_hook_for_tool, under a lock on the session's sessions/<digest>.tools, which keeps the last 16 ids), and the other runs return after marking that hooks ran. Claude Code still starts every run, so each duplicate still pays for the launcher, the interpreter and hooks.py's imports.

This PR previously also carried a standard-library gate in the launcher that answered a quiet PostToolBatch without starting Leaf, and a launcher that ran uv sync and the environment's interpreter directly. Both are gone: the gate was a second copy of what delivery reads, and #4141 is the launcher change that landed instead. AGENTS.md and every other contract the PR had rewritten are back to main's wording.

Measurement

One tool call's PreToolUse runs, started as Claude Code starts them through each arm's bin/leaf, on a claimed, stamped scratch page under a throwaway state home, with a 1.4 MB transcript in the payload. The arms are interleaved and alternate which goes first, 25 calls per cell, at a load of 9–12 on 18 cores. Times are medians; CPU is user plus system time across all runs of the call.

Runs for the call main wall branch wall main CPU branch CPU
1 (a plain leaf … command) 156 ms 154 ms 140 ms 141 ms
3 (a command Claude Code cannot read) 203 ms 160 ms 434 ms 285 ms

A single run costs the same on both. When all three rules match, the call's hooks finish 43 ms sooner and spend 149 ms less CPU. Each duplicate drops from about 147 ms of CPU to about 72 ms.

How often all three match: in this branch's leaf-dev journey claude-code (Claude Code 2.1.310), 2 of the 15 tool calls that ran the hook ran it three times, and the rest once. An earlier journey on main showed 1 of 15, and one on this branch's first version 4 of 17. Of the 2,619 Bash calls running leaf in this Mac's Claude Code transcripts from the last two days, 25% contain a $. That figure is an estimate. It assumes every such command matches all three rules, and Leaf's own development sessions make up much of the sample.

Tests

  • tests/model/test_hooks.py::test_one_tool_calls_hooks_do_its_work_once: a repeated PreToolUse for one tool_use_id leaves the turn as it found it, and another call's hook opens it again. The test fails with the dedupe off.
  • Ran tests/model/test_hooks.py, test_hook_registration.py and test_session_lifecycle.py (93 passed), and pre-commit on the changed files.
  • leaf-dev journey claude-code passed every step.

Overlap with #4145 and #3884

Both have since landed, and this branch carries a merge of main with them; the hook, claims and session tests pass on it.

Not verified

  • Linux. The measurement and journey ran on macOS.
  • Codex and Pi register no PreToolUse hook, so they never reach this code, and their journeys were not run.

Part of #4084.

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

Leaf's hooks took 1.0-1.6 s of a small page change's reply, 120-620 ms each.
Three mechanisms cut that.

The launcher runs the synced environment's interpreter directly. `uv run`
spent about 70 ms on every hook and command even with nothing to sync. The
environment now keeps a mark of its last `uv sync --no-dev --inexact`, naming
the tree it was synced for, and a lock or project file changed since, a
missing interpreter, or a mark naming another tree (an install that copied a
checkout) has uv sync first.

A tool boundary with nothing new needs no Leaf. A PostToolBatch that hands
nothing over keeps what it read (`state.boundary_reading`: this install's
registry, the session's own files, its claims, and their pages' event logs and
registries), taken before it reads the plans, and the launcher's gate answers
the next boundary whose reading is the same (`state.boundary_quiet`). Any
change after the reading, read or not, makes the next one differ, so new
input, a handover to confirm, a turn or claim change and the agent's own
`leaf` writes all run the hook whole. `session-lifetime.md` now states the
rule this rests on: every fact a tool boundary decides on lives in a file the
reading covers. The hooks mark is created once rather than touched by every
hook, so it no longer changes the reading.

One tool call's PreToolUse does its work once. Claude Code runs the
registration once per `if` rule the command matches, in parallel, and a
command it cannot read, such as one with a `$VAR`, matches all three
(measured at 2.1.310: the baseline journey ran three at once for a
`cd ...; R=...; grep $R/...` command). The first run for a `tool_use_id`
records it (`leases.first_hook_for_tool`) and the rest return.

Before and after, each hook as Claude Code runs it, main's payload built as an
arm beside this tree, interleaved, 15 runs each, load about 27-33 on 18 cores
(`.tmp/hookcost/time_hooks.py`, median ms):

- claimed PostToolBatch with nothing new: 308 -> 55
- claimed PostToolBatch run whole: 332 -> 263
- PreToolUse: 139 -> 91; its duplicate for one call: 141 -> 66
- claimed UserPromptSubmit: 312 -> 269
- unclaimed PreToolUse: 142 -> 86; unclaimed gated hooks unchanged (~55)

In `leaf-dev journey claude-code` (one run each, different agent paths and
load), PostToolBatch's median went from 356 to 273 ms over 25 and 28 runs; a
boundary after the agent's own `leaf` write still runs whole, and the agent ran
one at almost every step. Whole hook time per journey went from 23.5 to 22.5 s
with 8 more PreToolUse runs.

A new `quiet` record joins the protocol baseline at the current protocol.
Tests now witness Leaf's start with a stand-in package on the module path
rather than a recording uv, since the launcher no longer runs uv when the
environment is synced.

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

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The new launcher sync test fails in all nine hook variants on Linux because its fake project omits a file the freshness check requires.

Comment thread tests/model/test_hook_registration.py Resolved
…ng covers

Review of the first commit found three gaps.

A caller's `UV_PROJECT_ENVIRONMENT` had `uv sync` build the environment
elsewhere, so the launcher's mark could not be written and its interpreter was
missing: every command and hook exited 127, where `uv run` had succeeded. The
sync now runs without the variable, so the install always owns `.venv`. The
launcher test sets it, with a stand-in uv that builds where uv would; with the
variable kept, the test fails.

`session-lifetime.md` said every fact a tool boundary decides on lives in a
file its reading covers, which was false: a boundary also reads revisions,
`stream.json` and `data/`, delivery envelopes, claim lifetimes, Claude Code's
record of the session and the install's code. The reference now lists each and
why it can't add input, and a test runs a boundary in a fresh interpreter under
an audit hook and fails on any file it opens that neither the reading nor that
list accounts for (checked by dropping the page registry from the reading).

The reading kept its own stat triple, without `file_stamp`'s guard for a
same-size rewrite inside one tick of Linux's coarse write clock. `file_stamp`
and its clock move from `files.py` to `state.py`, the dependency-free home the
launcher's gate can import, and every caller imports it from there.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Oct 25, 2026
The overnight page copied each agent's one-line calls ("#3876: the
launcher's contract", "#3854: depending on Codex's private database"),
written for a reader who knows the PR. The user couldn't decide them
without asking what each meant. A decision now says what the user sees
today, what the PR changes and what each option leads to.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Oct 25, 2026
The backlog is now GitHub issues labelled `backlog`. Every item under
Now, Next and Etc in `TODO.md` became one issue, so a pull request that
says `Closes #N` links itself to its item, and a session finds untaken
work with a query instead of reading a file that has no claim signal.
#4000 landed first, so none of the new issues started a triage run (all
82 `tend-triage` runs were skipped).

**Query.**

```bash
gh issue list --search "label:backlog label:now -label:waits-on-user -linked:pr"
```

then `label:next` and `label:etc`. `-linked:pr` leaves out issues a pull
request already links with a closing keyword.

**What moved where.**

- 82 issues from #4007 to #4089 (#4067 is another session's), one per
bullet. Each is labelled `backlog` and its priority: 13 `now`, 29
`next`, 40 `etc`. Now and Next items also carry a theme mapped from
their `###` heading: `ux` (User experience; User continuity and mobile
access), `agent-experience` (Agent and author experience; The agent's
text interface), `layout` (Layout; Layout stability; Queues),
`review-tools` (Before/after comparison; Recorded interaction review)
and `dev-velocity`. Etc's two headings, Product and harness ideas and
Implementation candidates, sort kinds rather than subjects, so those
items carry no theme.
- 14 items also carry `waits-on-user`, the "Waits on the user" marking
from #3891 (`todo-review`), and their bodies take that branch's wording,
including its rewrite of the held-news item as "Keep a held-news count
whole as it grows" (#3459 landed the "+N" route). `TODO.md` says what
the label means, and the query above leaves those items out.
- After the migration, #3891's author asked for three more edits from
the grind PRs that touch these items: #4039 is retitled "Decide whether
Pixels should soften redrawn-shadow fringes" (#3838), #4039 and #4048
(#3840) also carry `waits-on-user`, and #4098, "Keep a window preference
from cramping a dashboard into a workspace", is the item #3913 puts in
place of #4033.
- Each title is the bullet's bold outcome. For the bullets whose bold
text is a label ("Multiplayer:", "MCP Apps:"), the title adds the
bullet's first clause.
- Each body is the bullet's text with its hard wraps joined (GitHub
renders a single newline as a line break), relative links made absolute,
and `notes/` paths linked. A footer gives the bullet's `TODO.md`
permalink, its heading, its position within its priority, the old `TODO
#N` id for the six that had one, and the theme section's introduction
where there was one. #4014's mention of the reply-widgets item now links
#4089.
- `TODO.md` keeps "Biggest current challenges" unchanged. Its priority
explanation now says the items live in issues, what the labels mean, and
how to query them.
- `/developing-leaf` gains "Take a backlog item": pick an unclaimed
issue that isn't waiting on the user, and open the PR early with `Closes
#N`. It points at `TODO.md` for the query, so the rule and the query
each have one home.
- Every reference to a current `TODO.md` item now names its issue:
`AGENTS.md`'s repository map, `/developing-leaf`, the thread snapshot
skips, `journey.py`, `thread_snapshots.py`, `llm.py`, `test_tabs.py`,
the Worker, two eval comments and five notes.
- #3891's two note edits come along (`notes/browser-support.md`'s
recheck rule, `notes/user-feedback-responsiveness.md`'s retired tone
lever), since #3891 will drop its `TODO.md` changes.

**Order.** Each issue's footer records its old position ("item 6 of 13
in Now"). I didn't keep an ordered index in `TODO.md`: it would be a
second list of the backlog that every new issue has to be added to by
hand, and it would drift from the labels. The priority label is the
ordering that stays current.

**Duplicates.** None of the 15 open issues duplicated an item, so every
item is a new issue.

**Mapping.** The old-item-to-issue table, with open PRs whose titles
match an item, is below; the same table is at
`~/.tmp/leaf.agent-afd0a8c0d63089ed9/backlog-mapping.md`.

<details><summary>82 items</summary>

| Issue | Priority | Old position | Old id | Title | Possible PRs |
|---|---|---|---|---|---|
| [#4007](#4007) | now › User
experience | 1 (TODO.md line 43) | | Make complete reading journeys feel
coherent | #3860, #3865 |
| [#4008](#4008) | now › User
experience | 2 (TODO.md line 47) | | Keep the Thread hierarchy clear | |
| [#4009](#4009) | now › User
experience | 3 (TODO.md line 49) | | Keep a long Thread's current status
visible | |
| [#4010](#4010) | now › User
experience | 4 (TODO.md line 53) | | Test annotation placement in
context (waits-on-user) | |
| [#4011](#4011) | now › User
experience | 5 (TODO.md line 57) | | Make the next move and its result
apparent | #3879 |
| [#4012](#4012) | now › User
experience | 6 (TODO.md line 62) | TODO #28 | Finish the floating panel
(waits-on-user) | |
| [#4013](#4013) | now › User
experience | 7 (TODO.md line 69) | | Keep a held-news count whole as it
grows (waits-on-user) | |
| [#4014](#4014) | now › User
experience | 8 (TODO.md line 80) | | Stop moving live content between
parents | |
| [#4015](#4015) | now › Agent
and author experience | 9 (TODO.md line 94) | | Wake idle Codex desktop
chats without user messages | |
| [#4016](#4016) | now › Agent
and author experience | 10 (TODO.md line 99) | | Consider a reminder
when revising decided content (waits-on-user) | |
| [#4017](#4017) | now › Agent
and author experience | 11 (TODO.md line 104) | TODO #20 | Act on the
plain HTML comparison | |
| [#4018](#4018) | now › Agent
and author experience | 12 (TODO.md line 118) | | Keep delegated work in
the panel's status on Codex and Pi | #3854 |
| [#4019](#4019) | now › Agent
and author experience | 13 (TODO.md line 123) | TODO #24 | Measure time
to an initial reviewable page and the value of review | |
| [#4020](#4020) | next | 1
(TODO.md line 149) | | Add a host-owned widget LLM allowance
(waits-on-user) | |
| [#4021](#4021) | next › User
continuity and mobile access | 2 (TODO.md line 159) | | Bring back a
rewrite Escape discarded | #3862 |
| [#4022](#4022) | next › User
continuity and mobile access | 3 (TODO.md line 163) | | Decide when a
page merits a separate phone composition (waits-on-user) | |
| [#4023](#4023) | next › User
continuity and mobile access | 4 (TODO.md line 169) | | Improve
maintained examples through a phone-quality queue | #3869, #3899, #3902
|
| [#4024](#4024) | next › User
continuity and mobile access | 5 (TODO.md line 175) | | Decide whether
Back may restore a leaf.page page whole (waits-on-user) | |
| [#4025](#4025) | next › User
continuity and mobile access | 6 (TODO.md line 182) | | Consider
automatic Leaf recovery on resume | |
| [#4026](#4026) | next › User
continuity and mobile access | 7 (TODO.md line 185) | | Verify the
native phone reading journey | |
| [#4027](#4027) | next › User
continuity and mobile access | 8 (TODO.md line 189) | | Finish what a
phone user still cannot reach | #3856, #3868, #3874, #3875 |
| [#4028](#4028) | next › User
continuity and mobile access | 9 (TODO.md line 199) | | Reconsider
thread navigation (waits-on-user) | |
| [#4029](#4029) | next › Layout
| 10 (TODO.md line 224) | | Show returning threads without moving the
current reading | #3883 |
| [#4030](#4030) | next › Layout
| 11 (TODO.md line 229) | | Let a page restyle Leaf's chrome on purpose
(waits-on-user) | |
| [#4031](#4031) | next › Layout
| 12 (TODO.md line 235) | | Let a block be a workspace | |
| [#4032](#4032) | next › Layout
| 13 (TODO.md line 245) | | Show each floating surface across the
content it can hold | |
| [#4033](#4033) | next › Layout
| 14 (TODO.md line 275) | | Test the Layouts on agents | #3913 |
| [#4098](#4098) | next › Layout
| 14, added by #3913 in #4033's place | | Keep a window preference from
cramping a dashboard into a workspace | |
| [#4034](#4034) | next › Layout
| 15 (TODO.md line 285) | | Layout values that wait for a task:
list-detail on a phone, canvas regions, slides | |
| [#4035](#4035) | next › Layout
| 16 (TODO.md line 288) | | Decide whether a too-narrow table fails a
page at the fixed widths (waits-on-user) | |
| [#4036](#4036) | next › Layout
stability | 17 (TODO.md line 298) | | Keep what a live revision adds
above the reader from moving it | |
| [#4037](#4037) | next › Layout
stability | 18 (TODO.md line 304) | | Keep the merge film's controls
still as it steps | |
| [#4038](#4038) | next › Queues
| 19 (TODO.md line 314) | | Keep the open item's group named on a phone
| #3853 |
| [#4039](#4039) | next ›
Before/after comparison | 20 (TODO.md line 323) | TODO #29 | Decide
whether Pixels should soften redrawn-shadow fringes (waits-on-user; was
"Explain the faint amber halo in Pixels") | #3838 |
| [#4040](#4040) | next ›
Recorded interaction review | 21 (TODO.md line 333) | | Explore DOM
selection in the imported timeline | |
| [#4041](#4041) | next › The
agent's text interface | 22 (TODO.md line 343) | | Decide the Leaf-owned
defects the bad-pages eval left open (waits-on-user) | |
| [#4042](#4042) | next › The
agent's text interface | 23 (TODO.md line 350) | | Read the full render
gate after handover | #3888 |
| [#4043](#4043) | next › The
agent's text interface | 24 (TODO.md line 366) | | Consider loading a
page once per render check (waits-on-user) | |
| [#4044](#4044) | next › The
agent's text interface | 25 (TODO.md line 372) | | Derive the waiting
status from the page's open obligation | |
| [#4045](#4045) | next ›
Development velocity | 26 (TODO.md line 380) | | Require `test` on
`main` again (waits-on-user) | |
| [#4046](#4046) | next ›
Development velocity | 27 (TODO.md line 386) | | Resume the thread
appearance gate (waits-on-user) | |
| [#4047](#4047) | next ›
Development velocity | 28 (TODO.md line 394) | | Guard thread appearance
on CI again | #3896 |
| [#4048](#4048) | next ›
Development velocity | 29 (TODO.md line 404) | | Keep the agent
journey's samples (waits-on-user) | #3840 |
| [#4049](#4049) | etc › Product
and harness ideas | 1 (TODO.md line 420) | | Consider Redo and a Changes
panel | |
| [#4050](#4050) | etc › Product
and harness ideas | 2 (TODO.md line 433) | | Link filenames to their
repository context | |
| [#4051](#4051) | etc › Product
and harness ideas | 3 (TODO.md line 438) | | Revisit the Claude desktop
app opening a page's file over the live page | |
| [#4052](#4052) | etc › Product
and harness ideas | 4 (TODO.md line 448) | | Decide the site's structure
before release | |
| [#4053](#4053) | etc › Product
and harness ideas | 5 (TODO.md line 451) | | Assess whether automatic
measurement freshness is useful | |
| [#4054](#4054) | etc › Product
and harness ideas | 6 (TODO.md line 457) | | Revisit where an abandoned
comment's words come back | |
| [#4055](#4055) | etc › Product
and harness ideas | 7 (TODO.md line 462) | | Revisit a pin's icons if
they read unclearly | |
| [#4056](#4056) | etc › Product
and harness ideas | 8 (TODO.md line 466) | | Revisit the reaction
tokens' meanings or glyphs if they confuse | |
| [#4057](#4057) | etc › Product
and harness ideas | 9 (TODO.md line 471) | TODO #30 | Try a feed of
ready-to-approve actions | |
| [#4058](#4058) | etc › Product
and harness ideas | 10 (TODO.md line 477) | | Explore independent jobs |
|
| [#4059](#4059) | etc › Product
and harness ideas | 11 (TODO.md line 480) | | Tell the agent when to ask
before ending its own to-do | |
| [#4060](#4060) | etc › Product
and harness ideas | 12 (TODO.md line 485) | | Let the user edit items in
the On view | |
| [#4061](#4061) | etc › Product
and harness ideas | 13 (TODO.md line 489) | | Multiplayer: let several
users share a page, each recorded as themselves | |
| [#4062](#4062) | etc › Product
and harness ideas | 14 (TODO.md line 495) | | Show which pane has focus,
and move between panes by key | |
| [#4063](#4063) | etc › Product
and harness ideas | 15 (TODO.md line 508) | | Expand everything waiting
with a keypress | |
| [#4064](#4064) | etc › Product
and harness ideas | 16 (TODO.md line 514) | | Let a user add, remove and
edit table rows | |
| [#4065](#4065) | etc › Product
and harness ideas | 17 (TODO.md line 519) | TODO #16 | Named widget
interfaces: let a typed reference name the interface its target
implements | |
| [#4066](#4066) | etc › Product
and harness ideas | 18 (TODO.md line 523) | | Visual review beside Leaf:
coordinate a real browser target through the harness | |
| [#4068](#4068) | etc › Product
and harness ideas | 19 (TODO.md line 526) | | Other harnesses: add a
blocking `leaf wait` route when another harness needs it | |
| [#4069](#4069) | etc › Product
and harness ideas | 20 (TODO.md line 528) | | Consider Leaf running the
agent session | |
| [#4070](#4070) | etc › Product
and harness ideas | 21 (TODO.md line 533) | | Decide whether an exported
page carries its threads | |
| [#4071](#4071) | etc › Product
and harness ideas | 22 (TODO.md line 540) | | Character bindings: let
users disable them | |
| [#4072](#4072) | etc › Product
and harness ideas | 23 (TODO.md line 541) | | Replacement diffs and
visual masks for repeated reviews | |
| [#4073](#4073) | etc › Product
and harness ideas | 24 (TODO.md line 543) | | Motion evidence: define
video, caption and transcript handling | |
| [#4074](#4074) | etc › Product
and harness ideas | 25 (TODO.md line 545) | | Revisit long-thread
folding after using summaries | |
| [#4075](#4075) | etc ›
Implementation candidates | 26 (TODO.md line 551) | | Remove the
early-key hold once startup is fast on slower machines too | |
| [#4076](#4076) | etc ›
Implementation candidates | 27 (TODO.md line 578) | | Draw the margin's
annotations once per thread pass | #3864 |
| [#4077](#4077) | etc ›
Implementation candidates | 28 (TODO.md line 587) | | Read moves exactly
where the before/after pair is a browser's capture | |
| [#4078](#4078) | etc ›
Implementation candidates | 29 (TODO.md line 597) | | Reduce
plugin-update downloads by cleaning Git history | |
| [#4079](#4079) | etc ›
Implementation candidates | 30 (TODO.md line 605) | | Set
interaction-trace privacy before sharing pages | |
| [#4080](#4080) | etc ›
Implementation candidates | 31 (TODO.md line 610) | | Make a leaf.page
dispatch survive its container | |
| [#4081](#4081) | etc ›
Implementation candidates | 32 (TODO.md line 616) | | Start each
release's containers on its own image | |
| [#4082](#4082) | etc ›
Implementation candidates | 33 (TODO.md line 629) | | Push page updates
instead of polling | |
| [#4083](#4083) | etc ›
Implementation candidates | 34 (TODO.md line 670) | | Claude Code tool
observation: a cheap hook for sessions holding pages | |
| [#4084](#4084) | etc ›
Implementation candidates | 35 (TODO.md line 672) | | Measure Leaf's
hook cost for sessions holding pages | #3876 |
| [#4085](#4085) | etc ›
Implementation candidates | 36 (TODO.md line 677) | | Invoker commands:
test `command` and `commandfor` once Leaf's Chromium floor allows | |
| [#4086](#4086) | etc ›
Implementation candidates | 37 (TODO.md line 681) | | MCP Apps: rebuild
inline hosting as a direct resource | |
| [#4087](#4087) | etc ›
Implementation candidates | 38 (TODO.md line 692) | | Release labels:
prefer an exact tag when Leaf adopts named releases | |
| [#4088](#4088) | etc ›
Implementation candidates | 39 (TODO.md line 693) | | Diff controls:
author-configurable wrapping and per-file review tracking | |
| [#4089](#4089) | etc ›
Implementation candidates | 40 (TODO.md line 695) | | Show a reply's
widgets in every view of it | |

</details>

**Not migrated cleanly.**

- Each section introduction (Layout, Layout stability, Queues, Recorded
interaction review) is copied into every issue of its section, since a
label can't carry it.
- Eval fixtures that quote a past session mentioning `TODO.md`
(`assessment-surfaces-pending-decisions`,
`record-asks-hold-their-premise`, `options-*`) are recorded inputs and
stay as they were. Two eval provenance comments and one line of
`notes/agent-usability-evals.md` name items that left `TODO.md` before
this change, so they have no issue to point at.
- The fold-button entry #3891 corrected is in neither `TODO.md`, and
#3928 fixed it, so it has no issue.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty and others added 2 commits October 25, 2026 12:08
Takes main's TODO.md, whose backlog moved to GitHub issues in #4090.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A prompt the user types while a turn runs gets its prompt hook at once, under
the running turn's `prompt_id`, and Leaf hands that turn the pending comment
inline. Claude Code writes that hook's context to the transcript only when the
turn takes the prompt in, after the turn's next tool boundary has run. So that
boundary cannot confirm the receipt. It hands nothing over and kept its
reading, and the launcher then answered every later boundary without starting
Leaf, because the transcript is not part of the reading. The receipt waited for
the next `leaf` command, Stop or prompt. Until then the page counted the
comment as pending, and an Escape in that window would end the turn with the
comment unreceived, which the prompt's watch reads as input to wake the session
for, though the model had read it.

A boundary now keeps its reading only when no page holds a handover awaiting
its receipt (`delivery.awaiting_receipt`, carried in `PagePlan.awaiting`). The
boundary after the transcript records the handover runs whole and confirms it.
`session-lifetime.md` ("The hook") and the `hook_transport` header now name the
transcript among the facts a boundary reads, and say why it holds back the
reading.

Evidence, on Claude Code 2.1.310:

- An interactive session in tmux with a probe hook that logs which earlier
  hook contexts the transcript holds when each hook runs: the second prompt's
  hook ran at 934.2 s, the PostToolBatch at 939.3 s did not yet see its
  context, and the PreToolUse at 940.7 s did. Headless `-p`, and
  `--input-format stream-json`, which runs a queued prompt's hook at the
  boundary instead, showed no such gap.
- Three of 758 hook context records in recent transcripts were written after
  the next model response, each one for a queued command.
- Every one of 47 Leaf inline handovers in those transcripts since #3917 was
  received at the first Leaf hook after it, so outside a queued prompt the
  transcript holds a handover by the next boundary.

`test_a_handover_the_transcript_records_late_is_received_at_the_next_boundary`
replays that order through the launcher's gate. It fails without the change, at
the receipt after the transcript records the handover.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty and others added 2 commits October 25, 2026 20:08
…ate and its own sync

The user chose to keep hook logic in the Leaf package. The quiet-boundary gate
was a second, standard-library copy of what delivery reads, kept equal to it by
a test; the launcher's `uv sync` shell gives way to #4141's launcher. Both
leave with their tests and the contract prose that described them, which
returns to main's. What stays is `leases.first_hook_for_tool`: of Claude
Code's parallel PreToolUse runs for one tool call, only the first does work.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@max-sixty max-sixty changed the title Cut what Leaf's hooks cost at each Claude Code tool boundary Do one tool call's PreToolUse work once, in its first hook run Oct 26, 2026
#4145 deletes leases.session_state_path, so a merge with it would leave
first_hook_for_tool calling a missing name. The hook's mark_hooks creates the
sessions directory before the dedupe asks, so session_file works on main too.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Oct 27, 2026
…ck (#4141)

`bin/leaf` no longer passes `--no-cache` to `uv run`. On main it passed
it wherever `.venv` existed, which cost every command and every hook in
a session holding a page tens of ms. Inside Codex's sandbox the launcher
now points uv's cache at `$TMPDIR/leaf-uv-cache`, so calls there get a
cache too. The change also drops the absolute-path check on
`LEAF_HOST_LAUNCHER`.

**Does the launcher need `uv sync`?** No. `uv run` locks and syncs the
project environment before running whenever the lock or project has
changed. On a scratch copy of this tree, adding a dependency to
`pyproject.toml` and relocking installed it on the next `bin/leaf
--root`, with main's launcher unchanged. A launcher-side `uv sync` (as
in #3876) is needed only to bypass `uv run` and exec `.venv/bin/python`
directly. With the cache, that bypass saves about 16 ms a call.

**Why the cache matters.** Without its cache, uv spawns the
environment's interpreter on every call to query it (`uv run -vv` logs
`Querying interpreter executable` only with the flag). Overhead over the
bare interpreter, 60 interleaved runs, load ~33 on 18 cores:

| | wall median | CPU median |
| --- | --: | --: |
| `.venv/bin/python -c pass` | 12.7 ms | 11.1 ms |
| `uv run` with cache | 29.1 ms | 24.8 ms |
| `uv run --no-cache` (main) | 53.5 ms | 48.0 ms |

End to end, `bin/leaf --root` went from 95.0 ± 5.6 ms on main to 71.5 ±
5.0 ms (hyperfine, 40 runs each). An independent run at load ~60
measured ~40 ms wall and 33 ms CPU per call, so the saving grows with
load.

**Codex's sandbox.** uv opens its cache even when there's nothing to
sync, and Codex's workspace-write sandbox writes only to the workspace,
`/tmp` and `$TMPDIR`, so it refuses `~/.cache/uv`. A `leaf` command run
directly there needs a cache uv can write. That covers `leaf --root`,
which `/developing-leaf` has agents run first, and a command whose
refusal names the MCP tool. The launcher sets
`UV_CACHE_DIR="${TMPDIR:-/tmp}/leaf-uv-cache"` when `CODEX_SANDBOX` or
`CODEX_SANDBOX_NETWORK_DISABLED` is set. These are Codex's markers for
its sandbox and the variables `machine.SANDBOX_REMEDIES` reads. Codex's
hooks and Leaf's MCP server run outside the sandbox and see neither.
Under `codex sandbox -c 'sandbox_mode="workspace-write"'`:

- `--root` prints the root.
- `page list` lists pages.
- `server start PAGE` exits 1 with the remedy naming the `run` tool, as
on main.
- The cache under `$TMPDIR` holds 12 KB.

**What else stays, measured:**

- The `--if-claimed` gate: an unclaimed hook takes 45 ms gated against
206 ms run whole through uv. Codex runs it after every tool call, and
Claude Code before every prompt and Stop, in sessions holding no page.
- The SessionEnd shortcut: it must release claims within the harness's
shutdown deadline, even before the install has an environment.
- The `SANDBOX_RUNTIME` bridge: it is Claude Code's sandbox route, and
it never reaches uv.
- `LEAF_HOST_LAUNCHER` redirection: the website container sets it
(`worker/leaf_website/__init__.py`) so Codex's native hooks run its
prepared environment. The suite's installation fixture and
`codex_tool.py`'s forwarded variables use it too. Only its absolute-path
validation goes, since every setter is Leaf code and passes an absolute
path.

The header now names the gate by its entry, `state.py hook-gate`, rather
than by `state.holds_claims`, which #4145 renames.

### Tests

- `test_a_codex_sandbox_refusal_names_the_tool` now also denies writes
to uv's cache (`uv cache dir`), as Codex's sandbox does. It passes. With
the sandbox line removed it fails with uv's lock error (exit 2).
- `tests/model/test_interact_layer.py` (the dispatch shape outside a
sandbox has no cache flag, and the relative-path refusal goes),
`tests/process/test_codex_tool.py`, `test_hook_gate.py`,
`test_bridge.py`, `tests/model/test_hook_registration.py`: 228 passed.
`tests/model/test_claims.py` and the installed-payload journey test
passed on the first commit, and the later commits don't touch what they
cover.
- No `leaf-dev journey` runs: hook dispatch is unchanged, and only uv's
cache location differs.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@max-sixty
max-sixty marked this pull request as ready for review October 27, 2026 05:41
max-sixty added a commit that referenced this pull request Oct 27, 2026
Click now parses and dispatches `leaf hook` and `leaf session-end` like
every other command, so the hand-rolled harness-entry parser in
`__main__.py` is gone. Options take any order and `=` forms (`leaf hook
--watch --harness=codex`), and help and usage errors come from the same
parser as the rest of the CLI.

Loading Click costs each managed hook about 8 ms of CPU. Main avoided
Click on that path on purpose; this accepts the cost so one parser owns
every command, and `__main__.py`'s docstring says so. The launcher's
`--if-claimed` gate and cold SessionEnd cleanup still run `state.py`
under `python -S` without Click or uv, so a session holding no page
doesn't pay it.

Command diagnostics take the command name from the path Click resolved,
replacing a second scan of `sys.argv`. The same cleanup removes several
single-use wrappers: `state.holds_claims` (callers use `held_claims`),
the session-path helpers in `leases.py` (storage is `state.session_file`
/ `sessions_home`), `cmd_hook`'s SessionEnd branch (every registration
calls `session-end`), and `hook_transport.render`'s callbacks (its one
caller, `carry_turn`, now runs the inline-or-pointer sequence itself).

## Bridge kept on its switch

The bridge client (`python -m leaf.bridge run|serve`) stays on main's
four-line `sys.argv` switch. It runs on every sandboxed `leaf` command,
and both its callers are Leaf's own (`bin/leaf` and the bridge's `serve`
spawn). A Click version made importing it cost 31.7 → 39.8 ms of CPU and
consumed a `--` meant for Leaf: `run --root -- x` reached Leaf as
`['--root', 'x']`. `tests/process/test_bridge.py` now holds it to
forwarding `--help`, `--version` and `--root -- x` verbatim.

## Behavior change

`leaf session-end x` (or any other malformed harness entry) now prints
the CLI's JSON usage error and exits 2, where it printed plain text and
exited 1. No harness reaches it: Claude Code's and Codex's SessionEnd
registrations and Pi's extension all run `bin/leaf session-end` with no
further arguments, which the launcher sends to the stdlib cold path, and
the two registrations end `|| exit 1`, so any failure status reads the
same to the harness. Only a hand-typed call sees the difference, and
exit 2 matches every other Leaf usage error.

## Validation

- An independent review ran the real journeys on this branch:
`claude-code`, `claude-code --sandbox`, `codex-app-server`,
`codex-queue` and `pi` passed every step.
- Focused tests after the review's fixes: `tests/process/test_bridge.py`
(10, including the verbatim-forwarding test, which fails against the
Click bridge); hook registration, hooks, session lifecycle, interaction
log, claims, concurrent claims and Codex adapter (218); CLI, usage, hook
and refusal selections of `test_interact_layer.py`,
`test_product_page.py` and `test_server_lifetime.py` (97). `pre-commit
run` on the changed files passes, vulture included.

## Overlap

#3876 (one tool call's PreToolUse work done once) touches `hooks.py`,
`leases.py` and `state.py` too. It no longer calls `state.holds_claims`,
and a local merge of main, #4141, #3876 and this branch passes the hook,
claims, session and CLI tests, so the two land in either order. #4141
has landed, and `bin/leaf`'s header now names the gate `state.py
hook-gate`.

Codex wrote the first commit; Claude Code applied the review's fixes and
wrote this description.

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

---------

Co-authored-by: Codex <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@max-sixty
max-sixty merged commit 6ac1a66 into main Oct 27, 2026
2 of 3 checks passed
@max-sixty
max-sixty deleted the grind/g-hook-cost branch October 27, 2026 06:21
max-sixty added a commit that referenced this pull request Oct 27, 2026
…ir reviews pass (#4511)

Renames `/grinding-backlog` to `/fan-out-backlog` and revises it with
what the first campaign's later stages showed: its drafts going stale
while they waited, the user's reversals, and Tend's review findings.

- **When to run one.** The maintainer isn't sure a backlog campaign
beats doing work as it comes up, and prefers that by default. So the
skill says to run one only when there are many spare tokens, not on a
schedule or from Tend.
- **Land as you go.** Once a PR's review and the reviews of its fixes
pass, the campaign marks it ready, and Tend reviews and lands it under
`running-tend`'s **Landing**. In the first campaign, drafts held for the
user waited 50 hours at the median while main took 297 commits. Other
sessions fixed 6 of the 47 first, and the user then landed the rest with
one choice.
- **Additions wait for the user.** A PR stays a draft, with its decision
on the user's page, when it leaves the user a call or adds something
beyond the repair and its test: a new mechanism, gate, public option,
dependency or protocol bump. The author's report lists these under a new
`adds` field, and the reviewer checks the list. Each PR the user
rejected or cut was an addition of this kind (#3876, #3896, #3854,
#3962).
- **Review weighs additions and every fix.** Reviewers weigh what a
change adds (`/developing-leaf`, "Weigh what a change adds") and review
every fix again. One unreviewed fix in the first campaign moved #3904's
check into the build and broke the eval comparison arms, until #4486
moved it back.
- **Counts come from GitHub**, since an orchestrating session that
compacts several times loses its counts. Ready PRs go a few at a time,
since six parallel landing agents once used up Tend's GitHub API quota.

> _This was written by Claude Code on behalf of max-sixty_
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.

2 participants