Repository navigation
Hold each short-lived Leaf process to the dependencies it may load, and keep the caller's directory off its module path - #5304
Merged
Merged
Conversation
…t uv Claude Code's prompt, tool-batch and Stop hooks, its pages follower and fork steps, and Codex's tool hook are registered `--if-claimed`. In a session holding a page, `bin/leaf` used to ask the standard-library gate in `state.py` and then start `uv run python -m leaf`: uv's project check and a second interpreter, about 40 ms of every such hook. The gate now runs the whole hook in its own interpreter (`state.answer_gated_hook`), loading site packages only once it finds a claim. `-P` keeps `src/leaf` off the module path, where `leaf/http` would shadow the standard library's `http`. ### Why a gated hook needs no sync Claude Code installs each plugin version into a directory of its own, and uv builds that directory's environment from that directory's lock, so the two can't drift. A tree updated in place can lag a changed lock: a checkout loaded with `--plugin-dir` or selected by a claim, or Codex's `local` plugin copy. Runtime dependencies changed in 24 commits since 8 September. Such a tree's ungated hooks and commands still run uv: every `leaf` command and the PreToolUse hook Claude Code runs before it, and Codex's prompt and Stop hooks. A gated hook that runs before the next of those and imports a dependency the environment lacks fails with an ImportError the harness shows; the next ungated run repairs the environment. That leaves a `--plugin-dir` session exposed after a pull until its agent next runs `leaf`, which a session holding a page does often. Behavior that changes: a `.venv/bin/python` that exists but can't start now fails a gated hook instead of sending it through uv. A missing or dangling one still sends it through uv. ### Handing a hook on Every hook of a session whose loaded plugin copy is older than the one installed since, or whose page a checkout claimed, hands itself to that launcher (`hooks.main`). A hook handed to another installed copy keeps `--if-claimed`, so it skips uv at both ends. One handed to a checkout drops it and syncs there: an agent updates its worktree mid-session, and an environment from before the watchfiles-to-watchdog change fails every follower and watch with `ModuleNotFoundError: watchdog` (reproduced by the Codex review of this change). ### Signals uv turned a SIGTERM into exit 143, which Leaf's Claude Code hooks module reads as the pages follower ending from outside rather than a failure to show the user. Without uv the follower would die by the signal, so it now unwinds and exits 128 plus the signal, as the watch does (`leases.release_on_termination`). Its `finally` now runs on that ending, releasing its fork lane and nudging any held thread it listed, and it checks for a raise a finalizer discarded before each wait. ### Evidence Each hook as a whole `bin/leaf` process on a copy of a real 71-event page claimed in a throwaway state home, the base launcher and gate (`cfc2385d2`) and this one interleaved in random order, each run from the same restored snapshot. Medians of 9 runs per arm, two runs at load 7. | | Base | This change | | --- | --- | --- | | UserPromptSubmit | 162–166 ms | 126–127 ms | | PostToolBatch | 163–169 ms | 121–126 ms | | Stop | 164–168 ms | 127–128 ms | | Clerk's fork step | 187–188 ms | 148–151 ms | | Up to handing the hook to another launcher | 83–84 ms | 45–46 ms | | Worker tool batch | 33 ms | 30 ms | | Session holding no claim | 33–34 ms | 30 ms | Every scenario printed the same output in both arms. ### Tests - `test_a_claimed_session_runs_its_gated_hooks_without_uv` runs the real launcher with a uv on the path that fails, and reads which hooks imported `leaf.hooks`; on the base, a claimed session's batch reaches uv. - `test_codex_tool_hook_runs_leaf_only_for_a_session_that_claimed_a_page` replaces the package with a stand-in that records the hook the gate's interpreter runs, and drops the broken-interpreter case. - `test_a_terminated_pages_follower_exits_with_its_signal` fails with -15 when the follower installs no handler. - The handoff test runs a gated hook and expects `--if-claimed` to cross to an installed copy and not to a checkout. - `leaf-dev journey claude-code`, whose session loads the plugin from this tree, passed every step.
Four tests each kept a hand-written list of modules a hook must not import, so a dependency nobody listed, or one loaded through a new path, crept onto the hook path unseen, as schema validation on every page read did until the last change. Each kind of short-lived process now has an allowlist of the runtime dependencies (`[project.dependencies]`) it may load, in `interact_support`: - `EVERY_TURN_DEPENDENCIES` (click): a hook in a session holding no page, `import leaf.hook_transport`, and a Codex tool hook with nothing to offer. - `READING_DEPENDENCIES` adds the markup, URL and Markdown parsers and psutil: a Stop hook reading the page its session holds. - `ADMITTING_DEPENDENCIES` adds jsonschema, referencing and regress: a prompt hook delivering a comment, and `thread reply`, which match handling clauses and admit events. A test runs the process in a fresh interpreter (`fresh_imports`) and fails on any runtime dependency outside its list, naming the chain of Leaf lines that first imported it. Matching dependency names rather than counting modules keeps the tests still under refactors and Python upgrades, and catches a library loaded because code used it, not only a moved import. The runtime dependencies come from the installed package's metadata, so the tests keep no copy of `pyproject.toml`'s list. The no-page test keeps its list of Leaf's own modules that page reading and serving would pull in, since the allowlists cover dependencies only. The prompt and reply cases are new; the Stop case replaces `test_a_hook_reading_a_page_it_holds_loads_no_schema_validator`. Planting `import jsonschema` at the top of `hook_transport` fails the transport and Stop cases; validation back on reads fails the Stop, prompt and reply cases, naming `leaf/layer.py -> leaf/validation/composition.py -> leaf/registry/validation.py`.
A gated hook ran in the gate's interpreter only in its own install, and a hook handed to a checkout the session selected went through `uv run` there, since an agent updates a checkout mid-session and its environment can then lack a dependency the new code imports. The gate now checks that itself (`state.answer_gated_hook`): `.venv/leaf-synced` records the modification time and size of `uv.lock` and `pyproject.toml` as of the last time uv synced the environment for a gated hook. Where they match, the hook runs in the gate's interpreter, at the cost of two stats. Where either differs, the gate hands itself to `uv run`, which syncs the environment and starts the gate again on whatever interpreter it leaves, passing the files' fingerprint from before the sync (`synced`). That run records the fingerprint only if the files still match it, so an update landing during the sync makes the next hook sync again rather than certifying files uv never saw, and then runs the hook. So every gated hook runs in one interpreter wherever it runs, a hook handed to any launcher keeps `--if-claimed`, and a `--plugin-dir` checkout or Codex's plugin copy no longer waits for a `leaf` command to repair its environment after a pull. On a miss the process the harness started becomes uv, as before this branch: uv syncs, may replace the interpreter when `requires-python` changes, takes the harness's signals and reports a failed sync with its own status. The hand-off writes the payload to a file on stdin and execs (`state.exec_with_input`), which the hook's hand-off to the session's selected launcher (`hooks.main`) now calls too. Not detected, by design: an environment changed behind uv's back while the lock stays the same, which `uv run` would have repaired, and an edit that keeps a file's size and modification time. The review's case, reproduced on this checkout: with `watchdog` uninstalled from the environment and `uv.lock` touched, a claimed Stop hook exited 0 and left `watchdog` installed. The Codex review of an earlier form, which ran `uv sync` as a child and then went on in the same interpreter, found that a sync replacing the interpreter left the hook on the old one, and that cancelling a watch during the sync orphaned uv; the hand-off removes both. Medians of 9 interleaved runs at load 7, the base launcher against this one with the record in place: prompt, batch and Stop hooks 191–196 ms against 146–151 ms, the clerk's fork step 213 against 174 ms. The Codex tool hook's launcher test now writes a lock, and its stand-in uv runs the gate's hand-off; it expects a hand-off at the first claimed hook, after the lock changes, and again after a change made during the sync, and none between. Recording the files as they stand after the sync fails that last case. The process test syncs with the real uv once, then fails any later uv.
…ide the gate A claimed session's gated hook used to continue in the gate's own process. The gate starts with -S, so it called `site.main()`, replaced `sys.argv` and `sys.stdin`, and imported Leaf there, with -P to keep `leaf/http` from shadowing `http`. A lock change made it hand itself to `uv run` and start again with a `synced` argument so that the second run could record the sync. This saved one interpreter start. Of the Claude Code plugins with real dependencies surveyed, none runs its program that way. The usual pattern is to build an environment once and have every hook run that environment's interpreter directly. Now, in a session holding a claim, the gate (`state.answer_gated_hook`) execs an ordinary `.venv/bin/python -m leaf` with the payload on stdin. Before that it runs `uv sync --inexact --no-dev`, as a child process, but only where `uv.lock` or `pyproject.toml` differs from `.venv/leaf-synced`. `--inexact` leaves a checkout's dev dependencies installed, as `uv run` does. The record still holds the two files as they were before the sync, so an update that lands during a sync makes the next hook sync again. The gate starts the interpreter by its path after the sync, so if the sync rebuilt the environment, the rebuilt one runs. A hook the gate skips is unchanged, and so is the hand-off to the session's selected launcher, which keeps `--if-claimed`. Medians of 11 interleaved runs at load 37–46, for the base (cfc2385), the in-process gate (406e98b) and this commit: - prompt, batch and Stop hooks: 172–173, 130–133 and 146–151 ms; - the clerk's fork step: 193, 155 and 171 ms; - the hop to the session's selected launcher: 89, 48 and 67 ms; - unclaimed sessions and worker batches: 30–34 ms in all three. So the second interpreter costs about 16 ms of the roughly 40 ms the branch saves on a claimed hook. With `watchdog` uninstalled from this checkout's environment and `uv.lock` touched, a claimed Stop hook exits 0 and leaves `watchdog` installed again, with the dev dependencies still in place. In the launcher test for the Codex tool hook, the stand-in uv now takes `sync`, and the stand-in package runs as `python -m leaf`. Writing the record after the sync, from the files as they stand then, still fails the case where the lock changes during the sync.
… module path The previous commit ran `uv sync` as a child of the gate. Codex's review found that cancelling a background watch during that sync killed the gate but left uv running, still holding the hook's captured stderr. The supervisor then stayed blocked in `communicate()` until the sync finished. So the gate again hands itself to `uv run` when `uv.lock` or `pyproject.toml` differs from `.venv/leaf-synced`. That makes uv the process the harness started: it syncs, takes the harness's signals, and starts the gate again with `synced` and the two files as they were before the sync. That second run records them only if they still match, and then, like any claimed hook, execs `.venv/bin/python -P -m leaf` rather than continuing inside the gate. The same review found that `python -m leaf` looks in the working directory first. A `leaf.py` in the task's directory therefore ran in place of Leaf's hook. This has been true since before the branch, through `uv run ... python -m leaf`. Both launches now pass `-P`, the flag Python provides to keep that directory off the module path. `interaction_log.launched`, which recognizes the launcher's `uv run` as this process's parent by its arguments, now expects `-P`. In the Codex tool hook's launcher test, the hook now runs from a directory whose `leaf.py` exits with an error. Without `-P` the test fails. Its stand-in uv runs the gate's hand-off again.
The branch had a hook registered `--if-claimed` skip uv in a session that holds a claim. It ran Leaf on the environment's interpreter, and went through uv only when `uv.lock` or `pyproject.toml` no longer matched a record of the last sync (`.venv/leaf-synced`). That record checked whether the lock files had changed, not whether the environment matched them. Matching the environment to the lock is uv's job, and uv does it better. On an idle machine, `uv run` costs about 16 ms more than starting the interpreter directly. About 6 ms of that is uv's check against the lock. The rest is uv's own start and the Python child it launches. Under load it costs about 25 ms, roughly a sixth of a claimed hook. In return the record, its re-entry through `uv run` with the files' state before the sync, and the `--if-claimed` hand-off to the selected launcher all go. The launcher's gate, `state.py`, the CLI and the hand-off in `hooks.main` are as on main, apart from two changes below. What stays from the branch: - The pages follower and the watch exit with 128 plus the signal that ends them, after releasing their lane or leases. Leaf's Claude Code module reads that exit as an ending from outside (`leases.release_on_termination`). uv passes the signal on to Python and returns the same status. - Both `uv run` launches pass `-P`. Without it, `python -m leaf` looks in the working directory first, and a `leaf.py` in the harness's working directory ran in place of Leaf. `interaction_log.launched`, which recognizes the launcher's uv by its arguments, expects the flag. - The tests that hold each short-lived Leaf process to the dependencies it may load. Main's gate tests come back. The claimed-session test now runs its hooks from a directory holding a `leaf.py` that exits with an error, and it fails when the launcher has no `-P`.
uv run passes a SIGTERM's exit status back, so the follower's own handling, added for a launch without uv, has nothing left to do. The follower test through the real launcher still expects 143.
leaf-agent
previously approved these changes
Nov 4, 2026
The shim test states the launcher's whole uv run command, and still expected python -m leaf after the launcher gained -P.
leaf-agent
approved these changes
Nov 4, 2026
max-sixty
added a commit
that referenced
this pull request
Nov 20, 2026
…leaf runs Leaf Keep the launcher at #5304's `-P` rather than `-I`. A hook inherits Claude Code's environment, so PYTHONPATH reaches one only where Claude Code itself was started with it: no setting, shell profile or running process on the machine sets one, and only dev tooling (the PYTHONPATH A/B bench, one Codex adapter journey test) sets one, for the process it starts. Console scripts, pipx and uv tools respect PYTHONPATH, and so does Leaf. The recorded `uv run` recursion (a PostToolBatch hook, 2026-11-04 04:42 UTC) came from the working directory: Claude Code runs a hook in Claude's current directory, which was a Leaf worktree's `src/`, and that launcher predated `-P`. The two children still ran `python -m` in the caller's working directory: from a directory holding a `leaf.py`, `leaf server start` failed with "did not start", and with `-P` the server comes up.
max-sixty
added a commit
that referenced
this pull request
Nov 22, 2026
…leaf runs Leaf (#6552) `leaf server start` spawns the page server, and the server spawns the handover reader, as `python -m leaf…` in the caller's working directory, so a `leaf.py` or `leaf/` there stands in for Leaf. From such a directory the server failed with "did not start"; from another Leaf checkout's `src/` it would run that checkout's code. This gives both spawns the `-P` that `bin/leaf` has had since #5304. The same cause produced the one `uv run` recursion error on record (a PostToolBatch hook, 2026-11-04 04:42 UTC). Claude Code runs a hook in Claude's current directory, which was a Leaf worktree's `src/`, on a launcher from before `-P`: each hop imported that tree's `leaf`, took itself for another launcher, and handed the hook on until uv's recursion limit. Leaf uses `-P` rather than `-I`, which would also ignore PYTHONPATH, because a hook inherits Claude Code's environment, nothing sets a PYTHONPATH naming a Leaf there, and console scripts respect PYTHONPATH too. Asked by max-sixty, who hasn't read this version. Server start from a directory holding a stray `leaf.py` now comes up; the hook gate, hook registration, launcher dispatch, handover journey and two-install Codex adapter journey tests pass locally. > _This was written by Claude Code on behalf of max-sixty_
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.
Two changes to Leaf's short-lived processes: tests that keep heavy imports from returning to the hook path, and a fix that stops a
leaf.pyin the agent's working directory from replacing Leaf.Each short-lived process has a dependency allowlist
Four tests each kept a hand-written list of modules a hook must not import, so a dependency nobody listed, or one loaded through a new path, crept onto the hook path unseen, as schema validation on every page read did until #5272. Each kind of short-lived process now has an allowlist of the runtime dependencies (
[project.dependencies]) it may load, intests/interact_support.py:EVERY_TURN_DEPENDENCIES(click): a hook in a session holding no page,import leaf.hook_transport, and a Codex tool hook with nothing to offer.READING_DEPENDENCIESadds the markup, URL and Markdown parsers and psutil: a Stop hook reading the page its session holds.ADMITTING_DEPENDENCIESadds jsonschema, referencing and regress: a prompt hook delivering a comment, andthread reply, which match handling clauses and admit events.A test runs the process in a fresh interpreter (
fresh_imports) and fails on any runtime dependency outside its list, naming the chain of Leaf lines that first imported it. Matching dependency names rather than counting modules keeps the tests stable under refactors and Python upgrades. The runtime dependencies come from the installed package's metadata, so the tests keep no copy ofpyproject.toml's list. The no-page test keeps its list of Leaf's own modules that page reading and serving would pull in, since the allowlists cover dependencies only.Planting
import jsonschemaat the top ofhook_transportfails the transport and Stop cases. Putting validation back on page reads fails the Stop, prompt and reply cases, namingleaf/layer.py -> leaf/validation/composition.py -> leaf/registry/validation.py.Leaf no longer imports from the caller's working directory
bin/leafranuv run ... python -m leaf, and-mputs the working directory first on the module path. A hook runs in the agent's project, so aleaf.pythere ran in place of Leaf's hook, and the hook's exit reported whatever that file did; Codex's review found it. Both launches now pass-P, Python's flag for leaving that directory off the path.interaction_log.launched, which recognises the launcher's uv by its arguments, expects the flag, as do the two tests that state the launcher's wholeuv runcommand. The claimed-session test intests/process/test_hook_gate.pynow runs its hooks from a directory holding aleaf.pythat exits with an error, and fails without-P.A new test,
test_a_terminated_pages_follower_exits_with_its_signal, stops the pages follower through the real launcher with SIGTERM and expects exit 143, which Leaf's Claude Code module reads as an ending from outside rather than a failure to show the user.Tried and dropped
This branch first ran a claimed session's gated hooks without
uv run, first by continuing inside the claim gate's-Sinterpreter, then by running.venv/bin/pythonbehind a record of the lock files as of the last sync. Medians at load 37–46: claimed hooks took 172 ms through uv, 146–151 ms on the venv's interpreter and 130–133 ms in-process. Both versions were dropped. The saving, about 16 ms idle and 25 ms loaded per claimed hook, didn't pay for interpreter tricks or for a second check of environment freshness beside uv's. #5246 holds the change that would remove most of a hook's cost, a resident process, now parked with theetclabel.Testing
The focused modules pass:
test_hook_gate,test_hook_registration,test_codex_adapter,test_interact_claude_code_module,test_session_lifecycleandtest_interaction_log, andtest_interact_layer's shim dispatch test.