Skip to content

Simplify hook and CLI entry through Click - #4145

Merged
max-sixty merged 5 commits into
mainfrom
simplify-hook-path
Oct 27, 2026
Merged

max-sixty merged 5 commits into
mainfrom
simplify-hook-path

Conversation

@max-sixty

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

Copy link
Copy Markdown
Owner

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

Let Click parse hook, session-end, and bridge commands and supply the resolved
command name for diagnostics. Hook options now use normal Click ordering, help,
and JSON usage errors; registrations retain their nonblocking exit behavior.

Keep the stdlib-only cold cleanup and unclaimed-hook gate: cold cleanup works
without uv and the gate avoids the measured managed-startup cost. Consolidate
session paths in state, use the canonical held-claim reading, remove the unused
hook cleanup route, and inline the sole delivery renderer without changing
receipt/deadline ordering. Update every in-tree caller and behavior test.

Focused lifecycle, transport, CLI, registration and sandbox-bridge checks pass.
Real Claude sandbox setup/reply passed, but process inspection prevents its
remaining journey; real Codex App Server startup is denied in this sandbox.

Co-Authored-By: Codex <[email protected]>
max-sixty added a commit that referenced this pull request Oct 25, 2026
Dropping `--no-cache` outright broke every direct `leaf` call in Codex's
workspace-write sandbox, `leaf --root` included, which works on main. The
launcher now passes it where Codex marks its sandbox (CODEX_SANDBOX,
CODEX_SANDBOX_NETWORK_DISABLED, the variables `machine.SANDBOX_REMEDIES`
reads) instead of wherever `.venv` exists, so the sandbox keeps main's
behavior and every other call keeps uv's cache.

The Codex sandbox refusal test now also denies writes to uv's cache, as the
real sandbox does; with the condition removed it fails with uv's lock error
(exit 2). The header names the gate's entry, `state.py hook-gate`, rather
than a function #4145 renames.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty and others added 3 commits October 25, 2026 15:06
The bridge client runs on every sandboxed `leaf` command, and its two callers
are Leaf's own (`bin/leaf` and the bridge's `serve` spawn), so it goes back to
main's `sys.argv` switch: Click there cost about 8 ms of import on each command
and consumed a `--` meant for Leaf (`run --root -- x` reached it as
`['--root', 'x']`). A test now holds the client to forwarding its arguments
verbatim.

`__main__.py` states the cost of Click on the hook path and why it's accepted.
Vulture ignores Click's `group_class` hook. References to the removed
`hook_transport.render`, SessionEnd's registration and the hook gate's measured
saving are corrected.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request 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
max-sixty marked this pull request as ready for review October 27, 2026 05:41
@max-sixty
max-sixty merged commit d8575e1 into main Oct 27, 2026
5 checks passed
@max-sixty
max-sixty deleted the simplify-hook-path branch October 27, 2026 06:08
max-sixty added a commit that referenced this pull request Oct 27, 2026
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.

- #4145 (`simplify-hook-path`) merges with this branch in either order,
with no conflict, and the dedupe test passes on a local merge of the
two. #4145 deletes `leases.session_state_path`, so `first_hook_for_tool`
names its file through `state.session_file`, which both keep. On `main`,
`session_file` does not create the `sessions/` directory, but the hook's
`mark_hooks` creates it before the dedupe runs; on #4145, `session_file`
creates it. #4145's rename of `holds_claims` to `held_claims` touches
lines this PR leaves alone.
- #3884 (`grind/g-lazy-imports`) shares no files with this PR and merges
cleanly. Its deferred imports make each whole hook run cheaper; this PR
removes the duplicate runs' work, so the two savings add.

### 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_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[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.

2 participants