From 81e1a61c5b7e83b1d6fa3eaadc2c6117e948fa26 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 19:53:21 +0530 Subject: [PATCH 1/4] The test gate advises at edit time and holds the end of a session only when a team turns blocking on By default the Stop test gate held a session whose transcript showed no test run since its last code change. It decided that by matching shell command text against a list of runners, package verbs and prose file names. Each review of the rule found commands it reads wrongly in both directions: `npm --prefix testapp run build`, `make testdata` and `grep -rn pytest .` count as a test run, and `make install test` and `gradlew integrationTests` count as none. A wrong hold costs the session one model request; a wrong pass skips the check without a word. The pattern that rejects install verbs is also cubic on one long line. `x install ` followed by `make test ` 2,000 times takes 16 s in the rule and 4,000 times takes 141 s, inside a synchronous regular expression that the hook's exit timer cannot interrupt, so that Stop waits for the client's hook timeout. The default Stop entry now exits before it reads its input. The line that names an edited file's tests on the tool call that edits it is unchanged, and so is LOOM_TEST_GATE=block, which holds the stop until the named tests ran. `testedSince`, `lastCodeChange`, `isProse` and its three patterns, `RUNNER`, `FETCHED`, `LEFT_OUT`, `startsRunner` and `rolloutCommand` are deleted with their tests and their documentation: block mode reaches none of them. Both plugin manifests move to 1.2.74. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 27 +- .../.claude-plugin/plugin.json | 2 +- integrations/claude-code-plugin/README.md | 6 +- .../claude-code-plugin/hooks/HOOKS.md | 38 ++- .../hooks/loom-test-gate.mjs | 45 ++-- .../claude-code-plugin/lib/test-gate.mjs | 157 ++--------- .../tests/code-hooks-failopen.test.mjs | 24 +- .../tests/test-gate.test.mjs | 243 ++---------------- .../codex-plugin/.codex-plugin/plugin.json | 2 +- .../codex-plugin/hooks/loom-test-gate.mjs | 45 ++-- integrations/codex-plugin/lib/test-gate.mjs | 157 ++--------- 11 files changed, 131 insertions(+), 615 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 26c5ccc123e..c40b25ceba0 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -60,10 +60,9 @@ end of this section are the exceptions. The plugin sends: against `HEAD`, to `code.impact` (`LOOM_BLAST_RADIUS=off` stops it); - the first time a session changes a file in an indexed checkout, with an edit tool or a shell command that names it, the outline of that file's uncommitted diff, to - `code.test_gate` (`LOOM_TEST_GATE=off` stops it), and once more at the Stop of a - session that ran no test since its last code change, for the files it changed. With - `LOOM_TEST_GATE=block` the outline goes at Stop only, for the files the session changed, - or for the whole uncommitted tree when the client gives no transcript. A diff's outline, up to 200,000 + `code.test_gate` (`LOOM_TEST_GATE=off` stops it). With `LOOM_TEST_GATE=block` the + outline goes at Stop instead, for the files the session changed, or for the whole + uncommitted tree when the client gives no transcript. A diff's outline, up to 200,000 characters, is its file paths, its hunk line ranges and, in a code file, the last identifier before the first `(` of each hunk header's context, usually the enclosing function's name. Git takes that context from a line above the hunk in the old file, @@ -550,7 +549,7 @@ The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. | PostToolUse, PostToolUseFailure (any tool) | `loom-capture.mjs` | one episodic observation per tool call (`observe.record`); a failed call is typed `error` | none | | Stop, SessionEnd | `loom-conversation.mjs` | appends new chat turns to the conversation plane (`conversation.append`) | `LOOM_CAPTURE_CONVERSATIONS=false` | | Stop | `loom-usage.mjs` | posts the session's token usage to `cost.record_turns` | `LOOM_USAGE=off` | -| Stop | `loom-test-gate.mjs` | for changes this session made, blocks "done" once with the tests `code.test_gate` says the change obliges, unless a test runner ran since the last code change or your latest prompt ends with "Do not run the tests"; with `LOOM_TEST_GATE=block`, unless pytest ran the named tests to its summary line and nothing was edited or run since ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | +| Stop | `loom-test-gate.mjs` | nothing by default: the gate never holds the end of a session. With `LOOM_TEST_GATE=block`, for changes this session made, blocks "done" once with the tests `code.test_gate` says the change obliges, unless your latest prompt ends with "Do not run the tests" or pytest ran the named tests to its summary line with no edit or run since ([the test gate](#the-test-gate)) | unset, or `LOOM_TEST_GATE=off` | | Stop | `loom-validate-gate.mjs` | blocks once when `namespace.validate` finds errors or warnings on the memory keys this session wrote | `LOOM_VALIDATE_GATE=off` | | Stop | `loom-namespace-health.mjs` | one line when `namespace.audit` finds a critical misuse of the namespace, pointing at the `loom-optimize` skill; the audit is asked once per session, by the first prompt's detached process, and told at a Stop | `LOOM_NAMESPACE_HEALTH=off` | | Stop, PreCompact | `loom-working-memory.mjs` | refreshes the working-memory note (`session:`): goal, git status, files edited, last reply | `LOOM_WORKING_MEMORY=off` | @@ -657,7 +656,7 @@ Beyond the off switches in the table: | `LOOM_PROMPT_PACK_MIN_CONF` | unset | a `retrieval_confidence` gate for search pointers (low risk is 0.7 up); unset, that label | | `LOOM_FILE_CONTEXT_TTL_MIN` | `30` | minutes before the same file's context is fetched again | | `LOOM_BLAST_DEPTH` | `1` | `code.impact` depth for the blast-radius line | -| `LOOM_TEST_GATE` | unset | `block`: no line at edit time, and a stop passes only on the named tests; `off`: no gate | +| `LOOM_TEST_GATE` | unset | unset: a line at edit time, no stop held; `block`: no line, the stop held; `off`: no gate | | `LOOM_TEST_GATE_DEPTH` | `2` | hops the test gate follows (1–3) | | `LOOM_OBSERVE_DEDUPE_S` | `60` | a repeated read in this window is not observed again; `0` disables | | `LOOM_OBSERVE_SKIP_TOOLS` | a built-in list | comma-separated tool names (with `*` globs) that produce no observation | @@ -690,22 +689,16 @@ Loom tests for src/app/router.py: .venv/bin/python -m pytest tests/test_router.p never runs the tests has still been told which ones they are. A file is asked about at its first change only, so a function changed later in the same file is not named. A test that shell command itself runs is not named on its own result. -- **At the end of the session.** A session that ran no test since its last code change - is held once per distinct change, with the tests the change obliges and the functions - the index links no test to. A held stop costs the session one more model request, so - any test run since that change lets the stop pass: a shell command that starts a test - runner and finished no earlier than the newest write among the code files the session - changed. A documentation or prose file (`.md`, `.rst`, a changelog, a `.txt` file under `docs/`) - written after the run holds nothing. The gate reads that command for a runner's name only. Which tests ran and how they went cannot be read - reliably from shell commands, so that judgement stays with the agent and with CI. The - plugin README lists the runners under **Stops that pass**. +- **At the end of the session.** Nothing. By default the gate informs and never holds + the stop. Which tests ran and how they went cannot be read reliably from shell + commands, so that judgement stays with the agent and with CI. To hold the stop until the named tests ran on the final tree, set `LOOM_TEST_GATE=block` in the environment Claude Code starts in. The gate then prints nothing at edit time, and blocks "done" once per distinct change unless the transcript already answers the ask; the plugin README lists the exact conditions under **Answered stops**. That mode also holds a -session that ran the tests in a way the gate does not read. `LOOM_TEST_GATE=off` turns -the gate off. +session that ran the tests in a way the gate does not read, and each held stop costs the +session one more model request. `LOOM_TEST_GATE=off` turns the gate off. ## The code shunt diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index e04778b8382..74c1c0b749a 100644 --- a/integrations/claude-code-plugin/.claude-plugin/plugin.json +++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "loom", "displayName": "ClickHouse Loom", - "version": "1.2.73", + "version": "1.2.74", "description": "Shared long-term memory and code intelligence for Claude Code, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 9fc773ed8b8..1d8e1c1dc1a 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -198,7 +198,7 @@ the duplicate, run `claude mcp remove -s user`. | `PostToolUse` (Bash / PowerShell) | `loom-test-gate.mjs` | **The tests are named when the file changes.** After a shell command in a loom-indexed repo, asks `code.test_gate` about each file the command changed (a dirty path it names, written since the session began) and attaches **one line** per file with the command of the tests the index links to it, or of the file itself when it is a test: `Loom tests for src/a.py: .venv/bin/python -m pytest tests/test_a.py`. Once per file and once per test per session, on the tool result, so it costs no model request; an edit tool's call gets the same line from `loom-blast-radius.mjs`. A file with no such test gets the changed functions the index links no test to: `Loom tests for src/a.py: the index links no test to Router::match`. A comment-only change names nothing (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | | `UserPromptSubmit` | `loom-prompt-recall.mjs` | **Default `first`**: one bounded recall on the first qualifying prompt of a session, including empty or abstaining answers. Clear named code-only questions skip default recall without consuming the attempt; mixed memory requests still qualify. `LOOM_PROMPT_RECALL=on` for every prompt, `off` to disable. One `context.pack` per prompt restricted to `memories`, `decisions`, `procedures` with the prompt as the query; injects the plane-tagged blocks the session has not seen, only when memory is not abstaining and `retrieval_confidence ≥ 0.5`, capped at 1,200 chars (`LOOM_PROMPT_RECALL_MAX_CHARS`). The memory-side sibling of the prompt pack: active retrieval — the model gets what memory knows about the prompt without asking — done per prompt, never per tool turn. | | `UserPromptSubmit` | `loom-prompt-pack.mjs` | On by default (`LOOM_PROMPT_PACK=off` turns it off). One bounded lookup: `code.symbol`, `code.callers` or `code.impact` for an explicit named question, otherwise `code.search` (top 3, no bodies). Self-contained requests, local-only changes and explicit memory questions skip code retrieval. Search emits only where the index labels its own answer low-risk (or, with `LOOM_PROMPT_PACK_MIN_CONF` set, from that confidence), and without abstention; its pointers are candidates, and nothing tells the model to stop searching; typed answers preserve ambiguity and static-analysis limits. Named implementation or behavior questions request a whole definition body within 600 server-budget tokens; location/signature requests stay pointer-only and oversized bodies stay elided. No fallback request follows an empty typed answer. Pointers are deduplicated within the current answer, so later prompts can receive changed evidence. | -| `Stop` | `loom-test-gate.mjs` | **Holds a session that ran no test since its last code change.** With uncommitted changes **this session made** in a loom-indexed repo (the dirty paths the transcript shows an edit tool targeted or a shell command named, written since the session began, by the file's modification time; a tree left dirty before the session gates nothing, even when a command reads or runs its files), asks `code.test_gate` what the change obliges — the tests that reach it, in evidence order with a `run` command when the harness is derivable, and the touched functions no test reaches — and blocks the stop **once** per distinct change with a reason that names them. The second stop on the same change passes. By default any test run since the last code change lets the stop pass, and nothing is asked (**Stops that pass**, below); with `LOOM_TEST_GATE=block` only a run of the named tests does (**Answered stops**, below). `LOOM_TEST_GATE=off` disables. | +| `Stop` | `loom-test-gate.mjs` | **Does nothing by default.** The test gate informs at edit time and never holds the end of a session: at a Stop the script exits before reading input. **`LOOM_TEST_GATE=block` holds the stop**: with uncommitted changes **this session made** in a loom-indexed repo (the dirty paths the transcript shows an edit tool targeted or a shell command named, written since the session began, by the file's modification time; a tree left dirty before the session gates nothing, even when a command reads or runs its files), asks `code.test_gate` what the change obliges — the tests that reach it, in evidence order with a `run` command when the harness is derivable, and the touched functions no test reaches — and blocks the stop **once** per distinct change with a reason that names them. The second stop on the same change passes, and so does a first stop the transcript already answers (**Answered stops**, below). `LOOM_TEST_GATE=off` disables. | | `Stop` | `loom-validate-gate.mjs` | **Compile green before done**: collects the memory keys this session wrote from the transcript, asks `namespace.validate` for a report scoped to exactly those keys, and blocks the stop **once** per distinct key set with the error and warning findings that name them (a conflict you opened, a fact whose `valid_to` has passed, an attestation your edit made stale) and each check's remedy. `info` findings never block; the second stop on the same keys passes. `LOOM_VALIDATE_GATE=off` disables. | | `Stop` | `loom-namespace-health.mjs` | **The store tells you when the namespace is misused**: once per session, one `namespace.audit` over the last day (no samples) for the session's namespace, asked by the first prompt's detached process so that a stop does not wait for it (a stop asks in place only when that process died before its answer); when it carries a critical finding — exact-key reads dwarfing searches, double-encoded values, rows the embedder gave up on, leases in the memory plane — you get **one line** naming the codes and `/loom-optimize`, once per session, at the first stop that finds the verdict, as a block-once reason (the one channel a Stop hook has to the model). Healthy namespace, no token, slow or down server: nothing. The same summary rides `context.pack` as the `namespace_health` section at session start. `LOOM_NAMESPACE_HEALTH=off` disables. | | `Stop` | `loom-usage.mjs` | Posts the session's own model usage (input, cache read, cache creation by TTL, output; deduped by message id, sidechains skipped) to `cost.record_turns`; the **server** prices it into `loom.agent_turn_usage` from the same table it prices its own upstream spend with. Turns "did loom make this session cheaper" into a standing series instead of a hand-run paired experiment. Needs a writer token. `LOOM_USAGE=off` disables. | @@ -215,9 +215,9 @@ the duplicate, run `claude mcp remove -s user`. **Tests at edit time.** The test gate names a file's tests on the tool call that changes it, where the agent is still working on the file. For a source file they are the tests the index links to it through its name, the test map or the call graph, each of them present in the checkout, with the tests that have no known runner listed by path; for a test file, the file's own command. A file with no test to name in the checkout gets the changed functions the index links no test to instead (`the index links no test to Router::match`), worded as the index's view, because its call graph is a floor. A file is asked about once per session, at its first change, so a function changed later in the same file is not named; a file the server gave no answer for is asked about once more, at the next call that names it; at most four files are asked about per tool call. A test is named once per session, so the test you edit after its source file adds no second line. A test the tool call's own command runs is not named on the result of that run: its command stands there whole, in this checkout, so `pytest tests/test_a.py::test_one`, `docker exec app pytest tests/test_a.py` and `echo "pytest tests/test_a.py"` still get the line. -**Stops that pass.** By default the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. +**The end of a session.** By default the test gate informs and never holds: it names a file's tests when the file changes, and the stop passes whatever the session ran. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads. A rule that holds the stop on that reading holds sessions that did the work, at one more model request each, and a rule that passes on it passes sessions that ran nothing. That judgement stays with the agent and with CI. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. In a Codex rollout that mode reads the session's changes from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), and a rollout that changed a file through any of them is held: a rollout answers nothing. -**Untested functions.** The index's call graph is a floor: a test may reach a function the graph holds no edge to, such as a constructor the test calls by building the object. Beside tests to run that the checkout has, the reason of a held stop therefore lists the functions as the index's view, `the index links no test to: … (the tests named here may still reach it)`. With no such test it reads `no test reaches: …` and asks for a test. +**Untested functions.** The index's call graph is a floor: a test may reach a function the graph holds no edge to, such as a constructor the test calls by building the object. Beside tests to run that the checkout has, the reason of a stop held with `LOOM_TEST_GATE=block` therefore lists the functions as the index's view, `the index links no test to: … (the tests named here may still reach it)`. With no such test it reads `no test reaches: …` and asks for a test. **Answered stops.** With `LOOM_TEST_GATE=block`, the test gate does not block, and so names no untested function, when it names tests, each of them is in the checkout and the transcript already answers the ask to run them, in one of two ways. Your latest prompt ends with the sentence "Do not run the tests" (also `don't` or `never`, and `tests`, `any tests` or `the test suite`). Or the transcript shows a Bash command that ran pytest on each named test, by its file or a directory above it that is below the checkout root, and whose output holds a whole summary line for each pytest in it: one that counts tests failed or passed and none deselected. A run that failed answers, since the session has read its failures; a collection that stopped at an error (`1 error in 0.12s`) does not, and neither does a line that counts a failure or an error when a pytest in the command has `--exitfirst`, `--maxfail` or a short flag holding `x` (`-x`, `-qx`, also `-rx`), since that run stopped before the files after it. No output answers that holds the line pytest prints above the summary of a run it ended early (`stopping after 1 failures`, `Interrupted: …`), which also shows a limit or `--sw` set in a configuration file or in `PYTEST_ADDOPTS`; `| tail -1` cuts that line, and such a run then answers. The command has no `--ignore`, `--deselect`, `--lf`, `--sw` or `--continue-on-collection-errors` and no quote in pytest's arguments; its runs count from the first pytest after which it runs only pytest, `tail`, `head`, `grep` and `echo` and holds no backquote and no redirect to a file other than `/dev/null`, so the second run of `git stash; pytest tests; git stash pop; pytest tests` answers and no run of `pytest tests; git stash; pytest tests; git stash pop` or of `pytest tests; git diff --stat` does; the transcript shows no edit-tool call and no other Bash or PowerShell call after that; no tracked file is deleted; and no uncommitted or untracked file was modified later. A run of the whole checkout names no path below the root, so a bare `pytest` and `pytest .` do not answer. Before pytest in its simple command only variable assignments, `env`, `timeout`, `uv run` or `poetry run`, an interpreter's `-m` and a path may stand: `python -u -m pytest tests` and `docker exec app pytest tests` do not answer. Runs in several commands add up only while each later command holds nothing before the first of its runs that count but what launches it: one that does anything else first, a `cd` included, answers for its own runs alone. The word after a pytest flag written without `=` is read as that flag's value, not as a path that ran, unless the flag is a cluster of `-q`, `-v`, `-x`, `-s` and `-l`: `pytest --no-header tests` does not answer. Quotes in the rest of the command are not read, so a `|`, `;` or `>` inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` does not answer. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 00b0c2bbfe7..5f82bcafda9 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -110,7 +110,7 @@ receives on stdout. | Stop, detached | loom-capture | session_id | none | observe.crystallize | no token | | Stop, detached | loom-conversation | transcript, last_assistant_message | none | conversation.append via the flusher | `LOOM_CAPTURE_CONVERSATIONS=false` | | Stop, detached | loom-usage | transcript | none | cost.record_turns | `LOOM_USAGE=off` | -| Stop | loom-test-gate | transcript, cwd | JSON block once | code.test_gate, when the transcript shows no test run since the last code change (`testedSince`); with LOOM_TEST_GATE=block, unless the named tests ran | `LOOM_TEST_GATE=off` | +| Stop | loom-test-gate | transcript, cwd | JSON block once | none by default: the script exits before it reads its input; with LOOM_TEST_GATE=block, code.test_gate, and the block unless the named tests ran | unset, or `LOOM_TEST_GATE=off` | | Stop | loom-validate-gate | transcript | JSON block once | namespace.validate | `LOOM_VALIDATE_GATE=off` | | Stop | loom-namespace-health | cwd, session_id | JSON block once | none: tells the stored verdict once (namespace.audit is asked here by a wiring with no detached process, on the first Stop, and when the prompt's ask is overdue) | `LOOM_NAMESPACE_HEALTH=off` | | Stop, detached | loom-working-memory | transcript, cwd | none | working_memory.set when the note changed | `LOOM_WORKING_MEMORY=off` | @@ -390,8 +390,8 @@ record: the run and its usage counters. prompt. A wiring that starts the script at Stop only (Codex, a hand-wired client) asks on the first Stop and waits for the answer. Later stops make no call. -- **loom-test-gate.** Names the tests of a changed file, and holds the - stop of a session that ran no test since its last code change. By default it names +- **loom-test-gate.** Names the tests of a changed file, and holds no + stop unless LOOM_TEST_GATE=block is set. By default it names them when the file changes: after a Bash or PowerShell command (and, through loom-blast-radius, after an edit tool) it takes the dirty paths the call named or targeted that were written @@ -409,28 +409,20 @@ record: the run and its usage counters. (`runsHere`). The line costs no model request. A call that names no unasked dirty file costs one git call and no request; in a checkout the shared cache says is not indexed, no git call either. - At Stop, with uncommitted changes this session made in a loom-indexed - repo (dirty paths the transcript shows an edit tool targeted or a shell - command named, written since the session's first row; a tree left dirty - before the session gates nothing; in a Codex rollout the calls read are - `apply_patch` and the shell tool under each name `rolloutShell` takes, - in either mode), it sends the change's paths, hunk + At Stop the default does nothing: the script exits before it reads its + input, and no stop is held. + With LOOM_TEST_GATE=block nothing is printed at edit time. At Stop, with + uncommitted changes this session made in a loom-indexed repo (dirty paths + the transcript shows an edit tool targeted or a shell command named, + written since the session's first row; a tree left dirty before the + session gates nothing; in a Codex rollout the calls read are `apply_patch` + and the shell tool under each name `rolloutShell` takes; with no + transcript, the whole dirty tree), it sends the change's paths, hunk ranges and function names only (`diffHeaders`) to code.test_gate for its obligations and blocks the stop once per distinct change with a reason - naming them. By default a stop passes, and asks the server nothing, when - the transcript holds a shell command that starts a test runner and - finished no earlier than the newest write among the changed code files, - documentation and prose left out by name - (`testedSince`, `lastCodeChange`): the command's text is read for a - runner's name only, not for which tests ran or how they went, so a run - that failed, was piped or ran between `git stash` and `git stash pop` - in the same command passes, in a Claude Code transcript or a Codex - rollout; a pop in a later command rewrites the changed files, and that - stop is held. With no transcript the default holds no stop. - With LOOM_TEST_GATE=block nothing is printed at edit time, and a Claude - Code stop passes only when its transcript already answers the ask to run - the named tests (`runAnswered` in lib/test-gate.mjs); a Codex rollout - answers nothing there. + naming them. A Claude Code stop passes only when its transcript already + answers the ask to run the named tests (`runAnswered` in + lib/test-gate.mjs); a Codex rollout answers nothing there. LOOM_TEST_GATE=off disables both; LOOM_TEST_GATE_DEPTH sets hops (1-3). - **loom-usage.** Reads the transcript's last MiB, dedupes assistant turns by message id (sidechains skipped) and posts their raw usage counters to diff --git a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs index 532b2be3784..27ab1e2cac7 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -11,30 +11,25 @@ // edited. An edit tool's call gets the same line from loom-blast-radius, the // one hook wired for those tools. // -// Stop: if the working tree has uncommitted changes THIS SESSION made -// in a loom-indexed repo, ask `code.test_gate` for the change's obligations -// (tests to run, untested touched functions) and block the stop ONCE per -// distinct change with a reason that names them. "This session's" is read -// from the transcript: dirty paths an edit tool targeted or a shell command -// named, written since the session began (by the file's modification time); -// a tree left dirty before the session does not gate a turn that changed -// nothing. By default any test run since the session's last code change -// lets the stop pass, whatever it ran and however it went (`testedSince`, -// `lastCodeChange` in lib/test-gate.mjs): the stop is held for a session -// that ran no test since its last code change, and nothing is asked of the -// server for one that ran some. A documentation file changed after the run -// holds nothing. +// At Stop the default does nothing: the line above informs, and the end of a +// session is never held. The script exits before it reads its input. // -// With LOOM_TEST_GATE=block nothing is named at edit time, and the stop -// passes only when a Claude Code transcript shows the named tests ran on the -// tree as it stands (`runAnswered`); a Codex rollout answers nothing there, -// so its stop blocks. +// With LOOM_TEST_GATE=block nothing is named at edit time, and the Stop +// holds: if the working tree has uncommitted changes THIS SESSION made in a +// loom-indexed repo, ask `code.test_gate` for the change's obligations (tests +// to run, untested touched functions) and block the stop ONCE per distinct +// change with a reason that names them. "This session's" is read from the +// transcript: dirty paths an edit tool targeted or a shell command named, +// written since the session began (by the file's modification time); a tree +// left dirty before the session does not gate a turn that changed nothing. +// The stop passes only when a Claude Code transcript shows the named tests +// ran on the tree as it stands (`runAnswered`); a Codex rollout answers +// nothing there, so its stop blocks. // // Fail-open everywhere: no token, not an indexed repo, clean tree, nothing // of the tree touched this session, server down, second stop on the same -// change — the agent stops as normal. Without a transcript path the default -// holds no stop, and LOOM_TEST_GATE=block takes the whole dirty tree as the -// change. +// change — the agent stops as normal. Without a transcript path +// LOOM_TEST_GATE=block takes the whole dirty tree as the change. // LOOM_TEST_GATE=off disables both; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. import crypto from "node:crypto"; @@ -65,13 +60,11 @@ import { gateMode, gatePayload, gateSignature, - lastCodeChange, newestChange, renderGate, runAnswered, sessionScope, sessionStart, - testedSince, testsIn, writtenSince, } from "../lib/test-gate.mjs"; @@ -97,7 +90,8 @@ async function advise(payload, token) { } async function main() { - if (MODE === "off" || (AFTER_TOOL && MODE === "block")) { + // The line at edit time is the default's, the hold at Stop is LOOM_TEST_GATE=block's. + if (MODE !== (AFTER_TOOL ? "advise" : "block")) { scheduleExit(0); return; } @@ -140,11 +134,6 @@ async function main() { scheduleExit(0); return; } - // The default holds the stop of a session whose transcript shows no test run since its last code change. - if (MODE === "advise" && (!transcript || testedSince(rows, lastCodeChange(root, changed)))) { - scheduleExit(0); - return; - } const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); if (!repo.indexed) { scheduleExit(0); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 5457eb9f899..1bdfb76cfd2 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -7,25 +7,22 @@ // the index links no test to when it has no test to name; once per file per // session (`adviceFiles`, `adviceLines`). // -// At Stop it holds a session that ran no test since its last code change. -// When the agent is about to stop with uncommitted changes in a -// loom-indexed repo, it asks -// `code.test_gate` what the change obliges: the tests that reach -// it (evidence-ordered, with a run command when derivable) and the touched -// functions no test reaches. If either list is non-empty and this exact -// change has not been gated yet this session, block the stop ONCE with a -// reason that names them: the tests are named before "done", not discovered -// in review. The second stop on the -// same change passes: the agent has seen the obligation and either ran the -// tests or chose not to, and a gate that nags is a gate that gets disabled. -// A block costs the session one more model request, so by default any test -// run since the last write to a changed code file lets the stop pass before -// anything is asked (`testedSince`, `lastCodeChange`): which tests it ran -// and how they went is the agent's to -// judge, and a hook that reads shell text to decide it blocks sessions that -// ran them. With LOOM_TEST_GATE=block nothing is named at edit time and the -// stop passes only when the transcript shows the named tests ran on the tree -// as it stands (`runAnswered`). +// At Stop the default does nothing: the line informs, and whether the tests +// ran and how they went is the agent's to judge. A rule that decides it from +// shell text holds sessions that ran them and passes sessions that did not. +// +// With LOOM_TEST_GATE=block nothing is named at edit time and the stop is +// held. When the agent is about to stop with uncommitted changes in a +// loom-indexed repo, the gate asks `code.test_gate` what the change obliges: +// the tests that reach it (evidence-ordered, with a run command when +// derivable) and the touched functions no test reaches. If either list is +// non-empty and this exact change has not been gated yet this session, it +// blocks the stop ONCE with a reason that names them: the tests are named +// before "done", not discovered in review. The second stop on the same +// change passes: the agent has seen the obligation and either ran the tests +// or chose not to, and a gate that nags is a gate that gets disabled. The +// first stop passes only when the transcript shows the named tests ran on +// the tree as it stands (`runAnswered`). // // The change is the session's, not the tree's: `sessionScope` keeps only // the dirty paths the transcript shows this session edited or named in a @@ -56,9 +53,9 @@ import { parseLines, readRange } from "./transcript.mjs"; const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "str_replace_editor", "apply_patch"]); /** What the gate does, from LOOM_TEST_GATE: "advise" names an edited file's - * tests on the tool call that edited it and holds the stop of a session that - * ran no test since its last code change (unset, or any on-word); "block" names - * nothing and holds the stop until the named tests ran; "off" does neither. */ + * tests on the tool call that edited it and holds no stop (unset, or any + * on-word); "block" names nothing and holds the stop until the named tests + * ran; "off" does neither. */ export function gateMode(env = process.env) { if ( String(env.LOOM_TEST_GATE ?? "") @@ -628,126 +625,10 @@ function runsHere(command, run) { return at >= 0 && /^(?:[\s;|&)]|$)/.test(command.slice(at + run.length)) && ranHere(command.slice(0, at)); } -// A shell command that starts a test runner, wrapped or piped in any way: a -// program `code.test_gate` names a run with or a common other one; a build -// tool with an argument in which `test` or `tests` follows no letter and no -// lower-case letter follows it (`make test-unit`, `npm run test`, `node -// --test`, `gradle :app:test`, `gradlew testDebugUnitTest`); a tool that runs -// a target or a script by its name, with a name that starts with `test` -// (`make testall`, `npm run testci`); or Gradle with a task that ends in -// `Test` after a lower-case letter (`gradlew integrationTest`). `import -// pytest`, `pytest.raises`, `make latest`, `go vet ./internal/testutil/...`, -// `cargo build -p testcontainers` and `gradlew compileTestJava` are not -// runs. A command that only mentions a runner counts: what is read is -// whether the session ran a test at all. -// -// After one of these verbs earlier in the simple command the name is a -// package: `pip install -U pytest`, `npm i -D @types/jest`, `yarn remove -// jest`, `go get github.com/stretchr/testify`. A flag is no verb: `npx -// --no-install jest` and `docker run --rm app pytest` run. A build tool's -// target of a verb's name hides the run after it: `make install test` is -// read as none. -const FETCHED = String.raw`\s(?:(?:un)?install|add|i|ci|get|remove|rm|update|upgrade|download|require)\s[^\n;|&]*`; -// What a build tool is told to leave out is no run, for every tool of the -// list: the word after `-x`, where Gradle takes a task to exclude (`gradle -// build -x test`), and `test.skip`, Maven's property (`mvn package -// -Dmaven.test.skip=true`). -const LEFT_OUT = String.raw`\s-x\s+\S*`; -const RUNNER = new RegExp( - String.raw`(? RUNNER.test(command.replace(/\\\n/g, "")); - /** True for the name of a Codex rollout's shell tool, under any of the names * `normalizeToolName` folds onto Bash. */ const rolloutShell = (name) => name === "exec" || normalizeToolName(name) === "Bash"; -/** The command text of a Codex rollout's shell call: its `arguments` JSON - * holds a string or an argv (`["go","test"]`), whose words no space joins. */ -function rolloutCommand(call) { - let input = call.input ?? call.arguments; - if (typeof input === "string") { - try { - input = JSON.parse(input); - } catch { - return input; - } - } - return commandText(input) || (typeof input === "string" ? input : ""); -} - -/** - * True when the transcript holds a shell command that starts a test runner - * (`RUNNER`) and finished at or after `since` (epoch ms), or has no dated - * result: Claude Code rows and Codex rollout calls, sidechains skipped. Its - * output is not read, so a run that failed or was piped into `grep` counts. - * So does one between `git stash` and `git stash pop` in the same command; a - * pop in a later command rewrites the changed files after the run. - */ -export function testedSince(objs, since) { - const done = new Map(); - const runs = []; - for (const o of objs || []) { - const at = Date.parse((o && o.timestamp) || ""); - if (o?.type === "response_item") { - const call = o.payload || {}; - if (/_output$/.test(call.type)) done.set(call.call_id, at); - else if (rolloutShell(call.name) && startsRunner(rolloutCommand(call))) { - runs.push(call.call_id); - } - continue; - } - const content = o && !o.isSidechain && o.message && o.message.content; - for (const b of Array.isArray(content) ? content : []) { - if (o.type === "user" && b?.type === "tool_result") done.set(b.tool_use_id, at); - else if ( - o.type === "assistant" && - b?.type === "tool_use" && - ["Bash", "PowerShell"].includes(normalizeToolName(b.name)) && - startsRunner(commandText(b.input)) - ) { - runs.push(b.id); - } - } - } - return runs.some((id) => !(done.get(id) < since)); -} - -// Documentation and prose by name: a test run answers no change to one. A -// `.txt` file is code (a requirements file, a build list, a test fixture) -// unless its name or a `docs` directory above it says prose: `CHANGES.txt`, -// `docs/releases/5.2.txt`. A requirements or a constraints file under `docs` -// stays code. -const PROSE = /\.(?:md|mdx|markdown|rst|adoc|asciidoc)$/i; -const CHANGELOG = /(?:^|\/)(?:CHANGELOG|CHANGES|HISTORY|NEWS)$/; -const PROSE_TXT = - /(?:^|\/)(?:changelog|changes|history|news|readme|license|notice|authors|docs?\/(?!.*(?:requirements|constraints)).*)\.txt$/i; -const isProse = (file) => CHANGELOG.test(file) || PROSE.test(file) || PROSE_TXT.test(file); - -/** The newest modification time, in epoch ms, among the code files of - * `files` under `root`: a test run that finished since then saw each of - * them as it stands. A documentation or prose file (`isProse`) is left out, - * so an edit to one after the run holds no stop, and so is a file that - * cannot be read (a deleted one). 0 when none is left. */ -export function lastCodeChange(root, files) { - let last = 0; - for (const file of files) { - if (isProse(file)) continue; - try { - last = Math.max(last, fs.statSync(path.join(root, file)).mtimeMs); - } catch { - // A deleted file has no time of its own. - } - } - return last; -} - // pytest's last line, whose order is fixed: failed, passed, skipped, // deselected, xfailed, xpassed, warnings, errors. A whole line starts at // "failed" or "passed" and names nothing deselected, so a -k subset is not diff --git a/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs b/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs index 500048e31a1..34ea0e7bb5d 100644 --- a/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs +++ b/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs @@ -115,8 +115,9 @@ async function withCapturingServer(fn) { return bodies; } -// The Stop test gate that takes only a run of the named tests as an answer. +// The Stop test gate holds a stop, and so reads its input and asks the server, only with this. const BLOCKING = { LOOM_TEST_GATE: "block" }; +const stopEnv = (hook) => (hook === "loom-test-gate.mjs" ? BLOCKING : {}); const HOOK_NAMES = [ "loom-code-shunt.mjs", @@ -129,7 +130,7 @@ const HOOK_NAMES = [ test("malformed, empty and non-object stdin: every code hook exits 0 and prints nothing", async () => { const tmp = freshTmp(); for (const hook of HOOK_NAMES) { - // The test gate reads its input at a Stop in either mode, and after a shell command. + // The test gate reads its input at a Stop with LOOM_TEST_GATE=block, and after a shell command. const starts = hook === "loom-test-gate.mjs" ? [{}, { env: BLOCKING }, { event: "PostToolUse" }] : [{}]; for (const stdin of ["{not json", "", "[]", "null", '"text"', "42"]) { for (const how of starts) { @@ -166,7 +167,7 @@ test("no token: nothing is asked of the server and nothing is printed", async () ["loom-test-gate.mjs", { cwd: dir, session_id: "s" }], ["loom-validate-gate.mjs", { cwd: dir, session_id: "s" }], ]) { - const r = await run(hook, payload, { tmp, url, token: "" }); + const r = await run(hook, payload, { tmp, url, token: "", env: stopEnv(hook) }); assert.equal(r.code, 0, hook); assert.equal(r.out, "", hook); } @@ -309,7 +310,7 @@ test("Stop gates: 401 and a hanging server both let the stop through", async () r = await run( hook, { cwd: dir, session_id: "s", transcript_path: transcript }, - { tmp, url, env: { LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, + { tmp, url, env: { ...stopEnv(hook), LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, ); assert.equal(r.code, 0, `${hook} ${status}`); assert.equal(r.out, "", `${hook} ${status}`); @@ -335,10 +336,7 @@ test("Stop gates: a Stop the gate itself caused never blocks again", async () => const r = await run( hook, { cwd: dir, session_id: "s", transcript_path: transcript, stop_hook_active: true }, - { - tmp, - url, - }, + { tmp, url, env: stopEnv(hook) }, ); assert.equal(r.out, "", hook); } @@ -401,7 +399,7 @@ test("blast radius and file context: 401 and a hanging server add nothing to the r = await run( hook, { ...edit, session_id: `s-${hook}-${attempt}` }, - { tmp, url, env: { LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, + { tmp, url, env: { ...stopEnv(hook), LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, ); assert.equal(r.code, 0, `${hook} ${status}`); assert.equal(r.out, "", `${hook} ${status}`); @@ -487,9 +485,13 @@ test("blast radius and test gate: only the diff's paths and hunk headers reach t }; // The edit's own requests: the radius and the tests line. await run("loom-blast-radius.mjs", edit, { tmp, url }); - await run("loom-test-gate.mjs", { cwd: dir, session_id: "s", transcript_path: transcript }, { tmp, url }); + await run( + "loom-test-gate.mjs", + { cwd: dir, session_id: "s", transcript_path: transcript }, + { tmp, url, env: BLOCKING }, + ); }); - // code.test_gate twice: for the tests line at the edit, and at the Stop of a session that ran no test. + // code.test_gate twice: for the tests line at the edit, and at the Stop that LOOM_TEST_GATE=block holds. for (const [op, times] of [ ["/v1/code.impact", 1], ["/v1/code.test_gate", 2], diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index 9a90c8395a9..2ae54577337 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -523,7 +523,7 @@ test("checkoutPython runs no pytest.py planted in the checkout", () => { import http from "node:http"; import { execFileSync, spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; -import { declinesTests, lastCodeChange, newestChange, runAnswered, testedSince } from "../lib/test-gate.mjs"; +import { declinesTests, newestChange, runAnswered } from "../lib/test-gate.mjs"; import { cachedUnindexed, cachePathFor } from "../lib/repo-scope.mjs"; import { hostEnv } from "./host-env.mjs"; @@ -918,203 +918,10 @@ test("a Codex rollout answers nothing", () => { assert.equal(answered(rollout), false); }); -test("any test run that finished since the change counts, whatever it ran and however it went", () => { - const since = Date.parse(edit()[0].timestamp); - for (const command of [ - SUITE, - "git stash; pytest tests; git stash pop", - "pytest tests/test_other.py -x 2>&1 | grep FAILED", - "sed -i s/1/2/ src/a.py && .venv/bin/python -m unittest discover", - "npx vitest run src/a.test.ts", - "go test ./pkg/...", - "go test ./...", - "make test-unit", - "npm run test", - "node --test", - "node --test tests/a.test.mjs", - "gradle :app:test", - "./gradlew testDebugUnitTest", - "make unit-tests", - "cargo nextest run", - "tests/clickhouse-test 01234_x", - "make testacc", - "make testall", - "npm run testci", - "./gradlew integrationTest", - "gradle connectedAndroidTest", - // A run after an install, in its own simple command. - "npm ci && npm test", - "pip install -e . && pytest", - "yarn add -D jest; yarn jest", - "for i in 1 2 3; do pytest tests; done", - "npx --no-install jest", - "docker run --rm app pytest", - "pip install -e . \\\n && pytest", - // A line continuation joins the run to its tool. - "make \\\n test", - ]) { - assert.equal(testedSince(bash(command, FAILED), since), true, command); - assert.equal(testedSince(call("PowerShell", { command }), since), true, command); - } - // A command that reads or writes a test, or installs, removes or updates a - // package, runs none; neither does a build tool whose argument holds `test` - // inside a word or at the start of a path's or a package's name, one that - // builds the tests, or one told to leave them out. - for (const command of [ - HEREDOC, - "sed -n 1,40p tests/test_a.py", - "cat pytest.ini", - "pip install pytest", - "git diff", - "npm install x@latest", - "go install y@latest", - "make latest", - "node scripts/attest.js", - "npm install @testing-library/react", - "go get github.com/stretchr/testify", - "npm install @playwright/test", - "npm install -D node-test", - "npm install --save-dev jest", - "yarn add -D jest", - "pnpm add -D vitest", - "pip install -U pytest", - "pip install 'pytest>=8'", - "uv add --dev pytest", - "npm i -D @types/jest", - "npm uninstall jest", - "npm rm jest", - "yarn remove jest", - "pnpm remove vitest", - "npm update jest", - "yarn upgrade jest", - "poetry update pytest", - "pip download pytest", - "composer require --dev phpunit/phpunit", - "pip install \\\n pytest", - "npm install --save-dev \\\n jest \\\n vitest", - "go vet ./internal/testutil/...", - "go build ./cmd/testserver", - "go generate ./testdata/...", - "bazel build //testing/...", - "bazel build //pkg:testlib", - "node scripts/testbed.js", - "cargo build -p testcontainers", - "gradle build -x test", - "./gradlew build -x integrationTest", - "./gradlew compileTestJava", - "./gradlew :app:compileDebugUnitTestKotlin", - "./gradlew processTestResources", - "gradle build -PskipTests", - "gradle assemble -DskipTests", - "mvn package -Dmaven.test.skip=true", - // A build tool's target of a verb's name hides the run after it. - "make install test", - "make ci test", - "mvn clean install test", - ]) { - assert.equal(testedSince(bash(command, ""), since), false, command); - } - assert.equal(testedSince(call("Read", { command: SUITE }), since), false); - assert.equal(testedSince(bash(SUITE, PASSED, { isSidechain: true }), since), false); - // A row of another type that copies the call is not the session's call. - assert.equal(testedSince([{ ...bash(SUITE, PASSED)[0], type: "api-request-blob" }], since), false); - // A run that finished before the change does not count; one with no dated result does. - const before = bash(SUITE, PASSED); - assert.equal(testedSince(before, Date.parse(before[1].timestamp) + 1), false); - assert.equal(testedSince(before.slice(0, 1), Date.parse(before[1].timestamp) + 1), true); - // A Codex rollout's shell call counts by its output row's time. - const item = (payload, ms) => ({ type: "response_item", timestamp: new Date(ms).toISOString(), payload }); - const rollout = [ - item( - { type: "function_call", name: "shell", call_id: "c1", arguments: '{"command":["pytest","tests","-q"]}' }, - 1e12, - ), - item({ type: "function_call_output", call_id: "c1", output: "3 passed in 0.10s" }, 1e12 + 1000), - ]; - assert.equal(testedSince(rollout, 1e12 + 500), true); - assert.equal(testedSince(rollout, 1e12 + 1500), false); - // Its arguments hold an argv, a shell wrapper's script or one string. - const shell = (args) => [item({ type: "function_call", name: "shell", call_id: "c2", arguments: args }, 1e12)]; - for (const args of [ - '{"command":["go","test","./..."]}', - '{"command":["npm","test"]}', - '{"command":["bash","-lc","make test-unit"]}', - '{"cmd":"npm run test"}', - "go test ./...", - ]) { - assert.equal(testedSince(shell(args), 1e12), true, args); - } - assert.equal(testedSince(shell('{"command":["npm","install","x@latest"]}'), 1e12), false); - // The shell tool counts under each name the client gives it; another tool that names a runner does not. - const named = (name) => [ - item({ type: "function_call", name, call_id: "c3", arguments: '{"command":"pytest -q"}' }, 1e12), - ]; - for (const name of ["exec", "exec_command", "shell", "shell_command", "local_shell", "container.exec"]) { - assert.equal(testedSince(named(name), 1e12), true, name); - } - assert.equal(testedSince(named("apply_patch"), 1e12), false); - assert.equal(testedSince([], 0), false); -}); - -test("the last code change is the most recently written code file that can be read", () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-last-code-")); - try { - for (const [file, at] of [ - ["a.py", 1e12], - ["b.py", 1e12 + 5000], - ["constraints.txt", 1e12 + 6000], - ["requirements/dev.txt", 1e12 + 6000], - ["tests/fixtures/expected.txt", 1e12 + 6000], - ["testdata/golden.txt", 1e12 + 6000], - ["docs/requirements.txt", 1e12 + 6000], - ["docs/releases/5.2.txt", 1e12 + 9000], - ["CHANGES.txt", 1e12 + 9000], - ["README.txt", 1e12 + 9000], - ["README.md", 1e12 + 9000], - ["notes.markdown", 1e12 + 9000], - ["guide.rst", 1e12 + 9000], - ["manual.asciidoc", 1e12 + 9000], - ["CHANGELOG", 1e12 + 9000], - ]) { - fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); - fs.writeFileSync(path.join(dir, file), "x\n"); - fs.utimesSync(path.join(dir, file), new Date(at), new Date(at)); - } - assert.equal(lastCodeChange(dir, ["b.py", "a.py", "deleted.py"]), 1e12 + 5000); - // Documentation and prose are left out: by extension, by a changelog's name, and a .txt file by a note's - // name or under a docs directory. - for (const file of [ - "README.md", - "notes.markdown", - "guide.rst", - "manual.asciidoc", - "CHANGELOG", - "docs/releases/5.2.txt", - "CHANGES.txt", - "README.txt", - ]) { - assert.equal(lastCodeChange(dir, ["a.py", "b.py", file]), 1e12 + 5000, file); - } - // Any other .txt file is code: a requirements file, also under docs, a test fixture. - for (const file of [ - "constraints.txt", - "requirements/dev.txt", - "tests/fixtures/expected.txt", - "testdata/golden.txt", - "docs/requirements.txt", - ]) { - assert.equal(lastCodeChange(dir, ["a.py", file]), 1e12 + 6000, file); - } - assert.equal(lastCodeChange(dir, ["README.md", "deleted.py"]), 0); - } finally { - fs.rmSync(dir, { recursive: true, force: true }); - } -}); - -test("the hook holds the stop of a session that ran no test since its last code change; LOOM_TEST_GATE=block also holds one whose named tests did not run on the final tree", async () => { +test("the hook holds no stop by default; LOOM_TEST_GATE=block holds one whose named tests did not run on the final tree", async () => { const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-gate-hook-"))); const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-gate-hook-tmp-"))); - for (const f of ["src/a.py", "src/b.py", "tests/test_a.py", "docs/guide.md"]) { + for (const f of ["src/a.py", "src/b.py", "tests/test_a.py"]) { fs.mkdirSync(path.join(dir, path.dirname(f)), { recursive: true }); fs.writeFileSync(path.join(dir, f), "def f():\n return 1\n"); } @@ -1172,41 +979,25 @@ test("the hook holds the stop of a session that ran no test since its last code try { const ran = [change, bash(SUITE, PASSED)]; const no = [said("Fix f. Do not run the test suite."), change]; - // The default: a change with no test run since it is held once, with the tests to run. - assert.match(await stop("d-never-ran", [change], ""), /"decision":"block".*pytest tests\/test_a\.py/); - assert.equal(await stop("d-never-ran", [change], ""), ""); - assert.match(await stop("d-ran-before", [ranBefore, change], ""), /"decision":"block"/); - assert.match(await stop("d-only-read", [change, bash("cat tests/test_a.py", "")], ""), /"decision":"block"/); - // Any run since the change passes: one that failed, ran another file, or was followed by more commands. - const asked = requests.length; - assert.equal(await stop("d-ran", ran, ""), ""); - assert.equal(await stop("d-failed", [change, bash("pytest tests/test_b.py -x | grep FAILED", "")], ""), ""); - assert.equal(await stop("d-then-more", [...ran, bash("rm src/helper.py", ""), bash("git diff", "")], ""), ""); - // A documentation file written after the run is not a code change. - const later = (file) => { - const edited = call("Edit", { file_path: path.join(dir, file) }, "updated"); - fs.appendFileSync(path.join(dir, file), "def h():\n return 3\n"); - touch(file, new Date(edited[1].timestamp)); - return edited; - }; - assert.equal(await stop("d-doc-after-run", [...ran, later("docs/guide.md")], ""), ""); - assert.equal(requests.length, asked, "a stop that passes on a test run asks the server nothing"); - // A second code file written after the run is: the run saw the first one only. - assert.match(await stop("d-run-between", [...ran, later("src/b.py")], ""), /"decision":"block"/); - execFileSync("git", ["checkout", "-q", "--", "src/b.py", "docs/guide.md"], { cwd: dir }); - assert.equal(await stop("d-ruled-out", no, ""), ""); - assert.match(await stop("never-ran", [change]), /"decision":"block".*pytest tests\/test_a\.py/); - assert.equal(await stop("never-ran", [change]), ""); - // A Codex rollout that changed the file through its shell tool is held in either mode, under each name of - // that tool; a call of another tool that names the file is no change. + // A Codex rollout that changed the file through its shell tool; a call of another tool that names the file + // is no change. const rollout = (name) => [ { type: "response_item", payload: { type: "function_call", name, arguments: '{"command":"sed -i s/1/2/ src/a.py"}' }, }, ]; + // The default holds no stop and asks the server nothing: a change with no test run, a run before the + // change, a rollout's change. + assert.equal(await stop("d-never-ran", [change], ""), ""); + assert.equal(await stop("d-ran-before", [ranBefore, change], ""), ""); + assert.equal(await stop("d-codex", rollout("shell_command"), ""), ""); + assert.deepEqual(requests, []); + // LOOM_TEST_GATE=block holds each of them, once per change. + assert.match(await stop("never-ran", [change]), /"decision":"block".*pytest tests\/test_a\.py/); + assert.equal(await stop("never-ran", [change]), ""); + assert.match(await stop("ran-before", [ranBefore, change]), /"decision":"block"/); assert.match(await stop("codex-block", rollout("shell_command")), /"decision":"block"/); - assert.match(await stop("codex-default", rollout("shell_command"), ""), /"decision":"block"/); assert.equal(await stop("codex-other-tool", rollout("read_file")), ""); // An untracked file whose name git would quote or a trim would cut does not hide the tree's age. const odd = process.platform === "win32" ? " naïve.txt" : ' na"ï\tve.txt'; @@ -1465,8 +1256,6 @@ test("a changed file's tests ride the tool call that changed it, once", async () write("src/old.py", "# a note\n"); assert.equal(await shell("echo '# a note' >> src/old.py"), null); assert.ok(!asked.some((a) => a.endsWith("src/old.py")), asked.join(", ")); - // This transcript shows no tool call, so the stop has no change of the session's to hold. - assert.equal(await run("loom-test-gate", "Stop", {}), null); // LOOM_TEST_GATE=block: nothing at edit time, the radius counts its tests, the stop is held. const blocking = { LOOM_TEST_GATE: "block" }; write("src/a.py", "def h():\n return 3\n"); @@ -1489,7 +1278,7 @@ test("a changed file's tests ride the tool call that changed it, once", async () assert.doesNotMatch(context(radius), /Loom tests for/); const stopped = await run("loom-test-gate", "Stop", { session_id: "b", transcript_path: "" }, blocking); assert.equal(stopped.decision, "block"); - // With no transcript nothing shows that the session ran no test: the default holds no stop. + // The same dirty tree by default: the stop is not held. assert.equal(await run("loom-test-gate", "Stop", { session_id: "n", transcript_path: "" }), null); // LOOM_TEST_GATE=off: neither. const off = { LOOM_TEST_GATE: "off" }; diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index f5135f747ff..3d844d9c56e 100644 --- a/integrations/codex-plugin/.codex-plugin/plugin.json +++ b/integrations/codex-plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "loom", - "version": "1.2.73", + "version": "1.2.74", "description": "Shared long-term memory and code intelligence for Codex, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/codex-plugin/hooks/loom-test-gate.mjs b/integrations/codex-plugin/hooks/loom-test-gate.mjs index 532b2be3784..27ab1e2cac7 100644 --- a/integrations/codex-plugin/hooks/loom-test-gate.mjs +++ b/integrations/codex-plugin/hooks/loom-test-gate.mjs @@ -11,30 +11,25 @@ // edited. An edit tool's call gets the same line from loom-blast-radius, the // one hook wired for those tools. // -// Stop: if the working tree has uncommitted changes THIS SESSION made -// in a loom-indexed repo, ask `code.test_gate` for the change's obligations -// (tests to run, untested touched functions) and block the stop ONCE per -// distinct change with a reason that names them. "This session's" is read -// from the transcript: dirty paths an edit tool targeted or a shell command -// named, written since the session began (by the file's modification time); -// a tree left dirty before the session does not gate a turn that changed -// nothing. By default any test run since the session's last code change -// lets the stop pass, whatever it ran and however it went (`testedSince`, -// `lastCodeChange` in lib/test-gate.mjs): the stop is held for a session -// that ran no test since its last code change, and nothing is asked of the -// server for one that ran some. A documentation file changed after the run -// holds nothing. +// At Stop the default does nothing: the line above informs, and the end of a +// session is never held. The script exits before it reads its input. // -// With LOOM_TEST_GATE=block nothing is named at edit time, and the stop -// passes only when a Claude Code transcript shows the named tests ran on the -// tree as it stands (`runAnswered`); a Codex rollout answers nothing there, -// so its stop blocks. +// With LOOM_TEST_GATE=block nothing is named at edit time, and the Stop +// holds: if the working tree has uncommitted changes THIS SESSION made in a +// loom-indexed repo, ask `code.test_gate` for the change's obligations (tests +// to run, untested touched functions) and block the stop ONCE per distinct +// change with a reason that names them. "This session's" is read from the +// transcript: dirty paths an edit tool targeted or a shell command named, +// written since the session began (by the file's modification time); a tree +// left dirty before the session does not gate a turn that changed nothing. +// The stop passes only when a Claude Code transcript shows the named tests +// ran on the tree as it stands (`runAnswered`); a Codex rollout answers +// nothing there, so its stop blocks. // // Fail-open everywhere: no token, not an indexed repo, clean tree, nothing // of the tree touched this session, server down, second stop on the same -// change — the agent stops as normal. Without a transcript path the default -// holds no stop, and LOOM_TEST_GATE=block takes the whole dirty tree as the -// change. +// change — the agent stops as normal. Without a transcript path +// LOOM_TEST_GATE=block takes the whole dirty tree as the change. // LOOM_TEST_GATE=off disables both; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. import crypto from "node:crypto"; @@ -65,13 +60,11 @@ import { gateMode, gatePayload, gateSignature, - lastCodeChange, newestChange, renderGate, runAnswered, sessionScope, sessionStart, - testedSince, testsIn, writtenSince, } from "../lib/test-gate.mjs"; @@ -97,7 +90,8 @@ async function advise(payload, token) { } async function main() { - if (MODE === "off" || (AFTER_TOOL && MODE === "block")) { + // The line at edit time is the default's, the hold at Stop is LOOM_TEST_GATE=block's. + if (MODE !== (AFTER_TOOL ? "advise" : "block")) { scheduleExit(0); return; } @@ -140,11 +134,6 @@ async function main() { scheduleExit(0); return; } - // The default holds the stop of a session whose transcript shows no test run since its last code change. - if (MODE === "advise" && (!transcript || testedSince(rows, lastCodeChange(root, changed)))) { - scheduleExit(0); - return; - } const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); if (!repo.indexed) { scheduleExit(0); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 5457eb9f899..1bdfb76cfd2 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -7,25 +7,22 @@ // the index links no test to when it has no test to name; once per file per // session (`adviceFiles`, `adviceLines`). // -// At Stop it holds a session that ran no test since its last code change. -// When the agent is about to stop with uncommitted changes in a -// loom-indexed repo, it asks -// `code.test_gate` what the change obliges: the tests that reach -// it (evidence-ordered, with a run command when derivable) and the touched -// functions no test reaches. If either list is non-empty and this exact -// change has not been gated yet this session, block the stop ONCE with a -// reason that names them: the tests are named before "done", not discovered -// in review. The second stop on the -// same change passes: the agent has seen the obligation and either ran the -// tests or chose not to, and a gate that nags is a gate that gets disabled. -// A block costs the session one more model request, so by default any test -// run since the last write to a changed code file lets the stop pass before -// anything is asked (`testedSince`, `lastCodeChange`): which tests it ran -// and how they went is the agent's to -// judge, and a hook that reads shell text to decide it blocks sessions that -// ran them. With LOOM_TEST_GATE=block nothing is named at edit time and the -// stop passes only when the transcript shows the named tests ran on the tree -// as it stands (`runAnswered`). +// At Stop the default does nothing: the line informs, and whether the tests +// ran and how they went is the agent's to judge. A rule that decides it from +// shell text holds sessions that ran them and passes sessions that did not. +// +// With LOOM_TEST_GATE=block nothing is named at edit time and the stop is +// held. When the agent is about to stop with uncommitted changes in a +// loom-indexed repo, the gate asks `code.test_gate` what the change obliges: +// the tests that reach it (evidence-ordered, with a run command when +// derivable) and the touched functions no test reaches. If either list is +// non-empty and this exact change has not been gated yet this session, it +// blocks the stop ONCE with a reason that names them: the tests are named +// before "done", not discovered in review. The second stop on the same +// change passes: the agent has seen the obligation and either ran the tests +// or chose not to, and a gate that nags is a gate that gets disabled. The +// first stop passes only when the transcript shows the named tests ran on +// the tree as it stands (`runAnswered`). // // The change is the session's, not the tree's: `sessionScope` keeps only // the dirty paths the transcript shows this session edited or named in a @@ -56,9 +53,9 @@ import { parseLines, readRange } from "./transcript.mjs"; const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "str_replace_editor", "apply_patch"]); /** What the gate does, from LOOM_TEST_GATE: "advise" names an edited file's - * tests on the tool call that edited it and holds the stop of a session that - * ran no test since its last code change (unset, or any on-word); "block" names - * nothing and holds the stop until the named tests ran; "off" does neither. */ + * tests on the tool call that edited it and holds no stop (unset, or any + * on-word); "block" names nothing and holds the stop until the named tests + * ran; "off" does neither. */ export function gateMode(env = process.env) { if ( String(env.LOOM_TEST_GATE ?? "") @@ -628,126 +625,10 @@ function runsHere(command, run) { return at >= 0 && /^(?:[\s;|&)]|$)/.test(command.slice(at + run.length)) && ranHere(command.slice(0, at)); } -// A shell command that starts a test runner, wrapped or piped in any way: a -// program `code.test_gate` names a run with or a common other one; a build -// tool with an argument in which `test` or `tests` follows no letter and no -// lower-case letter follows it (`make test-unit`, `npm run test`, `node -// --test`, `gradle :app:test`, `gradlew testDebugUnitTest`); a tool that runs -// a target or a script by its name, with a name that starts with `test` -// (`make testall`, `npm run testci`); or Gradle with a task that ends in -// `Test` after a lower-case letter (`gradlew integrationTest`). `import -// pytest`, `pytest.raises`, `make latest`, `go vet ./internal/testutil/...`, -// `cargo build -p testcontainers` and `gradlew compileTestJava` are not -// runs. A command that only mentions a runner counts: what is read is -// whether the session ran a test at all. -// -// After one of these verbs earlier in the simple command the name is a -// package: `pip install -U pytest`, `npm i -D @types/jest`, `yarn remove -// jest`, `go get github.com/stretchr/testify`. A flag is no verb: `npx -// --no-install jest` and `docker run --rm app pytest` run. A build tool's -// target of a verb's name hides the run after it: `make install test` is -// read as none. -const FETCHED = String.raw`\s(?:(?:un)?install|add|i|ci|get|remove|rm|update|upgrade|download|require)\s[^\n;|&]*`; -// What a build tool is told to leave out is no run, for every tool of the -// list: the word after `-x`, where Gradle takes a task to exclude (`gradle -// build -x test`), and `test.skip`, Maven's property (`mvn package -// -Dmaven.test.skip=true`). -const LEFT_OUT = String.raw`\s-x\s+\S*`; -const RUNNER = new RegExp( - String.raw`(? RUNNER.test(command.replace(/\\\n/g, "")); - /** True for the name of a Codex rollout's shell tool, under any of the names * `normalizeToolName` folds onto Bash. */ const rolloutShell = (name) => name === "exec" || normalizeToolName(name) === "Bash"; -/** The command text of a Codex rollout's shell call: its `arguments` JSON - * holds a string or an argv (`["go","test"]`), whose words no space joins. */ -function rolloutCommand(call) { - let input = call.input ?? call.arguments; - if (typeof input === "string") { - try { - input = JSON.parse(input); - } catch { - return input; - } - } - return commandText(input) || (typeof input === "string" ? input : ""); -} - -/** - * True when the transcript holds a shell command that starts a test runner - * (`RUNNER`) and finished at or after `since` (epoch ms), or has no dated - * result: Claude Code rows and Codex rollout calls, sidechains skipped. Its - * output is not read, so a run that failed or was piped into `grep` counts. - * So does one between `git stash` and `git stash pop` in the same command; a - * pop in a later command rewrites the changed files after the run. - */ -export function testedSince(objs, since) { - const done = new Map(); - const runs = []; - for (const o of objs || []) { - const at = Date.parse((o && o.timestamp) || ""); - if (o?.type === "response_item") { - const call = o.payload || {}; - if (/_output$/.test(call.type)) done.set(call.call_id, at); - else if (rolloutShell(call.name) && startsRunner(rolloutCommand(call))) { - runs.push(call.call_id); - } - continue; - } - const content = o && !o.isSidechain && o.message && o.message.content; - for (const b of Array.isArray(content) ? content : []) { - if (o.type === "user" && b?.type === "tool_result") done.set(b.tool_use_id, at); - else if ( - o.type === "assistant" && - b?.type === "tool_use" && - ["Bash", "PowerShell"].includes(normalizeToolName(b.name)) && - startsRunner(commandText(b.input)) - ) { - runs.push(b.id); - } - } - } - return runs.some((id) => !(done.get(id) < since)); -} - -// Documentation and prose by name: a test run answers no change to one. A -// `.txt` file is code (a requirements file, a build list, a test fixture) -// unless its name or a `docs` directory above it says prose: `CHANGES.txt`, -// `docs/releases/5.2.txt`. A requirements or a constraints file under `docs` -// stays code. -const PROSE = /\.(?:md|mdx|markdown|rst|adoc|asciidoc)$/i; -const CHANGELOG = /(?:^|\/)(?:CHANGELOG|CHANGES|HISTORY|NEWS)$/; -const PROSE_TXT = - /(?:^|\/)(?:changelog|changes|history|news|readme|license|notice|authors|docs?\/(?!.*(?:requirements|constraints)).*)\.txt$/i; -const isProse = (file) => CHANGELOG.test(file) || PROSE.test(file) || PROSE_TXT.test(file); - -/** The newest modification time, in epoch ms, among the code files of - * `files` under `root`: a test run that finished since then saw each of - * them as it stands. A documentation or prose file (`isProse`) is left out, - * so an edit to one after the run holds no stop, and so is a file that - * cannot be read (a deleted one). 0 when none is left. */ -export function lastCodeChange(root, files) { - let last = 0; - for (const file of files) { - if (isProse(file)) continue; - try { - last = Math.max(last, fs.statSync(path.join(root, file)).mtimeMs); - } catch { - // A deleted file has no time of its own. - } - } - return last; -} - // pytest's last line, whose order is fixed: failed, passed, skipped, // deselected, xfailed, xpassed, warnings, errors. A whole line starts at // "failed" or "passed" and names nothing deselected, so a -k subset is not From e790a409230472c7cc14611652ac02e04ca7cb93 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 19:54:27 +0530 Subject: [PATCH 2/4] Both plugin manifests hold 1.2.76, a version no other open pull request uses Two other open pull requests moved to 1.2.74 and 1.2.75 while this one was being opened, and two pull requests with one version ship only the first. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- integrations/claude-code-plugin/.claude-plugin/plugin.json | 2 +- integrations/codex-plugin/.codex-plugin/plugin.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 74c1c0b749a..3581fa14a07 100644 --- a/integrations/claude-code-plugin/.claude-plugin/plugin.json +++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "loom", "displayName": "ClickHouse Loom", - "version": "1.2.74", + "version": "1.2.76", "description": "Shared long-term memory and code intelligence for Claude Code, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index 3d844d9c56e..41506ef63cd 100644 --- a/integrations/codex-plugin/.codex-plugin/plugin.json +++ b/integrations/codex-plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "loom", - "version": "1.2.74", + "version": "1.2.76", "description": "Shared long-term memory and code intelligence for Codex, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" From 5041d07c8ba5fb3fe0f5e1eefa54baf216a1c312 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 20:23:24 +0530 Subject: [PATCH 3/4] The default hold at Stop stays, and a shell line of any length is read in linear time The two commits before this one removed the default hold. A session that changed code and ran no test would then end unheld, and no measured cost needed that: the default already held none of the recorded sessions. This commit puts the hook, the library, their tests and the documentation back as they were, so by default a session that ran no test since its last code change is held once, as before. What was wrong is the read of one long line. Each span of the runner pattern ran to the end of the simple command from every tool word, and the verb lookbehind ran back from every `test`, so `x install` followed by `make test` 2,000 times cost 17 s of CPU in one synchronous match, and eight times more at each doubling. Each span now ends after 256 characters: a tool and its argument, and a verb and the name after it, are read no further apart than that. That line now costs under a millisecond. The costliest line found costs 0.08 s at 20,000 characters, 0.77 s at 200,000 and 7.3 s at 2,000,000. No verdict changes on the commands of the existing tests or on 50,064 recorded shell commands. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 27 +- integrations/claude-code-plugin/README.md | 6 +- .../claude-code-plugin/hooks/HOOKS.md | 38 ++- .../hooks/loom-test-gate.mjs | 45 +-- .../claude-code-plugin/lib/test-gate.mjs | 162 +++++++++-- .../tests/code-hooks-failopen.test.mjs | 24 +- .../tests/test-gate.test.mjs | 259 ++++++++++++++++-- .../codex-plugin/hooks/loom-test-gate.mjs | 45 +-- integrations/codex-plugin/lib/test-gate.mjs | 162 +++++++++-- 9 files changed, 639 insertions(+), 129 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index c40b25ceba0..26c5ccc123e 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -60,9 +60,10 @@ end of this section are the exceptions. The plugin sends: against `HEAD`, to `code.impact` (`LOOM_BLAST_RADIUS=off` stops it); - the first time a session changes a file in an indexed checkout, with an edit tool or a shell command that names it, the outline of that file's uncommitted diff, to - `code.test_gate` (`LOOM_TEST_GATE=off` stops it). With `LOOM_TEST_GATE=block` the - outline goes at Stop instead, for the files the session changed, or for the whole - uncommitted tree when the client gives no transcript. A diff's outline, up to 200,000 + `code.test_gate` (`LOOM_TEST_GATE=off` stops it), and once more at the Stop of a + session that ran no test since its last code change, for the files it changed. With + `LOOM_TEST_GATE=block` the outline goes at Stop only, for the files the session changed, + or for the whole uncommitted tree when the client gives no transcript. A diff's outline, up to 200,000 characters, is its file paths, its hunk line ranges and, in a code file, the last identifier before the first `(` of each hunk header's context, usually the enclosing function's name. Git takes that context from a line above the hunk in the old file, @@ -549,7 +550,7 @@ The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. | PostToolUse, PostToolUseFailure (any tool) | `loom-capture.mjs` | one episodic observation per tool call (`observe.record`); a failed call is typed `error` | none | | Stop, SessionEnd | `loom-conversation.mjs` | appends new chat turns to the conversation plane (`conversation.append`) | `LOOM_CAPTURE_CONVERSATIONS=false` | | Stop | `loom-usage.mjs` | posts the session's token usage to `cost.record_turns` | `LOOM_USAGE=off` | -| Stop | `loom-test-gate.mjs` | nothing by default: the gate never holds the end of a session. With `LOOM_TEST_GATE=block`, for changes this session made, blocks "done" once with the tests `code.test_gate` says the change obliges, unless your latest prompt ends with "Do not run the tests" or pytest ran the named tests to its summary line with no edit or run since ([the test gate](#the-test-gate)) | unset, or `LOOM_TEST_GATE=off` | +| Stop | `loom-test-gate.mjs` | for changes this session made, blocks "done" once with the tests `code.test_gate` says the change obliges, unless a test runner ran since the last code change or your latest prompt ends with "Do not run the tests"; with `LOOM_TEST_GATE=block`, unless pytest ran the named tests to its summary line and nothing was edited or run since ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | | Stop | `loom-validate-gate.mjs` | blocks once when `namespace.validate` finds errors or warnings on the memory keys this session wrote | `LOOM_VALIDATE_GATE=off` | | Stop | `loom-namespace-health.mjs` | one line when `namespace.audit` finds a critical misuse of the namespace, pointing at the `loom-optimize` skill; the audit is asked once per session, by the first prompt's detached process, and told at a Stop | `LOOM_NAMESPACE_HEALTH=off` | | Stop, PreCompact | `loom-working-memory.mjs` | refreshes the working-memory note (`session:`): goal, git status, files edited, last reply | `LOOM_WORKING_MEMORY=off` | @@ -656,7 +657,7 @@ Beyond the off switches in the table: | `LOOM_PROMPT_PACK_MIN_CONF` | unset | a `retrieval_confidence` gate for search pointers (low risk is 0.7 up); unset, that label | | `LOOM_FILE_CONTEXT_TTL_MIN` | `30` | minutes before the same file's context is fetched again | | `LOOM_BLAST_DEPTH` | `1` | `code.impact` depth for the blast-radius line | -| `LOOM_TEST_GATE` | unset | unset: a line at edit time, no stop held; `block`: no line, the stop held; `off`: no gate | +| `LOOM_TEST_GATE` | unset | `block`: no line at edit time, and a stop passes only on the named tests; `off`: no gate | | `LOOM_TEST_GATE_DEPTH` | `2` | hops the test gate follows (1–3) | | `LOOM_OBSERVE_DEDUPE_S` | `60` | a repeated read in this window is not observed again; `0` disables | | `LOOM_OBSERVE_SKIP_TOOLS` | a built-in list | comma-separated tool names (with `*` globs) that produce no observation | @@ -689,16 +690,22 @@ Loom tests for src/app/router.py: .venv/bin/python -m pytest tests/test_router.p never runs the tests has still been told which ones they are. A file is asked about at its first change only, so a function changed later in the same file is not named. A test that shell command itself runs is not named on its own result. -- **At the end of the session.** Nothing. By default the gate informs and never holds - the stop. Which tests ran and how they went cannot be read reliably from shell - commands, so that judgement stays with the agent and with CI. +- **At the end of the session.** A session that ran no test since its last code change + is held once per distinct change, with the tests the change obliges and the functions + the index links no test to. A held stop costs the session one more model request, so + any test run since that change lets the stop pass: a shell command that starts a test + runner and finished no earlier than the newest write among the code files the session + changed. A documentation or prose file (`.md`, `.rst`, a changelog, a `.txt` file under `docs/`) + written after the run holds nothing. The gate reads that command for a runner's name only. Which tests ran and how they went cannot be read + reliably from shell commands, so that judgement stays with the agent and with CI. The + plugin README lists the runners under **Stops that pass**. To hold the stop until the named tests ran on the final tree, set `LOOM_TEST_GATE=block` in the environment Claude Code starts in. The gate then prints nothing at edit time, and blocks "done" once per distinct change unless the transcript already answers the ask; the plugin README lists the exact conditions under **Answered stops**. That mode also holds a -session that ran the tests in a way the gate does not read, and each held stop costs the -session one more model request. `LOOM_TEST_GATE=off` turns the gate off. +session that ran the tests in a way the gate does not read. `LOOM_TEST_GATE=off` turns +the gate off. ## The code shunt diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 1d8e1c1dc1a..51e88aecd7d 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -198,7 +198,7 @@ the duplicate, run `claude mcp remove -s user`. | `PostToolUse` (Bash / PowerShell) | `loom-test-gate.mjs` | **The tests are named when the file changes.** After a shell command in a loom-indexed repo, asks `code.test_gate` about each file the command changed (a dirty path it names, written since the session began) and attaches **one line** per file with the command of the tests the index links to it, or of the file itself when it is a test: `Loom tests for src/a.py: .venv/bin/python -m pytest tests/test_a.py`. Once per file and once per test per session, on the tool result, so it costs no model request; an edit tool's call gets the same line from `loom-blast-radius.mjs`. A file with no such test gets the changed functions the index links no test to: `Loom tests for src/a.py: the index links no test to Router::match`. A comment-only change names nothing (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | | `UserPromptSubmit` | `loom-prompt-recall.mjs` | **Default `first`**: one bounded recall on the first qualifying prompt of a session, including empty or abstaining answers. Clear named code-only questions skip default recall without consuming the attempt; mixed memory requests still qualify. `LOOM_PROMPT_RECALL=on` for every prompt, `off` to disable. One `context.pack` per prompt restricted to `memories`, `decisions`, `procedures` with the prompt as the query; injects the plane-tagged blocks the session has not seen, only when memory is not abstaining and `retrieval_confidence ≥ 0.5`, capped at 1,200 chars (`LOOM_PROMPT_RECALL_MAX_CHARS`). The memory-side sibling of the prompt pack: active retrieval — the model gets what memory knows about the prompt without asking — done per prompt, never per tool turn. | | `UserPromptSubmit` | `loom-prompt-pack.mjs` | On by default (`LOOM_PROMPT_PACK=off` turns it off). One bounded lookup: `code.symbol`, `code.callers` or `code.impact` for an explicit named question, otherwise `code.search` (top 3, no bodies). Self-contained requests, local-only changes and explicit memory questions skip code retrieval. Search emits only where the index labels its own answer low-risk (or, with `LOOM_PROMPT_PACK_MIN_CONF` set, from that confidence), and without abstention; its pointers are candidates, and nothing tells the model to stop searching; typed answers preserve ambiguity and static-analysis limits. Named implementation or behavior questions request a whole definition body within 600 server-budget tokens; location/signature requests stay pointer-only and oversized bodies stay elided. No fallback request follows an empty typed answer. Pointers are deduplicated within the current answer, so later prompts can receive changed evidence. | -| `Stop` | `loom-test-gate.mjs` | **Does nothing by default.** The test gate informs at edit time and never holds the end of a session: at a Stop the script exits before reading input. **`LOOM_TEST_GATE=block` holds the stop**: with uncommitted changes **this session made** in a loom-indexed repo (the dirty paths the transcript shows an edit tool targeted or a shell command named, written since the session began, by the file's modification time; a tree left dirty before the session gates nothing, even when a command reads or runs its files), asks `code.test_gate` what the change obliges — the tests that reach it, in evidence order with a `run` command when the harness is derivable, and the touched functions no test reaches — and blocks the stop **once** per distinct change with a reason that names them. The second stop on the same change passes, and so does a first stop the transcript already answers (**Answered stops**, below). `LOOM_TEST_GATE=off` disables. | +| `Stop` | `loom-test-gate.mjs` | **Holds a session that ran no test since its last code change.** With uncommitted changes **this session made** in a loom-indexed repo (the dirty paths the transcript shows an edit tool targeted or a shell command named, written since the session began, by the file's modification time; a tree left dirty before the session gates nothing, even when a command reads or runs its files), asks `code.test_gate` what the change obliges — the tests that reach it, in evidence order with a `run` command when the harness is derivable, and the touched functions no test reaches — and blocks the stop **once** per distinct change with a reason that names them. The second stop on the same change passes. By default any test run since the last code change lets the stop pass, and nothing is asked (**Stops that pass**, below); with `LOOM_TEST_GATE=block` only a run of the named tests does (**Answered stops**, below). `LOOM_TEST_GATE=off` disables. | | `Stop` | `loom-validate-gate.mjs` | **Compile green before done**: collects the memory keys this session wrote from the transcript, asks `namespace.validate` for a report scoped to exactly those keys, and blocks the stop **once** per distinct key set with the error and warning findings that name them (a conflict you opened, a fact whose `valid_to` has passed, an attestation your edit made stale) and each check's remedy. `info` findings never block; the second stop on the same keys passes. `LOOM_VALIDATE_GATE=off` disables. | | `Stop` | `loom-namespace-health.mjs` | **The store tells you when the namespace is misused**: once per session, one `namespace.audit` over the last day (no samples) for the session's namespace, asked by the first prompt's detached process so that a stop does not wait for it (a stop asks in place only when that process died before its answer); when it carries a critical finding — exact-key reads dwarfing searches, double-encoded values, rows the embedder gave up on, leases in the memory plane — you get **one line** naming the codes and `/loom-optimize`, once per session, at the first stop that finds the verdict, as a block-once reason (the one channel a Stop hook has to the model). Healthy namespace, no token, slow or down server: nothing. The same summary rides `context.pack` as the `namespace_health` section at session start. `LOOM_NAMESPACE_HEALTH=off` disables. | | `Stop` | `loom-usage.mjs` | Posts the session's own model usage (input, cache read, cache creation by TTL, output; deduped by message id, sidechains skipped) to `cost.record_turns`; the **server** prices it into `loom.agent_turn_usage` from the same table it prices its own upstream spend with. Turns "did loom make this session cheaper" into a standing series instead of a hand-run paired experiment. Needs a writer token. `LOOM_USAGE=off` disables. | @@ -215,9 +215,9 @@ the duplicate, run `claude mcp remove -s user`. **Tests at edit time.** The test gate names a file's tests on the tool call that changes it, where the agent is still working on the file. For a source file they are the tests the index links to it through its name, the test map or the call graph, each of them present in the checkout, with the tests that have no known runner listed by path; for a test file, the file's own command. A file with no test to name in the checkout gets the changed functions the index links no test to instead (`the index links no test to Router::match`), worded as the index's view, because its call graph is a floor. A file is asked about once per session, at its first change, so a function changed later in the same file is not named; a file the server gave no answer for is asked about once more, at the next call that names it; at most four files are asked about per tool call. A test is named once per session, so the test you edit after its source file adds no second line. A test the tool call's own command runs is not named on the result of that run: its command stands there whole, in this checkout, so `pytest tests/test_a.py::test_one`, `docker exec app pytest tests/test_a.py` and `echo "pytest tests/test_a.py"` still get the line. -**The end of a session.** By default the test gate informs and never holds: it names a file's tests when the file changes, and the stop passes whatever the session ran. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads. A rule that holds the stop on that reading holds sessions that did the work, at one more model request each, and a rule that passes on it passes sessions that ran nothing. That judgement stays with the agent and with CI. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. In a Codex rollout that mode reads the session's changes from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), and a rollout that changed a file through any of them is held: a rollout answers nothing. +**Stops that pass.** By default the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time that grows with its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. -**Untested functions.** The index's call graph is a floor: a test may reach a function the graph holds no edge to, such as a constructor the test calls by building the object. Beside tests to run that the checkout has, the reason of a stop held with `LOOM_TEST_GATE=block` therefore lists the functions as the index's view, `the index links no test to: … (the tests named here may still reach it)`. With no such test it reads `no test reaches: …` and asks for a test. +**Untested functions.** The index's call graph is a floor: a test may reach a function the graph holds no edge to, such as a constructor the test calls by building the object. Beside tests to run that the checkout has, the reason of a held stop therefore lists the functions as the index's view, `the index links no test to: … (the tests named here may still reach it)`. With no such test it reads `no test reaches: …` and asks for a test. **Answered stops.** With `LOOM_TEST_GATE=block`, the test gate does not block, and so names no untested function, when it names tests, each of them is in the checkout and the transcript already answers the ask to run them, in one of two ways. Your latest prompt ends with the sentence "Do not run the tests" (also `don't` or `never`, and `tests`, `any tests` or `the test suite`). Or the transcript shows a Bash command that ran pytest on each named test, by its file or a directory above it that is below the checkout root, and whose output holds a whole summary line for each pytest in it: one that counts tests failed or passed and none deselected. A run that failed answers, since the session has read its failures; a collection that stopped at an error (`1 error in 0.12s`) does not, and neither does a line that counts a failure or an error when a pytest in the command has `--exitfirst`, `--maxfail` or a short flag holding `x` (`-x`, `-qx`, also `-rx`), since that run stopped before the files after it. No output answers that holds the line pytest prints above the summary of a run it ended early (`stopping after 1 failures`, `Interrupted: …`), which also shows a limit or `--sw` set in a configuration file or in `PYTEST_ADDOPTS`; `| tail -1` cuts that line, and such a run then answers. The command has no `--ignore`, `--deselect`, `--lf`, `--sw` or `--continue-on-collection-errors` and no quote in pytest's arguments; its runs count from the first pytest after which it runs only pytest, `tail`, `head`, `grep` and `echo` and holds no backquote and no redirect to a file other than `/dev/null`, so the second run of `git stash; pytest tests; git stash pop; pytest tests` answers and no run of `pytest tests; git stash; pytest tests; git stash pop` or of `pytest tests; git diff --stat` does; the transcript shows no edit-tool call and no other Bash or PowerShell call after that; no tracked file is deleted; and no uncommitted or untracked file was modified later. A run of the whole checkout names no path below the root, so a bare `pytest` and `pytest .` do not answer. Before pytest in its simple command only variable assignments, `env`, `timeout`, `uv run` or `poetry run`, an interpreter's `-m` and a path may stand: `python -u -m pytest tests` and `docker exec app pytest tests` do not answer. Runs in several commands add up only while each later command holds nothing before the first of its runs that count but what launches it: one that does anything else first, a `cd` included, answers for its own runs alone. The word after a pytest flag written without `=` is read as that flag's value, not as a path that ran, unless the flag is a cluster of `-q`, `-v`, `-x`, `-s` and `-l`: `pytest --no-header tests` does not answer. Quotes in the rest of the command are not read, so a `|`, `;` or `>` inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` does not answer. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 5f82bcafda9..00b0c2bbfe7 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -110,7 +110,7 @@ receives on stdout. | Stop, detached | loom-capture | session_id | none | observe.crystallize | no token | | Stop, detached | loom-conversation | transcript, last_assistant_message | none | conversation.append via the flusher | `LOOM_CAPTURE_CONVERSATIONS=false` | | Stop, detached | loom-usage | transcript | none | cost.record_turns | `LOOM_USAGE=off` | -| Stop | loom-test-gate | transcript, cwd | JSON block once | none by default: the script exits before it reads its input; with LOOM_TEST_GATE=block, code.test_gate, and the block unless the named tests ran | unset, or `LOOM_TEST_GATE=off` | +| Stop | loom-test-gate | transcript, cwd | JSON block once | code.test_gate, when the transcript shows no test run since the last code change (`testedSince`); with LOOM_TEST_GATE=block, unless the named tests ran | `LOOM_TEST_GATE=off` | | Stop | loom-validate-gate | transcript | JSON block once | namespace.validate | `LOOM_VALIDATE_GATE=off` | | Stop | loom-namespace-health | cwd, session_id | JSON block once | none: tells the stored verdict once (namespace.audit is asked here by a wiring with no detached process, on the first Stop, and when the prompt's ask is overdue) | `LOOM_NAMESPACE_HEALTH=off` | | Stop, detached | loom-working-memory | transcript, cwd | none | working_memory.set when the note changed | `LOOM_WORKING_MEMORY=off` | @@ -390,8 +390,8 @@ record: the run and its usage counters. prompt. A wiring that starts the script at Stop only (Codex, a hand-wired client) asks on the first Stop and waits for the answer. Later stops make no call. -- **loom-test-gate.** Names the tests of a changed file, and holds no - stop unless LOOM_TEST_GATE=block is set. By default it names +- **loom-test-gate.** Names the tests of a changed file, and holds the + stop of a session that ran no test since its last code change. By default it names them when the file changes: after a Bash or PowerShell command (and, through loom-blast-radius, after an edit tool) it takes the dirty paths the call named or targeted that were written @@ -409,20 +409,28 @@ record: the run and its usage counters. (`runsHere`). The line costs no model request. A call that names no unasked dirty file costs one git call and no request; in a checkout the shared cache says is not indexed, no git call either. - At Stop the default does nothing: the script exits before it reads its - input, and no stop is held. - With LOOM_TEST_GATE=block nothing is printed at edit time. At Stop, with - uncommitted changes this session made in a loom-indexed repo (dirty paths - the transcript shows an edit tool targeted or a shell command named, - written since the session's first row; a tree left dirty before the - session gates nothing; in a Codex rollout the calls read are `apply_patch` - and the shell tool under each name `rolloutShell` takes; with no - transcript, the whole dirty tree), it sends the change's paths, hunk + At Stop, with uncommitted changes this session made in a loom-indexed + repo (dirty paths the transcript shows an edit tool targeted or a shell + command named, written since the session's first row; a tree left dirty + before the session gates nothing; in a Codex rollout the calls read are + `apply_patch` and the shell tool under each name `rolloutShell` takes, + in either mode), it sends the change's paths, hunk ranges and function names only (`diffHeaders`) to code.test_gate for its obligations and blocks the stop once per distinct change with a reason - naming them. A Claude Code stop passes only when its transcript already - answers the ask to run the named tests (`runAnswered` in - lib/test-gate.mjs); a Codex rollout answers nothing there. + naming them. By default a stop passes, and asks the server nothing, when + the transcript holds a shell command that starts a test runner and + finished no earlier than the newest write among the changed code files, + documentation and prose left out by name + (`testedSince`, `lastCodeChange`): the command's text is read for a + runner's name only, not for which tests ran or how they went, so a run + that failed, was piped or ran between `git stash` and `git stash pop` + in the same command passes, in a Claude Code transcript or a Codex + rollout; a pop in a later command rewrites the changed files, and that + stop is held. With no transcript the default holds no stop. + With LOOM_TEST_GATE=block nothing is printed at edit time, and a Claude + Code stop passes only when its transcript already answers the ask to run + the named tests (`runAnswered` in lib/test-gate.mjs); a Codex rollout + answers nothing there. LOOM_TEST_GATE=off disables both; LOOM_TEST_GATE_DEPTH sets hops (1-3). - **loom-usage.** Reads the transcript's last MiB, dedupes assistant turns by message id (sidechains skipped) and posts their raw usage counters to diff --git a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs index 27ab1e2cac7..532b2be3784 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -11,25 +11,30 @@ // edited. An edit tool's call gets the same line from loom-blast-radius, the // one hook wired for those tools. // -// At Stop the default does nothing: the line above informs, and the end of a -// session is never held. The script exits before it reads its input. +// Stop: if the working tree has uncommitted changes THIS SESSION made +// in a loom-indexed repo, ask `code.test_gate` for the change's obligations +// (tests to run, untested touched functions) and block the stop ONCE per +// distinct change with a reason that names them. "This session's" is read +// from the transcript: dirty paths an edit tool targeted or a shell command +// named, written since the session began (by the file's modification time); +// a tree left dirty before the session does not gate a turn that changed +// nothing. By default any test run since the session's last code change +// lets the stop pass, whatever it ran and however it went (`testedSince`, +// `lastCodeChange` in lib/test-gate.mjs): the stop is held for a session +// that ran no test since its last code change, and nothing is asked of the +// server for one that ran some. A documentation file changed after the run +// holds nothing. // -// With LOOM_TEST_GATE=block nothing is named at edit time, and the Stop -// holds: if the working tree has uncommitted changes THIS SESSION made in a -// loom-indexed repo, ask `code.test_gate` for the change's obligations (tests -// to run, untested touched functions) and block the stop ONCE per distinct -// change with a reason that names them. "This session's" is read from the -// transcript: dirty paths an edit tool targeted or a shell command named, -// written since the session began (by the file's modification time); a tree -// left dirty before the session does not gate a turn that changed nothing. -// The stop passes only when a Claude Code transcript shows the named tests -// ran on the tree as it stands (`runAnswered`); a Codex rollout answers -// nothing there, so its stop blocks. +// With LOOM_TEST_GATE=block nothing is named at edit time, and the stop +// passes only when a Claude Code transcript shows the named tests ran on the +// tree as it stands (`runAnswered`); a Codex rollout answers nothing there, +// so its stop blocks. // // Fail-open everywhere: no token, not an indexed repo, clean tree, nothing // of the tree touched this session, server down, second stop on the same -// change — the agent stops as normal. Without a transcript path -// LOOM_TEST_GATE=block takes the whole dirty tree as the change. +// change — the agent stops as normal. Without a transcript path the default +// holds no stop, and LOOM_TEST_GATE=block takes the whole dirty tree as the +// change. // LOOM_TEST_GATE=off disables both; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. import crypto from "node:crypto"; @@ -60,11 +65,13 @@ import { gateMode, gatePayload, gateSignature, + lastCodeChange, newestChange, renderGate, runAnswered, sessionScope, sessionStart, + testedSince, testsIn, writtenSince, } from "../lib/test-gate.mjs"; @@ -90,8 +97,7 @@ async function advise(payload, token) { } async function main() { - // The line at edit time is the default's, the hold at Stop is LOOM_TEST_GATE=block's. - if (MODE !== (AFTER_TOOL ? "advise" : "block")) { + if (MODE === "off" || (AFTER_TOOL && MODE === "block")) { scheduleExit(0); return; } @@ -134,6 +140,11 @@ async function main() { scheduleExit(0); return; } + // The default holds the stop of a session whose transcript shows no test run since its last code change. + if (MODE === "advise" && (!transcript || testedSince(rows, lastCodeChange(root, changed)))) { + scheduleExit(0); + return; + } const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); if (!repo.indexed) { scheduleExit(0); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 1bdfb76cfd2..37a7b8bc7ac 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -7,22 +7,25 @@ // the index links no test to when it has no test to name; once per file per // session (`adviceFiles`, `adviceLines`). // -// At Stop the default does nothing: the line informs, and whether the tests -// ran and how they went is the agent's to judge. A rule that decides it from -// shell text holds sessions that ran them and passes sessions that did not. -// -// With LOOM_TEST_GATE=block nothing is named at edit time and the stop is -// held. When the agent is about to stop with uncommitted changes in a -// loom-indexed repo, the gate asks `code.test_gate` what the change obliges: -// the tests that reach it (evidence-ordered, with a run command when -// derivable) and the touched functions no test reaches. If either list is -// non-empty and this exact change has not been gated yet this session, it -// blocks the stop ONCE with a reason that names them: the tests are named -// before "done", not discovered in review. The second stop on the same -// change passes: the agent has seen the obligation and either ran the tests -// or chose not to, and a gate that nags is a gate that gets disabled. The -// first stop passes only when the transcript shows the named tests ran on -// the tree as it stands (`runAnswered`). +// At Stop it holds a session that ran no test since its last code change. +// When the agent is about to stop with uncommitted changes in a +// loom-indexed repo, it asks +// `code.test_gate` what the change obliges: the tests that reach +// it (evidence-ordered, with a run command when derivable) and the touched +// functions no test reaches. If either list is non-empty and this exact +// change has not been gated yet this session, block the stop ONCE with a +// reason that names them: the tests are named before "done", not discovered +// in review. The second stop on the +// same change passes: the agent has seen the obligation and either ran the +// tests or chose not to, and a gate that nags is a gate that gets disabled. +// A block costs the session one more model request, so by default any test +// run since the last write to a changed code file lets the stop pass before +// anything is asked (`testedSince`, `lastCodeChange`): which tests it ran +// and how they went is the agent's to +// judge, and a hook that reads shell text to decide it blocks sessions that +// ran them. With LOOM_TEST_GATE=block nothing is named at edit time and the +// stop passes only when the transcript shows the named tests ran on the tree +// as it stands (`runAnswered`). // // The change is the session's, not the tree's: `sessionScope` keeps only // the dirty paths the transcript shows this session edited or named in a @@ -53,9 +56,9 @@ import { parseLines, readRange } from "./transcript.mjs"; const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "str_replace_editor", "apply_patch"]); /** What the gate does, from LOOM_TEST_GATE: "advise" names an edited file's - * tests on the tool call that edited it and holds no stop (unset, or any - * on-word); "block" names nothing and holds the stop until the named tests - * ran; "off" does neither. */ + * tests on the tool call that edited it and holds the stop of a session that + * ran no test since its last code change (unset, or any on-word); "block" names + * nothing and holds the stop until the named tests ran; "off" does neither. */ export function gateMode(env = process.env) { if ( String(env.LOOM_TEST_GATE ?? "") @@ -625,10 +628,131 @@ function runsHere(command, run) { return at >= 0 && /^(?:[\s;|&)]|$)/.test(command.slice(at + run.length)) && ranHere(command.slice(0, at)); } +// A shell command that starts a test runner, wrapped or piped in any way: a +// program `code.test_gate` names a run with or a common other one; a build +// tool with an argument in which `test` or `tests` follows no letter and no +// lower-case letter follows it (`make test-unit`, `npm run test`, `node +// --test`, `gradle :app:test`, `gradlew testDebugUnitTest`); a tool that runs +// a target or a script by its name, with a name that starts with `test` +// (`make testall`, `npm run testci`); or Gradle with a task that ends in +// `Test` after a lower-case letter (`gradlew integrationTest`). `import +// pytest`, `pytest.raises`, `make latest`, `go vet ./internal/testutil/...`, +// `cargo build -p testcontainers` and `gradlew compileTestJava` are not +// runs. A command that only mentions a runner counts: what is read is +// whether the session ran a test at all. +// +// After one of these verbs earlier in the simple command the name is a +// package: `pip install -U pytest`, `npm i -D @types/jest`, `yarn remove +// jest`, `go get github.com/stretchr/testify`. A flag is no verb: `npx +// --no-install jest` and `docker run --rm app pytest` run. A build tool's +// target of a verb's name hides the run after it: `make install test` is +// read as none. +// +// A tool and its argument, and a verb and the name after it, are read up to +// 256 characters apart in one simple command (`SPAN`). With no bound the read +// costs the cube of a line's length, and a Stop hook cannot interrupt it. +const SPAN = String.raw`[^\n;|&]{0,256}`; +const FETCHED = String.raw`\s(?:(?:un)?install|add|i|ci|get|remove|rm|update|upgrade|download|require)\s${SPAN}`; +// What a build tool is told to leave out is no run, for every tool of the +// list: the word after `-x`, where Gradle takes a task to exclude (`gradle +// build -x test`), and `test.skip`, Maven's property (`mvn package +// -Dmaven.test.skip=true`). +const LEFT_OUT = String.raw`\s-x\s+\S*`; +const RUNNER = new RegExp( + String.raw`(? RUNNER.test(command.replace(/\\\n/g, "")); + /** True for the name of a Codex rollout's shell tool, under any of the names * `normalizeToolName` folds onto Bash. */ const rolloutShell = (name) => name === "exec" || normalizeToolName(name) === "Bash"; +/** The command text of a Codex rollout's shell call: its `arguments` JSON + * holds a string or an argv (`["go","test"]`), whose words no space joins. */ +function rolloutCommand(call) { + let input = call.input ?? call.arguments; + if (typeof input === "string") { + try { + input = JSON.parse(input); + } catch { + return input; + } + } + return commandText(input) || (typeof input === "string" ? input : ""); +} + +/** + * True when the transcript holds a shell command that starts a test runner + * (`RUNNER`) and finished at or after `since` (epoch ms), or has no dated + * result: Claude Code rows and Codex rollout calls, sidechains skipped. Its + * output is not read, so a run that failed or was piped into `grep` counts. + * So does one between `git stash` and `git stash pop` in the same command; a + * pop in a later command rewrites the changed files after the run. + */ +export function testedSince(objs, since) { + const done = new Map(); + const runs = []; + for (const o of objs || []) { + const at = Date.parse((o && o.timestamp) || ""); + if (o?.type === "response_item") { + const call = o.payload || {}; + if (/_output$/.test(call.type)) done.set(call.call_id, at); + else if (rolloutShell(call.name) && startsRunner(rolloutCommand(call))) { + runs.push(call.call_id); + } + continue; + } + const content = o && !o.isSidechain && o.message && o.message.content; + for (const b of Array.isArray(content) ? content : []) { + if (o.type === "user" && b?.type === "tool_result") done.set(b.tool_use_id, at); + else if ( + o.type === "assistant" && + b?.type === "tool_use" && + ["Bash", "PowerShell"].includes(normalizeToolName(b.name)) && + startsRunner(commandText(b.input)) + ) { + runs.push(b.id); + } + } + } + return runs.some((id) => !(done.get(id) < since)); +} + +// Documentation and prose by name: a test run answers no change to one. A +// `.txt` file is code (a requirements file, a build list, a test fixture) +// unless its name or a `docs` directory above it says prose: `CHANGES.txt`, +// `docs/releases/5.2.txt`. A requirements or a constraints file under `docs` +// stays code. +const PROSE = /\.(?:md|mdx|markdown|rst|adoc|asciidoc)$/i; +const CHANGELOG = /(?:^|\/)(?:CHANGELOG|CHANGES|HISTORY|NEWS)$/; +const PROSE_TXT = + /(?:^|\/)(?:changelog|changes|history|news|readme|license|notice|authors|docs?\/(?!.*(?:requirements|constraints)).*)\.txt$/i; +const isProse = (file) => CHANGELOG.test(file) || PROSE.test(file) || PROSE_TXT.test(file); + +/** The newest modification time, in epoch ms, among the code files of + * `files` under `root`: a test run that finished since then saw each of + * them as it stands. A documentation or prose file (`isProse`) is left out, + * so an edit to one after the run holds no stop, and so is a file that + * cannot be read (a deleted one). 0 when none is left. */ +export function lastCodeChange(root, files) { + let last = 0; + for (const file of files) { + if (isProse(file)) continue; + try { + last = Math.max(last, fs.statSync(path.join(root, file)).mtimeMs); + } catch { + // A deleted file has no time of its own. + } + } + return last; +} + // pytest's last line, whose order is fixed: failed, passed, skipped, // deselected, xfailed, xpassed, warnings, errors. A whole line starts at // "failed" or "passed" and names nothing deselected, so a -k subset is not diff --git a/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs b/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs index 34ea0e7bb5d..500048e31a1 100644 --- a/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs +++ b/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs @@ -115,9 +115,8 @@ async function withCapturingServer(fn) { return bodies; } -// The Stop test gate holds a stop, and so reads its input and asks the server, only with this. +// The Stop test gate that takes only a run of the named tests as an answer. const BLOCKING = { LOOM_TEST_GATE: "block" }; -const stopEnv = (hook) => (hook === "loom-test-gate.mjs" ? BLOCKING : {}); const HOOK_NAMES = [ "loom-code-shunt.mjs", @@ -130,7 +129,7 @@ const HOOK_NAMES = [ test("malformed, empty and non-object stdin: every code hook exits 0 and prints nothing", async () => { const tmp = freshTmp(); for (const hook of HOOK_NAMES) { - // The test gate reads its input at a Stop with LOOM_TEST_GATE=block, and after a shell command. + // The test gate reads its input at a Stop in either mode, and after a shell command. const starts = hook === "loom-test-gate.mjs" ? [{}, { env: BLOCKING }, { event: "PostToolUse" }] : [{}]; for (const stdin of ["{not json", "", "[]", "null", '"text"', "42"]) { for (const how of starts) { @@ -167,7 +166,7 @@ test("no token: nothing is asked of the server and nothing is printed", async () ["loom-test-gate.mjs", { cwd: dir, session_id: "s" }], ["loom-validate-gate.mjs", { cwd: dir, session_id: "s" }], ]) { - const r = await run(hook, payload, { tmp, url, token: "", env: stopEnv(hook) }); + const r = await run(hook, payload, { tmp, url, token: "" }); assert.equal(r.code, 0, hook); assert.equal(r.out, "", hook); } @@ -310,7 +309,7 @@ test("Stop gates: 401 and a hanging server both let the stop through", async () r = await run( hook, { cwd: dir, session_id: "s", transcript_path: transcript }, - { tmp, url, env: { ...stopEnv(hook), LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, + { tmp, url, env: { LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, ); assert.equal(r.code, 0, `${hook} ${status}`); assert.equal(r.out, "", `${hook} ${status}`); @@ -336,7 +335,10 @@ test("Stop gates: a Stop the gate itself caused never blocks again", async () => const r = await run( hook, { cwd: dir, session_id: "s", transcript_path: transcript, stop_hook_active: true }, - { tmp, url, env: stopEnv(hook) }, + { + tmp, + url, + }, ); assert.equal(r.out, "", hook); } @@ -399,7 +401,7 @@ test("blast radius and file context: 401 and a hanging server add nothing to the r = await run( hook, { ...edit, session_id: `s-${hook}-${attempt}` }, - { tmp, url, env: { ...stopEnv(hook), LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, + { tmp, url, env: { LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, ); assert.equal(r.code, 0, `${hook} ${status}`); assert.equal(r.out, "", `${hook} ${status}`); @@ -485,13 +487,9 @@ test("blast radius and test gate: only the diff's paths and hunk headers reach t }; // The edit's own requests: the radius and the tests line. await run("loom-blast-radius.mjs", edit, { tmp, url }); - await run( - "loom-test-gate.mjs", - { cwd: dir, session_id: "s", transcript_path: transcript }, - { tmp, url, env: BLOCKING }, - ); + await run("loom-test-gate.mjs", { cwd: dir, session_id: "s", transcript_path: transcript }, { tmp, url }); }); - // code.test_gate twice: for the tests line at the edit, and at the Stop that LOOM_TEST_GATE=block holds. + // code.test_gate twice: for the tests line at the edit, and at the Stop of a session that ran no test. for (const [op, times] of [ ["/v1/code.impact", 1], ["/v1/code.test_gate", 2], diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index 2ae54577337..fef59b63bf3 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -523,7 +523,7 @@ test("checkoutPython runs no pytest.py planted in the checkout", () => { import http from "node:http"; import { execFileSync, spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; -import { declinesTests, newestChange, runAnswered } from "../lib/test-gate.mjs"; +import { declinesTests, lastCodeChange, newestChange, runAnswered, testedSince } from "../lib/test-gate.mjs"; import { cachedUnindexed, cachePathFor } from "../lib/repo-scope.mjs"; import { hostEnv } from "./host-env.mjs"; @@ -918,10 +918,219 @@ test("a Codex rollout answers nothing", () => { assert.equal(answered(rollout), false); }); -test("the hook holds no stop by default; LOOM_TEST_GATE=block holds one whose named tests did not run on the final tree", async () => { +test("any test run that finished since the change counts, whatever it ran and however it went", () => { + const since = Date.parse(edit()[0].timestamp); + for (const command of [ + SUITE, + "git stash; pytest tests; git stash pop", + "pytest tests/test_other.py -x 2>&1 | grep FAILED", + "sed -i s/1/2/ src/a.py && .venv/bin/python -m unittest discover", + "npx vitest run src/a.test.ts", + "go test ./pkg/...", + "go test ./...", + "make test-unit", + "npm run test", + "node --test", + "node --test tests/a.test.mjs", + "gradle :app:test", + "./gradlew testDebugUnitTest", + "make unit-tests", + "cargo nextest run", + "tests/clickhouse-test 01234_x", + "make testacc", + "make testall", + "npm run testci", + "./gradlew integrationTest", + "gradle connectedAndroidTest", + // A run after an install, in its own simple command. + "npm ci && npm test", + "pip install -e . && pytest", + "yarn add -D jest; yarn jest", + "for i in 1 2 3; do pytest tests; done", + "npx --no-install jest", + "docker run --rm app pytest", + "pip install -e . \\\n && pytest", + // A line continuation joins the run to its tool. + "make \\\n test", + ]) { + assert.equal(testedSince(bash(command, FAILED), since), true, command); + assert.equal(testedSince(call("PowerShell", { command }), since), true, command); + } + // A command that reads or writes a test, or installs, removes or updates a + // package, runs none; neither does a build tool whose argument holds `test` + // inside a word or at the start of a path's or a package's name, one that + // builds the tests, or one told to leave them out. + for (const command of [ + HEREDOC, + "sed -n 1,40p tests/test_a.py", + "cat pytest.ini", + "pip install pytest", + "git diff", + "npm install x@latest", + "go install y@latest", + "make latest", + "node scripts/attest.js", + "npm install @testing-library/react", + "go get github.com/stretchr/testify", + "npm install @playwright/test", + "npm install -D node-test", + "npm install --save-dev jest", + "yarn add -D jest", + "pnpm add -D vitest", + "pip install -U pytest", + "pip install 'pytest>=8'", + "uv add --dev pytest", + "npm i -D @types/jest", + "npm uninstall jest", + "npm rm jest", + "yarn remove jest", + "pnpm remove vitest", + "npm update jest", + "yarn upgrade jest", + "poetry update pytest", + "pip download pytest", + "composer require --dev phpunit/phpunit", + "pip install \\\n pytest", + "npm install --save-dev \\\n jest \\\n vitest", + "go vet ./internal/testutil/...", + "go build ./cmd/testserver", + "go generate ./testdata/...", + "bazel build //testing/...", + "bazel build //pkg:testlib", + "node scripts/testbed.js", + "cargo build -p testcontainers", + "gradle build -x test", + "./gradlew build -x integrationTest", + "./gradlew compileTestJava", + "./gradlew :app:compileDebugUnitTestKotlin", + "./gradlew processTestResources", + "gradle build -PskipTests", + "gradle assemble -DskipTests", + "mvn package -Dmaven.test.skip=true", + // A build tool's target of a verb's name hides the run after it. + "make install test", + "make ci test", + "mvn clean install test", + ]) { + assert.equal(testedSince(bash(command, ""), since), false, command); + } + assert.equal(testedSince(call("Read", { command: SUITE }), since), false); + assert.equal(testedSince(bash(SUITE, PASSED, { isSidechain: true }), since), false); + // A row of another type that copies the call is not the session's call. + assert.equal(testedSince([{ ...bash(SUITE, PASSED)[0], type: "api-request-blob" }], since), false); + // A run that finished before the change does not count; one with no dated result does. + const before = bash(SUITE, PASSED); + assert.equal(testedSince(before, Date.parse(before[1].timestamp) + 1), false); + assert.equal(testedSince(before.slice(0, 1), Date.parse(before[1].timestamp) + 1), true); + // A Codex rollout's shell call counts by its output row's time. + const item = (payload, ms) => ({ type: "response_item", timestamp: new Date(ms).toISOString(), payload }); + const rollout = [ + item( + { type: "function_call", name: "shell", call_id: "c1", arguments: '{"command":["pytest","tests","-q"]}' }, + 1e12, + ), + item({ type: "function_call_output", call_id: "c1", output: "3 passed in 0.10s" }, 1e12 + 1000), + ]; + assert.equal(testedSince(rollout, 1e12 + 500), true); + assert.equal(testedSince(rollout, 1e12 + 1500), false); + // Its arguments hold an argv, a shell wrapper's script or one string. + const shell = (args) => [item({ type: "function_call", name: "shell", call_id: "c2", arguments: args }, 1e12)]; + for (const args of [ + '{"command":["go","test","./..."]}', + '{"command":["npm","test"]}', + '{"command":["bash","-lc","make test-unit"]}', + '{"cmd":"npm run test"}', + "go test ./...", + ]) { + assert.equal(testedSince(shell(args), 1e12), true, args); + } + assert.equal(testedSince(shell('{"command":["npm","install","x@latest"]}'), 1e12), false); + // The shell tool counts under each name the client gives it; another tool that names a runner does not. + const named = (name) => [ + item({ type: "function_call", name, call_id: "c3", arguments: '{"command":"pytest -q"}' }, 1e12), + ]; + for (const name of ["exec", "exec_command", "shell", "shell_command", "local_shell", "container.exec"]) { + assert.equal(testedSince(named(name), 1e12), true, name); + } + assert.equal(testedSince(named("apply_patch"), 1e12), false); + assert.equal(testedSince([], 0), false); +}); + +test("a tool and its argument are read up to 256 characters apart, and a long line in time linear in its length", () => { + const ran = (command) => testedSince(bash(command, ""), 0); + assert.equal(ran(`make ${"a".repeat(255)} test`), true); + assert.equal(ran(`make ${"a".repeat(256)} test`), false); + // A verb further back than that names no package. + assert.equal(ran(`pip install ${"a".repeat(249)} pytest`), false); + assert.equal(ran(`pip install ${"a".repeat(250)} pytest`), true); + // Two lines of 20,000 characters. The first cost over 15 s of CPU with no + // bound; the second, where each tool has a verb and many `tests` within + // reach, is the costliest shape found with one. + const before = process.cpuUsage(); + assert.equal(ran(`x install ${"make test ".repeat(2000)}`), true); + assert.equal(ran(`${" npm".repeat(44)} rm${" tests".repeat(18)}`.repeat(70)), false); + assert.ok(process.cpuUsage(before).user < 2e6); +}); + +test("the last code change is the most recently written code file that can be read", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-last-code-")); + try { + for (const [file, at] of [ + ["a.py", 1e12], + ["b.py", 1e12 + 5000], + ["constraints.txt", 1e12 + 6000], + ["requirements/dev.txt", 1e12 + 6000], + ["tests/fixtures/expected.txt", 1e12 + 6000], + ["testdata/golden.txt", 1e12 + 6000], + ["docs/requirements.txt", 1e12 + 6000], + ["docs/releases/5.2.txt", 1e12 + 9000], + ["CHANGES.txt", 1e12 + 9000], + ["README.txt", 1e12 + 9000], + ["README.md", 1e12 + 9000], + ["notes.markdown", 1e12 + 9000], + ["guide.rst", 1e12 + 9000], + ["manual.asciidoc", 1e12 + 9000], + ["CHANGELOG", 1e12 + 9000], + ]) { + fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); + fs.writeFileSync(path.join(dir, file), "x\n"); + fs.utimesSync(path.join(dir, file), new Date(at), new Date(at)); + } + assert.equal(lastCodeChange(dir, ["b.py", "a.py", "deleted.py"]), 1e12 + 5000); + // Documentation and prose are left out: by extension, by a changelog's name, and a .txt file by a note's + // name or under a docs directory. + for (const file of [ + "README.md", + "notes.markdown", + "guide.rst", + "manual.asciidoc", + "CHANGELOG", + "docs/releases/5.2.txt", + "CHANGES.txt", + "README.txt", + ]) { + assert.equal(lastCodeChange(dir, ["a.py", "b.py", file]), 1e12 + 5000, file); + } + // Any other .txt file is code: a requirements file, also under docs, a test fixture. + for (const file of [ + "constraints.txt", + "requirements/dev.txt", + "tests/fixtures/expected.txt", + "testdata/golden.txt", + "docs/requirements.txt", + ]) { + assert.equal(lastCodeChange(dir, ["a.py", file]), 1e12 + 6000, file); + } + assert.equal(lastCodeChange(dir, ["README.md", "deleted.py"]), 0); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("the hook holds the stop of a session that ran no test since its last code change; LOOM_TEST_GATE=block also holds one whose named tests did not run on the final tree", async () => { const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-gate-hook-"))); const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-gate-hook-tmp-"))); - for (const f of ["src/a.py", "src/b.py", "tests/test_a.py"]) { + for (const f of ["src/a.py", "src/b.py", "tests/test_a.py", "docs/guide.md"]) { fs.mkdirSync(path.join(dir, path.dirname(f)), { recursive: true }); fs.writeFileSync(path.join(dir, f), "def f():\n return 1\n"); } @@ -979,25 +1188,41 @@ test("the hook holds no stop by default; LOOM_TEST_GATE=block holds one whose na try { const ran = [change, bash(SUITE, PASSED)]; const no = [said("Fix f. Do not run the test suite."), change]; - // A Codex rollout that changed the file through its shell tool; a call of another tool that names the file - // is no change. + // The default: a change with no test run since it is held once, with the tests to run. + assert.match(await stop("d-never-ran", [change], ""), /"decision":"block".*pytest tests\/test_a\.py/); + assert.equal(await stop("d-never-ran", [change], ""), ""); + assert.match(await stop("d-ran-before", [ranBefore, change], ""), /"decision":"block"/); + assert.match(await stop("d-only-read", [change, bash("cat tests/test_a.py", "")], ""), /"decision":"block"/); + // Any run since the change passes: one that failed, ran another file, or was followed by more commands. + const asked = requests.length; + assert.equal(await stop("d-ran", ran, ""), ""); + assert.equal(await stop("d-failed", [change, bash("pytest tests/test_b.py -x | grep FAILED", "")], ""), ""); + assert.equal(await stop("d-then-more", [...ran, bash("rm src/helper.py", ""), bash("git diff", "")], ""), ""); + // A documentation file written after the run is not a code change. + const later = (file) => { + const edited = call("Edit", { file_path: path.join(dir, file) }, "updated"); + fs.appendFileSync(path.join(dir, file), "def h():\n return 3\n"); + touch(file, new Date(edited[1].timestamp)); + return edited; + }; + assert.equal(await stop("d-doc-after-run", [...ran, later("docs/guide.md")], ""), ""); + assert.equal(requests.length, asked, "a stop that passes on a test run asks the server nothing"); + // A second code file written after the run is: the run saw the first one only. + assert.match(await stop("d-run-between", [...ran, later("src/b.py")], ""), /"decision":"block"/); + execFileSync("git", ["checkout", "-q", "--", "src/b.py", "docs/guide.md"], { cwd: dir }); + assert.equal(await stop("d-ruled-out", no, ""), ""); + assert.match(await stop("never-ran", [change]), /"decision":"block".*pytest tests\/test_a\.py/); + assert.equal(await stop("never-ran", [change]), ""); + // A Codex rollout that changed the file through its shell tool is held in either mode, under each name of + // that tool; a call of another tool that names the file is no change. const rollout = (name) => [ { type: "response_item", payload: { type: "function_call", name, arguments: '{"command":"sed -i s/1/2/ src/a.py"}' }, }, ]; - // The default holds no stop and asks the server nothing: a change with no test run, a run before the - // change, a rollout's change. - assert.equal(await stop("d-never-ran", [change], ""), ""); - assert.equal(await stop("d-ran-before", [ranBefore, change], ""), ""); - assert.equal(await stop("d-codex", rollout("shell_command"), ""), ""); - assert.deepEqual(requests, []); - // LOOM_TEST_GATE=block holds each of them, once per change. - assert.match(await stop("never-ran", [change]), /"decision":"block".*pytest tests\/test_a\.py/); - assert.equal(await stop("never-ran", [change]), ""); - assert.match(await stop("ran-before", [ranBefore, change]), /"decision":"block"/); assert.match(await stop("codex-block", rollout("shell_command")), /"decision":"block"/); + assert.match(await stop("codex-default", rollout("shell_command"), ""), /"decision":"block"/); assert.equal(await stop("codex-other-tool", rollout("read_file")), ""); // An untracked file whose name git would quote or a trim would cut does not hide the tree's age. const odd = process.platform === "win32" ? " naïve.txt" : ' na"ï\tve.txt'; @@ -1256,6 +1481,8 @@ test("a changed file's tests ride the tool call that changed it, once", async () write("src/old.py", "# a note\n"); assert.equal(await shell("echo '# a note' >> src/old.py"), null); assert.ok(!asked.some((a) => a.endsWith("src/old.py")), asked.join(", ")); + // This transcript shows no tool call, so the stop has no change of the session's to hold. + assert.equal(await run("loom-test-gate", "Stop", {}), null); // LOOM_TEST_GATE=block: nothing at edit time, the radius counts its tests, the stop is held. const blocking = { LOOM_TEST_GATE: "block" }; write("src/a.py", "def h():\n return 3\n"); @@ -1278,7 +1505,7 @@ test("a changed file's tests ride the tool call that changed it, once", async () assert.doesNotMatch(context(radius), /Loom tests for/); const stopped = await run("loom-test-gate", "Stop", { session_id: "b", transcript_path: "" }, blocking); assert.equal(stopped.decision, "block"); - // The same dirty tree by default: the stop is not held. + // With no transcript nothing shows that the session ran no test: the default holds no stop. assert.equal(await run("loom-test-gate", "Stop", { session_id: "n", transcript_path: "" }), null); // LOOM_TEST_GATE=off: neither. const off = { LOOM_TEST_GATE: "off" }; diff --git a/integrations/codex-plugin/hooks/loom-test-gate.mjs b/integrations/codex-plugin/hooks/loom-test-gate.mjs index 27ab1e2cac7..532b2be3784 100644 --- a/integrations/codex-plugin/hooks/loom-test-gate.mjs +++ b/integrations/codex-plugin/hooks/loom-test-gate.mjs @@ -11,25 +11,30 @@ // edited. An edit tool's call gets the same line from loom-blast-radius, the // one hook wired for those tools. // -// At Stop the default does nothing: the line above informs, and the end of a -// session is never held. The script exits before it reads its input. +// Stop: if the working tree has uncommitted changes THIS SESSION made +// in a loom-indexed repo, ask `code.test_gate` for the change's obligations +// (tests to run, untested touched functions) and block the stop ONCE per +// distinct change with a reason that names them. "This session's" is read +// from the transcript: dirty paths an edit tool targeted or a shell command +// named, written since the session began (by the file's modification time); +// a tree left dirty before the session does not gate a turn that changed +// nothing. By default any test run since the session's last code change +// lets the stop pass, whatever it ran and however it went (`testedSince`, +// `lastCodeChange` in lib/test-gate.mjs): the stop is held for a session +// that ran no test since its last code change, and nothing is asked of the +// server for one that ran some. A documentation file changed after the run +// holds nothing. // -// With LOOM_TEST_GATE=block nothing is named at edit time, and the Stop -// holds: if the working tree has uncommitted changes THIS SESSION made in a -// loom-indexed repo, ask `code.test_gate` for the change's obligations (tests -// to run, untested touched functions) and block the stop ONCE per distinct -// change with a reason that names them. "This session's" is read from the -// transcript: dirty paths an edit tool targeted or a shell command named, -// written since the session began (by the file's modification time); a tree -// left dirty before the session does not gate a turn that changed nothing. -// The stop passes only when a Claude Code transcript shows the named tests -// ran on the tree as it stands (`runAnswered`); a Codex rollout answers -// nothing there, so its stop blocks. +// With LOOM_TEST_GATE=block nothing is named at edit time, and the stop +// passes only when a Claude Code transcript shows the named tests ran on the +// tree as it stands (`runAnswered`); a Codex rollout answers nothing there, +// so its stop blocks. // // Fail-open everywhere: no token, not an indexed repo, clean tree, nothing // of the tree touched this session, server down, second stop on the same -// change — the agent stops as normal. Without a transcript path -// LOOM_TEST_GATE=block takes the whole dirty tree as the change. +// change — the agent stops as normal. Without a transcript path the default +// holds no stop, and LOOM_TEST_GATE=block takes the whole dirty tree as the +// change. // LOOM_TEST_GATE=off disables both; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. import crypto from "node:crypto"; @@ -60,11 +65,13 @@ import { gateMode, gatePayload, gateSignature, + lastCodeChange, newestChange, renderGate, runAnswered, sessionScope, sessionStart, + testedSince, testsIn, writtenSince, } from "../lib/test-gate.mjs"; @@ -90,8 +97,7 @@ async function advise(payload, token) { } async function main() { - // The line at edit time is the default's, the hold at Stop is LOOM_TEST_GATE=block's. - if (MODE !== (AFTER_TOOL ? "advise" : "block")) { + if (MODE === "off" || (AFTER_TOOL && MODE === "block")) { scheduleExit(0); return; } @@ -134,6 +140,11 @@ async function main() { scheduleExit(0); return; } + // The default holds the stop of a session whose transcript shows no test run since its last code change. + if (MODE === "advise" && (!transcript || testedSince(rows, lastCodeChange(root, changed)))) { + scheduleExit(0); + return; + } const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); if (!repo.indexed) { scheduleExit(0); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 1bdfb76cfd2..37a7b8bc7ac 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -7,22 +7,25 @@ // the index links no test to when it has no test to name; once per file per // session (`adviceFiles`, `adviceLines`). // -// At Stop the default does nothing: the line informs, and whether the tests -// ran and how they went is the agent's to judge. A rule that decides it from -// shell text holds sessions that ran them and passes sessions that did not. -// -// With LOOM_TEST_GATE=block nothing is named at edit time and the stop is -// held. When the agent is about to stop with uncommitted changes in a -// loom-indexed repo, the gate asks `code.test_gate` what the change obliges: -// the tests that reach it (evidence-ordered, with a run command when -// derivable) and the touched functions no test reaches. If either list is -// non-empty and this exact change has not been gated yet this session, it -// blocks the stop ONCE with a reason that names them: the tests are named -// before "done", not discovered in review. The second stop on the same -// change passes: the agent has seen the obligation and either ran the tests -// or chose not to, and a gate that nags is a gate that gets disabled. The -// first stop passes only when the transcript shows the named tests ran on -// the tree as it stands (`runAnswered`). +// At Stop it holds a session that ran no test since its last code change. +// When the agent is about to stop with uncommitted changes in a +// loom-indexed repo, it asks +// `code.test_gate` what the change obliges: the tests that reach +// it (evidence-ordered, with a run command when derivable) and the touched +// functions no test reaches. If either list is non-empty and this exact +// change has not been gated yet this session, block the stop ONCE with a +// reason that names them: the tests are named before "done", not discovered +// in review. The second stop on the +// same change passes: the agent has seen the obligation and either ran the +// tests or chose not to, and a gate that nags is a gate that gets disabled. +// A block costs the session one more model request, so by default any test +// run since the last write to a changed code file lets the stop pass before +// anything is asked (`testedSince`, `lastCodeChange`): which tests it ran +// and how they went is the agent's to +// judge, and a hook that reads shell text to decide it blocks sessions that +// ran them. With LOOM_TEST_GATE=block nothing is named at edit time and the +// stop passes only when the transcript shows the named tests ran on the tree +// as it stands (`runAnswered`). // // The change is the session's, not the tree's: `sessionScope` keeps only // the dirty paths the transcript shows this session edited or named in a @@ -53,9 +56,9 @@ import { parseLines, readRange } from "./transcript.mjs"; const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "str_replace_editor", "apply_patch"]); /** What the gate does, from LOOM_TEST_GATE: "advise" names an edited file's - * tests on the tool call that edited it and holds no stop (unset, or any - * on-word); "block" names nothing and holds the stop until the named tests - * ran; "off" does neither. */ + * tests on the tool call that edited it and holds the stop of a session that + * ran no test since its last code change (unset, or any on-word); "block" names + * nothing and holds the stop until the named tests ran; "off" does neither. */ export function gateMode(env = process.env) { if ( String(env.LOOM_TEST_GATE ?? "") @@ -625,10 +628,131 @@ function runsHere(command, run) { return at >= 0 && /^(?:[\s;|&)]|$)/.test(command.slice(at + run.length)) && ranHere(command.slice(0, at)); } +// A shell command that starts a test runner, wrapped or piped in any way: a +// program `code.test_gate` names a run with or a common other one; a build +// tool with an argument in which `test` or `tests` follows no letter and no +// lower-case letter follows it (`make test-unit`, `npm run test`, `node +// --test`, `gradle :app:test`, `gradlew testDebugUnitTest`); a tool that runs +// a target or a script by its name, with a name that starts with `test` +// (`make testall`, `npm run testci`); or Gradle with a task that ends in +// `Test` after a lower-case letter (`gradlew integrationTest`). `import +// pytest`, `pytest.raises`, `make latest`, `go vet ./internal/testutil/...`, +// `cargo build -p testcontainers` and `gradlew compileTestJava` are not +// runs. A command that only mentions a runner counts: what is read is +// whether the session ran a test at all. +// +// After one of these verbs earlier in the simple command the name is a +// package: `pip install -U pytest`, `npm i -D @types/jest`, `yarn remove +// jest`, `go get github.com/stretchr/testify`. A flag is no verb: `npx +// --no-install jest` and `docker run --rm app pytest` run. A build tool's +// target of a verb's name hides the run after it: `make install test` is +// read as none. +// +// A tool and its argument, and a verb and the name after it, are read up to +// 256 characters apart in one simple command (`SPAN`). With no bound the read +// costs the cube of a line's length, and a Stop hook cannot interrupt it. +const SPAN = String.raw`[^\n;|&]{0,256}`; +const FETCHED = String.raw`\s(?:(?:un)?install|add|i|ci|get|remove|rm|update|upgrade|download|require)\s${SPAN}`; +// What a build tool is told to leave out is no run, for every tool of the +// list: the word after `-x`, where Gradle takes a task to exclude (`gradle +// build -x test`), and `test.skip`, Maven's property (`mvn package +// -Dmaven.test.skip=true`). +const LEFT_OUT = String.raw`\s-x\s+\S*`; +const RUNNER = new RegExp( + String.raw`(? RUNNER.test(command.replace(/\\\n/g, "")); + /** True for the name of a Codex rollout's shell tool, under any of the names * `normalizeToolName` folds onto Bash. */ const rolloutShell = (name) => name === "exec" || normalizeToolName(name) === "Bash"; +/** The command text of a Codex rollout's shell call: its `arguments` JSON + * holds a string or an argv (`["go","test"]`), whose words no space joins. */ +function rolloutCommand(call) { + let input = call.input ?? call.arguments; + if (typeof input === "string") { + try { + input = JSON.parse(input); + } catch { + return input; + } + } + return commandText(input) || (typeof input === "string" ? input : ""); +} + +/** + * True when the transcript holds a shell command that starts a test runner + * (`RUNNER`) and finished at or after `since` (epoch ms), or has no dated + * result: Claude Code rows and Codex rollout calls, sidechains skipped. Its + * output is not read, so a run that failed or was piped into `grep` counts. + * So does one between `git stash` and `git stash pop` in the same command; a + * pop in a later command rewrites the changed files after the run. + */ +export function testedSince(objs, since) { + const done = new Map(); + const runs = []; + for (const o of objs || []) { + const at = Date.parse((o && o.timestamp) || ""); + if (o?.type === "response_item") { + const call = o.payload || {}; + if (/_output$/.test(call.type)) done.set(call.call_id, at); + else if (rolloutShell(call.name) && startsRunner(rolloutCommand(call))) { + runs.push(call.call_id); + } + continue; + } + const content = o && !o.isSidechain && o.message && o.message.content; + for (const b of Array.isArray(content) ? content : []) { + if (o.type === "user" && b?.type === "tool_result") done.set(b.tool_use_id, at); + else if ( + o.type === "assistant" && + b?.type === "tool_use" && + ["Bash", "PowerShell"].includes(normalizeToolName(b.name)) && + startsRunner(commandText(b.input)) + ) { + runs.push(b.id); + } + } + } + return runs.some((id) => !(done.get(id) < since)); +} + +// Documentation and prose by name: a test run answers no change to one. A +// `.txt` file is code (a requirements file, a build list, a test fixture) +// unless its name or a `docs` directory above it says prose: `CHANGES.txt`, +// `docs/releases/5.2.txt`. A requirements or a constraints file under `docs` +// stays code. +const PROSE = /\.(?:md|mdx|markdown|rst|adoc|asciidoc)$/i; +const CHANGELOG = /(?:^|\/)(?:CHANGELOG|CHANGES|HISTORY|NEWS)$/; +const PROSE_TXT = + /(?:^|\/)(?:changelog|changes|history|news|readme|license|notice|authors|docs?\/(?!.*(?:requirements|constraints)).*)\.txt$/i; +const isProse = (file) => CHANGELOG.test(file) || PROSE.test(file) || PROSE_TXT.test(file); + +/** The newest modification time, in epoch ms, among the code files of + * `files` under `root`: a test run that finished since then saw each of + * them as it stands. A documentation or prose file (`isProse`) is left out, + * so an edit to one after the run holds no stop, and so is a file that + * cannot be read (a deleted one). 0 when none is left. */ +export function lastCodeChange(root, files) { + let last = 0; + for (const file of files) { + if (isProse(file)) continue; + try { + last = Math.max(last, fs.statSync(path.join(root, file)).mtimeMs); + } catch { + // A deleted file has no time of its own. + } + } + return last; +} + // pytest's last line, whose order is fixed: failed, passed, skipped, // deselected, xfailed, xpassed, warnings, errors. A whole line starts at // "failed" or "passed" and names nothing deselected, so a -k subset is not From d117b1055273a6fa30732ac2d9f1aa38a439050f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 20:30:28 +0530 Subject: [PATCH 4/4] The README says a line is read in time proportional to its length "Time that grows with its length" was also true of the read it replaces. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- integrations/claude-code-plugin/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 4622ec042b1..1fcdbb46bd6 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -216,7 +216,7 @@ the duplicate, run `claude mcp remove -s user`. **Tests at edit time.** The test gate names a file's tests on the tool call that changes it, where the agent is still working on the file. For a source file they are the tests the index links to it through its name, the test map or the call graph, each of them present in the checkout, with the tests that have no known runner listed by path; for a test file, the file's own command. A file with no test to name in the checkout gets the changed functions the index links no test to instead (`the index links no test to Router::match`), worded as the index's view, because its call graph is a floor. A file is asked about once per session, at its first change, so a function changed later in the same file is not named; a file the server gave no answer for is asked about once more, at the next call that names it; at most four files are asked about per tool call. A test is named once per session, so the test you edit after its source file adds no second line. A test the tool call's own command runs is not named on the result of that run: its command stands there whole, in this checkout, so `pytest tests/test_a.py::test_one`, `docker exec app pytest tests/test_a.py` and `echo "pytest tests/test_a.py"` still get the line. -**Stops that pass.** By default the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time that grows with its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. +**Stops that pass.** By default the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. **Untested functions.** The index's call graph is a floor: a test may reach a function the graph holds no edge to, such as a constructor the test calls by building the object. Beside tests to run that the checkout has, the reason of a held stop therefore lists the functions as the index's view, `the index links no test to: … (the tests named here may still reach it)`. With no such test it reads `no test reaches: …` and asks for a test.