Repository navigation
Run uv with a cache everywhere, and drop the launcher's host-path check - #4141
Merged
Merged
Conversation
`bin/leaf` passed `--no-cache` to `uv run` once `.venv` existed, so that a `leaf` command run directly inside Codex's sandbox, which refuses writes to ~/.cache/uv, could start Python and print the sandbox remedy. Without its cache uv spawns the environment's interpreter to query it on every call (`uv run -vv` logs "Querying interpreter executable" only with the flag), which measured ~41 ms of overhead over the bare interpreter against ~16 ms with the cache (60 interleaved runs, load ~33 on 18 cores); `bin/leaf --root` went from 95 to 72 ms. Codex's sandboxed agent now runs `leaf` through the plugin's MCP server (#3331), outside the sandbox, so the flag paid ~25 ms on every command and claimed-session hook for a path the shipped instructions route around. Behavior change: a `leaf` command a Codex agent runs directly in its workspace-write sandbox now fails in uv ("Could not acquire lock ... ~/.cache/uv") instead of reaching Leaf's remedy naming the MCP tool. `uv run` already syncs the environment when the lock or project changes: on a scratch copy of the tree, adding a dependency and relocking installed it on the next `bin/leaf` call. So the launcher needs no sync step of its own. The absolute-path check on LEAF_HOST_LAUNCHER goes too: only Leaf sets the variable (the website container, the suite's installation fixture), always to an absolute path. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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]>
Codex's workspace-write sandbox writes only to the workspace and the temporary directories, so ~/.cache/uv is refused but $TMPDIR is not. Inside that sandbox the launcher now points UV_CACHE_DIR at $TMPDIR/leaf-uv-cache instead of passing `--no-cache`, so direct calls there keep uv's interpreter cache too, and the launcher loses its `cache` variable. Verified under `codex sandbox -c 'sandbox_mode="workspace-write"'`: `--root` and `page list` succeed, `server start` exits 1 naming the MCP tool, and the cache holds 12 KB. The sandbox refusal test, which denies ~/.cache/uv, fails with uv's lock error (exit 2) once the line is removed. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty
added a commit
that referenced
this pull request
Oct 26, 2026
…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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
max-sixty
marked this pull request as ready for review
October 27, 2026 05:19
leaf-agent
approved these changes
Oct 27, 2026
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]>
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
bin/leafno longer passes--no-cachetouv run. On main it passed it wherever.venvexisted, 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 onLEAF_HOST_LAUNCHER.Does the launcher need
uv sync? No.uv runlocks and syncs the project environment before running whenever the lock or project has changed. On a scratch copy of this tree, adding a dependency topyproject.tomland relocking installed it on the nextbin/leaf --root, with main's launcher unchanged. A launcher-sideuv sync(as in #3876) is needed only to bypassuv runand exec.venv/bin/pythondirectly. 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 -vvlogsQuerying interpreter executableonly with the flag). Overhead over the bare interpreter, 60 interleaved runs, load ~33 on 18 cores:.venv/bin/python -c passuv runwith cacheuv run --no-cache(main)End to end,
bin/leaf --rootwent 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,
/tmpand$TMPDIR, so it refuses~/.cache/uv. Aleafcommand run directly there needs a cache uv can write. That coversleaf --root, which/developing-leafhas agents run first, and a command whose refusal names the MCP tool. The launcher setsUV_CACHE_DIR="${TMPDIR:-/tmp}/leaf-uv-cache"whenCODEX_SANDBOXorCODEX_SANDBOX_NETWORK_DISABLEDis set. These are Codex's markers for its sandbox and the variablesmachine.SANDBOX_REMEDIESreads. Codex's hooks and Leaf's MCP server run outside the sandbox and see neither. Undercodex sandbox -c 'sandbox_mode="workspace-write"':--rootprints the root.page listlists pages.server start PAGEexits 1 with the remedy naming theruntool, as on main.$TMPDIRholds 12 KB.What else stays, measured:
--if-claimedgate: 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.SANDBOX_RUNTIMEbridge: it is Claude Code's sandbox route, and it never reaches uv.LEAF_HOST_LAUNCHERredirection: the website container sets it (worker/leaf_website/__init__.py) so Codex's native hooks run its prepared environment. The suite's installation fixture andcodex_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 bystate.holds_claims, which #4145 renames.Tests
test_a_codex_sandbox_refusal_names_the_toolnow 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.pyand the installed-payload journey test passed on the first commit, and the later commits don't touch what they cover.leaf-dev journeyruns: hook dispatch is unchanged, and only uv's cache location differs.