From dbdb8a617ba2fcee06aada5a8ead5c5468fd3b67 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 12:54:31 +0530 Subject: [PATCH 1/7] The test gate tells the agent which tests constrain an edited file when it edits it, and no longer blocks the end of a session by default The Stop test gate decided from a transcript's shell text whether the tests it names had run, and blocked the stop when it could not tell. In two recorded benchmark runs of one task it blocked 8 of 29 sessions with the plugin installed, and each of the 8 had run the named tests: with a whole-suite run that had failures, between `git stash` and `git stash pop`, before a `git checkout` of another file, behind `grep FAILED`, or beside a quoted `\|` in a grep pattern. A block costs one more model request and reply. The run after the last round of parsing rules blocked 5 of 15 sessions, against 3 of 14 before it. The gate no longer reads shell text by default. When a session first changes a file in an indexed checkout, the tool call that changed it comes back with one line of additional context naming the command of the tests `code.test_gate` links to that file: Loom: tests the index links to src/a.py: .venv/bin/python -m pytest tests/test_a.py The line is attached once per file per session and costs no model request. After a Bash or PowerShell command it comes from `loom-test-gate.mjs`, for each dirty file the command names that was written since the session began. After Edit, Write or MultiEdit it comes from `loom-blast-radius.mjs`, the one hook wired for those tools, where it replaces the radius's own count of tests, so an edit gets one line. An edited test file names nothing, and neither does a comment-only change. The stop is not held. `LOOM_TEST_GATE=block` keeps the blocking gate as it was and prints nothing at edit time. `LOOM_TEST_GATE=off` turns both off. No parsing rule became unused: the blocking gate still reads them all. The Codex plugin wires the same hook after its shell tool. Both plugin manifests move to 1.2.65. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 60 ++++- .../.claude-plugin/plugin.json | 2 +- integrations/claude-code-plugin/README.md | 15 +- .../claude-code-plugin/hooks/HOOKS.md | 42 +++- .../claude-code-plugin/hooks/hooks.json | 10 + .../hooks/loom-blast-radius.mjs | 69 +++--- .../hooks/loom-test-gate.mjs | 63 +++-- .../claude-code-plugin/lib/blast-radius.mjs | 8 +- .../claude-code-plugin/lib/test-gate.mjs | 183 +++++++++++++- .../tests/blast-radius.test.mjs | 9 + .../tests/code-hooks-failopen.test.mjs | 84 +++++-- .../tests/hooks-json.test.mjs | 12 + .../tests/test-gate.test.mjs | 230 +++++++++++++++++- .../codex-plugin/.codex-plugin/plugin.json | 2 +- integrations/codex-plugin/hooks/hooks.json | 11 + .../codex-plugin/hooks/loom-blast-radius.mjs | 69 +++--- .../codex-plugin/hooks/loom-test-gate.mjs | 63 +++-- .../codex-plugin/lib/blast-radius.mjs | 8 +- integrations/codex-plugin/lib/test-gate.mjs | 183 +++++++++++++- 19 files changed, 946 insertions(+), 177 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 6a63b5682d2..4cec6d13d9f 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -55,9 +55,11 @@ end of this section are the exceptions. The plugin sends: - token usage and the model name (Claude Code only); - after each edit in an indexed checkout, the outline of that file's uncommitted diff against `HEAD`, to `code.impact` (`LOOM_BLAST_RADIUS=off` stops it); -- at Stop in an indexed checkout, the outline of the diff of the files the session - changed, or of the whole uncommitted tree when the client gives no transcript, to - `code.test_gate` (`LOOM_TEST_GATE=off` stops it). A diff's outline, up to 200,000 +- 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 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, @@ -185,8 +187,8 @@ Every option is optional; Claude Code asks once, and an empty answer falls back Count agent tool calls and hook requests separately. Before Claude chooses a tool, the prompt hook can search the code index and supply matching symbols and line ranges. Claude can use those pointers through a targeted `Read` with no explicit Loom tool call. -The test gate also calls `code.test_gate` itself; it names test obligations and does not -execute the tests. Zero explicit calls alone does not establish that Loom was unused. +The test gate also calls `code.test_gate` itself; it names the tests linked to a changed +file and does not execute them. Zero explicit calls alone does not establish that Loom was unused. Check the setup in this order: @@ -384,11 +386,21 @@ It stays quiet for untracked files, empty diffs, repeated impact results, an una index or a failed request. Edits performed through `Bash`, including scripts using `python` or `sed`, do not match either edit hook. +The test gate's line does follow a shell edit. It runs on `PostToolUse` after `Bash` and +`PowerShell`, and rides the blast-radius hook after `Edit`, `Write` and `MultiEdit`. It +emits one line per changed file, `Loom: tests the index links to : `, the +first time the session changes that file, and only when the command names the file's +path, the file differs from `HEAD`, it was written after the session began, and the index +links it to a test the checkout has. It stays quiet for an edited test file, a +comment-only change, an untracked file, a file already asked about in the session, an +unavailable index or a failed request, and always with `LOOM_TEST_GATE=block` or `off`. + Headless sessions support `hookSpecificOutput.additionalContext`; ordinary visible assistant output does not prove whether that context reached the model. Capture `--debug hooks,mcp` output privately and redact tokens and authorization headers before sharing it. Include the hook event, tool name, hook output and relevant stream events. -Correlate them with server requests to `memory.for_file` and `code.impact` to distinguish +Correlate them with server requests to `memory.for_file`, `code.impact` and +`code.test_gate` to distinguish hook matching, request execution, nonempty context and delivery to the agent. ## Configuration @@ -464,12 +476,13 @@ The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. | PreToolUse (Read, Grep, Bash) | `loom-code-shunt.mjs` | the code shunt and the tracker shunt ([next section](#the-code-shunt)) | `LOOM_CODE_SHUNT=off`, `LOOM_TRACKER_SHUNT=off` | | PreToolUse (Edit, Write, MultiEdit, NotebookEdit) | `loom-file-context.mjs` | what Loom knows about the file about to change (`memory.for_file`): your rules and the repository's shared rules and design decisions; once per file per 30 min | `LOOM_FILE_CONTEXT=off` | | PostToolUse (Loom tools) | `loom-mentor-hint.mjs` | lifts a result's `hint` into context, once per hint code per session | `LOOM_MENTOR_HINTS=off` | -| PostToolUse (Edit, Write, MultiEdit) | `loom-blast-radius.mjs` | one line from `code.impact`: callers, tests reaching the change, co-change files not yet touched | `LOOM_BLAST_RADIUS=off` | +| PostToolUse (Edit, Write, MultiEdit) | `loom-blast-radius.mjs` | one line from `code.impact`: callers, tests reaching the change, co-change files not yet touched; on a file's first edit, the test gate's line beside it in place of the tests | `LOOM_BLAST_RADIUS=off` | +| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | one line per file the command changed, naming the command of the tests `code.test_gate` links to it; once per file per session, on the tool result, and never a blocked stop ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | | PostToolUse, PostToolUseFailure, Stop, SessionEnd | `loom-record.mjs` | runs the event's recording scripts (the rows below for those events, the gates excepted) in one process: detached after a tool call and at Stop, so the session does not wait for their requests, and in the hook itself at SessionEnd | each script's own | | 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 your latest prompt ends with "Do not run the tests", or pytest already ran them to its summary line, failures included, and nothing was edited or run since (exact conditions: **Answered stops** in the plugin README) | `LOOM_TEST_GATE=off` | +| Stop | `loom-test-gate.mjs` | only 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 already ran them to its summary line, failures included, and nothing was edited or run since (exact conditions: **Answered stops** in the plugin README) | `LOOM_TEST_GATE=block` | | 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` | on the first Stop, one line when `namespace.audit` finds a critical misuse of the namespace, pointing at the `loom-optimize` skill | `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` | @@ -570,6 +583,7 @@ Beyond the off switches in the table: | `LOOM_PROMPT_PACK_MIN_CONF` | unset | a `retrieval_confidence` gate for search pointers; unset, the index's low-risk 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` holds the stop in place of the edit-time line; `off` turns the gate off | | `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 | @@ -578,6 +592,36 @@ Beyond the off switches in the table: `integrations/claude-code-plugin/README.md` documents the remaining knobs. +## The test gate + +The test gate tells the agent which tests constrain a file when it changes the file. In +an indexed checkout, the tool call that first changes a file in a session comes back with +one extra line: + +```text +Loom: tests the index links to src/flask/blueprints.py: python3 -m pytest tests/test_blueprints.py +``` + +- **What it names.** The tests `code.test_gate` links to the file through its name, the + mined test map or the call graph, each of them present in the checkout, as one command + where the harness is known (`LOOM_CODE_TEST_GATE_RUN_TEMPLATES` on the server adds + yours) and by path where it is not. For pytest it names the checkout's interpreter + without starting it. +- **When.** Once per file per session, on the result of the edit tool or shell command + that changed the file. It costs no model request, and a session that never runs the + tests has still been told which ones they are. +- **What it does not do.** It does not check that the tests ran, and it never holds the + end of a session. Whether a session ran the right tests cannot be read reliably from + its shell commands, so that judgement stays with the agent and with CI. + +To hold the stop instead, 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 +with the tests the change obliges and the functions the index links no test to, unless +the transcript already answers the ask; the plugin README lists the exact conditions +under **Answered stops**. A block costs the session one more model request, also when the +session had run the tests in a way the gate does not read. `LOOM_TEST_GATE=off` turns the +gate off. + ## The code shunt Inside an indexed checkout, `loom-code-shunt.mjs` denies bulk reads and names the op to diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index db321857af1..288c8cc25eb 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.64", + "version": "1.2.65", "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 3b79737ad62..03fcb0863ca 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -95,8 +95,8 @@ Loom's MCP requests) run `node`, `git` and `grep` on your machine: `git` reads the checkout's remotes, branch, `HEAD` commit, status and diffs, and `grep` searches uncommitted files for the pattern of a grep the plugin redirects to the code index. The `loom-session` skill's brief script also runs `git log` for the -commits since the last brief. The test gate (the hook that, when a reply ends, -names the tests a change needs) runs no Python: for a pytest test it picks the +commits since the last brief. The test gate (the hook that names the tests the +index links to a file you change) runs no Python: for a pytest test it picks the interpreter of the checkout's virtualenv, the active one (`VIRTUAL_ENV`) or a `python3` or `python` on `PATH`, checking that the interpreter's file exists without running it. @@ -150,10 +150,11 @@ the duplicate, run `claude mcp remove -s user`. | `SessionStart` | `loom-session-start.mjs` | **First session, no credential:** signs this machine up (see `LOOM_AUTO_SIGNUP`) and points the user to the claim page for the namespace; nothing to paste. Then: injects a token-budgeted context primer (profile + relevant memories) via `context.pack`, so the agent starts knowing your context. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index was looked up, so a session start that prints nothing is a fault unless `LOOM_CODE_MAP=false`. How to route a lookup is in the MCP entry's startup instructions on a toolset with a `coding` part; any other toolset, and a wiring whose entry the plugin does not mount (Codex, a hand-wired client), gets it in the primer. **On by default**, once per session; `LOOM_INJECT_CONTEXT=false` to disable. | | `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about the target file (its files facet) and injects the rendered block as additional context — a constraint arrives **before** the edit, not as a review comment. One lookup per (session, file) per 30 min; never a permission decision. `LOOM_FILE_CONTEXT=off` disables. | | `PostToolUse` (loom tools) | `loom-mentor-hint.mjs` | **The store's advice reaches the model**: a loom tool result may carry one `hint` — the plane this agent is not using, named from the call it just made (a `memory.get` that missed, a search that abstained where the code index answers, a stack trace written as a memory, a duplicate write). The hook lifts it out of the result JSON into additional context, once per code per session. No request of its own. `LOOM_MENTOR_HINTS=off` disables. | -| `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. `LOOM_BLAST_RADIUS=off` disables. | +| `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which then stands in for the radius's count of tests, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | +| `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` which tests the index links to each file the command changed (a dirty path it names, written since the session began) and attaches **one line** per file with their command: `Loom: tests the index links to src/a.py: .venv/bin/python -m pytest tests/test_a.py`. Once per file 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 test file you edit names nothing, and neither does a comment-only change. The stop is never held: whether the tests ran is the agent's call (**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` | 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: the tests were named before "done", the choice to run them is the agent's. A stop whose transcript already answers the ask to run tests is not blocked, and so names no untested function (**Answered stops**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | +| `Stop` | `loom-test-gate.mjs` | **Only with `LOOM_TEST_GATE=block`**, in place of the line at edit time. 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: the tests were named before "done", the choice to run them is the agent's. A stop whose transcript already answers the ask to run tests is not blocked, and so names no untested function (**Answered stops**, below). | | `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**: on the first stop of a session, one `namespace.audit` over the last day (no samples) for the session's namespace; 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, 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. | @@ -168,9 +169,11 @@ the duplicate, run `claude mcp remove -s user`. **Team file rules.** The file-context hook reads two places in one `memory.for_file` request: your own namespace, and the repository's **primary code namespace** (its trunk branch's — `code-clickhouse` for every ClickHouse branch), named by the checkout's cached `code.repos` entry. A namespace you cannot read is skipped silently, so access follows repository access. Rules from the code namespace render as `Team rule (by alice, 3 days ago) [constraint]: … [id: ]` and design decisions (typed or tagged `decision`) as `Decision (by alice, 3 days ago) (pinned): … — source: [id: ]` (`(pinned)` only when someone pinned it, else no mark; `(source changed)` once its source document no longer says it), a newer rule the conflict check linked to an older one sits above it (`supersedes rule by …`, or `supersedes decision by …`), and one footer line says how to remove a wrong one. Every member of the repository may add a rule there (`memory.set` with `files` and the tag `constraint`) and revise or delete the rules they wrote; a maintainer may delete any — from an agent (`memory.delete` on the `[id:]` key) or from the dashboard (pick the code namespace under _show system_, open the memory, Delete). A refused delete answers a `hint` naming the author and what to do instead. `memory.set` fills `files` from the value when you do not pass it. Auto-extracted session facts never go to the code namespace. -**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 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. +**Tests at edit time.** The test gate names tests; it does not check that they ran. Deciding that from a transcript means reading shell text, and a session that runs the whole suite, compares against a stashed tree or pipes pytest through `grep` has run the tests in a way no fixed rule reads, so a gate that holds the stop on that reading holds sessions that did the work. By default the gate therefore says which tests the index links to a file on the tool call that changes it, where the agent is still working on the file, and leaves the end of the session alone. A file is asked about once per session, whatever the server answers, and at most four files per tool call. The line names commands only: the tests the index links to the file 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. A team that wants the stop held until the tests are named 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. -**Answered stops.** 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. +**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 blocking gate's reason 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. The scripts are standalone Node ESM (`.mjs`) with **zero dependencies** — no Loom SDK, no `node_modules`. They run on any Node ≥ 18 (global `fetch` + diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 4e2e472732e..f35fcfb4d8b 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -89,7 +89,8 @@ receives on stdout. | PreToolUse Read\|Grep\|Bash | loom-code-shunt | tool_name, tool_input, cwd | JSON permission decision | code.repos; deny text | `LOOM_CODE_SHUNT=off` | | PreToolUse Edit\|Write\|MultiEdit\|NotebookEdit | loom-file-context | tool_input, session_id | JSON additionalContext | memory.for_file | `LOOM_FILE_CONTEXT=off` | | PostToolUse loom tools | loom-mentor-hint | tool_name, tool_response | JSON additionalContext | none | `LOOM_MENTOR_HINTS=off` | -| PostToolUse Edit\|Write\|MultiEdit | loom-blast-radius | tool_input, cwd | JSON additionalContext | code.impact | `LOOM_BLAST_RADIUS=off` | +| PostToolUse Edit\|Write\|MultiEdit | loom-blast-radius | tool_input, cwd, transcript head | JSON additionalContext | code.impact; code.test_gate for a file's first edit | +| PostToolUse Bash\|PowerShell | loom-test-gate | tool_input, cwd, transcript head | JSON additionalContext | code.test_gate for each changed file the command names, once per file | | PostToolUse, PostToolUseFailure, Stop, SessionEnd (timeout 10) | loom-record | the payload | none | after a tool call and at Stop, starts one detached process, which runs the event's `detached` rows; at SessionEnd, runs the event's `in loom-record` rows itself | each script's own | | PostToolUse, PostToolUseFailure, detached | loom-capture | tool_*, session_id, cwd | none | observe.record; code.outcome; the recalled-keys stash | no token | | PreCompact | loom-capture | session_id | none | observe.crystallize | no token | @@ -98,7 +99,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 | `LOOM_TEST_GATE=off` | +| Stop | loom-test-gate | transcript, cwd | JSON block once | with LOOM_TEST_GATE=block only: code.test_gate | | Stop | loom-validate-gate | transcript | JSON block once | namespace.validate | `LOOM_VALIDATE_GATE=off` | | Stop | loom-namespace-health | cwd, session_id | JSON block once | namespace.audit (first Stop only) | `LOOM_NAMESPACE_HEALTH=off` | | Stop, detached | loom-working-memory | transcript, cwd | none | working_memory.set when the note changed | `LOOM_WORKING_MEMORY=off` | @@ -226,7 +227,10 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). only (`diffHeaders`) and asks code.impact (depth 1) what the touched symbols reach; injects one line — callers, tests reaching the change, and co-change partner files this session has not touched. The same touched set is - reported once per session. LOOM_BLAST_RADIUS=off disables. + reported once per session. It is the one hook wired for an edit tool, so + it also carries the test gate's line for the file's first edit (see + loom-test-gate), which replaces its own count of tests: one line per + edit. LOOM_BLAST_RADIUS=off disables the radius, not that line. - **loom-capture.** PostToolUse and PostToolUseFailure record one episodic `observe.record` per tool call (zero-token heuristic typing, inputs and outputs truncated to 800 characters, the session's run id attached); @@ -278,15 +282,29 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). namespace.audit over the last day (sample_limit=0); a critical finding gives the agent one line naming the codes and /loom-optimize, as a block-once reason. Later stops make no call. -- **loom-test-gate.** 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), 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 - whose transcript already answers the ask to run tests is not blocked - (`runAnswered` in lib/test-gate.mjs); a Codex rollout answers nothing. - LOOM_TEST_GATE=off disables; LOOM_TEST_GATE_DEPTH sets hops (1-3). +- **loom-test-gate.** Names the tests the index links to a changed file. + By default it does so when the file changes and never holds the stop: + 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 since the session's first row, asks code.test_gate about + each one not asked about yet this session (`adviceFiles`, `adviceLine` in + lib/test-gate.mjs; at most four per call; a comment-only change is not + asked about) and prints one line per file naming the commands of the + linked tests the checkout has, as additionalContext on that tool result: + no model request, and no reading of shell text to decide whether tests + ran. A changed test file names nothing. A call that names no unasked + dirty file costs one git call and no request. + With LOOM_TEST_GATE=block it holds the stop instead and prints nothing at + edit time: 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), 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 whose transcript already answers the ask + to run tests is not blocked (`runAnswered` in lib/test-gate.mjs); a Codex + rollout answers nothing. + 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 cost.record_turns; the server prices them. Not wired for Codex, whose diff --git a/integrations/claude-code-plugin/hooks/hooks.json b/integrations/claude-code-plugin/hooks/hooks.json index 4dcd9635e01..1713ba6a2cd 100644 --- a/integrations/claude-code-plugin/hooks/hooks.json +++ b/integrations/claude-code-plugin/hooks/hooks.json @@ -83,6 +83,16 @@ } ] }, + { + "matcher": "Bash|PowerShell", + "hooks": [ + { + "type": "command", + "command": "node", + "args": ["${CLAUDE_PLUGIN_ROOT}/hooks/loom-test-gate.mjs", "PostToolUse"] + } + ] + }, { "matcher": "*", "hooks": [ diff --git a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs index d152bc317e8..837e7bfffea 100644 --- a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs @@ -8,11 +8,18 @@ // the agent is still in the edit, which is when a missed sibling file is // cheap to fix. // +// The test gate's edit-time line rides the same context: the first edit of a +// file this session also asks `code.test_gate` which tests the index links +// to it and names their command (lib/test-gate.mjs), in place of the radius's +// own count of tests. This hook is the only one wired for an edit tool, so an +// edit gets one line. LOOM_TEST_GATE=block or off leaves the radius alone. +// // Fail-open everywhere: no token, not an indexed repo, untracked file, empty -// diff, server slow → nothing is printed. One bounded request (3 s). The same -// touched-symbol set for a file is reported once per session. +// diff, server slow → nothing is printed. Each request is bounded (3 s) and +// the two go out together. The same touched-symbol set for a file is reported +// once per session. // -// LOOM_BLAST_RADIUS=off disable +// LOOM_BLAST_RADIUS=off disable the radius; the tests line stays // LOOM_BLAST_MAX_NAMES=5 callers named inline // LOOM_BLAST_DEPTH=1 impact depth (1 or 2) // LOOM_BLAST_PER_HOP=50 impacted rows requested per hop (counts stay exact) @@ -35,15 +42,17 @@ import { relativeForLookup, targetPath } from "../lib/file-context.mjs"; import { resolveIndexedRepo } from "../lib/repo-scope.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; import { blastPayload, blastSignature, decideEmit, impactBody, renderBlast } from "../lib/blast-radius.mjs"; +import { adviceFiles, adviceLine, gateMode } from "../lib/test-gate.mjs"; const ENABLED = envSwitch("LOOM_BLAST_RADIUS", true); +const ADVISE = gateMode() === "advise"; const MAX_NAMES = Number(process.env.LOOM_BLAST_MAX_NAMES || 5); const DEPTH = Math.min(2, Math.max(1, Number(process.env.LOOM_BLAST_DEPTH || 1))); const PER_HOP = Math.min(500, Math.max(1, Number(process.env.LOOM_BLAST_PER_HOP || 50))); const TOOLS = new Set(["Edit", "Write", "MultiEdit", "apply_patch"]); async function main() { - if (!ENABLED) { + if (!ENABLED && !ADVISE) { scheduleExit(0); return; } @@ -87,37 +96,33 @@ async function main() { // on it yet; empty = the edit was a no-op or already committed. The outline is // sent in its place; with no `+++` path in it (a mode-only change, a binary file, // a header dropped for a line end) the server has nothing to read. - const diff = git(["diff", ...DIFF_ARGS, "--unified=0", "HEAD", "--", rel], root, { - timeoutMs: 2000, - raw: true, - }); + const diff = ENABLED + ? git(["diff", ...DIFF_ARGS, "--unified=0", "HEAD", "--", rel], root, { timeoutMs: 2000, raw: true }) + : ""; const outline = diffHeaders(diff, 200_000); - if (!/^\+\+\+ /m.test(outline)) { - scheduleExit(0); - return; - } + const files = ADVISE ? adviceFiles(payload, { root, cwd }).files : []; + const [impact, advice] = await Promise.all([ + /^\+\+\+ /m.test(outline) + ? postBounded("code.impact", impactBody(repo, outline, { depth: DEPTH, perHop: PER_HOP }), { + token, + serverUrl: resolveServerUrl(), + }) + : null, + files.length ? adviceLine(payload, files, { root, repo, token }) : "", + ]); - const impact = await postBounded("code.impact", impactBody(repo, outline, { depth: DEPTH, perHop: PER_HOP }), { - token, - serverUrl: resolveServerUrl(), - }); - if (!impact) { - scheduleExit(0); - return; + let blast = ""; + if (impact) { + const touchedPaths = git(["diff", "--name-only", "HEAD"], root, { timeoutMs: 2000 }) + .split("\n") + .map((s) => s.trim()) + .filter(Boolean); + const decision = decideEmit(readSessionState("blast", payload.session_id), rel, blastSignature(rel, impact)); + writeSessionState("blast", payload.session_id, decision.cache); + // The tests line names the command, so the radius does not count them too. + if (decision.emit) blast = renderBlast(rel, impact, { maxNames: MAX_NAMES, touchedPaths, tests: !advice }); } - - const touchedPaths = git(["diff", "--name-only", "HEAD"], root, { timeoutMs: 2000 }) - .split("\n") - .map((s) => s.trim()) - .filter(Boolean); - const decision = decideEmit(readSessionState("blast", payload.session_id), rel, blastSignature(rel, impact)); - writeSessionState("blast", payload.session_id, decision.cache); - if (!decision.emit) { - scheduleExit(0); - return; - } - - const text = renderBlast(rel, impact, { maxNames: MAX_NAMES, touchedPaths }); + const text = [blast, advice].filter(Boolean).join(" "); if (text) process.stdout.write(JSON.stringify(blastPayload(text)) + "\n"); scheduleExit(0); } diff --git a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs index 013b96f64e3..2ce175a0560 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -1,7 +1,18 @@ #!/usr/bin/env node -// loom-test-gate — Stop hook. +// loom-test-gate — PostToolUse (Bash|PowerShell) and Stop. // -// On Stop, if the working tree has uncommitted changes THIS SESSION made +// PostToolUse, the default (LOOM_TEST_GATE unset): after a shell command +// that changed files in a loom-indexed repo, ask `code.test_gate` which +// tests the index links to each one and attach ONE line per file naming +// their command, once per file per session. The line rides the tool result, +// so it costs no model request, and it arrives while the file is still +// being edited. An edit tool's call gets the same line from +// loom-blast-radius, the one hook wired for those tools. The stop is never +// held: whether the tests then ran is the agent's to judge. +// +// Stop, with LOOM_TEST_GATE=block: the gate holds the stop instead, and +// names nothing at edit time. 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 @@ -16,15 +27,13 @@ // of the tree touched this session, server down, second stop on the same // change — the agent stops as normal. Without a transcript path the whole // dirty tree is the change. -// LOOM_TEST_GATE=off disables; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. +// LOOM_TEST_GATE=off disables both; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. -import fs from "node:fs"; -import path from "node:path"; import crypto from "node:crypto"; import { git, gitToplevel, - pathUnder, + normalizeToolName, postBounded, readStdinJson, DIFF_ARGS, @@ -32,15 +41,19 @@ import { resolveServerUrl, resolveToken, scheduleExit, - envSwitch, } from "../lib/loom-client.mjs"; import { resolveIndexedRepo } from "../lib/repo-scope.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; import { readAllLines } from "../lib/transcript.mjs"; import { + adviceFiles, + adviceLine, + advicePayload, checkoutPython, commentOnlyDiff, decideBlock, + gateDepth, + gateMode, gatePayload, gateSignature, newestChange, @@ -48,14 +61,28 @@ import { runAnswered, sessionScope, sessionStart, + testsIn, writtenSince, } from "../lib/test-gate.mjs"; -const ENABLED = envSwitch("LOOM_TEST_GATE", true); -const DEPTH = Math.min(3, Math.max(1, Number(process.env.LOOM_TEST_GATE_DEPTH || 2))); +const MODE = gateMode(); +const DEPTH = gateDepth(); +const AFTER_TOOL = process.argv[2] === "PostToolUse"; + +/** After a shell command: the line for the files it changed, or nothing. */ +async function advise(payload, token) { + const tool = normalizeToolName(payload.tool_name); + if (tool !== "Bash" && tool !== "PowerShell") return; + const { root, files } = adviceFiles(payload, { cwd: payload.cwd || process.cwd() }); + if (!files.length) return; + const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); + if (!repo.indexed) return; + const out = advicePayload(await adviceLine(payload, files, { root, repo, token, depth: DEPTH })); + if (out) process.stdout.write(JSON.stringify(out) + "\n"); +} async function main() { - if (!ENABLED) { + if (MODE !== (AFTER_TOOL ? "advise" : "block")) { scheduleExit(0); return; } @@ -65,6 +92,11 @@ async function main() { return; } const payload = await readStdinJson(); + if (AFTER_TOOL) { + await advise(payload, token); + scheduleExit(0); + return; + } // A Stop fired by our own block must never block again. if (payload.stop_hook_active) { scheduleExit(0); @@ -127,16 +159,7 @@ async function main() { }, { token, serverUrl: resolveServerUrl() }, ); - const testExists = (testPath) => { - const target = path.resolve(root, testPath); - if (!pathUnder(root, target)) return false; - try { - return fs.statSync(target).isFile(); - } catch { - // A stale index row or another checkout's test is an explicit gap. - return false; - } - }; + const testExists = testsIn(root); // The newest file time among the uncommitted and untracked files. const lastModified = () => { const untracked = git(["ls-files", "-z", "--others", "--exclude-standard"], root, { diff --git a/integrations/claude-code-plugin/lib/blast-radius.mjs b/integrations/claude-code-plugin/lib/blast-radius.mjs index d4dd5cc6d21..9e8a93b6524 100644 --- a/integrations/claude-code-plugin/lib/blast-radius.mjs +++ b/integrations/claude-code-plugin/lib/blast-radius.mjs @@ -65,13 +65,15 @@ function base(p) { /** * Render the blast line, or "" when there is nothing worth saying. * `touchedPaths` = files edited this session (repo-relative) so co-change - * partners the agent already touched are not reported as missing. + * partners the agent already touched are not reported as missing. With + * `tests` false the tests reaching the change are left out: the test gate's + * line beside this one names their command. */ -export function renderBlast(rel, impact, { maxNames = 5, touchedPaths = [] } = {}) { +export function renderBlast(rel, impact, { maxNames = 5, touchedPaths = [], tests: namesTests = true } = {}) { if (!impact) return ""; const touched = (impact.touched_symbols || []).map((s) => short(s.qualified_name)).filter(Boolean); const impacted = (impact.impacted_symbols || []).filter((s) => s && s.qualified_name); - const tests = (impact.impacted_tests || []).filter((t) => t && t.test_path); + const tests = namesTests ? (impact.impacted_tests || []).filter((t) => t && t.test_path) : []; const already = new Set([rel, ...touchedPaths.map(String)]); const missing = (impact.co_change_missing || []).filter((m) => m && m.path && !already.has(String(m.path))); if (!impacted.length && !tests.length && !missing.length) return ""; // owners alone are not a radius diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 6a9521efd71..a84a07f2a4c 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1,7 +1,15 @@ -// Helpers for the loom-test-gate Stop hook (unit-tested). +// Helpers for the loom-test-gate hook (unit-tested). // -// When the agent is about to stop with uncommitted changes in a loom-indexed -// repo, ask `code.test_gate` what the change obliges: the tests that reach +// The gate names the tests the index links to a change, from +// `code.test_gate`. By default it names them when the file is edited: the +// tool call that changed a file carries one line with the command, once per +// file per session, and the stop is never held (`adviceFiles`, `adviceLine`). +// Whether a session then ran the tests is the agent's to judge: a hook that +// reads shell text to decide it blocks sessions that did. +// +// With LOOM_TEST_GATE=block the gate holds the stop instead. 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 @@ -21,10 +29,44 @@ import fs from "node:fs"; import path from "node:path"; -import { commandText, contentText, extractFiles, normalizeToolName, pathUnder } from "./loom-client.mjs"; +import { + commandText, + contentText, + DIFF_ARGS, + diffHeaders, + envSwitch, + extractFiles, + git, + gitToplevel, + normalizeToolName, + pathUnder, + postBounded, + resolveServerUrl, +} from "./loom-client.mjs"; +import { readSessionState, writeSessionState } from "./tmp-state.mjs"; +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 (unset, or any on-word); "block" + * holds the stop instead; "off" does neither. */ +export function gateMode(env = process.env) { + if ( + String(env.LOOM_TEST_GATE ?? "") + .trim() + .toLowerCase() === "block" + ) { + return "block"; + } + return envSwitch("LOOM_TEST_GATE", true, env) ? "advise" : "off"; +} + +/** The hops `code.test_gate` follows: LOOM_TEST_GATE_DEPTH, 1 to 3. */ +export function gateDepth(env = process.env) { + return Math.min(3, Math.max(1, Number(env.LOOM_TEST_GATE_DEPTH || 2))); +} + /** Stable signature of the change: sorted changed paths + the diff's hash. */ export function gateSignature(changedPaths, diffHash) { const paths = (changedPaths || []).map(String).filter(Boolean).sort(); @@ -62,18 +104,14 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists : []; const absent = new Set(missing); const tests = indexed.filter((t) => !absent.has(String(t.test_path || ""))); - const raw = [...new Set(tests.map((t) => String(t.run || "")).filter(Boolean))]; - const runs = onePytest(raw.slice(0, maxRuns)).map((r) => withPython(r, python)); + const { raw, text: runs } = runList(tests, { maxRuns, python }); const unknown = tests .filter((t) => !t.run) .map((t) => String(t.test_path || "")) .filter(Boolean); const untested = Array.isArray(gate.untested) ? gate.untested : []; const parts = []; - if (runs.length) { - const more = raw.length - maxRuns; - parts.push(`run: ${runs.join(" ; ")}${more > 0 ? ` (+${more} more)` : ""}`); - } + if (runs) parts.push(`run: ${runs}`); if (unknown.length) { const shown = unknown.slice(0, maxNames); const more = unknown.length - shown.length; @@ -93,7 +131,7 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists // a test that builds an object reaches a constructor the graph holds no // edge to. parts.push( - runs.length || unknown.length + runs || unknown.length ? `the index links no test to: ${list} (the tests named here may still reach ${total > 1 ? "them" : "it"})` : `no test reaches: ${list}`, ); @@ -104,7 +142,7 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists // that went hunting for a runner. Say what the obligation actually is. const tail = missing.length ? "Run the available tests and check the missing paths against the indexed revision (deleted, renamed or different checkout); use current equivalent tests or say why not. Missing tests are not passes." - : runs.length || unknown.length + : runs || unknown.length ? "Run the tests before finishing, or say why not." : "Add a test that reaches it, or say why none is needed."; const env = @@ -116,6 +154,35 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists const isPytest = (run) => /^pytest(\s|$)/.test(String(run || "")); +/** The distinct run commands of `tests` (`raw`) and the first `maxRuns` of + * them as one text, "" when no test has one. */ +function runList(tests, { maxRuns, python }) { + const raw = [...new Set(tests.map((t) => String(t.run || "")).filter(Boolean))]; + const runs = onePytest(raw.slice(0, maxRuns)).map((r) => withPython(r, python)); + const more = raw.length - maxRuns; + return { raw, text: runs.length ? `${runs.join(" ; ")}${more > 0 ? ` (+${more} more)` : ""}` : "" }; +} + +/** + * The edit-time line for `rel`: the commands of the tests the index links + * to it, or "" when it links none this checkout has. A changed test file is + * the gate's own row, not a link, so an edit to a test names nothing. The + * functions the index links no test to are not named: the graph is a floor, + * and the line has no reply in which the agent could say so. + */ +export function renderAdvice(rel, gate, { maxRuns = 4, maxNames = 4, python, testExists } = {}) { + const tests = (gate && Array.isArray(gate.tests) ? gate.tests : []).filter( + (t) => t && t.why !== "changed_test" && t.test_path && (!testExists || testExists(String(t.test_path))), + ); + const parts = [runList(tests, { maxRuns, python }).text].filter(Boolean); + const unknown = [...new Set(tests.filter((t) => !t.run).map((t) => String(t.test_path)))]; + if (unknown.length) { + const more = unknown.length - maxNames; + parts.push(`no known runner: ${unknown.slice(0, maxNames).join(", ")}${more > 0 ? ` (+${more})` : ""}`); + } + return parts.length ? `Loom: tests the index links to ${rel}: ${parts.join(" · ")}` : ""; +} + /** `runs` with every `pytest ` folded into the first one: one command to * copy and one process to start. A run with an option or a second word stays * its own command. */ @@ -239,6 +306,20 @@ export function gatePayload(text) { return text ? { decision: "block", reason: text } : null; } +/** PostToolUse payload: additional context only, never a decision. */ +export function advicePayload(text) { + return text ? { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text } } : null; +} + +/** A predicate: is `testPath` a file of the checkout at `root`? A stale + * index row or another checkout's test is not. */ +export function testsIn(root) { + return (testPath) => { + const target = path.resolve(root, testPath); + return Boolean(pathUnder(root, target)) && isFile(target); + }; +} + /** `p` as a repo-relative posix path under `root` (resolved against `cwd` * when relative); "" when it lies outside the repo or `root` is unknown. */ function relativeToRoot(root, p, cwd) { @@ -339,6 +420,84 @@ export function writtenSince(root, paths, since) { }); } +// How much of a transcript's head is read for the session's first row. +const HEAD_BYTES = 64 * 1024; +// Files asked about for one tool call: a command that names more waits for +// the next call that names them. +const MAX_ADVICE_FILES = 4; + +/** + * The files a PostToolUse payload's tool call changed that this session has + * not been advised on, with the checkout root: the dirty paths its edit tool + * targeted or its shell command named, written since the session began. That + * is `sessionScope` and `writtenSince` over the one call, the rule the + * blocking gate applies to the whole transcript, so a command that only reads + * a file left dirty before the session names nothing. The hook runs after + * every shell command, so a call that cannot name an unasked dirty file (a + * path is named with its last segment) costs one git call, not two. + */ +export function adviceFiles(payload, { cwd, root = "" } = {}) { + const dirty = git(["diff", "--name-only", "-z", "HEAD"], root || cwd, { timeoutMs: 2000, raw: true }) + .split("\0") + .filter(Boolean); + const seen = dirty.length ? readSessionState("testadvice", payload.session_id).seen || {} : {}; + const text = `${commandText(payload.tool_input)}\n${extractFiles(payload.tool_input).join("\n")}`; + const unasked = dirty.filter((rel) => !seen[rel] && text.includes(rel.slice(rel.lastIndexOf("/") + 1))); + const top = unasked.length ? root || gitToplevel(cwd) : ""; + if (!top) return { root, files: [] }; + const call = { type: "tool_use", name: payload.tool_name, input: payload.tool_input }; + const named = sessionScope(unasked, [{ type: "assistant", message: { content: [call] } }], { root: top, cwd }); + const head = named.length && payload.transcript_path ? readRange(payload.transcript_path, 0, HEAD_BYTES) : ""; + const files = writtenSince(top, named, sessionStart(parseLines(head.toString()))).slice(0, MAX_ADVICE_FILES); + return { root: top, files }; +} + +/** + * The additional context for `files` (from `adviceFiles`): one line per + * file the index links to tests, "" when it links none. Each file is asked + * about once per session, whatever the server answers, so a server that is + * down costs a session one bounded request per file and not one per tool + * call. A file whose change is comments only is not asked about and stays + * unasked: it owes no test until it changes code. Only the diff's paths, + * hunk ranges and function names are sent (`diffHeaders`). + */ +export async function adviceLine(payload, files, { root, repo, token, depth = gateDepth() } = {}) { + const asked = files + .map((rel) => [ + rel, + git(["diff", ...DIFF_ARGS, "--unified=0", "HEAD", "--", rel], root, { timeoutMs: 2000, raw: true }), + ]) + .filter(([, diff]) => !commentOnlyDiff(diff)); + if (!asked.length) return ""; + const seen = { ...readSessionState("testadvice", payload.session_id).seen }; + for (const [rel] of asked) seen[rel] = Date.now(); + const keys = Object.keys(seen); + if (keys.length > 300) keys.slice(0, keys.length - 300).forEach((k) => delete seen[k]); + writeSessionState("testadvice", payload.session_id, { seen }); + const gates = await Promise.all( + asked.map(([rel, diff]) => + postBounded( + "code.test_gate", + { + org: repo.org, + namespace: repo.namespace, + files: [rel], + diff: diffHeaders(diff, 200_000), + depth, + consumer: "claude-code-testgate", + }, + { token, serverUrl: resolveServerUrl() }, + ), + ), + ); + const needsPython = gates.some((gate) => (gate?.tests || []).some((t) => isPytest(t?.run))); + const opts = { python: needsPython ? checkoutPython(root) : undefined, testExists: testsIn(root) }; + return asked + .map(([rel], i) => renderAdvice(rel, gates[i], opts)) + .filter(Boolean) + .join("\n"); +} + // The prompt's last sentence, whole: "Do not run the test suite.", "Please // don't run any tests". A sentence that says more (`do not run // tests/test_slow.py`, "If lint fails, do not run the tests.") or that is not diff --git a/integrations/claude-code-plugin/tests/blast-radius.test.mjs b/integrations/claude-code-plugin/tests/blast-radius.test.mjs index 67085f42cbc..d632851a5ea 100644 --- a/integrations/claude-code-plugin/tests/blast-radius.test.mjs +++ b/integrations/claude-code-plugin/tests/blast-radius.test.mjs @@ -42,6 +42,15 @@ test("renderBlast names callers, tests and untouched partners in one line", () = assert.ok(text.length < 520, `line stays short: ${text.length}`); }); +test("beside the test gate's line the radius counts no tests, and tests alone are then no radius", () => { + const text = renderBlast("src/Storages/MergeTree/MergeTreeData.cpp", IMPACT, { tests: false }); + assert.match(text, /3 callers in 2 files/); + assert.doesNotMatch(text, /tests reaching it/); + const onlyTests = { touched_symbols: IMPACT.touched_symbols, impacted_tests: IMPACT.impacted_tests }; + assert.match(renderBlast("a.cpp", onlyTests), /tests reaching it: 1/); + assert.equal(renderBlast("a.cpp", onlyTests, { tests: false }), ""); +}); + test("partners the session already touched are not reported as missing", () => { const text = renderBlast("src/Storages/MergeTree/MergeTreeData.cpp", IMPACT, { touchedPaths: ["src/Storages/MergeTree/MergeTreeData.h"], 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 7e8e83ff39e..924d70a7775 100644 --- a/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs +++ b/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs @@ -47,10 +47,10 @@ function seedIndexed(root, tmp) { } /** Run one hook; `stdin` is a string (sent as is) or an object (JSON). */ -function run(hook, stdin, { tmp, url = REFUSED, token = "t", env = {} }) { +function run(hook, stdin, { tmp, url = REFUSED, token = "t", env = {}, event = "X" }) { return new Promise((resolve) => { const started = Date.now(); - const child = spawn(process.execPath, [path.join(HOOKS, hook), "X"], { + const child = spawn(process.execPath, [path.join(HOOKS, hook), event], { env: hostEnv({ PATH: process.env.PATH, HOME: tmp, @@ -115,6 +115,9 @@ async function withCapturingServer(fn) { return bodies; } +// The Stop test gate holds a stop only when asked to. +const BLOCKING = { LOOM_TEST_GATE: "block" }; + const HOOK_NAMES = [ "loom-code-shunt.mjs", "loom-file-context.mjs", @@ -158,10 +161,14 @@ 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: BLOCKING }); assert.equal(r.code, 0, hook); assert.equal(r.out, "", hook); } + const shell = { tool_name: "Bash", tool_input: { command: "sed -i s/0/1/ src/a.cpp" }, cwd: dir, session_id: "s" }; + fs.appendFileSync(path.join(dir, "src/a.cpp"), "int g() { return 1; }\n"); + const r = await run("loom-test-gate.mjs", shell, { tmp, url, token: "", event: "PostToolUse" }); + assert.equal(r.code + r.out, "0"); assert.deepEqual(seen, []); }); }); @@ -297,7 +304,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: { ...BLOCKING, LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" } }, ); assert.equal(r.code, 0, `${hook} ${status}`); assert.equal(r.out, "", `${hook} ${status}`); @@ -326,6 +333,7 @@ test("Stop gates: a Stop the gate itself caused never blocks again", async () => { tmp, url, + env: BLOCKING, }, ); assert.equal(r.out, "", hook); @@ -334,6 +342,43 @@ test("Stop gates: a Stop the gate itself caused never blocks again", async () => }); }); +test("test gate after a shell command: 401 and a hanging server add nothing to the call, and the file is asked about once", async () => { + for (const status of [401, null]) { + await withServer(status, async (url, seen, arrived) => { + const op = "/v1/code.test_gate"; + const { dir, tmp } = dirtySession(); + const shell = { tool_name: "Bash", tool_input: { command: "sed -i s/0/1/ src/a.cpp" }, cwd: dir }; + const bounds = { LOOM_HOOK_TIMEOUT_MS: "500", LOOM_HOOK_EXIT_MS: "500" }; + // A request can fail before the server observes it; require a witnessed run. + let r; + let session; + for (let attempt = 0; attempt < 3 && !arrived.has(op); attempt++) { + session = `s-${attempt}`; + r = await run( + "loom-test-gate.mjs", + { ...shell, session_id: session }, + { tmp, url, env: bounds, event: "PostToolUse" }, + ); + assert.equal(r.code, 0, `${status}`); + assert.equal(r.out, "", `${status}`); + assert.ok(r.ms < 7000, `${status} took ${r.ms} ms`); + } + assert.ok(arrived.has(op), `${status}: never sent ${op} in three runs`); + const after = r.closedAt - arrived.get(op); + assert.ok(after < 1500, `${status}: ${after} ms after its request (${r.ms} ms in all)`); + // The same session's next command names the file again: no second request. + const asked = seen.length; + const again = await run( + "loom-test-gate.mjs", + { ...shell, session_id: session }, + { tmp, url, env: bounds, event: "PostToolUse" }, + ); + assert.equal(again.out, ""); + assert.equal(seen.length, asked, seen.join(",")); + }); + } +}); + test("blast radius and file context: 401 and a hanging server add nothing to the edit", async () => { for (const status of [401, null]) { await withServer(status, async (url, seen, arrived) => { @@ -438,18 +483,29 @@ test("blast radius and test gate: only the diff's paths and hunk headers reach t cwd: dir, session_id: "s", }; + // 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 }, + ); }); - for (const op of ["/v1/code.impact", "/v1/code.test_gate"]) { - const sent = bodies.find((b) => b.url === op); - assert.ok(sent, `${op} not called: ${JSON.stringify(bodies.map((b) => b.url))}`); - assert.ok(!sent.body.diff.includes("s3cr3t-value"), op); - assert.ok(!sent.body.diff.includes("decrypted-by-textconv"), op); - assert.ok(!sent.body.diff.includes("int g()"), `${op} sends no changed line`); - assert.match(sent.body.diff, /^\+\+\+ b\/src\/a\.cpp$/m, `${op} keeps the path`); - assert.match(sent.body.diff, /^@@ .*\+\d+/m, `${op} keeps the hunk header`); - assert.equal(sent.body.diff.match(/^@@ /gm).length, 2, `${op} keeps the two hunks apart`); + // code.test_gate twice: for the tests line at the edit, and for the blocking gate's Stop. + for (const [op, times] of [ + ["/v1/code.impact", 1], + ["/v1/code.test_gate", 2], + ]) { + const all = bodies.filter((b) => b.url === op); + assert.equal(all.length, times, `${op}: ${JSON.stringify(bodies.map((b) => b.url))}`); + for (const sent of all) { + assert.ok(!sent.body.diff.includes("s3cr3t-value"), op); + assert.ok(!sent.body.diff.includes("decrypted-by-textconv"), op); + assert.ok(!sent.body.diff.includes("int g()"), `${op} sends no changed line`); + assert.match(sent.body.diff, /^\+\+\+ b\/src\/a\.cpp$/m, `${op} keeps the path`); + assert.match(sent.body.diff, /^@@ .*\+\d+/m, `${op} keeps the hunk header`); + assert.equal(sent.body.diff.match(/^@@ /gm).length, 2, `${op} keeps the two hunks apart`); + } } }); diff --git a/integrations/claude-code-plugin/tests/hooks-json.test.mjs b/integrations/claude-code-plugin/tests/hooks-json.test.mjs index 552354a1602..aa4deb966e0 100644 --- a/integrations/claude-code-plugin/tests/hooks-json.test.mjs +++ b/integrations/claude-code-plugin/tests/hooks-json.test.mjs @@ -34,6 +34,18 @@ test("the Stop gates are wired directly: the host reads what they print", () => assert.deepEqual(wired("Stop"), ["loom-record", "loom-test-gate", "loom-validate-gate", "loom-namespace-health"]); }); +test("one hook names a changed file's tests per tool: the blast radius after an edit tool, the test gate after a shell", () => { + // Both print additional context for the call; a tool that started both would get the tests line twice. + const tools = (script) => + manifest.hooks.PostToolUse.filter((g) => g.hooks.some((h) => h.args[0].endsWith(`/hooks/${script}.mjs`))).flatMap( + (g) => g.matcher.split("|"), + ); + assert.deepEqual(tools("loom-blast-radius"), ["Edit", "Write", "MultiEdit"]); + assert.deepEqual(tools("loom-test-gate"), ["Bash", "PowerShell"]); + const gate = manifest.hooks.PostToolUse.flatMap((g) => g.hooks).find((h) => h.args[0].endsWith("loom-test-gate.mjs")); + assert.equal(gate.args[1], "PostToolUse", "the script reads its event from this argument"); +}); + test("the SessionEnd hook declares a timeout: Claude Code gives the event 1.5 s by default", () => { // The launcher runs the event's five recording scripts in its own process // and waits for them: a slow server or a loaded machine passes the default diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index 892df2a1406..b6be062e157 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -5,10 +5,13 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { + advicePayload, checkoutPython, decideBlock, + gateMode, gatePayload, gateSignature, + renderAdvice, renderGate, sessionScope, sessionStart, @@ -32,6 +35,53 @@ const GATE = { untested_total: 2, }; +test("the gate advises at edit time unless LOOM_TEST_GATE says block or off", () => { + assert.equal(gateMode({}), "advise"); + for (const v of ["on", "1", "true", "", "advise", "anything"]) + assert.equal(gateMode({ LOOM_TEST_GATE: v }), "advise", v); + for (const v of ["block", " Block ", "BLOCK"]) assert.equal(gateMode({ LOOM_TEST_GATE: v }), "block", v); + for (const v of ["off", "0", "false", "no"]) assert.equal(gateMode({ LOOM_TEST_GATE: v }), "off", v); +}); + +test("the edit-time line names the commands of the tests the index links to the file", () => { + const text = renderAdvice("src/a.py", GATE, { python: ".venv/bin/python" }); + assert.equal( + text, + "Loom: tests the index links to src/a.py: .venv/bin/python -m pytest tests/unit/test_a.py · no known runner: src/x/tests/gtest_parts.cpp", + ); + // No function is named: the graph is a floor, and the line asks for no reply. + assert.doesNotMatch(text, /renameTempPartAndAdd|no test reaches|links no test/); + assert.deepEqual(advicePayload(text), { + hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text }, + }); +}); + +test("an edited test file, a test the checkout lacks and an empty answer name nothing", () => { + const own = { tests: [{ test_path: "tests/test_a.py", why: "changed_test", run: "pytest tests/test_a.py" }] }; + assert.equal(renderAdvice("tests/test_a.py", own), ""); + const gone = { tests: [{ test_path: "tests/gone.py", why: "test_map", run: "pytest tests/gone.py" }] }; + assert.equal(renderAdvice("src/a.py", gone, { testExists: () => false }), ""); + assert.match(renderAdvice("src/a.py", gone, { testExists: () => true }), /: pytest tests\/gone\.py$/); + for (const none of [null, {}, { tests: [] }, { untested: [{ qualified_name: "m::f" }] }]) { + assert.equal(renderAdvice("src/a.py", none), ""); + } + assert.equal(advicePayload(""), null); +}); + +test("the edit-time line folds pytest files into one command and counts the commands it leaves out", () => { + const many = { + tests: ["a", "b", "c", "d", "e", "f"].map((n) => ({ + test_path: `tests/test_${n}.py`, + why: "graph_hop", + run: `pytest tests/test_${n}.py`, + })), + }; + assert.equal( + renderAdvice("src/a.py", many), + "Loom: tests the index links to src/a.py: pytest tests/test_a.py tests/test_b.py tests/test_c.py tests/test_d.py (+2 more)", + ); +}); + test("signature is order-independent over paths and bound to the diff", () => { assert.equal(gateSignature(["b.py", "a.py"], "h1"), gateSignature(["a.py", "b.py"], "h1")); assert.notEqual(gateSignature(["a.py"], "h1"), gateSignature(["a.py"], "h2")); @@ -828,7 +878,7 @@ test("a Codex rollout answers nothing", () => { assert.equal(answered(rollout), false); }); -test("the hook blocks a change whose tests never ran and lets an answered one stop", async () => { +test("with LOOM_TEST_GATE=block the hook blocks a change whose tests never ran and lets an answered one stop", 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"]) { @@ -874,6 +924,7 @@ test("the hook blocks a change whose tests never ran and lets an answered one st TMPDIR: tmp, LOOM_BASE_URL: `http://127.0.0.1:${server.address().port}`, LOOM_API_KEY: "t", + LOOM_TEST_GATE: "block", }), stdio: ["pipe", "pipe", "ignore"], }); @@ -920,3 +971,180 @@ test("the hook blocks a change whose tests never ran and lets an answered one st fs.rmSync(tmp, { recursive: true, force: true }); } }); + +// --- the default: the tests are named on the call that changed the file + +test("a changed file's tests ride the tool call that changed it, once, and the stop is never held", async () => { + const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-advice-"))); + const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-advice-tmp-"))); + for (const f of ["src/a.py", "src/b.py", "src/old.py", "tests/test_a.py", "tests/test_b.py"]) { + fs.mkdirSync(path.join(dir, path.dirname(f)), { recursive: true }); + fs.writeFileSync(path.join(dir, f), "def f():\n return 1\n"); + } + for (const args of [ + ["init", "-q"], + ["add", "."], + ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "c"], + ]) { + execFileSync("git", args, { cwd: dir, stdio: "ignore" }); + } + fs.writeFileSync( + cachePathFor(dir, tmp), + JSON.stringify({ ts: Date.now(), indexed: true, org: "o", namespace: "code-x", repo: "x/y", prefixes: [] }), + ); + // The session began a minute ago; src/old.py was left dirty an hour before it. + const transcript = path.join(tmp, "t.jsonl"); + fs.writeFileSync( + transcript, + JSON.stringify({ type: "user", timestamp: new Date(Date.now() - 60_000).toISOString() }) + "\n", + ); + const write = (file, text, when = new Date()) => { + fs.appendFileSync(path.join(dir, file), text); + fs.utimesSync(path.join(dir, file), when, when); + }; + write("src/old.py", "def parked():\n return 0\n", new Date(Date.now() - 3_600_000)); + const asked = []; + const server = http.createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + const body = JSON.parse(raw || "{}"); + asked.push([req.url, ...(body.files || [])].join(" ")); + const stem = (body.files || []).map((f) => (f.match(/^src\/(\w+)\.py$/) || [])[1]).filter(Boolean); + const answer = { + "/v1/code.test_gate": { + obligations: true, + tests: [ + ...(body.files || []) + .filter((f) => f.startsWith("tests/")) + .map((f) => ({ test_path: f, why: "changed_test", run: `pytest ${f}` })), + ...stem.map((n) => ({ + test_path: `tests/test_${n}.py`, + why: "stem_partner", + run: `pytest tests/test_${n}.py`, + })), + ], + untested: [{ qualified_name: "m::g" }], + }, + "/v1/code.impact": { + touched_symbols: [{ qualified_name: "m::g" }], + impacted_symbols: [{ qualified_name: "m::caller", path: "src/c.py" }], + impacted_tests: [{ test_path: "tests/test_b.py" }], + }, + }[req.url]; + res.end(JSON.stringify(answer || {})); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const run = (script, event, payload, env = {}) => + new Promise((resolve) => { + const child = spawn( + process.execPath, + [fileURLToPath(new URL(`../hooks/${script}.mjs`, import.meta.url)), event], + { + env: hostEnv({ + PATH: process.env.PATH, + HOME: tmp, + TMPDIR: tmp, + LOOM_BASE_URL: `http://127.0.0.1:${server.address().port}`, + LOOM_API_KEY: "t", + ...env, + }), + stdio: ["pipe", "pipe", "ignore"], + }, + ); + let out = ""; + child.stdout.on("data", (c) => (out += c)); + child.on("close", () => resolve(out ? JSON.parse(out) : null)); + child.stdin.end(JSON.stringify({ cwd: dir, session_id: "s", transcript_path: transcript, ...payload })); + }); + const shell = (command, env) => + run("loom-test-gate", "PostToolUse", { tool_name: "Bash", tool_input: { command } }, env); + const context = (out) => out?.hookSpecificOutput?.additionalContext ?? ""; + try { + // A command that changes nothing, or only reads a file left dirty before the session, asks nothing. + assert.equal(await shell("ls src; cat src/old.py"), null); + assert.deepEqual(asked, []); + // One command edits a source file and its test: one line, for the source file. + write("src/a.py", "def g():\n return 2\n"); + write("tests/test_a.py", "def test_g():\n assert True\n"); + const edit = "python - <<'EOF'\nopen('src/a.py','a').write('x')\nopen('tests/test_a.py','a').write('y')\nEOF"; + const first = await shell(edit); + assert.equal(first.hookSpecificOutput.hookEventName, "PostToolUse"); + assert.match(context(first), /^Loom: tests the index links to src\/a\.py: (?:\S+ -m )?pytest tests\/test_a\.py$/); + assert.equal(first.decision, undefined); + assert.deepEqual(asked.sort(), ["/v1/code.test_gate src/a.py", "/v1/code.test_gate tests/test_a.py"]); + // Later commands that name the file, a test run among them, add nothing and ask nothing. + assert.equal(await shell(edit), null); + assert.equal(await shell("python -m pytest tests/test_a.py -q; git diff src/a.py"), null); + assert.equal(asked.length, 2); + // An edit tool's call carries the line beside the blast radius, which then counts no tests. + write("src/b.py", "def g():\n return 2\n"); + const edited = await run("loom-blast-radius", "PostToolUse", { + tool_name: "Edit", + tool_input: { file_path: path.join(dir, "src/b.py") }, + }); + assert.match( + context(edited), + /^Loom blast radius for src\/b\.py \(edited m::g\): 1 caller in 1 file: m::caller \(c\.py\)\. /, + ); + assert.match(context(edited), / Loom: tests the index links to src\/b\.py: (?:\S+ -m )?pytest tests\/test_b\.py$/); + assert.doesNotMatch(context(edited), /tests reaching it/); + // The shell hook leaves an edit tool's call to that hook, and the file is asked about once. + assert.equal( + await run("loom-test-gate", "PostToolUse", { + tool_name: "Edit", + tool_input: { file_path: path.join(dir, "src/b.py") }, + }), + null, + ); + assert.equal(await shell("sed -i s/2/3/ src/b.py"), null); + // A comment-only change owes no test and stays unasked until it changes code. + write("src/old.py", "# a note\n"); + execFileSync("git", ["checkout", "-q", "--", "src/old.py"], { cwd: dir }); + 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(", ")); + // The stop is not held, whatever the session ran. + 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"); + assert.equal( + await run( + "loom-test-gate", + "PostToolUse", + { session_id: "b", tool_name: "Bash", tool_input: { command: edit } }, + blocking, + ), + null, + ); + const radius = await run( + "loom-blast-radius", + "PostToolUse", + { session_id: "b", tool_name: "Edit", tool_input: { file_path: path.join(dir, "src/a.py") } }, + blocking, + ); + assert.match(context(radius), /tests reaching it: 1 \(test_b\.py\)/); + assert.doesNotMatch(context(radius), /tests the index links/); + const stopped = await run("loom-test-gate", "Stop", { session_id: "b", transcript_path: "" }, blocking); + assert.equal(stopped.decision, "block"); + // LOOM_TEST_GATE=off: neither. + const off = { LOOM_TEST_GATE: "off" }; + assert.equal( + await run( + "loom-test-gate", + "PostToolUse", + { session_id: "o", tool_name: "Bash", tool_input: { command: edit } }, + off, + ), + null, + ); + assert.equal(await run("loom-test-gate", "Stop", { session_id: "o", transcript_path: "" }, off), null); + } finally { + server.closeAllConnections(); + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); + fs.rmSync(tmp, { recursive: true, force: true }); + } +}); diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index 2c1f5f357c9..5960bd646ab 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.64", + "version": "1.2.65", "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/hooks.json b/integrations/codex-plugin/hooks/hooks.json index 5a30bdcddaf..ba6f6f786ac 100644 --- a/integrations/codex-plugin/hooks/hooks.json +++ b/integrations/codex-plugin/hooks/hooks.json @@ -85,6 +85,17 @@ } ] }, + { + "matcher": "Bash|shell|exec_command|local_shell", + "hooks": [ + { + "type": "command", + "statusMessage": "Loom: Name linked tests", + "command": "sh \"${PLUGIN_ROOT}/bin/loom-node\" \"${PLUGIN_ROOT}/hooks/loom-test-gate.mjs\" PostToolUse codex", + "commandWindows": "node \"${PLUGIN_ROOT}/hooks/loom-test-gate.mjs\" PostToolUse codex" + } + ] + }, { "matcher": "*", "hooks": [ diff --git a/integrations/codex-plugin/hooks/loom-blast-radius.mjs b/integrations/codex-plugin/hooks/loom-blast-radius.mjs index d152bc317e8..837e7bfffea 100644 --- a/integrations/codex-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/codex-plugin/hooks/loom-blast-radius.mjs @@ -8,11 +8,18 @@ // the agent is still in the edit, which is when a missed sibling file is // cheap to fix. // +// The test gate's edit-time line rides the same context: the first edit of a +// file this session also asks `code.test_gate` which tests the index links +// to it and names their command (lib/test-gate.mjs), in place of the radius's +// own count of tests. This hook is the only one wired for an edit tool, so an +// edit gets one line. LOOM_TEST_GATE=block or off leaves the radius alone. +// // Fail-open everywhere: no token, not an indexed repo, untracked file, empty -// diff, server slow → nothing is printed. One bounded request (3 s). The same -// touched-symbol set for a file is reported once per session. +// diff, server slow → nothing is printed. Each request is bounded (3 s) and +// the two go out together. The same touched-symbol set for a file is reported +// once per session. // -// LOOM_BLAST_RADIUS=off disable +// LOOM_BLAST_RADIUS=off disable the radius; the tests line stays // LOOM_BLAST_MAX_NAMES=5 callers named inline // LOOM_BLAST_DEPTH=1 impact depth (1 or 2) // LOOM_BLAST_PER_HOP=50 impacted rows requested per hop (counts stay exact) @@ -35,15 +42,17 @@ import { relativeForLookup, targetPath } from "../lib/file-context.mjs"; import { resolveIndexedRepo } from "../lib/repo-scope.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; import { blastPayload, blastSignature, decideEmit, impactBody, renderBlast } from "../lib/blast-radius.mjs"; +import { adviceFiles, adviceLine, gateMode } from "../lib/test-gate.mjs"; const ENABLED = envSwitch("LOOM_BLAST_RADIUS", true); +const ADVISE = gateMode() === "advise"; const MAX_NAMES = Number(process.env.LOOM_BLAST_MAX_NAMES || 5); const DEPTH = Math.min(2, Math.max(1, Number(process.env.LOOM_BLAST_DEPTH || 1))); const PER_HOP = Math.min(500, Math.max(1, Number(process.env.LOOM_BLAST_PER_HOP || 50))); const TOOLS = new Set(["Edit", "Write", "MultiEdit", "apply_patch"]); async function main() { - if (!ENABLED) { + if (!ENABLED && !ADVISE) { scheduleExit(0); return; } @@ -87,37 +96,33 @@ async function main() { // on it yet; empty = the edit was a no-op or already committed. The outline is // sent in its place; with no `+++` path in it (a mode-only change, a binary file, // a header dropped for a line end) the server has nothing to read. - const diff = git(["diff", ...DIFF_ARGS, "--unified=0", "HEAD", "--", rel], root, { - timeoutMs: 2000, - raw: true, - }); + const diff = ENABLED + ? git(["diff", ...DIFF_ARGS, "--unified=0", "HEAD", "--", rel], root, { timeoutMs: 2000, raw: true }) + : ""; const outline = diffHeaders(diff, 200_000); - if (!/^\+\+\+ /m.test(outline)) { - scheduleExit(0); - return; - } + const files = ADVISE ? adviceFiles(payload, { root, cwd }).files : []; + const [impact, advice] = await Promise.all([ + /^\+\+\+ /m.test(outline) + ? postBounded("code.impact", impactBody(repo, outline, { depth: DEPTH, perHop: PER_HOP }), { + token, + serverUrl: resolveServerUrl(), + }) + : null, + files.length ? adviceLine(payload, files, { root, repo, token }) : "", + ]); - const impact = await postBounded("code.impact", impactBody(repo, outline, { depth: DEPTH, perHop: PER_HOP }), { - token, - serverUrl: resolveServerUrl(), - }); - if (!impact) { - scheduleExit(0); - return; + let blast = ""; + if (impact) { + const touchedPaths = git(["diff", "--name-only", "HEAD"], root, { timeoutMs: 2000 }) + .split("\n") + .map((s) => s.trim()) + .filter(Boolean); + const decision = decideEmit(readSessionState("blast", payload.session_id), rel, blastSignature(rel, impact)); + writeSessionState("blast", payload.session_id, decision.cache); + // The tests line names the command, so the radius does not count them too. + if (decision.emit) blast = renderBlast(rel, impact, { maxNames: MAX_NAMES, touchedPaths, tests: !advice }); } - - const touchedPaths = git(["diff", "--name-only", "HEAD"], root, { timeoutMs: 2000 }) - .split("\n") - .map((s) => s.trim()) - .filter(Boolean); - const decision = decideEmit(readSessionState("blast", payload.session_id), rel, blastSignature(rel, impact)); - writeSessionState("blast", payload.session_id, decision.cache); - if (!decision.emit) { - scheduleExit(0); - return; - } - - const text = renderBlast(rel, impact, { maxNames: MAX_NAMES, touchedPaths }); + const text = [blast, advice].filter(Boolean).join(" "); if (text) process.stdout.write(JSON.stringify(blastPayload(text)) + "\n"); scheduleExit(0); } diff --git a/integrations/codex-plugin/hooks/loom-test-gate.mjs b/integrations/codex-plugin/hooks/loom-test-gate.mjs index 013b96f64e3..2ce175a0560 100644 --- a/integrations/codex-plugin/hooks/loom-test-gate.mjs +++ b/integrations/codex-plugin/hooks/loom-test-gate.mjs @@ -1,7 +1,18 @@ #!/usr/bin/env node -// loom-test-gate — Stop hook. +// loom-test-gate — PostToolUse (Bash|PowerShell) and Stop. // -// On Stop, if the working tree has uncommitted changes THIS SESSION made +// PostToolUse, the default (LOOM_TEST_GATE unset): after a shell command +// that changed files in a loom-indexed repo, ask `code.test_gate` which +// tests the index links to each one and attach ONE line per file naming +// their command, once per file per session. The line rides the tool result, +// so it costs no model request, and it arrives while the file is still +// being edited. An edit tool's call gets the same line from +// loom-blast-radius, the one hook wired for those tools. The stop is never +// held: whether the tests then ran is the agent's to judge. +// +// Stop, with LOOM_TEST_GATE=block: the gate holds the stop instead, and +// names nothing at edit time. 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 @@ -16,15 +27,13 @@ // of the tree touched this session, server down, second stop on the same // change — the agent stops as normal. Without a transcript path the whole // dirty tree is the change. -// LOOM_TEST_GATE=off disables; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. +// LOOM_TEST_GATE=off disables both; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. -import fs from "node:fs"; -import path from "node:path"; import crypto from "node:crypto"; import { git, gitToplevel, - pathUnder, + normalizeToolName, postBounded, readStdinJson, DIFF_ARGS, @@ -32,15 +41,19 @@ import { resolveServerUrl, resolveToken, scheduleExit, - envSwitch, } from "../lib/loom-client.mjs"; import { resolveIndexedRepo } from "../lib/repo-scope.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; import { readAllLines } from "../lib/transcript.mjs"; import { + adviceFiles, + adviceLine, + advicePayload, checkoutPython, commentOnlyDiff, decideBlock, + gateDepth, + gateMode, gatePayload, gateSignature, newestChange, @@ -48,14 +61,28 @@ import { runAnswered, sessionScope, sessionStart, + testsIn, writtenSince, } from "../lib/test-gate.mjs"; -const ENABLED = envSwitch("LOOM_TEST_GATE", true); -const DEPTH = Math.min(3, Math.max(1, Number(process.env.LOOM_TEST_GATE_DEPTH || 2))); +const MODE = gateMode(); +const DEPTH = gateDepth(); +const AFTER_TOOL = process.argv[2] === "PostToolUse"; + +/** After a shell command: the line for the files it changed, or nothing. */ +async function advise(payload, token) { + const tool = normalizeToolName(payload.tool_name); + if (tool !== "Bash" && tool !== "PowerShell") return; + const { root, files } = adviceFiles(payload, { cwd: payload.cwd || process.cwd() }); + if (!files.length) return; + const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); + if (!repo.indexed) return; + const out = advicePayload(await adviceLine(payload, files, { root, repo, token, depth: DEPTH })); + if (out) process.stdout.write(JSON.stringify(out) + "\n"); +} async function main() { - if (!ENABLED) { + if (MODE !== (AFTER_TOOL ? "advise" : "block")) { scheduleExit(0); return; } @@ -65,6 +92,11 @@ async function main() { return; } const payload = await readStdinJson(); + if (AFTER_TOOL) { + await advise(payload, token); + scheduleExit(0); + return; + } // A Stop fired by our own block must never block again. if (payload.stop_hook_active) { scheduleExit(0); @@ -127,16 +159,7 @@ async function main() { }, { token, serverUrl: resolveServerUrl() }, ); - const testExists = (testPath) => { - const target = path.resolve(root, testPath); - if (!pathUnder(root, target)) return false; - try { - return fs.statSync(target).isFile(); - } catch { - // A stale index row or another checkout's test is an explicit gap. - return false; - } - }; + const testExists = testsIn(root); // The newest file time among the uncommitted and untracked files. const lastModified = () => { const untracked = git(["ls-files", "-z", "--others", "--exclude-standard"], root, { diff --git a/integrations/codex-plugin/lib/blast-radius.mjs b/integrations/codex-plugin/lib/blast-radius.mjs index d4dd5cc6d21..9e8a93b6524 100644 --- a/integrations/codex-plugin/lib/blast-radius.mjs +++ b/integrations/codex-plugin/lib/blast-radius.mjs @@ -65,13 +65,15 @@ function base(p) { /** * Render the blast line, or "" when there is nothing worth saying. * `touchedPaths` = files edited this session (repo-relative) so co-change - * partners the agent already touched are not reported as missing. + * partners the agent already touched are not reported as missing. With + * `tests` false the tests reaching the change are left out: the test gate's + * line beside this one names their command. */ -export function renderBlast(rel, impact, { maxNames = 5, touchedPaths = [] } = {}) { +export function renderBlast(rel, impact, { maxNames = 5, touchedPaths = [], tests: namesTests = true } = {}) { if (!impact) return ""; const touched = (impact.touched_symbols || []).map((s) => short(s.qualified_name)).filter(Boolean); const impacted = (impact.impacted_symbols || []).filter((s) => s && s.qualified_name); - const tests = (impact.impacted_tests || []).filter((t) => t && t.test_path); + const tests = namesTests ? (impact.impacted_tests || []).filter((t) => t && t.test_path) : []; const already = new Set([rel, ...touchedPaths.map(String)]); const missing = (impact.co_change_missing || []).filter((m) => m && m.path && !already.has(String(m.path))); if (!impacted.length && !tests.length && !missing.length) return ""; // owners alone are not a radius diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 6a9521efd71..a84a07f2a4c 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1,7 +1,15 @@ -// Helpers for the loom-test-gate Stop hook (unit-tested). +// Helpers for the loom-test-gate hook (unit-tested). // -// When the agent is about to stop with uncommitted changes in a loom-indexed -// repo, ask `code.test_gate` what the change obliges: the tests that reach +// The gate names the tests the index links to a change, from +// `code.test_gate`. By default it names them when the file is edited: the +// tool call that changed a file carries one line with the command, once per +// file per session, and the stop is never held (`adviceFiles`, `adviceLine`). +// Whether a session then ran the tests is the agent's to judge: a hook that +// reads shell text to decide it blocks sessions that did. +// +// With LOOM_TEST_GATE=block the gate holds the stop instead. 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 @@ -21,10 +29,44 @@ import fs from "node:fs"; import path from "node:path"; -import { commandText, contentText, extractFiles, normalizeToolName, pathUnder } from "./loom-client.mjs"; +import { + commandText, + contentText, + DIFF_ARGS, + diffHeaders, + envSwitch, + extractFiles, + git, + gitToplevel, + normalizeToolName, + pathUnder, + postBounded, + resolveServerUrl, +} from "./loom-client.mjs"; +import { readSessionState, writeSessionState } from "./tmp-state.mjs"; +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 (unset, or any on-word); "block" + * holds the stop instead; "off" does neither. */ +export function gateMode(env = process.env) { + if ( + String(env.LOOM_TEST_GATE ?? "") + .trim() + .toLowerCase() === "block" + ) { + return "block"; + } + return envSwitch("LOOM_TEST_GATE", true, env) ? "advise" : "off"; +} + +/** The hops `code.test_gate` follows: LOOM_TEST_GATE_DEPTH, 1 to 3. */ +export function gateDepth(env = process.env) { + return Math.min(3, Math.max(1, Number(env.LOOM_TEST_GATE_DEPTH || 2))); +} + /** Stable signature of the change: sorted changed paths + the diff's hash. */ export function gateSignature(changedPaths, diffHash) { const paths = (changedPaths || []).map(String).filter(Boolean).sort(); @@ -62,18 +104,14 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists : []; const absent = new Set(missing); const tests = indexed.filter((t) => !absent.has(String(t.test_path || ""))); - const raw = [...new Set(tests.map((t) => String(t.run || "")).filter(Boolean))]; - const runs = onePytest(raw.slice(0, maxRuns)).map((r) => withPython(r, python)); + const { raw, text: runs } = runList(tests, { maxRuns, python }); const unknown = tests .filter((t) => !t.run) .map((t) => String(t.test_path || "")) .filter(Boolean); const untested = Array.isArray(gate.untested) ? gate.untested : []; const parts = []; - if (runs.length) { - const more = raw.length - maxRuns; - parts.push(`run: ${runs.join(" ; ")}${more > 0 ? ` (+${more} more)` : ""}`); - } + if (runs) parts.push(`run: ${runs}`); if (unknown.length) { const shown = unknown.slice(0, maxNames); const more = unknown.length - shown.length; @@ -93,7 +131,7 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists // a test that builds an object reaches a constructor the graph holds no // edge to. parts.push( - runs.length || unknown.length + runs || unknown.length ? `the index links no test to: ${list} (the tests named here may still reach ${total > 1 ? "them" : "it"})` : `no test reaches: ${list}`, ); @@ -104,7 +142,7 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists // that went hunting for a runner. Say what the obligation actually is. const tail = missing.length ? "Run the available tests and check the missing paths against the indexed revision (deleted, renamed or different checkout); use current equivalent tests or say why not. Missing tests are not passes." - : runs.length || unknown.length + : runs || unknown.length ? "Run the tests before finishing, or say why not." : "Add a test that reaches it, or say why none is needed."; const env = @@ -116,6 +154,35 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists const isPytest = (run) => /^pytest(\s|$)/.test(String(run || "")); +/** The distinct run commands of `tests` (`raw`) and the first `maxRuns` of + * them as one text, "" when no test has one. */ +function runList(tests, { maxRuns, python }) { + const raw = [...new Set(tests.map((t) => String(t.run || "")).filter(Boolean))]; + const runs = onePytest(raw.slice(0, maxRuns)).map((r) => withPython(r, python)); + const more = raw.length - maxRuns; + return { raw, text: runs.length ? `${runs.join(" ; ")}${more > 0 ? ` (+${more} more)` : ""}` : "" }; +} + +/** + * The edit-time line for `rel`: the commands of the tests the index links + * to it, or "" when it links none this checkout has. A changed test file is + * the gate's own row, not a link, so an edit to a test names nothing. The + * functions the index links no test to are not named: the graph is a floor, + * and the line has no reply in which the agent could say so. + */ +export function renderAdvice(rel, gate, { maxRuns = 4, maxNames = 4, python, testExists } = {}) { + const tests = (gate && Array.isArray(gate.tests) ? gate.tests : []).filter( + (t) => t && t.why !== "changed_test" && t.test_path && (!testExists || testExists(String(t.test_path))), + ); + const parts = [runList(tests, { maxRuns, python }).text].filter(Boolean); + const unknown = [...new Set(tests.filter((t) => !t.run).map((t) => String(t.test_path)))]; + if (unknown.length) { + const more = unknown.length - maxNames; + parts.push(`no known runner: ${unknown.slice(0, maxNames).join(", ")}${more > 0 ? ` (+${more})` : ""}`); + } + return parts.length ? `Loom: tests the index links to ${rel}: ${parts.join(" · ")}` : ""; +} + /** `runs` with every `pytest ` folded into the first one: one command to * copy and one process to start. A run with an option or a second word stays * its own command. */ @@ -239,6 +306,20 @@ export function gatePayload(text) { return text ? { decision: "block", reason: text } : null; } +/** PostToolUse payload: additional context only, never a decision. */ +export function advicePayload(text) { + return text ? { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text } } : null; +} + +/** A predicate: is `testPath` a file of the checkout at `root`? A stale + * index row or another checkout's test is not. */ +export function testsIn(root) { + return (testPath) => { + const target = path.resolve(root, testPath); + return Boolean(pathUnder(root, target)) && isFile(target); + }; +} + /** `p` as a repo-relative posix path under `root` (resolved against `cwd` * when relative); "" when it lies outside the repo or `root` is unknown. */ function relativeToRoot(root, p, cwd) { @@ -339,6 +420,84 @@ export function writtenSince(root, paths, since) { }); } +// How much of a transcript's head is read for the session's first row. +const HEAD_BYTES = 64 * 1024; +// Files asked about for one tool call: a command that names more waits for +// the next call that names them. +const MAX_ADVICE_FILES = 4; + +/** + * The files a PostToolUse payload's tool call changed that this session has + * not been advised on, with the checkout root: the dirty paths its edit tool + * targeted or its shell command named, written since the session began. That + * is `sessionScope` and `writtenSince` over the one call, the rule the + * blocking gate applies to the whole transcript, so a command that only reads + * a file left dirty before the session names nothing. The hook runs after + * every shell command, so a call that cannot name an unasked dirty file (a + * path is named with its last segment) costs one git call, not two. + */ +export function adviceFiles(payload, { cwd, root = "" } = {}) { + const dirty = git(["diff", "--name-only", "-z", "HEAD"], root || cwd, { timeoutMs: 2000, raw: true }) + .split("\0") + .filter(Boolean); + const seen = dirty.length ? readSessionState("testadvice", payload.session_id).seen || {} : {}; + const text = `${commandText(payload.tool_input)}\n${extractFiles(payload.tool_input).join("\n")}`; + const unasked = dirty.filter((rel) => !seen[rel] && text.includes(rel.slice(rel.lastIndexOf("/") + 1))); + const top = unasked.length ? root || gitToplevel(cwd) : ""; + if (!top) return { root, files: [] }; + const call = { type: "tool_use", name: payload.tool_name, input: payload.tool_input }; + const named = sessionScope(unasked, [{ type: "assistant", message: { content: [call] } }], { root: top, cwd }); + const head = named.length && payload.transcript_path ? readRange(payload.transcript_path, 0, HEAD_BYTES) : ""; + const files = writtenSince(top, named, sessionStart(parseLines(head.toString()))).slice(0, MAX_ADVICE_FILES); + return { root: top, files }; +} + +/** + * The additional context for `files` (from `adviceFiles`): one line per + * file the index links to tests, "" when it links none. Each file is asked + * about once per session, whatever the server answers, so a server that is + * down costs a session one bounded request per file and not one per tool + * call. A file whose change is comments only is not asked about and stays + * unasked: it owes no test until it changes code. Only the diff's paths, + * hunk ranges and function names are sent (`diffHeaders`). + */ +export async function adviceLine(payload, files, { root, repo, token, depth = gateDepth() } = {}) { + const asked = files + .map((rel) => [ + rel, + git(["diff", ...DIFF_ARGS, "--unified=0", "HEAD", "--", rel], root, { timeoutMs: 2000, raw: true }), + ]) + .filter(([, diff]) => !commentOnlyDiff(diff)); + if (!asked.length) return ""; + const seen = { ...readSessionState("testadvice", payload.session_id).seen }; + for (const [rel] of asked) seen[rel] = Date.now(); + const keys = Object.keys(seen); + if (keys.length > 300) keys.slice(0, keys.length - 300).forEach((k) => delete seen[k]); + writeSessionState("testadvice", payload.session_id, { seen }); + const gates = await Promise.all( + asked.map(([rel, diff]) => + postBounded( + "code.test_gate", + { + org: repo.org, + namespace: repo.namespace, + files: [rel], + diff: diffHeaders(diff, 200_000), + depth, + consumer: "claude-code-testgate", + }, + { token, serverUrl: resolveServerUrl() }, + ), + ), + ); + const needsPython = gates.some((gate) => (gate?.tests || []).some((t) => isPytest(t?.run))); + const opts = { python: needsPython ? checkoutPython(root) : undefined, testExists: testsIn(root) }; + return asked + .map(([rel], i) => renderAdvice(rel, gates[i], opts)) + .filter(Boolean) + .join("\n"); +} + // The prompt's last sentence, whole: "Do not run the test suite.", "Please // don't run any tests". A sentence that says more (`do not run // tests/test_slow.py`, "If lint fails, do not run the tests.") or that is not From 7cc852952d4eed4425769619b80261e99b45a1b9 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 13:04:46 +0530 Subject: [PATCH 2/7] The edit-time tests line names a changed test's own command and names each test once per session The line named only the tests the index links to a changed file, so an index that links a source file to no test said nothing about a change to that file and its test: the blocking gate's ask for such a change is the changed test itself. That is the case in the recorded runs, whose index holds no test-map row. A changed test file with a known runner names its own command, as the blocking gate does. A test is named once per session, so a session that edits a source file and then the test the index links to it gets one line, not two with the same command. A file under a tests directory that no runner takes names nothing. The line reads `Loom tests for : `, which holds for both cases. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 43 +++++----- integrations/claude-code-plugin/README.md | 8 +- .../claude-code-plugin/hooks/HOOKS.md | 23 ++--- .../hooks/loom-blast-radius.mjs | 6 +- .../hooks/loom-test-gate.mjs | 15 ++-- .../claude-code-plugin/lib/test-gate.mjs | 83 ++++++++++++------- .../tests/test-gate.test.mjs | 57 ++++++++----- .../codex-plugin/hooks/loom-blast-radius.mjs | 6 +- .../codex-plugin/hooks/loom-test-gate.mjs | 15 ++-- integrations/codex-plugin/lib/test-gate.mjs | 83 ++++++++++++------- 10 files changed, 208 insertions(+), 131 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 4cec6d13d9f..7e9da3cabca 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -9,7 +9,7 @@ The `loom` plugin for Claude Code does three things in one install: call, and the agent has nothing to remember to do. - **Steers the agent to the code index** inside a Loom-indexed repository. Whole-file reads and tree-wide greps are redirected to `code.*` operations, and an edit gets the - file's rules before it and its blast radius after it. + file's rules before it, and its blast radius and the tests linked to the file after it. Source: `integrations/claude-code-plugin/`, Node ESM scripts with no dependencies. The Codex build runs the same scripts; see [codex.md](codex.md). @@ -388,12 +388,13 @@ index or a failed request. Edits performed through `Bash`, including scripts usi The test gate's line does follow a shell edit. It runs on `PostToolUse` after `Bash` and `PowerShell`, and rides the blast-radius hook after `Edit`, `Write` and `MultiEdit`. It -emits one line per changed file, `Loom: tests the index links to : `, the -first time the session changes that file, and only when the command names the file's -path, the file differs from `HEAD`, it was written after the session began, and the index -links it to a test the checkout has. It stays quiet for an edited test file, a -comment-only change, an untracked file, a file already asked about in the session, an -unavailable index or a failed request, and always with `LOOM_TEST_GATE=block` or `off`. +emits one line per changed file, `Loom tests for : `, the first time the +session changes that file, and only when the command names the file's path, the file +differs from `HEAD`, it was written after the session began, and it has a test to name: +one the index links to it and the checkout has, or the file itself when it is a test. It +stays quiet for a file whose tests an earlier line named, a comment-only change, an +untracked file, a file already asked about in the session, an unavailable index or a +failed request, and always with `LOOM_TEST_GATE=block` or `off`. Headless sessions support `hookSpecificOutput.additionalContext`; ordinary visible assistant output does not prove whether that context reached the model. Capture @@ -477,7 +478,7 @@ The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. | PreToolUse (Edit, Write, MultiEdit, NotebookEdit) | `loom-file-context.mjs` | what Loom knows about the file about to change (`memory.for_file`): your rules and the repository's shared rules and design decisions; once per file per 30 min | `LOOM_FILE_CONTEXT=off` | | PostToolUse (Loom tools) | `loom-mentor-hint.mjs` | lifts a result's `hint` into context, once per hint code per session | `LOOM_MENTOR_HINTS=off` | | PostToolUse (Edit, Write, MultiEdit) | `loom-blast-radius.mjs` | one line from `code.impact`: callers, tests reaching the change, co-change files not yet touched; on a file's first edit, the test gate's line beside it in place of the tests | `LOOM_BLAST_RADIUS=off` | -| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | one line per file the command changed, naming the command of the tests `code.test_gate` links to it; once per file per session, on the tool result, and never a blocked stop ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | +| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | one line per file the command changed, naming the command of the file's tests (`code.test_gate`); once per file and per test per session, on the tool result, and never a blocked stop ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | | PostToolUse, PostToolUseFailure, Stop, SessionEnd | `loom-record.mjs` | runs the event's recording scripts (the rows below for those events, the gates excepted) in one process: detached after a tool call and at Stop, so the session does not wait for their requests, and in the hook itself at SessionEnd | each script's own | | 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` | @@ -595,24 +596,26 @@ Beyond the off switches in the table: ## The test gate The test gate tells the agent which tests constrain a file when it changes the file. In -an indexed checkout, the tool call that first changes a file in a session comes back with -one extra line: +an indexed checkout, the tool call that first changes a file comes back with one extra +line when Loom has a test to name for it: ```text -Loom: tests the index links to src/flask/blueprints.py: python3 -m pytest tests/test_blueprints.py +Loom tests for src/flask/blueprints.py: python3 -m pytest tests/test_blueprints.py ``` -- **What it names.** The tests `code.test_gate` links to the file through its name, the - mined test map or the call graph, each of them present in the checkout, as one command - where the harness is known (`LOOM_CODE_TEST_GATE_RUN_TEMPLATES` on the server adds - yours) and by path where it is not. For pytest it names the checkout's interpreter - without starting it. -- **When.** Once per file per session, on the result of the edit tool or shell command - that changed the file. It costs no model request, and a session that never runs the - tests has still been told which ones they are. +- **What it names.** For a source file, the tests `code.test_gate` links to it through + its name, the mined test map or the call graph, each of them present in the checkout. + For a test file, the file itself. A test is given as one command where the harness is + known (`LOOM_CODE_TEST_GATE_RUN_TEMPLATES` on the server adds yours) and by path where + it is not. For pytest the line names the checkout's interpreter without starting it. +- **When.** Once per file and once per test per session, on the result of the edit tool + or shell command that changed the file. It costs no model request, and a session that + never runs the tests has still been told which ones they are. - **What it does not do.** It does not check that the tests ran, and it never holds the end of a session. Whether a session ran the right tests cannot be read reliably from - its shell commands, so that judgement stays with the agent and with CI. + its shell commands, so that judgement stays with the agent and with CI. It names no + function the index links no test to, and a source file the index links to no test gets + no line. To hold the stop instead, 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 diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 03fcb0863ca..c9456102219 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -95,8 +95,8 @@ Loom's MCP requests) run `node`, `git` and `grep` on your machine: `git` reads the checkout's remotes, branch, `HEAD` commit, status and diffs, and `grep` searches uncommitted files for the pattern of a grep the plugin redirects to the code index. The `loom-session` skill's brief script also runs `git log` for the -commits since the last brief. The test gate (the hook that names the tests the -index links to a file you change) runs no Python: for a pytest test it picks the +commits since the last brief. The test gate (the hook that names the tests of a +file you change) runs no Python: for a pytest test it picks the interpreter of the checkout's virtualenv, the active one (`VIRTUAL_ENV`) or a `python3` or `python` on `PATH`, checking that the interpreter's file exists without running it. @@ -151,7 +151,7 @@ the duplicate, run `claude mcp remove -s user`. | `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about the target file (its files facet) and injects the rendered block as additional context — a constraint arrives **before** the edit, not as a review comment. One lookup per (session, file) per 30 min; never a permission decision. `LOOM_FILE_CONTEXT=off` disables. | | `PostToolUse` (loom tools) | `loom-mentor-hint.mjs` | **The store's advice reaches the model**: a loom tool result may carry one `hint` — the plane this agent is not using, named from the call it just made (a `memory.get` that missed, a search that abstained where the code index answers, a stack trace written as a memory, a duplicate write). The hook lifts it out of the result JSON into additional context, once per code per session. No request of its own. `LOOM_MENTOR_HINTS=off` disables. | | `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which then stands in for the radius's count of tests, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | -| `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` which tests the index links to each file the command changed (a dirty path it names, written since the session began) and attaches **one line** per file with their command: `Loom: tests the index links to src/a.py: .venv/bin/python -m pytest tests/test_a.py`. Once per file 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 test file you edit names nothing, and neither does a comment-only change. The stop is never held: whether the tests ran is the agent's call (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | +| `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 the index links to no test names nothing, and neither does a comment-only change. The stop is never held: whether the tests ran is the agent's call (**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` | **Only with `LOOM_TEST_GATE=block`**, in place of the line at edit time. 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: the tests were named before "done", the choice to run them is the agent's. A stop whose transcript already answers the ask to run tests is not blocked, and so names no untested function (**Answered stops**, below). | @@ -169,7 +169,7 @@ the duplicate, run `claude mcp remove -s user`. **Team file rules.** The file-context hook reads two places in one `memory.for_file` request: your own namespace, and the repository's **primary code namespace** (its trunk branch's — `code-clickhouse` for every ClickHouse branch), named by the checkout's cached `code.repos` entry. A namespace you cannot read is skipped silently, so access follows repository access. Rules from the code namespace render as `Team rule (by alice, 3 days ago) [constraint]: … [id: ]` and design decisions (typed or tagged `decision`) as `Decision (by alice, 3 days ago) (pinned): … — source: [id: ]` (`(pinned)` only when someone pinned it, else no mark; `(source changed)` once its source document no longer says it), a newer rule the conflict check linked to an older one sits above it (`supersedes rule by …`, or `supersedes decision by …`), and one footer line says how to remove a wrong one. Every member of the repository may add a rule there (`memory.set` with `files` and the tag `constraint`) and revise or delete the rules they wrote; a maintainer may delete any — from an agent (`memory.delete` on the `[id:]` key) or from the dashboard (pick the code namespace under _show system_, open the memory, Delete). A refused delete answers a `hint` naming the author and what to do instead. `memory.set` fills `files` from the value when you do not pass it. Auto-extracted session facts never go to the code namespace. -**Tests at edit time.** The test gate names tests; it does not check that they ran. Deciding that from a transcript means reading shell text, and a session that runs the whole suite, compares against a stashed tree or pipes pytest through `grep` has run the tests in a way no fixed rule reads, so a gate that holds the stop on that reading holds sessions that did the work. By default the gate therefore says which tests the index links to a file on the tool call that changes it, where the agent is still working on the file, and leaves the end of the session alone. A file is asked about once per session, whatever the server answers, and at most four files per tool call. The line names commands only: the tests the index links to the file 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. A team that wants the stop held until the tests are named 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. +**Tests at edit time.** The test gate names tests; it does not check that they ran. Deciding that from a transcript means reading shell text, and a session that runs the whole suite, compares against a stashed tree or pipes pytest through `grep` has run the tests in a way no fixed rule reads, so a gate that holds the stop on that reading holds sessions that did the work. By default the gate therefore names a file's tests on the tool call that changes it, where the agent is still working on the file, and leaves the end of the session alone. 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. The line names commands only, and no function the index links no test to. A file is asked about once per session, whatever the server answers, and at most four files per tool call; a test is named once per session, so the test you edit after its source file adds no second line. A source file the index links to no test gets no line. A team that wants the stop held until the tests are named 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 blocking gate's reason 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. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index f35fcfb4d8b..53e031287e5 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -282,18 +282,19 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). namespace.audit over the last day (sample_limit=0); a critical finding gives the agent one line naming the codes and /loom-optimize, as a block-once reason. Later stops make no call. -- **loom-test-gate.** Names the tests the index links to a changed file. - By default it does so when the file changes and never holds the stop: - 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 since the session's first row, asks code.test_gate about - each one not asked about yet this session (`adviceFiles`, `adviceLine` in +- **loom-test-gate.** Names the tests of a changed file. By default it + does so when the file changes and never holds the stop: 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 + since the session's first row, asks code.test_gate about each one not + asked about yet this session (`adviceFiles`, `adviceLine` in lib/test-gate.mjs; at most four per call; a comment-only change is not - asked about) and prints one line per file naming the commands of the - linked tests the checkout has, as additionalContext on that tool result: - no model request, and no reading of shell text to decide whether tests - ran. A changed test file names nothing. A call that names no unasked - dirty file costs one git call and no request. + asked about) and prints one line per file as additionalContext on that + tool result: the commands of the tests the index links to the file that + the checkout has, or the file's own command when it is a test. A test is + named once per session. The line costs no model request, and nothing + reads shell text to decide whether tests ran. A call that names no + unasked dirty file costs one git call and no request. With LOOM_TEST_GATE=block it holds the stop instead and prints nothing at edit time: with uncommitted changes this session made in a loom-indexed repo (dirty paths the transcript shows an edit tool targeted or a shell diff --git a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs index 837e7bfffea..1bccdd66e95 100644 --- a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs @@ -9,9 +9,9 @@ // cheap to fix. // // The test gate's edit-time line rides the same context: the first edit of a -// file this session also asks `code.test_gate` which tests the index links -// to it and names their command (lib/test-gate.mjs), in place of the radius's -// own count of tests. This hook is the only one wired for an edit tool, so an +// file this session also asks `code.test_gate` for the file's tests and names +// their command (lib/test-gate.mjs), in place of the radius's own count of +// tests. This hook is the only one wired for an edit tool, so an // edit gets one line. LOOM_TEST_GATE=block or off leaves the radius alone. // // Fail-open everywhere: no token, not an indexed repo, untracked file, empty diff --git a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs index 2ce175a0560..40378f207d8 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -2,13 +2,14 @@ // loom-test-gate — PostToolUse (Bash|PowerShell) and Stop. // // PostToolUse, the default (LOOM_TEST_GATE unset): after a shell command -// that changed files in a loom-indexed repo, ask `code.test_gate` which -// tests the index links to each one and attach ONE line per file naming -// their command, once per file per session. The line rides the tool result, -// so it costs no model request, and it arrives while the file is still -// being edited. An edit tool's call gets the same line from -// loom-blast-radius, the one hook wired for those tools. The stop is never -// held: whether the tests then ran is the agent's to judge. +// that changed files in a loom-indexed repo, ask `code.test_gate` about each +// one and attach ONE line per file naming the command of the tests the +// index links to it, or of the file itself when it is a test; once per file +// and once per test per session. The line rides the tool result, so it +// costs no model request, and it arrives while the file is still being +// edited. An edit tool's call gets the same line from loom-blast-radius, the +// one hook wired for those tools. The stop is never held: whether the tests +// then ran is the agent's to judge. // // Stop, with LOOM_TEST_GATE=block: the gate holds the stop instead, and // names nothing at edit time. If the working tree has uncommitted changes diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index a84a07f2a4c..a9d9fdaecaa 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1,11 +1,12 @@ // Helpers for the loom-test-gate hook (unit-tested). // -// The gate names the tests the index links to a change, from -// `code.test_gate`. By default it names them when the file is edited: the -// tool call that changed a file carries one line with the command, once per -// file per session, and the stop is never held (`adviceFiles`, `adviceLine`). -// Whether a session then ran the tests is the agent's to judge: a hook that -// reads shell text to decide it blocks sessions that did. +// The gate names the tests a change obliges, from `code.test_gate`. By +// default it names them when the file is edited: the tool call that changed +// a file carries one line with the command of the tests the index links to +// it, or of the file itself when it is a test, once per file per session, +// and the stop is never held (`adviceFiles`, `adviceLine`). Whether a +// session then ran the tests is the agent's to judge: a hook that reads +// shell text to decide it blocks sessions that did. // // With LOOM_TEST_GATE=block the gate holds the stop instead. When the agent // is about to stop with uncommitted changes in a loom-indexed repo, it asks @@ -164,23 +165,33 @@ function runList(tests, { maxRuns, python }) { } /** - * The edit-time line for `rel`: the commands of the tests the index links - * to it, or "" when it links none this checkout has. A changed test file is - * the gate's own row, not a link, so an edit to a test names nothing. The - * functions the index links no test to are not named: the graph is a floor, - * and the line has no reply in which the agent could say so. + * The tests of a `code.test_gate` answer about `rel` alone that the + * edit-time line names: the ones the checkout has. For a source file they + * are the tests the index links to it; for a test file, the file itself. + * A file under a tests directory that no runner takes (a fixture, a + * conftest) is not a test to run for its own change. */ -export function renderAdvice(rel, gate, { maxRuns = 4, maxNames = 4, python, testExists } = {}) { - const tests = (gate && Array.isArray(gate.tests) ? gate.tests : []).filter( - (t) => t && t.why !== "changed_test" && t.test_path && (!testExists || testExists(String(t.test_path))), +export function adviceTests(rel, gate, testExists) { + return (gate && Array.isArray(gate.tests) ? gate.tests : []).filter( + (t) => + t && t.test_path && (t.run || String(t.test_path) !== rel) && (!testExists || testExists(String(t.test_path))), ); +} + +/** + * The edit-time line for `rel` from `tests` (see `adviceTests`), or "" when + * there are none: their commands, then the tests no runner is known for. No + * function the index links no test to is named: the graph is a floor, and + * the line has no reply in which the agent could say so. + */ +export function renderAdvice(rel, tests, { maxRuns = 4, maxNames = 4, python } = {}) { const parts = [runList(tests, { maxRuns, python }).text].filter(Boolean); const unknown = [...new Set(tests.filter((t) => !t.run).map((t) => String(t.test_path)))]; if (unknown.length) { const more = unknown.length - maxNames; parts.push(`no known runner: ${unknown.slice(0, maxNames).join(", ")}${more > 0 ? ` (+${more})` : ""}`); } - return parts.length ? `Loom: tests the index links to ${rel}: ${parts.join(" · ")}` : ""; + return parts.length ? `Loom tests for ${rel}: ${parts.join(" · ")}` : ""; } /** `runs` with every `pytest ` folded into the first one: one command to @@ -452,14 +463,23 @@ export function adviceFiles(payload, { cwd, root = "" } = {}) { return { root: top, files }; } +/** `map` without its oldest keys beyond `max`. */ +function newest(map, max = 300) { + const keys = Object.keys(map); + for (const k of keys.slice(0, Math.max(0, keys.length - max))) delete map[k]; + return map; +} + /** * The additional context for `files` (from `adviceFiles`): one line per - * file the index links to tests, "" when it links none. Each file is asked - * about once per session, whatever the server answers, so a server that is - * down costs a session one bounded request per file and not one per tool - * call. A file whose change is comments only is not asked about and stays - * unasked: it owes no test until it changes code. Only the diff's paths, - * hunk ranges and function names are sent (`diffHeaders`). + * file that has tests to name, "" when none has. Each file is asked about + * once per session, whatever the server answers, so a server that is down + * costs a session one bounded request per file and not one per tool call. A + * file whose change is comments only is not asked about and stays unasked: + * it owes no test until it changes code. A test is named once per session: + * the test file a session edits after the source file it tests adds no + * second line with the same command. Only the diff's paths, hunk ranges and + * function names are sent (`diffHeaders`). */ export async function adviceLine(payload, files, { root, repo, token, depth = gateDepth() } = {}) { const asked = files @@ -469,11 +489,10 @@ export async function adviceLine(payload, files, { root, repo, token, depth = ga ]) .filter(([, diff]) => !commentOnlyDiff(diff)); if (!asked.length) return ""; - const seen = { ...readSessionState("testadvice", payload.session_id).seen }; + const state = () => readSessionState("testadvice", payload.session_id); + const seen = { ...state().seen }; for (const [rel] of asked) seen[rel] = Date.now(); - const keys = Object.keys(seen); - if (keys.length > 300) keys.slice(0, keys.length - 300).forEach((k) => delete seen[k]); - writeSessionState("testadvice", payload.session_id, { seen }); + writeSessionState("testadvice", payload.session_id, { ...state(), seen: newest(seen) }); const gates = await Promise.all( asked.map(([rel, diff]) => postBounded( @@ -490,10 +509,18 @@ export async function adviceLine(payload, files, { root, repo, token, depth = ga ), ), ); - const needsPython = gates.some((gate) => (gate?.tests || []).some((t) => isPytest(t?.run))); - const opts = { python: needsPython ? checkoutPython(root) : undefined, testExists: testsIn(root) }; + const named = { ...state().named }; + const testExists = testsIn(root); + const tests = asked.map(([rel], i) => { + const fresh = adviceTests(rel, gates[i], testExists).filter((t) => !named[t.test_path]); + for (const t of fresh) named[t.test_path] = Date.now(); + return fresh; + }); + if (!tests.some((t) => t.length)) return ""; + writeSessionState("testadvice", payload.session_id, { ...state(), named: newest(named) }); + const python = tests.flat().some((t) => isPytest(t.run)) ? checkoutPython(root) : undefined; return asked - .map(([rel], i) => renderAdvice(rel, gates[i], opts)) + .map(([rel], i) => renderAdvice(rel, tests[i], { python })) .filter(Boolean) .join("\n"); } diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index b6be062e157..e47e6765e24 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -6,6 +6,7 @@ import os from "node:os"; import path from "node:path"; import { advicePayload, + adviceTests, checkoutPython, decideBlock, gateMode, @@ -44,10 +45,10 @@ test("the gate advises at edit time unless LOOM_TEST_GATE says block or off", () }); test("the edit-time line names the commands of the tests the index links to the file", () => { - const text = renderAdvice("src/a.py", GATE, { python: ".venv/bin/python" }); + const text = renderAdvice("src/a.py", adviceTests("src/a.py", GATE), { python: ".venv/bin/python" }); assert.equal( text, - "Loom: tests the index links to src/a.py: .venv/bin/python -m pytest tests/unit/test_a.py · no known runner: src/x/tests/gtest_parts.cpp", + "Loom tests for src/a.py: .venv/bin/python -m pytest tests/unit/test_a.py · no known runner: src/x/tests/gtest_parts.cpp", ); // No function is named: the graph is a floor, and the line asks for no reply. assert.doesNotMatch(text, /renameTempPartAndAdd|no test reaches|links no test/); @@ -56,29 +57,37 @@ test("the edit-time line names the commands of the tests the index links to the }); }); -test("an edited test file, a test the checkout lacks and an empty answer name nothing", () => { +test("a changed test names its own command; a file no runner takes, a test the checkout lacks and an empty answer name nothing", () => { + const line = (rel, gate, testExists) => renderAdvice(rel, adviceTests(rel, gate, testExists)); const own = { tests: [{ test_path: "tests/test_a.py", why: "changed_test", run: "pytest tests/test_a.py" }] }; - assert.equal(renderAdvice("tests/test_a.py", own), ""); + assert.equal(line("tests/test_a.py", own), "Loom tests for tests/test_a.py: pytest tests/test_a.py"); + // A fixture or a conftest under tests/ is the gate's row for itself, with no runner. + const fixture = { tests: [{ test_path: "tests/conftest.py", why: "changed_test", run: "", run_unknown: true }] }; + assert.equal(line("tests/conftest.py", fixture), ""); const gone = { tests: [{ test_path: "tests/gone.py", why: "test_map", run: "pytest tests/gone.py" }] }; - assert.equal(renderAdvice("src/a.py", gone, { testExists: () => false }), ""); - assert.match(renderAdvice("src/a.py", gone, { testExists: () => true }), /: pytest tests\/gone\.py$/); + assert.equal( + line("src/a.py", gone, () => false), + "", + ); + assert.equal( + line("src/a.py", gone, () => true), + "Loom tests for src/a.py: pytest tests/gone.py", + ); for (const none of [null, {}, { tests: [] }, { untested: [{ qualified_name: "m::f" }] }]) { - assert.equal(renderAdvice("src/a.py", none), ""); + assert.equal(line("src/a.py", none), ""); } assert.equal(advicePayload(""), null); }); test("the edit-time line folds pytest files into one command and counts the commands it leaves out", () => { - const many = { - tests: ["a", "b", "c", "d", "e", "f"].map((n) => ({ - test_path: `tests/test_${n}.py`, - why: "graph_hop", - run: `pytest tests/test_${n}.py`, - })), - }; + const many = ["a", "b", "c", "d", "e", "f"].map((n) => ({ + test_path: `tests/test_${n}.py`, + why: "graph_hop", + run: `pytest tests/test_${n}.py`, + })); assert.equal( renderAdvice("src/a.py", many), - "Loom: tests the index links to src/a.py: pytest tests/test_a.py tests/test_b.py tests/test_c.py tests/test_d.py (+2 more)", + "Loom tests for src/a.py: pytest tests/test_a.py tests/test_b.py tests/test_c.py tests/test_d.py (+2 more)", ); }); @@ -977,7 +986,7 @@ test("with LOOM_TEST_GATE=block the hook blocks a change whose tests never ran a test("a changed file's tests ride the tool call that changed it, once, and the stop is never held", async () => { const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-advice-"))); const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-advice-tmp-"))); - for (const f of ["src/a.py", "src/b.py", "src/old.py", "tests/test_a.py", "tests/test_b.py"]) { + for (const f of ["src/a.py", "src/b.py", "src/old.py", "tests/test_a.py", "tests/test_b.py", "tests/test_c.py"]) { fs.mkdirSync(path.join(dir, path.dirname(f)), { recursive: true }); fs.writeFileSync(path.join(dir, f), "def f():\n return 1\n"); } @@ -1065,13 +1074,13 @@ test("a changed file's tests ride the tool call that changed it, once, and the s // A command that changes nothing, or only reads a file left dirty before the session, asks nothing. assert.equal(await shell("ls src; cat src/old.py"), null); assert.deepEqual(asked, []); - // One command edits a source file and its test: one line, for the source file. + // One command edits a source file and its test: one line, since the test is named once. write("src/a.py", "def g():\n return 2\n"); write("tests/test_a.py", "def test_g():\n assert True\n"); const edit = "python - <<'EOF'\nopen('src/a.py','a').write('x')\nopen('tests/test_a.py','a').write('y')\nEOF"; const first = await shell(edit); assert.equal(first.hookSpecificOutput.hookEventName, "PostToolUse"); - assert.match(context(first), /^Loom: tests the index links to src\/a\.py: (?:\S+ -m )?pytest tests\/test_a\.py$/); + assert.match(context(first), /^Loom tests for src\/a\.py: (?:\S+ -m )?pytest tests\/test_a\.py$/); assert.equal(first.decision, undefined); assert.deepEqual(asked.sort(), ["/v1/code.test_gate src/a.py", "/v1/code.test_gate tests/test_a.py"]); // Later commands that name the file, a test run among them, add nothing and ask nothing. @@ -1088,7 +1097,7 @@ test("a changed file's tests ride the tool call that changed it, once, and the s context(edited), /^Loom blast radius for src\/b\.py \(edited m::g\): 1 caller in 1 file: m::caller \(c\.py\)\. /, ); - assert.match(context(edited), / Loom: tests the index links to src\/b\.py: (?:\S+ -m )?pytest tests\/test_b\.py$/); + assert.match(context(edited), / Loom tests for src\/b\.py: (?:\S+ -m )?pytest tests\/test_b\.py$/); assert.doesNotMatch(context(edited), /tests reaching it/); // The shell hook leaves an edit tool's call to that hook, and the file is asked about once. assert.equal( @@ -1099,6 +1108,14 @@ test("a changed file's tests ride the tool call that changed it, once, and the s null, ); assert.equal(await shell("sed -i s/2/3/ src/b.py"), null); + // The test of a file already named adds no second line when it changes; another test names itself. + write("tests/test_b.py", "def test_g():\n assert True\n"); + assert.equal(await shell("sed -i s/1/2/ tests/test_b.py"), null); + write("tests/test_c.py", "def test_g():\n assert True\n"); + assert.match( + context(await shell("sed -i s/1/2/ tests/test_c.py")), + /^Loom tests for tests\/test_c\.py: (?:\S+ -m )?pytest tests\/test_c\.py$/, + ); // A comment-only change owes no test and stays unasked until it changes code. write("src/old.py", "# a note\n"); execFileSync("git", ["checkout", "-q", "--", "src/old.py"], { cwd: dir }); @@ -1126,7 +1143,7 @@ test("a changed file's tests ride the tool call that changed it, once, and the s blocking, ); assert.match(context(radius), /tests reaching it: 1 \(test_b\.py\)/); - assert.doesNotMatch(context(radius), /tests the index links/); + 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"); // LOOM_TEST_GATE=off: neither. diff --git a/integrations/codex-plugin/hooks/loom-blast-radius.mjs b/integrations/codex-plugin/hooks/loom-blast-radius.mjs index 837e7bfffea..1bccdd66e95 100644 --- a/integrations/codex-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/codex-plugin/hooks/loom-blast-radius.mjs @@ -9,9 +9,9 @@ // cheap to fix. // // The test gate's edit-time line rides the same context: the first edit of a -// file this session also asks `code.test_gate` which tests the index links -// to it and names their command (lib/test-gate.mjs), in place of the radius's -// own count of tests. This hook is the only one wired for an edit tool, so an +// file this session also asks `code.test_gate` for the file's tests and names +// their command (lib/test-gate.mjs), in place of the radius's own count of +// tests. This hook is the only one wired for an edit tool, so an // edit gets one line. LOOM_TEST_GATE=block or off leaves the radius alone. // // Fail-open everywhere: no token, not an indexed repo, untracked file, empty diff --git a/integrations/codex-plugin/hooks/loom-test-gate.mjs b/integrations/codex-plugin/hooks/loom-test-gate.mjs index 2ce175a0560..40378f207d8 100644 --- a/integrations/codex-plugin/hooks/loom-test-gate.mjs +++ b/integrations/codex-plugin/hooks/loom-test-gate.mjs @@ -2,13 +2,14 @@ // loom-test-gate — PostToolUse (Bash|PowerShell) and Stop. // // PostToolUse, the default (LOOM_TEST_GATE unset): after a shell command -// that changed files in a loom-indexed repo, ask `code.test_gate` which -// tests the index links to each one and attach ONE line per file naming -// their command, once per file per session. The line rides the tool result, -// so it costs no model request, and it arrives while the file is still -// being edited. An edit tool's call gets the same line from -// loom-blast-radius, the one hook wired for those tools. The stop is never -// held: whether the tests then ran is the agent's to judge. +// that changed files in a loom-indexed repo, ask `code.test_gate` about each +// one and attach ONE line per file naming the command of the tests the +// index links to it, or of the file itself when it is a test; once per file +// and once per test per session. The line rides the tool result, so it +// costs no model request, and it arrives while the file is still being +// edited. An edit tool's call gets the same line from loom-blast-radius, the +// one hook wired for those tools. The stop is never held: whether the tests +// then ran is the agent's to judge. // // Stop, with LOOM_TEST_GATE=block: the gate holds the stop instead, and // names nothing at edit time. If the working tree has uncommitted changes diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index a84a07f2a4c..a9d9fdaecaa 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1,11 +1,12 @@ // Helpers for the loom-test-gate hook (unit-tested). // -// The gate names the tests the index links to a change, from -// `code.test_gate`. By default it names them when the file is edited: the -// tool call that changed a file carries one line with the command, once per -// file per session, and the stop is never held (`adviceFiles`, `adviceLine`). -// Whether a session then ran the tests is the agent's to judge: a hook that -// reads shell text to decide it blocks sessions that did. +// The gate names the tests a change obliges, from `code.test_gate`. By +// default it names them when the file is edited: the tool call that changed +// a file carries one line with the command of the tests the index links to +// it, or of the file itself when it is a test, once per file per session, +// and the stop is never held (`adviceFiles`, `adviceLine`). Whether a +// session then ran the tests is the agent's to judge: a hook that reads +// shell text to decide it blocks sessions that did. // // With LOOM_TEST_GATE=block the gate holds the stop instead. When the agent // is about to stop with uncommitted changes in a loom-indexed repo, it asks @@ -164,23 +165,33 @@ function runList(tests, { maxRuns, python }) { } /** - * The edit-time line for `rel`: the commands of the tests the index links - * to it, or "" when it links none this checkout has. A changed test file is - * the gate's own row, not a link, so an edit to a test names nothing. The - * functions the index links no test to are not named: the graph is a floor, - * and the line has no reply in which the agent could say so. + * The tests of a `code.test_gate` answer about `rel` alone that the + * edit-time line names: the ones the checkout has. For a source file they + * are the tests the index links to it; for a test file, the file itself. + * A file under a tests directory that no runner takes (a fixture, a + * conftest) is not a test to run for its own change. */ -export function renderAdvice(rel, gate, { maxRuns = 4, maxNames = 4, python, testExists } = {}) { - const tests = (gate && Array.isArray(gate.tests) ? gate.tests : []).filter( - (t) => t && t.why !== "changed_test" && t.test_path && (!testExists || testExists(String(t.test_path))), +export function adviceTests(rel, gate, testExists) { + return (gate && Array.isArray(gate.tests) ? gate.tests : []).filter( + (t) => + t && t.test_path && (t.run || String(t.test_path) !== rel) && (!testExists || testExists(String(t.test_path))), ); +} + +/** + * The edit-time line for `rel` from `tests` (see `adviceTests`), or "" when + * there are none: their commands, then the tests no runner is known for. No + * function the index links no test to is named: the graph is a floor, and + * the line has no reply in which the agent could say so. + */ +export function renderAdvice(rel, tests, { maxRuns = 4, maxNames = 4, python } = {}) { const parts = [runList(tests, { maxRuns, python }).text].filter(Boolean); const unknown = [...new Set(tests.filter((t) => !t.run).map((t) => String(t.test_path)))]; if (unknown.length) { const more = unknown.length - maxNames; parts.push(`no known runner: ${unknown.slice(0, maxNames).join(", ")}${more > 0 ? ` (+${more})` : ""}`); } - return parts.length ? `Loom: tests the index links to ${rel}: ${parts.join(" · ")}` : ""; + return parts.length ? `Loom tests for ${rel}: ${parts.join(" · ")}` : ""; } /** `runs` with every `pytest ` folded into the first one: one command to @@ -452,14 +463,23 @@ export function adviceFiles(payload, { cwd, root = "" } = {}) { return { root: top, files }; } +/** `map` without its oldest keys beyond `max`. */ +function newest(map, max = 300) { + const keys = Object.keys(map); + for (const k of keys.slice(0, Math.max(0, keys.length - max))) delete map[k]; + return map; +} + /** * The additional context for `files` (from `adviceFiles`): one line per - * file the index links to tests, "" when it links none. Each file is asked - * about once per session, whatever the server answers, so a server that is - * down costs a session one bounded request per file and not one per tool - * call. A file whose change is comments only is not asked about and stays - * unasked: it owes no test until it changes code. Only the diff's paths, - * hunk ranges and function names are sent (`diffHeaders`). + * file that has tests to name, "" when none has. Each file is asked about + * once per session, whatever the server answers, so a server that is down + * costs a session one bounded request per file and not one per tool call. A + * file whose change is comments only is not asked about and stays unasked: + * it owes no test until it changes code. A test is named once per session: + * the test file a session edits after the source file it tests adds no + * second line with the same command. Only the diff's paths, hunk ranges and + * function names are sent (`diffHeaders`). */ export async function adviceLine(payload, files, { root, repo, token, depth = gateDepth() } = {}) { const asked = files @@ -469,11 +489,10 @@ export async function adviceLine(payload, files, { root, repo, token, depth = ga ]) .filter(([, diff]) => !commentOnlyDiff(diff)); if (!asked.length) return ""; - const seen = { ...readSessionState("testadvice", payload.session_id).seen }; + const state = () => readSessionState("testadvice", payload.session_id); + const seen = { ...state().seen }; for (const [rel] of asked) seen[rel] = Date.now(); - const keys = Object.keys(seen); - if (keys.length > 300) keys.slice(0, keys.length - 300).forEach((k) => delete seen[k]); - writeSessionState("testadvice", payload.session_id, { seen }); + writeSessionState("testadvice", payload.session_id, { ...state(), seen: newest(seen) }); const gates = await Promise.all( asked.map(([rel, diff]) => postBounded( @@ -490,10 +509,18 @@ export async function adviceLine(payload, files, { root, repo, token, depth = ga ), ), ); - const needsPython = gates.some((gate) => (gate?.tests || []).some((t) => isPytest(t?.run))); - const opts = { python: needsPython ? checkoutPython(root) : undefined, testExists: testsIn(root) }; + const named = { ...state().named }; + const testExists = testsIn(root); + const tests = asked.map(([rel], i) => { + const fresh = adviceTests(rel, gates[i], testExists).filter((t) => !named[t.test_path]); + for (const t of fresh) named[t.test_path] = Date.now(); + return fresh; + }); + if (!tests.some((t) => t.length)) return ""; + writeSessionState("testadvice", payload.session_id, { ...state(), named: newest(named) }); + const python = tests.flat().some((t) => isPytest(t.run)) ? checkoutPython(root) : undefined; return asked - .map(([rel], i) => renderAdvice(rel, gates[i], opts)) + .map(([rel], i) => renderAdvice(rel, tests[i], { python })) .filter(Boolean) .join("\n"); } From d4eb3221bef5c252ea30bc59f532934425ad4ef7 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 13:42:11 +0530 Subject: [PATCH 3/7] The test gate's docs example names no particular project Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 7e9da3cabca..4799668eb21 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -600,7 +600,7 @@ an indexed checkout, the tool call that first changes a file comes back with one line when Loom has a test to name for it: ```text -Loom tests for src/flask/blueprints.py: python3 -m pytest tests/test_blueprints.py +Loom tests for src/app/router.py: .venv/bin/python -m pytest tests/test_router.py ``` - **What it names.** For a source file, the tests `code.test_gate` links to it through From 1972876389d6d7591e8c566230452ad17d7f086b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 14:52:24 +0530 Subject: [PATCH 4/7] The edit-time tests line names the functions the index links no test to, and not a test the command itself ran A changed source file the index links to no test got no line, and the stop is no longer held, so a session that changed source and added or ran no test was told nothing. The line now names the changed functions for a file that has no test to run in the checkout: `Loom tests for : the index links no test to `, worded as the index's view, once per file. A test whose command the call's own command holds is not named: the line arrived on the result of that very run. Only the tests a line printed count as named, so one folded into "(+N more)" is still named when its own file changes. The blast radius leaves its count of tests out only where the line names tests for the edited file, not for another file of the same call. After a shell command, a checkout the shared cache says is not indexed costs no git call: the root is found by its `.git` entry. The docs say that a file is asked about at its first change only, the hook tables name each row's off switch again, and both manifests take 1.2.69. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- 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 | 25 ++-- .../hooks/loom-blast-radius.mjs | 16 ++- .../hooks/loom-test-gate.mjs | 17 ++- .../claude-code-plugin/lib/repo-scope.mjs | 18 +++ .../claude-code-plugin/lib/test-gate.mjs | 123 ++++++++++++------ .../tests/test-gate.test.mjs | 74 ++++++++++- .../codex-plugin/.codex-plugin/plugin.json | 2 +- .../codex-plugin/hooks/loom-blast-radius.mjs | 16 ++- .../codex-plugin/hooks/loom-test-gate.mjs | 17 ++- integrations/codex-plugin/lib/repo-scope.mjs | 18 +++ integrations/codex-plugin/lib/test-gate.mjs | 123 ++++++++++++------ 14 files changed, 350 insertions(+), 134 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 4799668eb21..7962bd0357b 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -390,11 +390,12 @@ The test gate's line does follow a shell edit. It runs on `PostToolUse` after `B `PowerShell`, and rides the blast-radius hook after `Edit`, `Write` and `MultiEdit`. It emits one line per changed file, `Loom tests for : `, the first time the session changes that file, and only when the command names the file's path, the file -differs from `HEAD`, it was written after the session began, and it has a test to name: -one the index links to it and the checkout has, or the file itself when it is a test. It -stays quiet for a file whose tests an earlier line named, a comment-only change, an -untracked file, a file already asked about in the session, an unavailable index or a -failed request, and always with `LOOM_TEST_GATE=block` or `off`. +differs from `HEAD`, it was written after the session began, and there is something to +name: a test the index links to it and the checkout has, the file itself when it is a +test, or, with no such test, the changed functions the index links no test to. It +stays quiet for a file whose tests an earlier line named or the command itself ran, a +comment-only change, an untracked file, a file already asked about in the session, an +unavailable index or a failed request, and always with `LOOM_TEST_GATE=block` or `off`. Headless sessions support `hookSpecificOutput.additionalContext`; ordinary visible assistant output does not prove whether that context reached the model. Capture @@ -478,12 +479,12 @@ The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. | PreToolUse (Edit, Write, MultiEdit, NotebookEdit) | `loom-file-context.mjs` | what Loom knows about the file about to change (`memory.for_file`): your rules and the repository's shared rules and design decisions; once per file per 30 min | `LOOM_FILE_CONTEXT=off` | | PostToolUse (Loom tools) | `loom-mentor-hint.mjs` | lifts a result's `hint` into context, once per hint code per session | `LOOM_MENTOR_HINTS=off` | | PostToolUse (Edit, Write, MultiEdit) | `loom-blast-radius.mjs` | one line from `code.impact`: callers, tests reaching the change, co-change files not yet touched; on a file's first edit, the test gate's line beside it in place of the tests | `LOOM_BLAST_RADIUS=off` | -| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | one line per file the command changed, naming the command of the file's tests (`code.test_gate`); once per file and per test per session, on the tool result, and never a blocked stop ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | +| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | one line per file the command changed, naming the command of the file's tests, or the changed functions the index links no test to (`code.test_gate`); once per file and per test per session, on the tool result, and never a blocked stop ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | | PostToolUse, PostToolUseFailure, Stop, SessionEnd | `loom-record.mjs` | runs the event's recording scripts (the rows below for those events, the gates excepted) in one process: detached after a tool call and at Stop, so the session does not wait for their requests, and in the hook itself at SessionEnd | each script's own | | 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` | only 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 already ran them to its summary line, failures included, and nothing was edited or run since (exact conditions: **Answered stops** in the plugin README) | `LOOM_TEST_GATE=block` | +| Stop | `loom-test-gate.mjs` | only 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 already ran them to its summary line, failures included, and nothing was edited or run since (exact conditions: **Answered stops** in the plugin README) | off unless `LOOM_TEST_GATE=block` | | 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` | on the first Stop, one line when `namespace.audit` finds a critical misuse of the namespace, pointing at the `loom-optimize` skill | `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` | @@ -608,14 +609,18 @@ Loom tests for src/app/router.py: .venv/bin/python -m pytest tests/test_router.p For a test file, the file itself. A test is given as one command where the harness is known (`LOOM_CODE_TEST_GATE_RUN_TEMPLATES` on the server adds yours) and by path where it is not. For pytest the line names the checkout's interpreter without starting it. +- **With no test to name.** A source file with no such test in the checkout gets the + changed functions in place of a command: `the index links no test to Router::match`. + That is the index's view, not a fact about your tests: its call graph is a floor, and + a test can reach a function the graph holds no edge to. - **When.** Once per file and once per test per session, on the result of the edit tool or shell command that changed the file. It costs no model request, and a session that - never runs the tests has still been told which ones they are. + 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 whose command that shell command already holds is not named on its own result. - **What it does not do.** It does not check that the tests ran, and it never holds the end of a session. Whether a session ran the right tests cannot be read reliably from - its shell commands, so that judgement stays with the agent and with CI. It names no - function the index links no test to, and a source file the index links to no test gets - no line. + its shell commands, so that judgement stays with the agent and with CI. To hold the stop instead, 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 diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 288c8cc25eb..2c54f8fe797 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.65", + "version": "1.2.69", "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 c9456102219..9a98fa29c2a 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -150,8 +150,8 @@ the duplicate, run `claude mcp remove -s user`. | `SessionStart` | `loom-session-start.mjs` | **First session, no credential:** signs this machine up (see `LOOM_AUTO_SIGNUP`) and points the user to the claim page for the namespace; nothing to paste. Then: injects a token-budgeted context primer (profile + relevant memories) via `context.pack`, so the agent starts knowing your context. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index was looked up, so a session start that prints nothing is a fault unless `LOOM_CODE_MAP=false`. How to route a lookup is in the MCP entry's startup instructions on a toolset with a `coding` part; any other toolset, and a wiring whose entry the plugin does not mount (Codex, a hand-wired client), gets it in the primer. **On by default**, once per session; `LOOM_INJECT_CONTEXT=false` to disable. | | `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about the target file (its files facet) and injects the rendered block as additional context — a constraint arrives **before** the edit, not as a review comment. One lookup per (session, file) per 30 min; never a permission decision. `LOOM_FILE_CONTEXT=off` disables. | | `PostToolUse` (loom tools) | `loom-mentor-hint.mjs` | **The store's advice reaches the model**: a loom tool result may carry one `hint` — the plane this agent is not using, named from the call it just made (a `memory.get` that missed, a search that abstained where the code index answers, a stack trace written as a memory, a duplicate write). The hook lifts it out of the result JSON into additional context, once per code per session. No request of its own. `LOOM_MENTOR_HINTS=off` disables. | -| `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which then stands in for the radius's count of tests, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | -| `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 the index links to no test names nothing, and neither does a comment-only change. The stop is never held: whether the tests ran is the agent's call (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | +| `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which stands in for the radius's count of tests where it names the file's tests, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | +| `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. The stop is never held: whether the tests ran is the agent's call (**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` | **Only with `LOOM_TEST_GATE=block`**, in place of the line at edit time. 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: the tests were named before "done", the choice to run them is the agent's. A stop whose transcript already answers the ask to run tests is not blocked, and so names no untested function (**Answered stops**, below). | @@ -169,7 +169,7 @@ the duplicate, run `claude mcp remove -s user`. **Team file rules.** The file-context hook reads two places in one `memory.for_file` request: your own namespace, and the repository's **primary code namespace** (its trunk branch's — `code-clickhouse` for every ClickHouse branch), named by the checkout's cached `code.repos` entry. A namespace you cannot read is skipped silently, so access follows repository access. Rules from the code namespace render as `Team rule (by alice, 3 days ago) [constraint]: … [id: ]` and design decisions (typed or tagged `decision`) as `Decision (by alice, 3 days ago) (pinned): … — source: [id: ]` (`(pinned)` only when someone pinned it, else no mark; `(source changed)` once its source document no longer says it), a newer rule the conflict check linked to an older one sits above it (`supersedes rule by …`, or `supersedes decision by …`), and one footer line says how to remove a wrong one. Every member of the repository may add a rule there (`memory.set` with `files` and the tag `constraint`) and revise or delete the rules they wrote; a maintainer may delete any — from an agent (`memory.delete` on the `[id:]` key) or from the dashboard (pick the code namespace under _show system_, open the memory, Delete). A refused delete answers a `hint` naming the author and what to do instead. `memory.set` fills `files` from the value when you do not pass it. Auto-extracted session facts never go to the code namespace. -**Tests at edit time.** The test gate names tests; it does not check that they ran. Deciding that from a transcript means reading shell text, and a session that runs the whole suite, compares against a stashed tree or pipes pytest through `grep` has run the tests in a way no fixed rule reads, so a gate that holds the stop on that reading holds sessions that did the work. By default the gate therefore names a file's tests on the tool call that changes it, where the agent is still working on the file, and leaves the end of the session alone. 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. The line names commands only, and no function the index links no test to. A file is asked about once per session, whatever the server answers, and at most four files per tool call; a test is named once per session, so the test you edit after its source file adds no second line. A source file the index links to no test gets no line. A team that wants the stop held until the tests are named 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. +**Tests at edit time.** The test gate names tests; it does not check that they ran. Deciding that from a transcript means reading shell text, and a session that runs the whole suite, compares against a stashed tree or pipes pytest through `grep` has run the tests in a way no fixed rule reads, so a gate that holds the stop on that reading holds sessions that did the work. By default the gate therefore names a file's tests on the tool call that changes it, where the agent is still working on the file, and leaves the end of the session alone. 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 and whatever the server answers, so a function changed later in the same file is not named; 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, and a test whose command the tool call's own command already holds is not named on the result of that run. A team that wants the stop held until the tests are named 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 blocking gate's reason 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. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 53e031287e5..c68a5c46380 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -89,8 +89,8 @@ receives on stdout. | PreToolUse Read\|Grep\|Bash | loom-code-shunt | tool_name, tool_input, cwd | JSON permission decision | code.repos; deny text | `LOOM_CODE_SHUNT=off` | | PreToolUse Edit\|Write\|MultiEdit\|NotebookEdit | loom-file-context | tool_input, session_id | JSON additionalContext | memory.for_file | `LOOM_FILE_CONTEXT=off` | | PostToolUse loom tools | loom-mentor-hint | tool_name, tool_response | JSON additionalContext | none | `LOOM_MENTOR_HINTS=off` | -| PostToolUse Edit\|Write\|MultiEdit | loom-blast-radius | tool_input, cwd, transcript head | JSON additionalContext | code.impact; code.test_gate for a file's first edit | -| PostToolUse Bash\|PowerShell | loom-test-gate | tool_input, cwd, transcript head | JSON additionalContext | code.test_gate for each changed file the command names, once per file | +| PostToolUse Edit\|Write\|MultiEdit | loom-blast-radius | tool_input, cwd, transcript head | JSON additionalContext | code.impact; code.test_gate for a file's first edit (`LOOM_TEST_GATE=off` or `block` stops that one) | `LOOM_BLAST_RADIUS=off` | +| PostToolUse Bash\|PowerShell | loom-test-gate | tool_input, cwd, transcript head | JSON additionalContext | code.test_gate for each changed file the command names, once per file | `LOOM_TEST_GATE=off` or `block` | | PostToolUse, PostToolUseFailure, Stop, SessionEnd (timeout 10) | loom-record | the payload | none | after a tool call and at Stop, starts one detached process, which runs the event's `detached` rows; at SessionEnd, runs the event's `in loom-record` rows itself | each script's own | | PostToolUse, PostToolUseFailure, detached | loom-capture | tool_*, session_id, cwd | none | observe.record; code.outcome; the recalled-keys stash | no token | | PreCompact | loom-capture | session_id | none | observe.crystallize | no token | @@ -99,7 +99,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 | with LOOM_TEST_GATE=block only: code.test_gate | +| Stop | loom-test-gate | transcript, cwd | JSON block once | with LOOM_TEST_GATE=block only: code.test_gate | 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 | namespace.audit (first Stop only) | `LOOM_NAMESPACE_HEALTH=off` | | Stop, detached | loom-working-memory | transcript, cwd | none | working_memory.set when the note changed | `LOOM_WORKING_MEMORY=off` | @@ -229,8 +229,8 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). partner files this session has not touched. The same touched set is reported once per session. It is the one hook wired for an edit tool, so it also carries the test gate's line for the file's first edit (see - loom-test-gate), which replaces its own count of tests: one line per - edit. LOOM_BLAST_RADIUS=off disables the radius, not that line. + loom-test-gate), which replaces its own count of tests where it names + the file's tests: one line per edit. LOOM_BLAST_RADIUS=off disables the radius, not that line. - **loom-capture.** PostToolUse and PostToolUseFailure record one episodic `observe.record` per tool call (zero-token heuristic typing, inputs and outputs truncated to 800 characters, the session's run id attached); @@ -287,14 +287,19 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). PowerShell command (and, through loom-blast-radius, after an edit tool) it takes the dirty paths the call named or targeted that were written since the session's first row, asks code.test_gate about each one not - asked about yet this session (`adviceFiles`, `adviceLine` in + asked about yet this session (`adviceFiles`, `adviceLines` in lib/test-gate.mjs; at most four per call; a comment-only change is not asked about) and prints one line per file as additionalContext on that tool result: the commands of the tests the index links to the file that - the checkout has, or the file's own command when it is a test. A test is - named once per session. The line costs no model request, and nothing - reads shell text to decide whether tests ran. A call that names no - unasked dirty file costs one git call and no request. + the checkout has, or the file's own command when it is a test. A file + with no such test gets the changed functions the index links no test + to. A file is asked about at its first change only, so a function + changed later in it is not named. A test is named once per session, and + not when the call's own command holds its command. The line costs no + model request, and nothing reads shell text to decide whether tests + ran. 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. With LOOM_TEST_GATE=block it holds the stop instead and prints nothing at edit time: with uncommitted changes this session made in a loom-indexed repo (dirty paths the transcript shows an edit tool targeted or a shell diff --git a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs index 1bccdd66e95..e77f1a8c5dc 100644 --- a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs @@ -11,8 +11,9 @@ // The test gate's edit-time line rides the same context: the first edit of a // file this session also asks `code.test_gate` for the file's tests and names // their command (lib/test-gate.mjs), in place of the radius's own count of -// tests. This hook is the only one wired for an edit tool, so an -// edit gets one line. LOOM_TEST_GATE=block or off leaves the radius alone. +// tests, or names the changed functions the index links no test to. This hook +// is the only one wired for an edit tool, so an edit gets one line. +// LOOM_TEST_GATE=block or off leaves the radius alone. // // Fail-open everywhere: no token, not an indexed repo, untracked file, empty // diff, server slow → nothing is printed. Each request is bounded (3 s) and @@ -42,7 +43,7 @@ import { relativeForLookup, targetPath } from "../lib/file-context.mjs"; import { resolveIndexedRepo } from "../lib/repo-scope.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; import { blastPayload, blastSignature, decideEmit, impactBody, renderBlast } from "../lib/blast-radius.mjs"; -import { adviceFiles, adviceLine, gateMode } from "../lib/test-gate.mjs"; +import { adviceFiles, adviceLines, gateMode } from "../lib/test-gate.mjs"; const ENABLED = envSwitch("LOOM_BLAST_RADIUS", true); const ADVISE = gateMode() === "advise"; @@ -108,7 +109,7 @@ async function main() { serverUrl: resolveServerUrl(), }) : null, - files.length ? adviceLine(payload, files, { root, repo, token }) : "", + files.length ? adviceLines(payload, files, { root, repo, token }) : [], ]); let blast = ""; @@ -119,10 +120,11 @@ async function main() { .filter(Boolean); const decision = decideEmit(readSessionState("blast", payload.session_id), rel, blastSignature(rel, impact)); writeSessionState("blast", payload.session_id, decision.cache); - // The tests line names the command, so the radius does not count them too. - if (decision.emit) blast = renderBlast(rel, impact, { maxNames: MAX_NAMES, touchedPaths, tests: !advice }); + // A tests line for this file names their command, so the radius does not count them too. + const named = advice.some((a) => a.rel === rel && a.tests); + if (decision.emit) blast = renderBlast(rel, impact, { maxNames: MAX_NAMES, touchedPaths, tests: !named }); } - const text = [blast, advice].filter(Boolean).join(" "); + const text = [blast, advice.map((a) => a.text).join("\n")].filter(Boolean).join(" "); if (text) process.stdout.write(JSON.stringify(blastPayload(text)) + "\n"); scheduleExit(0); } diff --git a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs index 40378f207d8..721ebb5ae44 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -4,8 +4,9 @@ // PostToolUse, the default (LOOM_TEST_GATE unset): after a shell command // that changed files in a loom-indexed repo, ask `code.test_gate` about each // one and attach ONE line per file naming the command of the tests the -// index links to it, or of the file itself when it is a test; once per file -// and once per test per session. The line rides the tool result, so it +// index links to it, or of the file itself when it is a test, or the changed +// functions the index links no test to when there is no test to name; once +// per file and once per test per session. The line rides the tool result, so it // costs no model request, and it arrives while the file is still being // edited. An edit tool's call gets the same line from loom-blast-radius, the // one hook wired for those tools. The stop is never held: whether the tests @@ -43,12 +44,12 @@ import { resolveToken, scheduleExit, } from "../lib/loom-client.mjs"; -import { resolveIndexedRepo } from "../lib/repo-scope.mjs"; +import { cachedUnindexed, resolveIndexedRepo } from "../lib/repo-scope.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; import { readAllLines } from "../lib/transcript.mjs"; import { adviceFiles, - adviceLine, + adviceLines, advicePayload, checkoutPython, commentOnlyDiff, @@ -74,11 +75,15 @@ const AFTER_TOOL = process.argv[2] === "PostToolUse"; async function advise(payload, token) { const tool = normalizeToolName(payload.tool_name); if (tool !== "Bash" && tool !== "PowerShell") return; - const { root, files } = adviceFiles(payload, { cwd: payload.cwd || process.cwd() }); + const cwd = payload.cwd || process.cwd(); + // This runs after every shell command: a checkout already known to have no index costs no git call. + if (cachedUnindexed(cwd)) return; + const { root, files } = adviceFiles(payload, { cwd }); if (!files.length) return; const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); if (!repo.indexed) return; - const out = advicePayload(await adviceLine(payload, files, { root, repo, token, depth: DEPTH })); + const lines = await adviceLines(payload, files, { root, repo, token, depth: DEPTH }); + const out = advicePayload(lines.map((l) => l.text).join("\n")); if (out) process.stdout.write(JSON.stringify(out) + "\n"); } diff --git a/integrations/claude-code-plugin/lib/repo-scope.mjs b/integrations/claude-code-plugin/lib/repo-scope.mjs index 0e91066bcc8..4b2cafce881 100644 --- a/integrations/claude-code-plugin/lib/repo-scope.mjs +++ b/integrations/claude-code-plugin/lib/repo-scope.mjs @@ -7,7 +7,9 @@ // {ts, indexed:true, org, namespace, repo, branch, prefixes, asOf, fetchedAt}. // A definite answer is trusted CACHE_TTL_MS; an unresolved one (the server // did not answer) UNRESOLVED_TTL_MS, then the next caller retries. +import fs from "node:fs"; import os from "node:os"; +import path from "node:path"; import { git, postBounded, resolveCodeRepo, resolveToken, shuntCachePath } from "./loom-client.mjs"; import { repoSlug } from "./code-shunt.mjs"; import { readPrivateFile, writeJsonFile } from "./tmp-state.mjs"; @@ -116,6 +118,22 @@ export function readCache(root, now = Date.now(), tmp = os.tmpdir()) { } } +/** True when the shared cache holds a fresh, definite answer that the + * checkout around `cwd` is not indexed. For a hook that runs after every + * shell command: the root is the nearest directory above `cwd` with a `.git` + * entry, found without starting git. Where git would name another root, or + * nothing has looked the checkout up yet, there is no entry and the answer + * is false. */ +export function cachedUnindexed(cwd, { now = Date.now(), tmp = os.tmpdir() } = {}) { + for (let dir = path.resolve(String(cwd || ".")); ; dir = path.dirname(dir)) { + if (fs.existsSync(path.join(dir, ".git"))) { + const entry = readCache(dir, now, tmp); + return Boolean(entry && !entry.indexed && !entry.unresolved); + } + if (dir === path.dirname(dir)) return false; + } +} + export function writeCache(root, entry, tmp = os.tmpdir()) { writeJsonFile(cachePathFor(root, tmp), entry); // tmp not writable: fine } diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index a9d9fdaecaa..5d049cf8fc9 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -3,8 +3,9 @@ // The gate names the tests a change obliges, from `code.test_gate`. By // default it names them when the file is edited: the tool call that changed // a file carries one line with the command of the tests the index links to -// it, or of the file itself when it is a test, once per file per session, -// and the stop is never held (`adviceFiles`, `adviceLine`). Whether a +// it, or of the file itself when it is a test, or with the changed functions +// the index links no test to when it has no test to name; once per file per +// session, and the stop is never held (`adviceFiles`, `adviceLines`). Whether a // session then ran the tests is the agent's to judge: a hook that reads // shell text to decide it blocks sessions that did. // @@ -124,10 +125,7 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists parts.push(`indexed tests not present in this checkout: ${shown.join(", ")}${more > 0 ? ` (+${more})` : ""}`); } if (untested.length) { - const names = [...new Set(untested.map((u) => short(u.qualified_name)))].filter(Boolean); - const shown = names.slice(0, maxNames); - const total = gate.untested_total || names.length; - const list = `${shown.join(", ")}${total > shown.length ? ` (+${total - shown.length})` : ""}`; + const { list, total } = untestedNames(gate, maxNames); // Beside tests to run, "no test reaches" reads as a fact about them, and // a test that builds an object reaches a constructor the graph holds no // edge to. @@ -155,6 +153,17 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists const isPytest = (run) => /^pytest(\s|$)/.test(String(run || "")); +/** The functions of a gate's `untested`, by short name: the first `maxNames` + * as `list`, with a count of the rest, and how many there are in `total`. */ +function untestedNames(gate, maxNames = 4) { + const untested = gate && Array.isArray(gate.untested) ? gate.untested : []; + const names = [...new Set(untested.map((u) => short(u.qualified_name)))].filter(Boolean); + const shown = names.slice(0, maxNames); + const total = (gate && gate.untested_total) || names.length; + const more = total > shown.length ? ` (+${total - shown.length})` : ""; + return { list: shown.length ? `${shown.join(", ")}${more}` : "", total }; +} + /** The distinct run commands of `tests` (`raw`) and the first `maxRuns` of * them as one text, "" when no test has one. */ function runList(tests, { maxRuns, python }) { @@ -179,21 +188,31 @@ export function adviceTests(rel, gate, testExists) { } /** - * The edit-time line for `rel` from `tests` (see `adviceTests`), or "" when - * there are none: their commands, then the tests no runner is known for. No - * function the index links no test to is named: the graph is a floor, and - * the line has no reply in which the agent could say so. + * The edit-time line for `rel` from `tests` (see `adviceTests`): their + * commands, then the tests no runner is known for. With no test, it names + * `untested`, the changed functions the index links no test to, as the + * index's view: the graph is a floor, and the line has no reply in which the + * agent could say that a test does reach them. "" when there is neither. */ -export function renderAdvice(rel, tests, { maxRuns = 4, maxNames = 4, python } = {}) { +export function renderAdvice(rel, tests, { maxRuns = 4, maxNames = 4, python, untested = "" } = {}) { const parts = [runList(tests, { maxRuns, python }).text].filter(Boolean); const unknown = [...new Set(tests.filter((t) => !t.run).map((t) => String(t.test_path)))]; if (unknown.length) { const more = unknown.length - maxNames; parts.push(`no known runner: ${unknown.slice(0, maxNames).join(", ")}${more > 0 ? ` (+${more})` : ""}`); } + if (!parts.length && untested) parts.push(`the index links no test to ${untested}`); return parts.length ? `Loom tests for ${rel}: ${parts.join(" · ")}` : ""; } +/** The tests of `tests` that `renderAdvice` prints: those of its first + * `maxRuns` commands and its first `maxNames` paths with no known runner. */ +export function printedTests(tests, { maxRuns = 4, maxNames = 4 } = {}) { + const runs = [...new Set(tests.map((t) => String(t.run || "")).filter(Boolean))].slice(0, maxRuns); + const paths = [...new Set(tests.filter((t) => !t.run).map((t) => String(t.test_path)))].slice(0, maxNames); + return tests.filter((t) => (t.run ? runs.includes(String(t.run)) : paths.includes(String(t.test_path)))); +} + /** `runs` with every `pytest ` folded into the first one: one command to * copy and one process to start. A run with an option or a second word stays * its own command. */ @@ -470,29 +489,46 @@ function newest(map, max = 300) { return map; } +/** Adds `keys` to the session's test-advice map `field` (`seen`: files asked + * about; `named`: tests a line named). The state is read and written here + * with nothing between, not locked: two hooks of one session that write in + * the same instant (parallel tool calls) keep one's entries, and the other's + * file is then asked about twice or its test named twice. */ +function remember(sessionId, field, keys) { + const state = readSessionState("testadvice", sessionId); + const map = { ...state[field] }; + for (const key of keys) map[key] = Date.now(); + writeSessionState("testadvice", sessionId, { ...state, [field]: newest(map) }); +} + /** - * The additional context for `files` (from `adviceFiles`): one line per - * file that has tests to name, "" when none has. Each file is asked about - * once per session, whatever the server answers, so a server that is down - * costs a session one bounded request per file and not one per tool call. A - * file whose change is comments only is not asked about and stays unasked: - * it owes no test until it changes code. A test is named once per session: - * the test file a session edits after the source file it tests adds no - * second line with the same command. Only the diff's paths, hunk ranges and - * function names are sent (`diffHeaders`). + * The edit-time lines for `files` (from `adviceFiles`), as `{ rel, text, + * tests }` for each file that has one: `tests` counts the tests `text` names, + * 0 when it names the functions the index links no test to. Each file is + * asked about once per session, at its first change and whatever the server + * answers, so a server that is down costs a session one bounded request per + * file and not one per tool call; a function changed later in the same file + * is not asked about. A file whose change is comments only is not asked + * about and stays unasked: it owes no test until it changes code. A test is + * named once per session: the test file a session edits after the source + * file it tests adds no second line with the same command. A test whose + * command the call's own command holds is not named: the line would arrive + * on the result of that run. Only the diff's paths, hunk ranges and function + * names are sent (`diffHeaders`). */ -export async function adviceLine(payload, files, { root, repo, token, depth = gateDepth() } = {}) { +export async function adviceLines(payload, files, { root, repo, token, depth = gateDepth() } = {}) { const asked = files .map((rel) => [ rel, git(["diff", ...DIFF_ARGS, "--unified=0", "HEAD", "--", rel], root, { timeoutMs: 2000, raw: true }), ]) .filter(([, diff]) => !commentOnlyDiff(diff)); - if (!asked.length) return ""; - const state = () => readSessionState("testadvice", payload.session_id); - const seen = { ...state().seen }; - for (const [rel] of asked) seen[rel] = Date.now(); - writeSessionState("testadvice", payload.session_id, { ...state(), seen: newest(seen) }); + if (!asked.length) return []; + remember( + payload.session_id, + "seen", + asked.map(([rel]) => rel), + ); const gates = await Promise.all( asked.map(([rel, diff]) => postBounded( @@ -509,20 +545,29 @@ export async function adviceLine(payload, files, { root, repo, token, depth = ga ), ), ); - const named = { ...state().named }; + const named = { ...readSessionState("testadvice", payload.session_id).named }; + const command = commandText(payload.tool_input); const testExists = testsIn(root); - const tests = asked.map(([rel], i) => { - const fresh = adviceTests(rel, gates[i], testExists).filter((t) => !named[t.test_path]); - for (const t of fresh) named[t.test_path] = Date.now(); - return fresh; - }); - if (!tests.some((t) => t.length)) return ""; - writeSessionState("testadvice", payload.session_id, { ...state(), named: newest(named) }); - const python = tests.flat().some((t) => isPytest(t.run)) ? checkoutPython(root) : undefined; - return asked - .map(([rel], i) => renderAdvice(rel, tests[i], { python })) - .filter(Boolean) - .join("\n"); + let python; + const lines = []; + const printed = []; + for (const [i, [rel]] of asked.entries()) { + const tests = adviceTests(rel, gates[i], testExists); + const fresh = tests.filter((t) => !named[t.test_path] && !(t.run && command.includes(t.run))); + if (python === undefined && fresh.some((t) => isPytest(t.run))) python = checkoutPython(root); + // Functions are named only for a file with no test to run in this checkout. + const untested = tests.length ? "" : untestedNames(gates[i]).list; + const text = renderAdvice(rel, fresh, { python, untested }); + if (!text) continue; + // A test folded into "(+N more)" was not shown, so its own change still names it. + for (const t of printedTests(fresh)) { + named[t.test_path] = Date.now(); + printed.push(t.test_path); + } + lines.push({ rel, text, tests: fresh.length }); + } + if (printed.length) remember(payload.session_id, "named", printed); + return lines; } // The prompt's last sentence, whole: "Do not run the test suite.", "Please diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index e47e6765e24..040695b08e9 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -12,6 +12,7 @@ import { gateMode, gatePayload, gateSignature, + printedTests, renderAdvice, renderGate, sessionScope, @@ -50,8 +51,12 @@ test("the edit-time line names the commands of the tests the index links to the text, "Loom tests for src/a.py: .venv/bin/python -m pytest tests/unit/test_a.py · no known runner: src/x/tests/gtest_parts.cpp", ); - // No function is named: the graph is a floor, and the line asks for no reply. + // Beside tests to run no function is named: the graph is a floor, and the line asks for no reply. assert.doesNotMatch(text, /renameTempPartAndAdd|no test reaches|links no test/); + assert.equal( + renderAdvice("src/a.py", adviceTests("src/a.py", GATE), { python: ".venv/bin/python", untested: "Foo::bar" }), + text, + ); assert.deepEqual(advicePayload(text), { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text }, }); @@ -79,6 +84,14 @@ test("a changed test names its own command; a file no runner takes, a test the c assert.equal(advicePayload(""), null); }); +test("a file with no test to name gets the functions the index links no test to, as the index's view", () => { + assert.equal( + renderAdvice("src/a.py", [], { untested: "MergeTreeData::renameTempPartAndAdd, Foo::bar" }), + "Loom tests for src/a.py: the index links no test to MergeTreeData::renameTempPartAndAdd, Foo::bar", + ); + assert.equal(renderAdvice("src/a.py", [], { untested: "" }), ""); +}); + test("the edit-time line folds pytest files into one command and counts the commands it leaves out", () => { const many = ["a", "b", "c", "d", "e", "f"].map((n) => ({ test_path: `tests/test_${n}.py`, @@ -89,6 +102,12 @@ test("the edit-time line folds pytest files into one command and counts the comm renderAdvice("src/a.py", many), "Loom tests for src/a.py: pytest tests/test_a.py tests/test_b.py tests/test_c.py tests/test_d.py (+2 more)", ); + // The two it leaves out were not shown, so they are not marked as named. + const unknown = ["g", "h", "i", "j", "k"].map((n) => ({ test_path: `spec/${n}.cpp`, run: "" })); + assert.deepEqual( + printedTests([...many, ...unknown]).map((t) => t.test_path), + [...many.slice(0, 4), ...unknown.slice(0, 4)].map((t) => t.test_path), + ); }); test("signature is order-independent over paths and bound to the diff", () => { @@ -493,7 +512,7 @@ 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 { cachePathFor } from "../lib/repo-scope.mjs"; +import { cachedUnindexed, cachePathFor } from "../lib/repo-scope.mjs"; import { hostEnv } from "./host-env.mjs"; const said = (content, extra = {}) => ({ type: "user", message: { content }, ...extra }); @@ -983,10 +1002,35 @@ test("with LOOM_TEST_GATE=block the hook blocks a change whose tests never ran a // --- the default: the tests are named on the call that changed the file +test("a checkout the cache says is not indexed is known without git; no other entry says so", () => { + const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-unindexed-"))); + const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-unindexed-tmp-"))); + const below = path.join(dir, "src", "pkg"); + fs.mkdirSync(below, { recursive: true }); + fs.mkdirSync(path.join(dir, ".git")); + const cached = (entry) => { + fs.writeFileSync(cachePathFor(dir, tmp), JSON.stringify(entry)); + return cachedUnindexed(below, { tmp }); + }; + try { + assert.equal(cachedUnindexed(below, { tmp }), false); + assert.equal(cached({ ts: Date.now(), indexed: false }), true); + assert.equal(cachedUnindexed(dir, { tmp }), true); + // The server did not answer, the answer is old, or the checkout is indexed. + assert.equal(cached({ ts: Date.now(), indexed: false, unresolved: true }), false); + assert.equal(cached({ ts: Date.now() - 3_600_000, indexed: false }), false); + assert.equal(cached({ ts: Date.now(), indexed: true, org: "o", namespace: "code-x" }), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + fs.rmSync(tmp, { recursive: true, force: true }); + } +}); + test("a changed file's tests ride the tool call that changed it, once, and the stop is never held", async () => { const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-advice-"))); const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-advice-tmp-"))); - for (const f of ["src/a.py", "src/b.py", "src/old.py", "tests/test_a.py", "tests/test_b.py", "tests/test_c.py"]) { + const sources = ["src/a.py", "src/b.py", "src/d.py", "src/f.py", "src/old.py"]; + for (const f of [...sources, "tests/test_a.py", "tests/test_b.py", "tests/test_c.py", "tests/test_e.py"]) { fs.mkdirSync(path.join(dir, path.dirname(f)), { recursive: true }); fs.writeFileSync(path.join(dir, f), "def f():\n return 1\n"); } @@ -1033,7 +1077,7 @@ test("a changed file's tests ride the tool call that changed it, once, and the s run: `pytest tests/test_${n}.py`, })), ], - untested: [{ qualified_name: "m::g" }], + untested: stem.length ? [{ qualified_name: "m::g" }] : [], }, "/v1/code.impact": { touched_symbols: [{ qualified_name: "m::g" }], @@ -1116,6 +1160,28 @@ test("a changed file's tests ride the tool call that changed it, once, and the s context(await shell("sed -i s/1/2/ tests/test_c.py")), /^Loom tests for tests\/test_c\.py: (?:\S+ -m )?pytest tests\/test_c\.py$/, ); + // A file with no test in the checkout gets the functions the index links no test to, once. + write("src/d.py", "def g():\n return 2\n"); + assert.equal( + context(await shell("sed -i s/1/2/ src/d.py")), + "Loom tests for src/d.py: the index links no test to m::g", + ); + assert.equal(await shell("sed -i s/2/3/ src/d.py"), null); + // After an edit tool that line names no test, so the radius keeps its own count. + write("src/f.py", "def g():\n return 2\n"); + const unlinked = await run("loom-blast-radius", "PostToolUse", { + tool_name: "Edit", + tool_input: { file_path: path.join(dir, "src/f.py") }, + }); + assert.match( + context(unlinked), + /tests reaching it: 1 \(test_b\.py\).* Loom tests for src\/f\.py: the index links no test to m::g$/, + ); + // A test the command itself runs is not named on the result of that run, nor later. + write("tests/test_e.py", "def test_g():\n assert True\n"); + assert.equal(await shell("python -m pytest tests/test_e.py -q"), null); + assert.ok(asked.includes("/v1/code.test_gate tests/test_e.py"), asked.join(", ")); + assert.equal(await shell("sed -i s/1/2/ tests/test_e.py"), null); // A comment-only change owes no test and stays unasked until it changes code. write("src/old.py", "# a note\n"); execFileSync("git", ["checkout", "-q", "--", "src/old.py"], { cwd: dir }); diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index 5960bd646ab..a580f09f236 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.65", + "version": "1.2.69", "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-blast-radius.mjs b/integrations/codex-plugin/hooks/loom-blast-radius.mjs index 1bccdd66e95..e77f1a8c5dc 100644 --- a/integrations/codex-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/codex-plugin/hooks/loom-blast-radius.mjs @@ -11,8 +11,9 @@ // The test gate's edit-time line rides the same context: the first edit of a // file this session also asks `code.test_gate` for the file's tests and names // their command (lib/test-gate.mjs), in place of the radius's own count of -// tests. This hook is the only one wired for an edit tool, so an -// edit gets one line. LOOM_TEST_GATE=block or off leaves the radius alone. +// tests, or names the changed functions the index links no test to. This hook +// is the only one wired for an edit tool, so an edit gets one line. +// LOOM_TEST_GATE=block or off leaves the radius alone. // // Fail-open everywhere: no token, not an indexed repo, untracked file, empty // diff, server slow → nothing is printed. Each request is bounded (3 s) and @@ -42,7 +43,7 @@ import { relativeForLookup, targetPath } from "../lib/file-context.mjs"; import { resolveIndexedRepo } from "../lib/repo-scope.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; import { blastPayload, blastSignature, decideEmit, impactBody, renderBlast } from "../lib/blast-radius.mjs"; -import { adviceFiles, adviceLine, gateMode } from "../lib/test-gate.mjs"; +import { adviceFiles, adviceLines, gateMode } from "../lib/test-gate.mjs"; const ENABLED = envSwitch("LOOM_BLAST_RADIUS", true); const ADVISE = gateMode() === "advise"; @@ -108,7 +109,7 @@ async function main() { serverUrl: resolveServerUrl(), }) : null, - files.length ? adviceLine(payload, files, { root, repo, token }) : "", + files.length ? adviceLines(payload, files, { root, repo, token }) : [], ]); let blast = ""; @@ -119,10 +120,11 @@ async function main() { .filter(Boolean); const decision = decideEmit(readSessionState("blast", payload.session_id), rel, blastSignature(rel, impact)); writeSessionState("blast", payload.session_id, decision.cache); - // The tests line names the command, so the radius does not count them too. - if (decision.emit) blast = renderBlast(rel, impact, { maxNames: MAX_NAMES, touchedPaths, tests: !advice }); + // A tests line for this file names their command, so the radius does not count them too. + const named = advice.some((a) => a.rel === rel && a.tests); + if (decision.emit) blast = renderBlast(rel, impact, { maxNames: MAX_NAMES, touchedPaths, tests: !named }); } - const text = [blast, advice].filter(Boolean).join(" "); + const text = [blast, advice.map((a) => a.text).join("\n")].filter(Boolean).join(" "); if (text) process.stdout.write(JSON.stringify(blastPayload(text)) + "\n"); scheduleExit(0); } diff --git a/integrations/codex-plugin/hooks/loom-test-gate.mjs b/integrations/codex-plugin/hooks/loom-test-gate.mjs index 40378f207d8..721ebb5ae44 100644 --- a/integrations/codex-plugin/hooks/loom-test-gate.mjs +++ b/integrations/codex-plugin/hooks/loom-test-gate.mjs @@ -4,8 +4,9 @@ // PostToolUse, the default (LOOM_TEST_GATE unset): after a shell command // that changed files in a loom-indexed repo, ask `code.test_gate` about each // one and attach ONE line per file naming the command of the tests the -// index links to it, or of the file itself when it is a test; once per file -// and once per test per session. The line rides the tool result, so it +// index links to it, or of the file itself when it is a test, or the changed +// functions the index links no test to when there is no test to name; once +// per file and once per test per session. The line rides the tool result, so it // costs no model request, and it arrives while the file is still being // edited. An edit tool's call gets the same line from loom-blast-radius, the // one hook wired for those tools. The stop is never held: whether the tests @@ -43,12 +44,12 @@ import { resolveToken, scheduleExit, } from "../lib/loom-client.mjs"; -import { resolveIndexedRepo } from "../lib/repo-scope.mjs"; +import { cachedUnindexed, resolveIndexedRepo } from "../lib/repo-scope.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; import { readAllLines } from "../lib/transcript.mjs"; import { adviceFiles, - adviceLine, + adviceLines, advicePayload, checkoutPython, commentOnlyDiff, @@ -74,11 +75,15 @@ const AFTER_TOOL = process.argv[2] === "PostToolUse"; async function advise(payload, token) { const tool = normalizeToolName(payload.tool_name); if (tool !== "Bash" && tool !== "PowerShell") return; - const { root, files } = adviceFiles(payload, { cwd: payload.cwd || process.cwd() }); + const cwd = payload.cwd || process.cwd(); + // This runs after every shell command: a checkout already known to have no index costs no git call. + if (cachedUnindexed(cwd)) return; + const { root, files } = adviceFiles(payload, { cwd }); if (!files.length) return; const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); if (!repo.indexed) return; - const out = advicePayload(await adviceLine(payload, files, { root, repo, token, depth: DEPTH })); + const lines = await adviceLines(payload, files, { root, repo, token, depth: DEPTH }); + const out = advicePayload(lines.map((l) => l.text).join("\n")); if (out) process.stdout.write(JSON.stringify(out) + "\n"); } diff --git a/integrations/codex-plugin/lib/repo-scope.mjs b/integrations/codex-plugin/lib/repo-scope.mjs index 0e91066bcc8..4b2cafce881 100644 --- a/integrations/codex-plugin/lib/repo-scope.mjs +++ b/integrations/codex-plugin/lib/repo-scope.mjs @@ -7,7 +7,9 @@ // {ts, indexed:true, org, namespace, repo, branch, prefixes, asOf, fetchedAt}. // A definite answer is trusted CACHE_TTL_MS; an unresolved one (the server // did not answer) UNRESOLVED_TTL_MS, then the next caller retries. +import fs from "node:fs"; import os from "node:os"; +import path from "node:path"; import { git, postBounded, resolveCodeRepo, resolveToken, shuntCachePath } from "./loom-client.mjs"; import { repoSlug } from "./code-shunt.mjs"; import { readPrivateFile, writeJsonFile } from "./tmp-state.mjs"; @@ -116,6 +118,22 @@ export function readCache(root, now = Date.now(), tmp = os.tmpdir()) { } } +/** True when the shared cache holds a fresh, definite answer that the + * checkout around `cwd` is not indexed. For a hook that runs after every + * shell command: the root is the nearest directory above `cwd` with a `.git` + * entry, found without starting git. Where git would name another root, or + * nothing has looked the checkout up yet, there is no entry and the answer + * is false. */ +export function cachedUnindexed(cwd, { now = Date.now(), tmp = os.tmpdir() } = {}) { + for (let dir = path.resolve(String(cwd || ".")); ; dir = path.dirname(dir)) { + if (fs.existsSync(path.join(dir, ".git"))) { + const entry = readCache(dir, now, tmp); + return Boolean(entry && !entry.indexed && !entry.unresolved); + } + if (dir === path.dirname(dir)) return false; + } +} + export function writeCache(root, entry, tmp = os.tmpdir()) { writeJsonFile(cachePathFor(root, tmp), entry); // tmp not writable: fine } diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index a9d9fdaecaa..5d049cf8fc9 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -3,8 +3,9 @@ // The gate names the tests a change obliges, from `code.test_gate`. By // default it names them when the file is edited: the tool call that changed // a file carries one line with the command of the tests the index links to -// it, or of the file itself when it is a test, once per file per session, -// and the stop is never held (`adviceFiles`, `adviceLine`). Whether a +// it, or of the file itself when it is a test, or with the changed functions +// the index links no test to when it has no test to name; once per file per +// session, and the stop is never held (`adviceFiles`, `adviceLines`). Whether a // session then ran the tests is the agent's to judge: a hook that reads // shell text to decide it blocks sessions that did. // @@ -124,10 +125,7 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists parts.push(`indexed tests not present in this checkout: ${shown.join(", ")}${more > 0 ? ` (+${more})` : ""}`); } if (untested.length) { - const names = [...new Set(untested.map((u) => short(u.qualified_name)))].filter(Boolean); - const shown = names.slice(0, maxNames); - const total = gate.untested_total || names.length; - const list = `${shown.join(", ")}${total > shown.length ? ` (+${total - shown.length})` : ""}`; + const { list, total } = untestedNames(gate, maxNames); // Beside tests to run, "no test reaches" reads as a fact about them, and // a test that builds an object reaches a constructor the graph holds no // edge to. @@ -155,6 +153,17 @@ export function renderGate(gate, { maxRuns = 4, maxNames = 4, python, testExists const isPytest = (run) => /^pytest(\s|$)/.test(String(run || "")); +/** The functions of a gate's `untested`, by short name: the first `maxNames` + * as `list`, with a count of the rest, and how many there are in `total`. */ +function untestedNames(gate, maxNames = 4) { + const untested = gate && Array.isArray(gate.untested) ? gate.untested : []; + const names = [...new Set(untested.map((u) => short(u.qualified_name)))].filter(Boolean); + const shown = names.slice(0, maxNames); + const total = (gate && gate.untested_total) || names.length; + const more = total > shown.length ? ` (+${total - shown.length})` : ""; + return { list: shown.length ? `${shown.join(", ")}${more}` : "", total }; +} + /** The distinct run commands of `tests` (`raw`) and the first `maxRuns` of * them as one text, "" when no test has one. */ function runList(tests, { maxRuns, python }) { @@ -179,21 +188,31 @@ export function adviceTests(rel, gate, testExists) { } /** - * The edit-time line for `rel` from `tests` (see `adviceTests`), or "" when - * there are none: their commands, then the tests no runner is known for. No - * function the index links no test to is named: the graph is a floor, and - * the line has no reply in which the agent could say so. + * The edit-time line for `rel` from `tests` (see `adviceTests`): their + * commands, then the tests no runner is known for. With no test, it names + * `untested`, the changed functions the index links no test to, as the + * index's view: the graph is a floor, and the line has no reply in which the + * agent could say that a test does reach them. "" when there is neither. */ -export function renderAdvice(rel, tests, { maxRuns = 4, maxNames = 4, python } = {}) { +export function renderAdvice(rel, tests, { maxRuns = 4, maxNames = 4, python, untested = "" } = {}) { const parts = [runList(tests, { maxRuns, python }).text].filter(Boolean); const unknown = [...new Set(tests.filter((t) => !t.run).map((t) => String(t.test_path)))]; if (unknown.length) { const more = unknown.length - maxNames; parts.push(`no known runner: ${unknown.slice(0, maxNames).join(", ")}${more > 0 ? ` (+${more})` : ""}`); } + if (!parts.length && untested) parts.push(`the index links no test to ${untested}`); return parts.length ? `Loom tests for ${rel}: ${parts.join(" · ")}` : ""; } +/** The tests of `tests` that `renderAdvice` prints: those of its first + * `maxRuns` commands and its first `maxNames` paths with no known runner. */ +export function printedTests(tests, { maxRuns = 4, maxNames = 4 } = {}) { + const runs = [...new Set(tests.map((t) => String(t.run || "")).filter(Boolean))].slice(0, maxRuns); + const paths = [...new Set(tests.filter((t) => !t.run).map((t) => String(t.test_path)))].slice(0, maxNames); + return tests.filter((t) => (t.run ? runs.includes(String(t.run)) : paths.includes(String(t.test_path)))); +} + /** `runs` with every `pytest ` folded into the first one: one command to * copy and one process to start. A run with an option or a second word stays * its own command. */ @@ -470,29 +489,46 @@ function newest(map, max = 300) { return map; } +/** Adds `keys` to the session's test-advice map `field` (`seen`: files asked + * about; `named`: tests a line named). The state is read and written here + * with nothing between, not locked: two hooks of one session that write in + * the same instant (parallel tool calls) keep one's entries, and the other's + * file is then asked about twice or its test named twice. */ +function remember(sessionId, field, keys) { + const state = readSessionState("testadvice", sessionId); + const map = { ...state[field] }; + for (const key of keys) map[key] = Date.now(); + writeSessionState("testadvice", sessionId, { ...state, [field]: newest(map) }); +} + /** - * The additional context for `files` (from `adviceFiles`): one line per - * file that has tests to name, "" when none has. Each file is asked about - * once per session, whatever the server answers, so a server that is down - * costs a session one bounded request per file and not one per tool call. A - * file whose change is comments only is not asked about and stays unasked: - * it owes no test until it changes code. A test is named once per session: - * the test file a session edits after the source file it tests adds no - * second line with the same command. Only the diff's paths, hunk ranges and - * function names are sent (`diffHeaders`). + * The edit-time lines for `files` (from `adviceFiles`), as `{ rel, text, + * tests }` for each file that has one: `tests` counts the tests `text` names, + * 0 when it names the functions the index links no test to. Each file is + * asked about once per session, at its first change and whatever the server + * answers, so a server that is down costs a session one bounded request per + * file and not one per tool call; a function changed later in the same file + * is not asked about. A file whose change is comments only is not asked + * about and stays unasked: it owes no test until it changes code. A test is + * named once per session: the test file a session edits after the source + * file it tests adds no second line with the same command. A test whose + * command the call's own command holds is not named: the line would arrive + * on the result of that run. Only the diff's paths, hunk ranges and function + * names are sent (`diffHeaders`). */ -export async function adviceLine(payload, files, { root, repo, token, depth = gateDepth() } = {}) { +export async function adviceLines(payload, files, { root, repo, token, depth = gateDepth() } = {}) { const asked = files .map((rel) => [ rel, git(["diff", ...DIFF_ARGS, "--unified=0", "HEAD", "--", rel], root, { timeoutMs: 2000, raw: true }), ]) .filter(([, diff]) => !commentOnlyDiff(diff)); - if (!asked.length) return ""; - const state = () => readSessionState("testadvice", payload.session_id); - const seen = { ...state().seen }; - for (const [rel] of asked) seen[rel] = Date.now(); - writeSessionState("testadvice", payload.session_id, { ...state(), seen: newest(seen) }); + if (!asked.length) return []; + remember( + payload.session_id, + "seen", + asked.map(([rel]) => rel), + ); const gates = await Promise.all( asked.map(([rel, diff]) => postBounded( @@ -509,20 +545,29 @@ export async function adviceLine(payload, files, { root, repo, token, depth = ga ), ), ); - const named = { ...state().named }; + const named = { ...readSessionState("testadvice", payload.session_id).named }; + const command = commandText(payload.tool_input); const testExists = testsIn(root); - const tests = asked.map(([rel], i) => { - const fresh = adviceTests(rel, gates[i], testExists).filter((t) => !named[t.test_path]); - for (const t of fresh) named[t.test_path] = Date.now(); - return fresh; - }); - if (!tests.some((t) => t.length)) return ""; - writeSessionState("testadvice", payload.session_id, { ...state(), named: newest(named) }); - const python = tests.flat().some((t) => isPytest(t.run)) ? checkoutPython(root) : undefined; - return asked - .map(([rel], i) => renderAdvice(rel, tests[i], { python })) - .filter(Boolean) - .join("\n"); + let python; + const lines = []; + const printed = []; + for (const [i, [rel]] of asked.entries()) { + const tests = adviceTests(rel, gates[i], testExists); + const fresh = tests.filter((t) => !named[t.test_path] && !(t.run && command.includes(t.run))); + if (python === undefined && fresh.some((t) => isPytest(t.run))) python = checkoutPython(root); + // Functions are named only for a file with no test to run in this checkout. + const untested = tests.length ? "" : untestedNames(gates[i]).list; + const text = renderAdvice(rel, fresh, { python, untested }); + if (!text) continue; + // A test folded into "(+N more)" was not shown, so its own change still names it. + for (const t of printedTests(fresh)) { + named[t.test_path] = Date.now(); + printed.push(t.test_path); + } + lines.push({ rel, text, tests: fresh.length }); + } + if (printed.length) remember(payload.session_id, "named", printed); + return lines; } // The prompt's last sentence, whole: "Do not run the test suite.", "Please From 461fc7c0abb25b76a9e0e5005fba6069f93d3cd7 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 15:39:17 +0530 Subject: [PATCH 5/7] By default the test gate holds the stop of a session that changed code and ran no test since The default no longer held any stop, so a session that edited source and ran no test ended unasked: with every test run taken out of the 29 recorded sessions, none was held. The measured fault was narrower: the gate read from shell text which tests ran and how they went, and held sessions that had run them. At Stop the default now runs the blocking gate's steps with one earlier exit: any shell command that starts a test runner and finished no earlier than the oldest write among the session's changed files lets the stop pass, before anything is asked of the server (`testedSince`, `oldestChange`). The command is read for a runner's name only, in a Claude Code transcript or a Codex rollout; its output is not read. A session that ran none is held once per distinct change with the gate's reason. With no transcript the default holds no stop. `LOOM_TEST_GATE=block` keeps the stricter reading and names nothing at edit time. At edit time: - A file the server gave no answer for stays unasked for one more call that names it; it was marked as asked before the request, so one timeout silenced it for the session. - A test is left out of the line only when the call's command runs its whole command in this checkout. A substring match also dropped it for `pytest tests/test_a.py::test_one`, `docker exec app pytest tests/test_a.py` and `echo "pytest tests/test_a.py"`. The malformed-input test starts the gate after a shell command and in both Stop modes. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 44 +++--- integrations/claude-code-plugin/README.md | 10 +- .../claude-code-plugin/hooks/HOOKS.md | 37 +++-- .../hooks/loom-test-gate.mjs | 33 +++-- .../claude-code-plugin/lib/test-gate.mjs | 127 ++++++++++++++---- .../tests/code-hooks-failopen.test.mjs | 42 +++--- .../tests/test-gate.test.mjs | 127 ++++++++++++++++-- .../codex-plugin/hooks/loom-test-gate.mjs | 33 +++-- integrations/codex-plugin/lib/test-gate.mjs | 127 ++++++++++++++---- 9 files changed, 445 insertions(+), 135 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 7962bd0357b..41168b97b12 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -57,9 +57,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 changed code and ran no test since, 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, @@ -395,7 +396,8 @@ name: a test the index links to it and the checkout has, the file itself when it test, or, with no such test, the changed functions the index links no test to. It stays quiet for a file whose tests an earlier line named or the command itself ran, a comment-only change, an untracked file, a file already asked about in the session, an -unavailable index or a failed request, and always with `LOOM_TEST_GATE=block` or `off`. +unavailable index or a request that failed twice, and always with `LOOM_TEST_GATE=block` +or `off`. Headless sessions support `hookSpecificOutput.additionalContext`; ordinary visible assistant output does not prove whether that context reached the model. Capture @@ -479,12 +481,12 @@ The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. | PreToolUse (Edit, Write, MultiEdit, NotebookEdit) | `loom-file-context.mjs` | what Loom knows about the file about to change (`memory.for_file`): your rules and the repository's shared rules and design decisions; once per file per 30 min | `LOOM_FILE_CONTEXT=off` | | PostToolUse (Loom tools) | `loom-mentor-hint.mjs` | lifts a result's `hint` into context, once per hint code per session | `LOOM_MENTOR_HINTS=off` | | PostToolUse (Edit, Write, MultiEdit) | `loom-blast-radius.mjs` | one line from `code.impact`: callers, tests reaching the change, co-change files not yet touched; on a file's first edit, the test gate's line beside it in place of the tests | `LOOM_BLAST_RADIUS=off` | -| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | one line per file the command changed, naming the command of the file's tests, or the changed functions the index links no test to (`code.test_gate`); once per file and per test per session, on the tool result, and never a blocked stop ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | +| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | one line per file the command changed, naming the command of the file's tests, or the changed functions the index links no test to (`code.test_gate`); once per file and per test per session, on the tool result ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | | PostToolUse, PostToolUseFailure, Stop, SessionEnd | `loom-record.mjs` | runs the event's recording scripts (the rows below for those events, the gates excepted) in one process: detached after a tool call and at Stop, so the session does not wait for their requests, and in the hook itself at SessionEnd | each script's own | | 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` | only 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 already ran them to its summary line, failures included, and nothing was edited or run since (exact conditions: **Answered stops** in the plugin README) | off unless `LOOM_TEST_GATE=block` | +| 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 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` | on the first Stop, one line when `namespace.audit` finds a critical misuse of the namespace, pointing at the `loom-optimize` skill | `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` | @@ -585,7 +587,7 @@ Beyond the off switches in the table: | `LOOM_PROMPT_PACK_MIN_CONF` | unset | a `retrieval_confidence` gate for search pointers; unset, the index's low-risk 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` holds the stop in place of the edit-time line; `off` turns the gate off | +| `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 | @@ -617,18 +619,22 @@ Loom tests for src/app/router.py: .venv/bin/python -m pytest tests/test_router.p or shell command that changed the file. It costs no model request, and a session that 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 whose command that shell command already holds is not named on its own result. -- **What it does not do.** It does not check that the tests ran, and it never holds the - end of a session. Whether a session ran the right tests cannot be read reliably from - its shell commands, so that judgement stays with the agent and with CI. - -To hold the stop instead, 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 -with the tests the change obliges and the functions the index links no test to, unless -the transcript already answers the ask; the plugin README lists the exact conditions -under **Answered stops**. A block costs the session one more model request, also when the -session had run the tests in a way the gate does not read. `LOOM_TEST_GATE=off` turns the -gate off. + test that shell command itself runs is not named on its own result. +- **At the end of the session.** A session that changed code and ran no test since 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 lets the stop pass: a shell command that starts a test runner and finished no + earlier than the oldest write among the files the session changed. 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. `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 9a98fa29c2a..727fcd82928 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -151,10 +151,10 @@ the duplicate, run `claude mcp remove -s user`. | `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about the target file (its files facet) and injects the rendered block as additional context — a constraint arrives **before** the edit, not as a review comment. One lookup per (session, file) per 30 min; never a permission decision. `LOOM_FILE_CONTEXT=off` disables. | | `PostToolUse` (loom tools) | `loom-mentor-hint.mjs` | **The store's advice reaches the model**: a loom tool result may carry one `hint` — the plane this agent is not using, named from the call it just made (a `memory.get` that missed, a search that abstained where the code index answers, a stack trace written as a memory, a duplicate write). The hook lifts it out of the result JSON into additional context, once per code per session. No request of its own. `LOOM_MENTOR_HINTS=off` disables. | | `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which stands in for the radius's count of tests where it names the file's tests, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | -| `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. The stop is never held: whether the tests ran is the agent's call (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | +| `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` | **Only with `LOOM_TEST_GATE=block`**, in place of the line at edit time. 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: the tests were named before "done", the choice to run them is the agent's. A stop whose transcript already answers the ask to run tests is not blocked, and so names no untested function (**Answered stops**, below). | +| `Stop` | `loom-test-gate.mjs` | **Holds a session that changed code and ran no test.** 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 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**: on the first stop of a session, one `namespace.audit` over the last day (no samples) for the session's namespace; 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, 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. | @@ -169,9 +169,11 @@ the duplicate, run `claude mcp remove -s user`. **Team file rules.** The file-context hook reads two places in one `memory.for_file` request: your own namespace, and the repository's **primary code namespace** (its trunk branch's — `code-clickhouse` for every ClickHouse branch), named by the checkout's cached `code.repos` entry. A namespace you cannot read is skipped silently, so access follows repository access. Rules from the code namespace render as `Team rule (by alice, 3 days ago) [constraint]: … [id: ]` and design decisions (typed or tagged `decision`) as `Decision (by alice, 3 days ago) (pinned): … — source: [id: ]` (`(pinned)` only when someone pinned it, else no mark; `(source changed)` once its source document no longer says it), a newer rule the conflict check linked to an older one sits above it (`supersedes rule by …`, or `supersedes decision by …`), and one footer line says how to remove a wrong one. Every member of the repository may add a rule there (`memory.set` with `files` and the tag `constraint`) and revise or delete the rules they wrote; a maintainer may delete any — from an agent (`memory.delete` on the `[id:]` key) or from the dashboard (pick the code namespace under _show system_, open the memory, Delete). A refused delete answers a `hint` naming the author and what to do instead. `memory.set` fills `files` from the value when you do not pass it. Auto-extracted session facts never go to the code namespace. -**Tests at edit time.** The test gate names tests; it does not check that they ran. Deciding that from a transcript means reading shell text, and a session that runs the whole suite, compares against a stashed tree or pipes pytest through `grep` has run the tests in a way no fixed rule reads, so a gate that holds the stop on that reading holds sessions that did the work. By default the gate therefore names a file's tests on the tool call that changes it, where the agent is still working on the file, and leaves the end of the session alone. 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 and whatever the server answers, so a function changed later in the same file is not named; 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, and a test whose command the tool call's own command already holds is not named on the result of that run. A team that wants the stop held until the tests are named 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. +**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. -**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 blocking gate's reason 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. +**Stops that pass.** By default the test gate holds the end of a session only when the session changed code and ran no test since. 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 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 oldest write among the files the session changed. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with `test` among its arguments. 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 whose every changed file was written 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. 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. **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 c68a5c46380..df00887edef 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -99,7 +99,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 | with LOOM_TEST_GATE=block only: code.test_gate | 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 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 | namespace.audit (first Stop only) | `LOOM_NAMESPACE_HEALTH=off` | | Stop, detached | loom-working-memory | transcript, cwd | none | working_memory.set when the note changed | `LOOM_WORKING_MEMORY=off` | @@ -282,8 +282,9 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). namespace.audit over the last day (sample_limit=0); a critical finding gives the agent one line naming the codes and /loom-optimize, as a block-once reason. Later stops make no call. -- **loom-test-gate.** Names the tests of a changed file. By default it - does so when the file changes and never holds the stop: after a Bash or +- **loom-test-gate.** Names the tests of a changed file, and holds the + stop of a session that changed code and ran no test. 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 since the session's first row, asks code.test_gate about each one not @@ -294,22 +295,30 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). the checkout has, or the file's own command when it is a test. A file with no such test gets the changed functions the index links no test to. A file is asked about at its first change only, so a function - changed later in it is not named. A test is named once per session, and - not when the call's own command holds its command. The line costs no - model request, and nothing reads shell text to decide whether tests - ran. 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. - With LOOM_TEST_GATE=block it holds the stop instead and prints nothing at - edit time: with uncommitted changes this session made in a loom-indexed + changed later in it is not named; one the server gave no answer for is + asked about once more. A test is named once per session, and not when + the call's own command runs it in this checkout as a whole command + (`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), 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 whose transcript already answers the ask - to run tests is not blocked (`runAnswered` in lib/test-gate.mjs); a Codex - rollout answers nothing. + 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 oldest write among the changed files + (`testedSince`, `oldestChange`): 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` + passes, in a Claude Code transcript or a Codex rollout. 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 721ebb5ae44..234515f9b21 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -9,26 +9,30 @@ // per file and once per test per session. The line rides the tool result, so it // costs no model request, and it arrives while the file is still being // edited. An edit tool's call gets the same line from loom-blast-radius, the -// one hook wired for those tools. The stop is never held: whether the tests -// then ran is the agent's to judge. +// one hook wired for those tools. // -// Stop, with LOOM_TEST_GATE=block: the gate holds the stop instead, and -// names nothing at edit time. If the working tree has uncommitted changes -// THIS SESSION made +// 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. A Claude Code transcript that already answers the ask does not -// block either (`runAnswered` in lib/test-gate.mjs); a Codex rollout answers -// nothing, so its stop blocks. +// nothing. By default any test run since the change lets the stop pass, +// whatever it ran and however it went (`testedSince` in lib/test-gate.mjs): +// the stop is held for a session that changed code and ran no test, and +// nothing is asked of the server for one that ran some. +// +// 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 the whole -// dirty tree is 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"; @@ -59,10 +63,12 @@ import { gatePayload, gateSignature, newestChange, + oldestChange, renderGate, runAnswered, sessionScope, sessionStart, + testedSince, testsIn, writtenSince, } from "../lib/test-gate.mjs"; @@ -88,7 +94,7 @@ async function advise(payload, token) { } async function main() { - if (MODE !== (AFTER_TOOL ? "advise" : "block")) { + if (MODE === "off" || (AFTER_TOOL && MODE === "block")) { scheduleExit(0); return; } @@ -131,6 +137,11 @@ async function main() { scheduleExit(0); return; } + // The default holds the stop of a session whose transcript shows no test run since its change. + if (MODE === "advise" && (!transcript || testedSince(rows, oldestChange(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 5d049cf8fc9..a343a6f76bb 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -5,11 +5,9 @@ // a file carries one line with the command of the tests the index links to // it, or of the file itself when it is a test, or with the changed functions // the index links no test to when it has no test to name; once per file per -// session, and the stop is never held (`adviceFiles`, `adviceLines`). Whether a -// session then ran the tests is the agent's to judge: a hook that reads -// shell text to decide it blocks sessions that did. +// session (`adviceFiles`, `adviceLines`). // -// With LOOM_TEST_GATE=block the gate holds the stop instead. When the agent +// At Stop it holds a session that changed code and ran no test. 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 @@ -19,8 +17,13 @@ // 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 stop whose transcript already answers the ask is not blocked at all -// (`runAnswered`): a block costs the session one more model request. +// A block costs the session one more model request, so by default any test +// run since the change lets the stop pass before anything is asked +// (`testedSince`): 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 @@ -51,8 +54,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 (unset, or any on-word); "block" - * holds the stop instead; "off" does neither. */ + * tests on the tool call that edited it and holds the stop of a session that + * ran no test since its 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 ?? "") @@ -490,7 +494,8 @@ function newest(map, max = 300) { } /** Adds `keys` to the session's test-advice map `field` (`seen`: files asked - * about; `named`: tests a line named). The state is read and written here + * about; `retried`: files to ask about once more; `named`: tests a line + * named). The state is read and written here * with nothing between, not locked: two hooks of one session that write in * the same instant (parallel tool calls) keep one's entries, and the other's * file is then asked about twice or its test named twice. */ @@ -505,15 +510,16 @@ function remember(sessionId, field, keys) { * The edit-time lines for `files` (from `adviceFiles`), as `{ rel, text, * tests }` for each file that has one: `tests` counts the tests `text` names, * 0 when it names the functions the index links no test to. Each file is - * asked about once per session, at its first change and whatever the server - * answers, so a server that is down costs a session one bounded request per - * file and not one per tool call; a function changed later in the same file - * is not asked about. A file whose change is comments only is not asked + * asked about once per session, at its first change, so a function changed + * later in the same file is not asked about. A file the server gave no + * answer for is asked about once more, at the next call that names it, so a + * server that is down costs a session two bounded requests per file and not + * one per tool call. A file whose change is comments only is not asked * about and stays unasked: it owes no test until it changes code. A test is * named once per session: the test file a session edits after the source - * file it tests adds no second line with the same command. A test whose - * command the call's own command holds is not named: the line would arrive - * on the result of that run. Only the diff's paths, hunk ranges and function + * file it tests adds no second line with the same command. A test the call's + * own command runs is not named (`runsHere`): the line would arrive on the + * result of that run. Only the diff's paths, hunk ranges and function * names are sent (`diffHeaders`). */ export async function adviceLines(payload, files, { root, repo, token, depth = gateDepth() } = {}) { @@ -524,11 +530,6 @@ export async function adviceLines(payload, files, { root, repo, token, depth = g ]) .filter(([, diff]) => !commentOnlyDiff(diff)); if (!asked.length) return []; - remember( - payload.session_id, - "seen", - asked.map(([rel]) => rel), - ); const gates = await Promise.all( asked.map(([rel, diff]) => postBounded( @@ -545,7 +546,19 @@ export async function adviceLines(payload, files, { root, repo, token, depth = g ), ), ); - const named = { ...readSessionState("testadvice", payload.session_id).named }; + const state = readSessionState("testadvice", payload.session_id); + const rels = asked.map(([rel]) => rel); + // No answer (a timeout, a 5xx): the file stays unasked for one more call that names it. + const again = rels.filter((rel, i) => !gates[i] && !(state.retried || {})[rel]); + if (again.length) remember(payload.session_id, "retried", again); + if (again.length < rels.length) { + remember( + payload.session_id, + "seen", + rels.filter((rel) => !again.includes(rel)), + ); + } + const named = { ...state.named }; const command = commandText(payload.tool_input); const testExists = testsIn(root); let python; @@ -553,7 +566,7 @@ export async function adviceLines(payload, files, { root, repo, token, depth = g const printed = []; for (const [i, [rel]] of asked.entries()) { const tests = adviceTests(rel, gates[i], testExists); - const fresh = tests.filter((t) => !named[t.test_path] && !(t.run && command.includes(t.run))); + const fresh = tests.filter((t) => !named[t.test_path] && !(t.run && runsHere(command, String(t.run)))); if (python === undefined && fresh.some((t) => isPytest(t.run))) python = checkoutPython(root); // Functions are named only for a file with no test to run in this checkout. const untested = tests.length ? "" : untestedNames(gates[i]).list; @@ -604,6 +617,74 @@ const ELSEWHERE = /\b(?:ssh|docker|podman|kubectl)\s/; /** True when `head`, a command's text up to a pytest run, shows the run * started in this checkout. */ const ranHere = (head) => !ELSEWHERE.test(head) && LAUNCHER.test(head.split(/[;&|(\n]/).pop()); +/** True when `command` runs `run`, a test's whole command, in this checkout: + * `pytest tests/test_a.py::test_one` runs one test of the file, and `echo + * "pytest tests/test_a.py"` and `docker exec app pytest tests/test_a.py` run + * nothing here. */ +function runsHere(command, run) { + const at = command.indexOf(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, or a +// build tool with `test` among its arguments (`make test-unit`, `npm run +// test`, `node --test`). `import pytest`, `pip install pytest` and +// `pytest.raises` are not runs. A command that only mentions a runner counts: +// what is read is whether the session ran a test at all. +const RUNNER = + /(? !(done.get(id) < since)); +} + +/** The oldest modification time, in epoch ms, among `files` under `root`: a + * test run that finished since then saw at least one of them as it stands. + * 0 when none can be read (each one deleted). */ +export function oldestChange(root, files) { + const times = files.flatMap((file) => { + try { + return [fs.statSync(path.join(root, file)).mtimeMs]; + } catch { + return []; + } + }); + return times.length ? Math.min(...times) : 0; +} + // 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 924d70a7775..3e3651caf18 100644 --- a/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs +++ b/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs @@ -115,7 +115,7 @@ async function withCapturingServer(fn) { return bodies; } -// The Stop test gate holds a stop only when asked to. +// The Stop test gate that takes only a run of the named tests as an answer. const BLOCKING = { LOOM_TEST_GATE: "block" }; const HOOK_NAMES = [ @@ -129,11 +129,16 @@ 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. + const starts = hook === "loom-test-gate.mjs" ? [{}, { env: BLOCKING }, { event: "PostToolUse" }] : [{}]; for (const stdin of ["{not json", "", "[]", "null", '"text"', "42"]) { - const r = await run(hook, stdin, { tmp }); - assert.equal(r.code, 0, `${hook} on ${JSON.stringify(stdin)}`); - assert.equal(r.out, "", `${hook} on ${JSON.stringify(stdin)}`); - assert.equal(r.err, "", `${hook} writes no stack trace on ${JSON.stringify(stdin)}`); + for (const how of starts) { + const as = `${hook} ${JSON.stringify(how)} on ${JSON.stringify(stdin)}`; + const r = await run(hook, stdin, { tmp, ...how }); + assert.equal(r.code, 0, as); + assert.equal(r.out, "", as); + assert.equal(r.err, "", `no stack trace: ${as}`); + } } } }); @@ -161,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: BLOCKING }); + const r = await run(hook, payload, { tmp, url, token: "" }); assert.equal(r.code, 0, hook); assert.equal(r.out, "", hook); } @@ -304,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: { ...BLOCKING, 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}`); @@ -333,7 +338,6 @@ test("Stop gates: a Stop the gate itself caused never blocks again", async () => { tmp, url, - env: BLOCKING, }, ); assert.equal(r.out, "", hook); @@ -342,7 +346,7 @@ test("Stop gates: a Stop the gate itself caused never blocks again", async () => }); }); -test("test gate after a shell command: 401 and a hanging server add nothing to the call, and the file is asked about once", async () => { +test("test gate after a shell command: 401 and a hanging server add nothing to the call, and the file is asked about once more", async () => { for (const status of [401, null]) { await withServer(status, async (url, seen, arrived) => { const op = "/v1/code.test_gate"; @@ -366,14 +370,12 @@ test("test gate after a shell command: 401 and a hanging server add nothing to t assert.ok(arrived.has(op), `${status}: never sent ${op} in three runs`); const after = r.closedAt - arrived.get(op); assert.ok(after < 1500, `${status}: ${after} ms after its request (${r.ms} ms in all)`); - // The same session's next command names the file again: no second request. + // The same session's next command names the file again: one more request, then none. + const again = () => + run("loom-test-gate.mjs", { ...shell, session_id: session }, { tmp, url, env: bounds, event: "PostToolUse" }); + assert.equal((await again()).out, ""); const asked = seen.length; - const again = await run( - "loom-test-gate.mjs", - { ...shell, session_id: session }, - { tmp, url, env: bounds, event: "PostToolUse" }, - ); - assert.equal(again.out, ""); + assert.equal((await again()).out, ""); assert.equal(seen.length, asked, seen.join(",")); }); } @@ -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 for the blocking gate's Stop. + // 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 040695b08e9..bab3eb20a67 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -511,7 +511,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, newestChange, oldestChange, runAnswered, testedSince } from "../lib/test-gate.mjs"; import { cachedUnindexed, cachePathFor } from "../lib/repo-scope.mjs"; import { hostEnv } from "./host-env.mjs"; @@ -906,7 +906,66 @@ test("a Codex rollout answers nothing", () => { assert.equal(answered(rollout), false); }); -test("with LOOM_TEST_GATE=block the hook blocks a change whose tests never ran and lets an answered one stop", 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/...", + "make test-unit", + "node --test tests/a.test.mjs", + "tests/clickhouse-test 01234_x", + ]) { + 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 a runner, runs none. + for (const command of [HEREDOC, "sed -n 1,40p tests/test_a.py", "cat pytest.ini", "pip install pytest", "git diff"]) { + 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); + assert.equal(testedSince([], 0), false); +}); + +test("the oldest change is the least recently written file that can be read", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-oldest-")); + try { + for (const [file, at] of [ + ["a.py", 1e12], + ["b.py", 1e12 + 5000], + ]) { + fs.writeFileSync(path.join(dir, file), "x\n"); + fs.utimesSync(path.join(dir, file), new Date(at), new Date(at)); + } + assert.equal(oldestChange(dir, ["b.py", "a.py", "deleted.py"]), 1e12); + assert.equal(oldestChange(dir, ["deleted.py"]), 0); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("the hook holds the stop of a change with no test run; 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"]) { @@ -921,6 +980,7 @@ test("with LOOM_TEST_GATE=block the hook blocks a change whose tests never ran a execFileSync("git", args, { cwd: dir, stdio: "ignore" }); } fs.appendFileSync(path.join(dir, "src/a.py"), "def g():\n return 2\n"); + const ranBefore = bash(SUITE, PASSED); const change = call("Edit", { file_path: path.join(dir, "src/a.py") }, "updated"); // The change is as old as the session's first row, until something rewrites a file. const touch = (file, when) => fs.utimesSync(path.join(dir, file), when, when); @@ -929,13 +989,15 @@ test("with LOOM_TEST_GATE=block the hook blocks a change whose tests never ran a cachePathFor(dir, tmp), JSON.stringify({ ts: Date.now(), indexed: true, org: "o", namespace: "code-x", repo: "x/y", prefixes: [] }), ); + const requests = []; const server = http.createServer((req, res) => { + requests.push(req.url); req.resume(); req.on("end", () => res.end(JSON.stringify(req.url === "/v1/code.test_gate" ? RUN_GATE : {}))); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); const hook = fileURLToPath(new URL("../hooks/loom-test-gate.mjs", import.meta.url)); - const stop = (session, rows) => + const stop = (session, rows, mode = "block") => new Promise((resolve) => { const transcript = path.join(tmp, `${session}.jsonl`); fs.writeFileSync( @@ -952,7 +1014,7 @@ test("with LOOM_TEST_GATE=block the hook blocks a change whose tests never ran a TMPDIR: tmp, LOOM_BASE_URL: `http://127.0.0.1:${server.address().port}`, LOOM_API_KEY: "t", - LOOM_TEST_GATE: "block", + ...(mode ? { LOOM_TEST_GATE: mode } : {}), }), stdio: ["pipe", "pipe", "ignore"], }); @@ -964,6 +1026,18 @@ test("with LOOM_TEST_GATE=block the hook blocks a change whose tests never ran a 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", "")], ""), ""); + assert.equal(requests.length, asked, "a stop that passes on a test run asks the server nothing"); + 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]), ""); // An untracked file whose name git would quote or a trim would cut does not hide the tree's age. @@ -1026,11 +1100,12 @@ test("a checkout the cache says is not indexed is known without git; no other en } }); -test("a changed file's tests ride the tool call that changed it, once, and the stop is never held", async () => { +test("a changed file's tests ride the tool call that changed it, once", async () => { const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-advice-"))); const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-advice-tmp-"))); - const sources = ["src/a.py", "src/b.py", "src/d.py", "src/f.py", "src/old.py"]; - for (const f of [...sources, "tests/test_a.py", "tests/test_b.py", "tests/test_c.py", "tests/test_e.py"]) { + const sources = ["src/a.py", "src/b.py", "src/d.py", "src/f.py", "src/j.py", "src/k.py", "src/old.py"]; + const tests = ["a", "b", "c", "e", "g", "h", "i"].map((n) => `tests/test_${n}.py`); + for (const f of [...sources, ...tests]) { fs.mkdirSync(path.join(dir, path.dirname(f)), { recursive: true }); fs.writeFileSync(path.join(dir, f), "def f():\n return 1\n"); } @@ -1057,12 +1132,18 @@ test("a changed file's tests ride the tool call that changed it, once, and the s }; write("src/old.py", "def parked():\n return 0\n", new Date(Date.now() - 3_600_000)); const asked = []; + // How many of the next requests get a 500. + let failing = 0; const server = http.createServer((req, res) => { let raw = ""; req.on("data", (c) => (raw += c)); req.on("end", () => { const body = JSON.parse(raw || "{}"); asked.push([req.url, ...(body.files || [])].join(" ")); + if (failing-- > 0) { + res.statusCode = 500; + return res.end("{}"); + } const stem = (body.files || []).map((f) => (f.match(/^src\/(\w+)\.py$/) || [])[1]).filter(Boolean); const answer = { "/v1/code.test_gate": { @@ -1182,13 +1263,41 @@ test("a changed file's tests ride the tool call that changed it, once, and the s assert.equal(await shell("python -m pytest tests/test_e.py -q"), null); assert.ok(asked.includes("/v1/code.test_gate tests/test_e.py"), asked.join(", ")); assert.equal(await shell("sed -i s/1/2/ tests/test_e.py"), null); + // A command that runs one test of the file, runs it elsewhere or only prints its command did not run it here. + for (const [n, command] of [ + ["g", "sed -i s/1/2/ tests/test_g.py && pytest tests/test_g.py::test_g"], + ["h", "docker exec app pytest tests/test_h.py"], + ["i", 'echo "pytest tests/test_i.py"'], + ]) { + write(`tests/test_${n}.py`, "def test_g():\n assert True\n"); + assert.match( + context(await shell(command)), + new RegExp(`^Loom tests for tests/test_${n}\\.py: (?:\\S+ -m )?pytest tests/test_${n}\\.py$`), + command, + ); + } + // A file the server gave no answer for is asked about at the next call that names it, once. + failing = 1; + write("src/j.py", "def g():\n return 2\n"); + assert.equal(await shell("sed -i s/1/2/ src/j.py"), null); + assert.equal( + context(await shell("sed -i s/2/3/ src/j.py")), + "Loom tests for src/j.py: the index links no test to m::g", + ); + failing = 2; + write("src/k.py", "def g():\n return 2\n"); + assert.equal(await shell("sed -i s/1/2/ src/k.py"), null); + assert.equal(await shell("sed -i s/2/3/ src/k.py"), null); + assert.equal(await shell("sed -i s/3/4/ src/k.py"), null); + assert.equal(asked.filter((a) => a.endsWith("src/k.py")).length, 2, asked.join(", ")); + failing = 0; // A comment-only change owes no test and stays unasked until it changes code. write("src/old.py", "# a note\n"); execFileSync("git", ["checkout", "-q", "--", "src/old.py"], { cwd: dir }); 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(", ")); - // The stop is not held, whatever the session ran. + // 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" }; @@ -1212,6 +1321,8 @@ test("a changed file's tests ride the tool call that changed it, once, and the s 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. + 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" }; assert.equal( diff --git a/integrations/codex-plugin/hooks/loom-test-gate.mjs b/integrations/codex-plugin/hooks/loom-test-gate.mjs index 721ebb5ae44..234515f9b21 100644 --- a/integrations/codex-plugin/hooks/loom-test-gate.mjs +++ b/integrations/codex-plugin/hooks/loom-test-gate.mjs @@ -9,26 +9,30 @@ // per file and once per test per session. The line rides the tool result, so it // costs no model request, and it arrives while the file is still being // edited. An edit tool's call gets the same line from loom-blast-radius, the -// one hook wired for those tools. The stop is never held: whether the tests -// then ran is the agent's to judge. +// one hook wired for those tools. // -// Stop, with LOOM_TEST_GATE=block: the gate holds the stop instead, and -// names nothing at edit time. If the working tree has uncommitted changes -// THIS SESSION made +// 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. A Claude Code transcript that already answers the ask does not -// block either (`runAnswered` in lib/test-gate.mjs); a Codex rollout answers -// nothing, so its stop blocks. +// nothing. By default any test run since the change lets the stop pass, +// whatever it ran and however it went (`testedSince` in lib/test-gate.mjs): +// the stop is held for a session that changed code and ran no test, and +// nothing is asked of the server for one that ran some. +// +// 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 the whole -// dirty tree is 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"; @@ -59,10 +63,12 @@ import { gatePayload, gateSignature, newestChange, + oldestChange, renderGate, runAnswered, sessionScope, sessionStart, + testedSince, testsIn, writtenSince, } from "../lib/test-gate.mjs"; @@ -88,7 +94,7 @@ async function advise(payload, token) { } async function main() { - if (MODE !== (AFTER_TOOL ? "advise" : "block")) { + if (MODE === "off" || (AFTER_TOOL && MODE === "block")) { scheduleExit(0); return; } @@ -131,6 +137,11 @@ async function main() { scheduleExit(0); return; } + // The default holds the stop of a session whose transcript shows no test run since its change. + if (MODE === "advise" && (!transcript || testedSince(rows, oldestChange(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 5d049cf8fc9..a343a6f76bb 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -5,11 +5,9 @@ // a file carries one line with the command of the tests the index links to // it, or of the file itself when it is a test, or with the changed functions // the index links no test to when it has no test to name; once per file per -// session, and the stop is never held (`adviceFiles`, `adviceLines`). Whether a -// session then ran the tests is the agent's to judge: a hook that reads -// shell text to decide it blocks sessions that did. +// session (`adviceFiles`, `adviceLines`). // -// With LOOM_TEST_GATE=block the gate holds the stop instead. When the agent +// At Stop it holds a session that changed code and ran no test. 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 @@ -19,8 +17,13 @@ // 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 stop whose transcript already answers the ask is not blocked at all -// (`runAnswered`): a block costs the session one more model request. +// A block costs the session one more model request, so by default any test +// run since the change lets the stop pass before anything is asked +// (`testedSince`): 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 @@ -51,8 +54,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 (unset, or any on-word); "block" - * holds the stop instead; "off" does neither. */ + * tests on the tool call that edited it and holds the stop of a session that + * ran no test since its 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 ?? "") @@ -490,7 +494,8 @@ function newest(map, max = 300) { } /** Adds `keys` to the session's test-advice map `field` (`seen`: files asked - * about; `named`: tests a line named). The state is read and written here + * about; `retried`: files to ask about once more; `named`: tests a line + * named). The state is read and written here * with nothing between, not locked: two hooks of one session that write in * the same instant (parallel tool calls) keep one's entries, and the other's * file is then asked about twice or its test named twice. */ @@ -505,15 +510,16 @@ function remember(sessionId, field, keys) { * The edit-time lines for `files` (from `adviceFiles`), as `{ rel, text, * tests }` for each file that has one: `tests` counts the tests `text` names, * 0 when it names the functions the index links no test to. Each file is - * asked about once per session, at its first change and whatever the server - * answers, so a server that is down costs a session one bounded request per - * file and not one per tool call; a function changed later in the same file - * is not asked about. A file whose change is comments only is not asked + * asked about once per session, at its first change, so a function changed + * later in the same file is not asked about. A file the server gave no + * answer for is asked about once more, at the next call that names it, so a + * server that is down costs a session two bounded requests per file and not + * one per tool call. A file whose change is comments only is not asked * about and stays unasked: it owes no test until it changes code. A test is * named once per session: the test file a session edits after the source - * file it tests adds no second line with the same command. A test whose - * command the call's own command holds is not named: the line would arrive - * on the result of that run. Only the diff's paths, hunk ranges and function + * file it tests adds no second line with the same command. A test the call's + * own command runs is not named (`runsHere`): the line would arrive on the + * result of that run. Only the diff's paths, hunk ranges and function * names are sent (`diffHeaders`). */ export async function adviceLines(payload, files, { root, repo, token, depth = gateDepth() } = {}) { @@ -524,11 +530,6 @@ export async function adviceLines(payload, files, { root, repo, token, depth = g ]) .filter(([, diff]) => !commentOnlyDiff(diff)); if (!asked.length) return []; - remember( - payload.session_id, - "seen", - asked.map(([rel]) => rel), - ); const gates = await Promise.all( asked.map(([rel, diff]) => postBounded( @@ -545,7 +546,19 @@ export async function adviceLines(payload, files, { root, repo, token, depth = g ), ), ); - const named = { ...readSessionState("testadvice", payload.session_id).named }; + const state = readSessionState("testadvice", payload.session_id); + const rels = asked.map(([rel]) => rel); + // No answer (a timeout, a 5xx): the file stays unasked for one more call that names it. + const again = rels.filter((rel, i) => !gates[i] && !(state.retried || {})[rel]); + if (again.length) remember(payload.session_id, "retried", again); + if (again.length < rels.length) { + remember( + payload.session_id, + "seen", + rels.filter((rel) => !again.includes(rel)), + ); + } + const named = { ...state.named }; const command = commandText(payload.tool_input); const testExists = testsIn(root); let python; @@ -553,7 +566,7 @@ export async function adviceLines(payload, files, { root, repo, token, depth = g const printed = []; for (const [i, [rel]] of asked.entries()) { const tests = adviceTests(rel, gates[i], testExists); - const fresh = tests.filter((t) => !named[t.test_path] && !(t.run && command.includes(t.run))); + const fresh = tests.filter((t) => !named[t.test_path] && !(t.run && runsHere(command, String(t.run)))); if (python === undefined && fresh.some((t) => isPytest(t.run))) python = checkoutPython(root); // Functions are named only for a file with no test to run in this checkout. const untested = tests.length ? "" : untestedNames(gates[i]).list; @@ -604,6 +617,74 @@ const ELSEWHERE = /\b(?:ssh|docker|podman|kubectl)\s/; /** True when `head`, a command's text up to a pytest run, shows the run * started in this checkout. */ const ranHere = (head) => !ELSEWHERE.test(head) && LAUNCHER.test(head.split(/[;&|(\n]/).pop()); +/** True when `command` runs `run`, a test's whole command, in this checkout: + * `pytest tests/test_a.py::test_one` runs one test of the file, and `echo + * "pytest tests/test_a.py"` and `docker exec app pytest tests/test_a.py` run + * nothing here. */ +function runsHere(command, run) { + const at = command.indexOf(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, or a +// build tool with `test` among its arguments (`make test-unit`, `npm run +// test`, `node --test`). `import pytest`, `pip install pytest` and +// `pytest.raises` are not runs. A command that only mentions a runner counts: +// what is read is whether the session ran a test at all. +const RUNNER = + /(? !(done.get(id) < since)); +} + +/** The oldest modification time, in epoch ms, among `files` under `root`: a + * test run that finished since then saw at least one of them as it stands. + * 0 when none can be read (each one deleted). */ +export function oldestChange(root, files) { + const times = files.flatMap((file) => { + try { + return [fs.statSync(path.join(root, file)).mtimeMs]; + } catch { + return []; + } + }); + return times.length ? Math.min(...times) : 0; +} + // 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 099a281fb2abc1f733e7bd8073cc15d32d7e3111 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 17:00:14 +0530 Subject: [PATCH 6/7] By default the test gate holds the stop of a session that ran no test since its last code change The default Stop compared the last test run with the oldest write among the session's changed files, so a session that edited one file, ran a test and then edited a second code file was not held. - The run is compared with the newest write among the changed code files (`lastCodeChange`). A file that is documentation or prose by its name (`.md`, `.mdx`, `.rst`, `.adoc`, `.txt` other than `CMakeLists.txt` and a requirements file, or a `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS` file) is left out, so a note written after the run holds nothing. A deleted file is left out too, as before. - A build tool counts as a test run only when `test` follows no letter in one of its arguments: `npm install x@latest`, `go install y@latest`, `make latest` and `node scripts/attest.js` no longer count, and `make test-unit`, `npm run test`, `node --test`, `go test ./...` and `gradle :app:test` still do. `nextest` is named as a runner, so `cargo nextest run` still counts. - A Codex rollout's shell call is read as its command text. Its `arguments` JSON can hold an argv such as `["go","test","./..."]`, whose words no space joins, so a build tool's run was not seen there. `LOOM_TEST_GATE=block` is unchanged. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 17 ++--- integrations/claude-code-plugin/README.md | 50 ++++++------- .../claude-code-plugin/hooks/HOOKS.md | 9 +-- .../hooks/loom-test-gate.mjs | 16 +++-- .../claude-code-plugin/lib/test-gate.mjs | 68 ++++++++++++------ .../tests/test-gate.test.mjs | 70 ++++++++++++++++--- .../codex-plugin/hooks/loom-test-gate.mjs | 16 +++-- integrations/codex-plugin/lib/test-gate.mjs | 68 ++++++++++++------ 8 files changed, 214 insertions(+), 100 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 41168b97b12..4de23ab0427 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -58,7 +58,7 @@ end of this section are the exceptions. The plugin sends: - 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 changed code and ran no test since, for the files it changed. With + 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 @@ -486,7 +486,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 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` | 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` | on the first Stop, one line when `namespace.audit` finds a critical misuse of the namespace, pointing at the `loom-optimize` skill | `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` | @@ -620,12 +620,13 @@ 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 changed code and ran no test since 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 lets the stop pass: a shell command that starts a test runner and finished no - earlier than the oldest write among the files the session changed. The gate reads that - command for a runner's name only. Which tests ran and how they went cannot be read +- **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`, `.txt`, a changelog) 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**. diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 727fcd82928..42d4be5d031 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -142,36 +142,36 @@ the duplicate, run `claude mcp remove -s user`. ## What it wires -| Lifecycle event | Script | What it does | -| --------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `PostToolUse`, `PostToolUseFailure`, `Stop`, `SessionEnd` | `loom-record.mjs` | Runs the event's recording scripts (`loom-capture`, `loom-conversation`, `loom-usage`, `loom-working-memory`, `loom-run`'s close, `loom-session-memory`, `loom-session-brief`) in one process. After a tool call and at `Stop` that process is detached and the hook exits, so the session does not wait for their requests. At `SessionEnd` it is the hook itself, which exits when they have returned: a host torn down when the client exits would end a detached process first. | -| `PostToolUse` | `loom-capture.mjs` | Records one episodic observation of the tool action (heuristic type, file list). | -| `PostToolUseFailure` | `loom-capture.mjs` | Same, typed `error` — the bug-triage signal (errors + the subsequent fix). | -| `SessionStart` | `loom-session-start.mjs` | **First session, no credential:** signs this machine up (see `LOOM_AUTO_SIGNUP`) and points the user to the claim page for the namespace; nothing to paste. Then: injects a token-budgeted context primer (profile + relevant memories) via `context.pack`, so the agent starts knowing your context. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index was looked up, so a session start that prints nothing is a fault unless `LOOM_CODE_MAP=false`. How to route a lookup is in the MCP entry's startup instructions on a toolset with a `coding` part; any other toolset, and a wiring whose entry the plugin does not mount (Codex, a hand-wired client), gets it in the primer. **On by default**, once per session; `LOOM_INJECT_CONTEXT=false` to disable. | -| `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about the target file (its files facet) and injects the rendered block as additional context — a constraint arrives **before** the edit, not as a review comment. One lookup per (session, file) per 30 min; never a permission decision. `LOOM_FILE_CONTEXT=off` disables. | -| `PostToolUse` (loom tools) | `loom-mentor-hint.mjs` | **The store's advice reaches the model**: a loom tool result may carry one `hint` — the plane this agent is not using, named from the call it just made (a `memory.get` that missed, a search that abstained where the code index answers, a stack trace written as a memory, a duplicate write). The hook lifts it out of the result JSON into additional context, once per code per session. No request of its own. `LOOM_MENTOR_HINTS=off` disables. | -| `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which stands in for the radius's count of tests where it names the file's tests, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | -| `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 changed code and ran no test.** 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 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**: on the first stop of a session, one `namespace.audit` over the last day (no samples) for the session's namespace; 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, 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. | -| `UserPromptSubmit` | `loom-run.mjs` | Opens the session's **run** on the first prompt (`run.begin`: goal = the prompt, `run_id = cc-`, or the id `run.begin` answers instead; the SessionStart primer and the first prompt's recall go out before that answer, so their `context.pack` exposure rows keep the derived id, or on a resumed session the previous run's id). Later prompts are no-ops once a begin was answered or refused; after a timeout, a 408, 429 or 5xx the next prompt asks again with the same id, and SessionEnd closes it if no answer ever came. Until then the session's run-state file in the temp directory (readable by you only) holds that begin's body, which every retry re-sends: the prompt, redacted and cut to 8000 characters. One row per session in `loom.agent_runs`; every observation the capture hook records carries the same `run_id`, so `run.get` replays the session — goal, observations, memories written, cost. `LOOM_RUN_LEDGER=off` disables. | -| `SessionEnd` | `loom-run.mjs` | Closes the run (`run.complete`) with the transcript's last assistant text as `final_response` and `outcome: none` — the hook knows the run ended, not whether it succeeded, and never guesses which memories were used; that stays the agent's own `run.complete` call (`memories_used`, `reflection`). | -| `PreCompact` | `loom-capture.mjs` | Crystallizes the session before the context window is dropped. | -| `Stop`, `PreCompact` | `loom-working-memory.mjs` | Writes the session's **working-memory note** — one `working_memory.set` per project (`session:`, agent scope): the goal (first prompt), `git status --short --branch`, the files edited this session, the last reply — framed as a bookmark, not a source of facts (the next session's model answered a fact question from this line without searching). Deduped on content, so an unchanged turn writes nothing. `context.pack` loads working memory first in the SessionStart primer and Claude Code fires SessionStart again after a compaction, so the note written a moment before the drop is the first thing the agent reads after it. Not retrieval memory: never embedded or ranked. `LOOM_WORKING_MEMORY=off` disables. With `LOOM_PLUGIN_SCRATCHPAD=1` the Stop hook also appends the turn's one-line conclusion to the run's `scratchpad` block at run scope. | -| `Stop` / `SessionEnd` | `loom-capture.mjs` | Crystallizes the finished session. | -| `PreCompact`, `SessionEnd` | `loom-session-brief.mjs` | Revises the branch's **session brief**: the transcript since the last save becomes typed events (asks, replies, edits, commands with their descriptions, errors, reads, todo lists, PR/commit identifiers a command printed; zero model tokens) posted to `session.brief_save`, which condenses them under a budget and revises `auto//` — goal, status, next steps, decisions and why, what was tried and dropped, what was done, open questions, files, the rules you set, pointers. The `loom-session` skill restores one on request: you pick which (a number from `list`, a key, or a session) and restores it with the client's compaction summary (or `--transcript` for every recorded turn as well). Not retrieval memory: never embedded or ranked. Detached flusher; per-session cursor; a first save needs an ask and some work behind it. `LOOM_SESSION_BRIEF=off` disables. | -| `SessionEnd` | `loom-session-memory.mjs` | Hands the session's real turns (last 200, bounded) to `memory.set_from_messages(defer=true)` once, so loom extracts the facts, writes the **session summary**, judges the outcome and distils reflections. The turns are kept as the facts' source evidence. A session with under 40 bytes (UTF-8) of user and assistant text is not sent, because the extraction call's fixed prompt outweighs what it can yield: a rule stated in it is not extracted, and it gets no session summary, outcome judgement or reflections. `LOOM_SESSION_MEMORY=off` disables. | -| `Stop` / `SessionEnd` | `loom-conversation.mjs` | Appends new chat turns from the transcript to the conversation plane (→ the dashboard's Conversations page). Deterministic, every turn; per-session cursor + `msg_id`=transcript uuid dedup. Text blocks only — an image the user pasted becomes a `[image: ]` placeholder beside its text, and a tool result that returned images leaves one `tool` turn `[image: N image results returned by a tool]`; the bytes never leave the machine. Off-switch: `LOOM_CAPTURE_CONVERSATIONS=false`. | +| Lifecycle event | Script | What it does | +| --------------------------------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `PostToolUse`, `PostToolUseFailure`, `Stop`, `SessionEnd` | `loom-record.mjs` | Runs the event's recording scripts (`loom-capture`, `loom-conversation`, `loom-usage`, `loom-working-memory`, `loom-run`'s close, `loom-session-memory`, `loom-session-brief`) in one process. After a tool call and at `Stop` that process is detached and the hook exits, so the session does not wait for their requests. At `SessionEnd` it is the hook itself, which exits when they have returned: a host torn down when the client exits would end a detached process first. | +| `PostToolUse` | `loom-capture.mjs` | Records one episodic observation of the tool action (heuristic type, file list). | +| `PostToolUseFailure` | `loom-capture.mjs` | Same, typed `error` — the bug-triage signal (errors + the subsequent fix). | +| `SessionStart` | `loom-session-start.mjs` | **First session, no credential:** signs this machine up (see `LOOM_AUTO_SIGNUP`) and points the user to the claim page for the namespace; nothing to paste. Then: injects a token-budgeted context primer (profile + relevant memories) via `context.pack`, so the agent starts knowing your context. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index was looked up, so a session start that prints nothing is a fault unless `LOOM_CODE_MAP=false`. How to route a lookup is in the MCP entry's startup instructions on a toolset with a `coding` part; any other toolset, and a wiring whose entry the plugin does not mount (Codex, a hand-wired client), gets it in the primer. **On by default**, once per session; `LOOM_INJECT_CONTEXT=false` to disable. | +| `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about the target file (its files facet) and injects the rendered block as additional context — a constraint arrives **before** the edit, not as a review comment. One lookup per (session, file) per 30 min; never a permission decision. `LOOM_FILE_CONTEXT=off` disables. | +| `PostToolUse` (loom tools) | `loom-mentor-hint.mjs` | **The store's advice reaches the model**: a loom tool result may carry one `hint` — the plane this agent is not using, named from the call it just made (a `memory.get` that missed, a search that abstained where the code index answers, a stack trace written as a memory, a duplicate write). The hook lifts it out of the result JSON into additional context, once per code per session. No request of its own. `LOOM_MENTOR_HINTS=off` disables. | +| `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which stands in for the radius's count of tests where it names the file's tests, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | +| `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-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**: on the first stop of a session, one `namespace.audit` over the last day (no samples) for the session's namespace; 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, 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. | +| `UserPromptSubmit` | `loom-run.mjs` | Opens the session's **run** on the first prompt (`run.begin`: goal = the prompt, `run_id = cc-`, or the id `run.begin` answers instead; the SessionStart primer and the first prompt's recall go out before that answer, so their `context.pack` exposure rows keep the derived id, or on a resumed session the previous run's id). Later prompts are no-ops once a begin was answered or refused; after a timeout, a 408, 429 or 5xx the next prompt asks again with the same id, and SessionEnd closes it if no answer ever came. Until then the session's run-state file in the temp directory (readable by you only) holds that begin's body, which every retry re-sends: the prompt, redacted and cut to 8000 characters. One row per session in `loom.agent_runs`; every observation the capture hook records carries the same `run_id`, so `run.get` replays the session — goal, observations, memories written, cost. `LOOM_RUN_LEDGER=off` disables. | +| `SessionEnd` | `loom-run.mjs` | Closes the run (`run.complete`) with the transcript's last assistant text as `final_response` and `outcome: none` — the hook knows the run ended, not whether it succeeded, and never guesses which memories were used; that stays the agent's own `run.complete` call (`memories_used`, `reflection`). | +| `PreCompact` | `loom-capture.mjs` | Crystallizes the session before the context window is dropped. | +| `Stop`, `PreCompact` | `loom-working-memory.mjs` | Writes the session's **working-memory note** — one `working_memory.set` per project (`session:`, agent scope): the goal (first prompt), `git status --short --branch`, the files edited this session, the last reply — framed as a bookmark, not a source of facts (the next session's model answered a fact question from this line without searching). Deduped on content, so an unchanged turn writes nothing. `context.pack` loads working memory first in the SessionStart primer and Claude Code fires SessionStart again after a compaction, so the note written a moment before the drop is the first thing the agent reads after it. Not retrieval memory: never embedded or ranked. `LOOM_WORKING_MEMORY=off` disables. With `LOOM_PLUGIN_SCRATCHPAD=1` the Stop hook also appends the turn's one-line conclusion to the run's `scratchpad` block at run scope. | +| `Stop` / `SessionEnd` | `loom-capture.mjs` | Crystallizes the finished session. | +| `PreCompact`, `SessionEnd` | `loom-session-brief.mjs` | Revises the branch's **session brief**: the transcript since the last save becomes typed events (asks, replies, edits, commands with their descriptions, errors, reads, todo lists, PR/commit identifiers a command printed; zero model tokens) posted to `session.brief_save`, which condenses them under a budget and revises `auto//` — goal, status, next steps, decisions and why, what was tried and dropped, what was done, open questions, files, the rules you set, pointers. The `loom-session` skill restores one on request: you pick which (a number from `list`, a key, or a session) and restores it with the client's compaction summary (or `--transcript` for every recorded turn as well). Not retrieval memory: never embedded or ranked. Detached flusher; per-session cursor; a first save needs an ask and some work behind it. `LOOM_SESSION_BRIEF=off` disables. | +| `SessionEnd` | `loom-session-memory.mjs` | Hands the session's real turns (last 200, bounded) to `memory.set_from_messages(defer=true)` once, so loom extracts the facts, writes the **session summary**, judges the outcome and distils reflections. The turns are kept as the facts' source evidence. A session with under 40 bytes (UTF-8) of user and assistant text is not sent, because the extraction call's fixed prompt outweighs what it can yield: a rule stated in it is not extracted, and it gets no session summary, outcome judgement or reflections. `LOOM_SESSION_MEMORY=off` disables. | +| `Stop` / `SessionEnd` | `loom-conversation.mjs` | Appends new chat turns from the transcript to the conversation plane (→ the dashboard's Conversations page). Deterministic, every turn; per-session cursor + `msg_id`=transcript uuid dedup. Text blocks only — an image the user pasted becomes a `[image: ]` placeholder beside its text, and a tool result that returned images leaves one `tool` turn `[image: N image results returned by a tool]`; the bytes never leave the machine. Off-switch: `LOOM_CAPTURE_CONVERSATIONS=false`. | **Team file rules.** The file-context hook reads two places in one `memory.for_file` request: your own namespace, and the repository's **primary code namespace** (its trunk branch's — `code-clickhouse` for every ClickHouse branch), named by the checkout's cached `code.repos` entry. A namespace you cannot read is skipped silently, so access follows repository access. Rules from the code namespace render as `Team rule (by alice, 3 days ago) [constraint]: … [id: ]` and design decisions (typed or tagged `decision`) as `Decision (by alice, 3 days ago) (pinned): … — source: [id: ]` (`(pinned)` only when someone pinned it, else no mark; `(source changed)` once its source document no longer says it), a newer rule the conflict check linked to an older one sits above it (`supersedes rule by …`, or `supersedes decision by …`), and one footer line says how to remove a wrong one. Every member of the repository may add a rule there (`memory.set` with `files` and the tag `constraint`) and revise or delete the rules they wrote; a maintainer may delete any — from an agent (`memory.delete` on the `[id:]` key) or from the dashboard (pick the code namespace under _show system_, open the memory, Delete). A refused delete answers a `hint` naming the author and what to do instead. `memory.set` fills `files` from the value when you do not pass it. Auto-extracted session facts never go to the code namespace. **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 changed code and ran no test since. 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 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 oldest write among the files the session changed. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with `test` among its arguments. 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 whose every changed file was written 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. 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 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 (`.md`, `.mdx`, `.rst`, `.adoc`, `.txt` other than `CMakeLists.txt` and a requirements file, or a `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS` file) is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. 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`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` follows no letter (`make test-unit`, `node --test`, `gradle :app:test`, but not `npm install x@latest`). 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. 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. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index df00887edef..d5bcc125119 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -99,7 +99,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 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 | 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 | namespace.audit (first Stop only) | `LOOM_NAMESPACE_HEALTH=off` | | Stop, detached | loom-working-memory | transcript, cwd | none | working_memory.set when the note changed | `LOOM_WORKING_MEMORY=off` | @@ -283,7 +283,7 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). gives the agent one line naming the codes and /loom-optimize, as a block-once reason. Later stops make no call. - **loom-test-gate.** Names the tests of a changed file, and holds the - stop of a session that changed code and ran no test. By default it names + 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 @@ -309,8 +309,9 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). 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 oldest write among the changed files - (`testedSince`, `oldestChange`): the command's text is read for a + 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` passes, in a Claude Code transcript or a Codex rollout. With no diff --git a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs index 234515f9b21..deecee88c48 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -18,10 +18,12 @@ // 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 change lets the stop pass, -// whatever it ran and however it went (`testedSince` in lib/test-gate.mjs): -// the stop is held for a session that changed code and ran no test, and -// nothing is asked of the server for one that ran some. +// 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 // passes only when a Claude Code transcript shows the named tests ran on the @@ -62,8 +64,8 @@ import { gateMode, gatePayload, gateSignature, + lastCodeChange, newestChange, - oldestChange, renderGate, runAnswered, sessionScope, @@ -137,8 +139,8 @@ async function main() { scheduleExit(0); return; } - // The default holds the stop of a session whose transcript shows no test run since its change. - if (MODE === "advise" && (!transcript || testedSince(rows, oldestChange(root, changed)))) { + // 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; } diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index a343a6f76bb..93d0f5c22e9 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -7,8 +7,9 @@ // 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 changed code and ran no test. When the agent -// is about to stop with uncommitted changes in a loom-indexed repo, it asks +// 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 @@ -18,8 +19,9 @@ // 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 change lets the stop pass before anything is asked -// (`testedSince`): which tests it ran and how they went is the agent's to +// 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 @@ -55,7 +57,7 @@ const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "str_r /** 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 change (unset, or any on-word); "block" names + * 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 ( @@ -628,12 +630,27 @@ function runsHere(command, run) { // 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, or a -// build tool with `test` among its arguments (`make test-unit`, `npm run -// test`, `node --test`). `import pytest`, `pip install pytest` and -// `pytest.raises` are not runs. A command that only mentions a runner counts: -// what is read is whether the session ran a test at all. +// build tool with an argument in which `test` follows no letter (`make +// test-unit`, `npm run test`, `node --test`, `gradle :app:test`). `import +// pytest`, `pip install pytest`, `pytest.raises`, `npm install x@latest` and +// `node scripts/attest.js` are not runs. A command that only mentions a +// runner counts: what is read is whether the session ran a test at all. const RUNNER = - /(? !(done.get(id) < since)); } -/** The oldest modification time, in epoch ms, among `files` under `root`: a - * test run that finished since then saw at least one of them as it stands. - * 0 when none can be read (each one deleted). */ -export function oldestChange(root, files) { - const times = files.flatMap((file) => { +// Documentation and prose by name: a test run answers no change to one. +// `CMakeLists.txt` and a requirements file are code. +const PROSE = /\.(?:md|mdx|rst|txt|adoc)$/i; +const CHANGELOG = /(?:^|\/)(?:CHANGELOG|CHANGES|HISTORY|NEWS)$/; +const CODE_TXT = /(?:^|\/)(?:CMakeLists|[^/]*requirements[^/]*)\.txt$/i; +const isProse = (file) => CHANGELOG.test(file) || (PROSE.test(file) && !CODE_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 { - return [fs.statSync(path.join(root, file)).mtimeMs]; + last = Math.max(last, fs.statSync(path.join(root, file)).mtimeMs); } catch { - return []; + // A deleted file has no time of its own. } - }); - return times.length ? Math.min(...times) : 0; + } + return last; } // pytest's last line, whose order is fixed: failed, passed, skipped, diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index bab3eb20a67..f5ba72d7012 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -511,7 +511,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, oldestChange, runAnswered, testedSince } 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"; @@ -915,15 +915,31 @@ test("any test run that finished since the change counts, whatever it ran and ho "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", + "cargo nextest run", "tests/clickhouse-test 01234_x", ]) { 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 a runner, runs none. - for (const command of [HEREDOC, "sed -n 1,40p tests/test_a.py", "cat pytest.ini", "pip install pytest", "git diff"]) { + // A command that reads or writes a test, or installs a runner, runs none; + // neither does a build tool whose argument holds `test` inside a word. + 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", + ]) { assert.equal(testedSince(bash(command, ""), since), false, command); } assert.equal(testedSince(call("Read", { command: SUITE }), since), false); @@ -945,30 +961,55 @@ test("any test run that finished since the change counts, whatever it ran and ho ]; 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); assert.equal(testedSince([], 0), false); }); -test("the oldest change is the least recently written file that can be read", () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-oldest-")); +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], + ["CMakeLists.txt", 1e12 + 6000], + ["dev-requirements.txt", 1e12 + 7000], + ["README.md", 1e12 + 9000], + ["notes.txt", 1e12 + 9000], + ["guide.rst", 1e12 + 9000], + ["CHANGELOG", 1e12 + 9000], ]) { fs.writeFileSync(path.join(dir, file), "x\n"); fs.utimesSync(path.join(dir, file), new Date(at), new Date(at)); } - assert.equal(oldestChange(dir, ["b.py", "a.py", "deleted.py"]), 1e12); - assert.equal(oldestChange(dir, ["deleted.py"]), 0); + assert.equal(lastCodeChange(dir, ["b.py", "a.py", "deleted.py"]), 1e12 + 5000); + // Documentation and prose are left out, by extension or by a changelog's name. + assert.equal( + lastCodeChange(dir, ["a.py", "b.py", "README.md", "notes.txt", "guide.rst", "CHANGELOG"]), + 1e12 + 5000, + ); + assert.equal(lastCodeChange(dir, ["a.py", "CMakeLists.txt"]), 1e12 + 6000); + assert.equal(lastCodeChange(dir, ["a.py", "dev-requirements.txt"]), 1e12 + 7000); + 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 change with no test run; LOOM_TEST_GATE=block also holds one whose named tests did not run on the final tree", async () => { +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"); } @@ -1036,7 +1077,18 @@ test("the hook holds the stop of a change with no test run; LOOM_TEST_GATE=block 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]), ""); diff --git a/integrations/codex-plugin/hooks/loom-test-gate.mjs b/integrations/codex-plugin/hooks/loom-test-gate.mjs index 234515f9b21..deecee88c48 100644 --- a/integrations/codex-plugin/hooks/loom-test-gate.mjs +++ b/integrations/codex-plugin/hooks/loom-test-gate.mjs @@ -18,10 +18,12 @@ // 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 change lets the stop pass, -// whatever it ran and however it went (`testedSince` in lib/test-gate.mjs): -// the stop is held for a session that changed code and ran no test, and -// nothing is asked of the server for one that ran some. +// 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 // passes only when a Claude Code transcript shows the named tests ran on the @@ -62,8 +64,8 @@ import { gateMode, gatePayload, gateSignature, + lastCodeChange, newestChange, - oldestChange, renderGate, runAnswered, sessionScope, @@ -137,8 +139,8 @@ async function main() { scheduleExit(0); return; } - // The default holds the stop of a session whose transcript shows no test run since its change. - if (MODE === "advise" && (!transcript || testedSince(rows, oldestChange(root, changed)))) { + // 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; } diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index a343a6f76bb..93d0f5c22e9 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -7,8 +7,9 @@ // 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 changed code and ran no test. When the agent -// is about to stop with uncommitted changes in a loom-indexed repo, it asks +// 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 @@ -18,8 +19,9 @@ // 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 change lets the stop pass before anything is asked -// (`testedSince`): which tests it ran and how they went is the agent's to +// 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 @@ -55,7 +57,7 @@ const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "str_r /** 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 change (unset, or any on-word); "block" names + * 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 ( @@ -628,12 +630,27 @@ function runsHere(command, run) { // 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, or a -// build tool with `test` among its arguments (`make test-unit`, `npm run -// test`, `node --test`). `import pytest`, `pip install pytest` and -// `pytest.raises` are not runs. A command that only mentions a runner counts: -// what is read is whether the session ran a test at all. +// build tool with an argument in which `test` follows no letter (`make +// test-unit`, `npm run test`, `node --test`, `gradle :app:test`). `import +// pytest`, `pip install pytest`, `pytest.raises`, `npm install x@latest` and +// `node scripts/attest.js` are not runs. A command that only mentions a +// runner counts: what is read is whether the session ran a test at all. const RUNNER = - /(? !(done.get(id) < since)); } -/** The oldest modification time, in epoch ms, among `files` under `root`: a - * test run that finished since then saw at least one of them as it stands. - * 0 when none can be read (each one deleted). */ -export function oldestChange(root, files) { - const times = files.flatMap((file) => { +// Documentation and prose by name: a test run answers no change to one. +// `CMakeLists.txt` and a requirements file are code. +const PROSE = /\.(?:md|mdx|rst|txt|adoc)$/i; +const CHANGELOG = /(?:^|\/)(?:CHANGELOG|CHANGES|HISTORY|NEWS)$/; +const CODE_TXT = /(?:^|\/)(?:CMakeLists|[^/]*requirements[^/]*)\.txt$/i; +const isProse = (file) => CHANGELOG.test(file) || (PROSE.test(file) && !CODE_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 { - return [fs.statSync(path.join(root, file)).mtimeMs]; + last = Math.max(last, fs.statSync(path.join(root, file)).mtimeMs); } catch { - return []; + // A deleted file has no time of its own. } - }); - return times.length ? Math.min(...times) : 0; + } + return last; } // pytest's last line, whose order is fixed: failed, passed, skipped, From 98876a1fa75218dcb86335829d4f84213fa043fc Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 28 Nov 2026 17:37:06 +0530 Subject: [PATCH 7/7] A package install or a Codex shell call under another name does not decide the default Stop wrongly - A build tool counts as a test run when `test` or `tests` follows no letter and no lower-case letter follows it. `npm install @testing-library/react` and `go get github.com/stretchr/testify` do not count; `make test-unit`, `make unit-tests`, `gradle :app:test` and `gradlew testDebugUnitTest` do. - `testedSince` takes a Codex rollout's shell call under each name `normalizeToolName` folds onto Bash (`shell_command`, `local_shell`, `container.exec`), not only `exec`, `exec_command` and `shell`: a session that ran its tests through one of those was held. - The Claude Code page's paragraph on what the hooks run locally says what the plugin README says of the test gate; a unit test keeps the two equal. - The sender census pins `lib/repo-scope.mjs` of both plugins at its current content. The file gained `cachedUnindexed`, which reads the shared cache and sends nothing; its three reviewed call sites are unchanged. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 2 +- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/lib/test-gate.mjs | 20 ++++++++++++------- .../tests/test-gate.test.mjs | 12 +++++++++++ integrations/codex-plugin/lib/test-gate.mjs | 20 ++++++++++++------- tests/unit/session_content_senders.json | 4 ++-- 6 files changed, 42 insertions(+), 18 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 133cc4a535f..e9095f9d4d0 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -508,7 +508,7 @@ requests) run `node`, `git` and `grep` on your machine: `git` reads the checkout remotes, branch, `HEAD` commit, status and diffs, and `grep` searches uncommitted files for the pattern of a grep the plugin redirects to the code index. The `loom-session` skill's brief script also runs `git log` for the commits since the last brief. The test -gate (the hook that, when a reply ends, names the tests a change needs) runs no Python: +gate (the hook that names the tests of a file you change) runs no Python: for a pytest test it picks the interpreter of the checkout's virtualenv, the active one (`VIRTUAL_ENV`) or a `python3` or `python` on `PATH`, checking that the interpreter's file exists without running it. diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 7bb750f775b..390b300cfe7 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -172,7 +172,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 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 (`.md`, `.mdx`, `.rst`, `.adoc`, `.txt` other than `CMakeLists.txt` and a requirements file, or a `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS` file) is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. 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`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` follows no letter (`make test-unit`, `node --test`, `gradle :app:test`, but not `npm install x@latest`). 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. 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 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 (`.md`, `.mdx`, `.rst`, `.adoc`, `.txt` other than `CMakeLists.txt` and a requirements file, or a `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS` file) is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. 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`, `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 `npm install x@latest` or `npm install @testing-library/react`). 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. 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. diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 93d0f5c22e9..8b1ea2ebe66 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -630,13 +630,19 @@ function runsHere(command, run) { // 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, or a -// build tool with an argument in which `test` follows no letter (`make -// test-unit`, `npm run test`, `node --test`, `gradle :app:test`). `import -// pytest`, `pip install pytest`, `pytest.raises`, `npm install x@latest` and -// `node scripts/attest.js` are not runs. A command that only mentions a -// runner counts: what is read is whether the session ran a test at all. +// 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`). `import +// pytest`, `pip install pytest`, `pytest.raises`, `npm install x@latest`, +// `npm install @testing-library/react` and `node scripts/attest.js` are not +// runs. A command that only mentions a runner counts: what is read is +// whether the session ran a test at all. const RUNNER = - /(? 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. */ @@ -667,7 +673,7 @@ export function testedSince(objs, since) { if (o?.type === "response_item") { const call = o.payload || {}; if (/_output$/.test(call.type)) done.set(call.call_id, at); - else if (["exec", "exec_command", "shell"].includes(call.name) && RUNNER.test(rolloutCommand(call))) { + else if (rolloutShell(call.name) && RUNNER.test(rolloutCommand(call))) { runs.push(call.call_id); } continue; diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index f5ba72d7012..27bedb39d70 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -921,6 +921,8 @@ test("any test run that finished since the change counts, whatever it ran and ho "node --test", "node --test tests/a.test.mjs", "gradle :app:test", + "./gradlew testDebugUnitTest", + "make unit-tests", "cargo nextest run", "tests/clickhouse-test 01234_x", ]) { @@ -939,6 +941,8 @@ test("any test run that finished since the change counts, whatever it ran and ho "go install y@latest", "make latest", "node scripts/attest.js", + "npm install @testing-library/react", + "go get github.com/stretchr/testify", ]) { assert.equal(testedSince(bash(command, ""), since), false, command); } @@ -973,6 +977,14 @@ test("any test run that finished since the change counts, whatever it ran and ho 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); }); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 93d0f5c22e9..8b1ea2ebe66 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -630,13 +630,19 @@ function runsHere(command, run) { // 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, or a -// build tool with an argument in which `test` follows no letter (`make -// test-unit`, `npm run test`, `node --test`, `gradle :app:test`). `import -// pytest`, `pip install pytest`, `pytest.raises`, `npm install x@latest` and -// `node scripts/attest.js` are not runs. A command that only mentions a -// runner counts: what is read is whether the session ran a test at all. +// 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`). `import +// pytest`, `pip install pytest`, `pytest.raises`, `npm install x@latest`, +// `npm install @testing-library/react` and `node scripts/attest.js` are not +// runs. A command that only mentions a runner counts: what is read is +// whether the session ran a test at all. const RUNNER = - /(? 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. */ @@ -667,7 +673,7 @@ export function testedSince(objs, since) { if (o?.type === "response_item") { const call = o.payload || {}; if (/_output$/.test(call.type)) done.set(call.call_id, at); - else if (["exec", "exec_command", "shell"].includes(call.name) && RUNNER.test(rolloutCommand(call))) { + else if (rolloutShell(call.name) && RUNNER.test(rolloutCommand(call))) { runs.push(call.call_id); } continue; diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index dacb440e828..8fa28f65a27 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -394,7 +394,7 @@ "integrations/claude-code-plugin/lib/loom-client.mjs": "77deae655319bb4dbec3981e38949144d0493041150127b72822876952a1d144", "integrations/claude-code-plugin/lib/namespace-health.mjs": "c8a9aab01f1e996c97643aee7b8f367bf6447f7a6c74dec01a70dc50a0caa182", "integrations/claude-code-plugin/lib/prompt-pack.mjs": "63a0d74d6777b5f98071e500206c5c9c8f284d987e04a853a244cf5f8580ab45", - "integrations/claude-code-plugin/lib/repo-scope.mjs": "127a7daefbe4cdaf014a58351f1b3cec068220985ac940a2952f161a8c881108", + "integrations/claude-code-plugin/lib/repo-scope.mjs": "b89eb707f495d458c449e20b36384284bc34261139bd60545aa7b93dea582f1e", "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "63ed14793cf0fb6a1df0df9e70652e86a76c95114c3003fe83bdba48e2e7a12e", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", @@ -409,7 +409,7 @@ "integrations/codex-plugin/lib/loom-client.mjs": "77deae655319bb4dbec3981e38949144d0493041150127b72822876952a1d144", "integrations/codex-plugin/lib/namespace-health.mjs": "c8a9aab01f1e996c97643aee7b8f367bf6447f7a6c74dec01a70dc50a0caa182", "integrations/codex-plugin/lib/prompt-pack.mjs": "63a0d74d6777b5f98071e500206c5c9c8f284d987e04a853a244cf5f8580ab45", - "integrations/codex-plugin/lib/repo-scope.mjs": "127a7daefbe4cdaf014a58351f1b3cec068220985ac940a2952f161a8c881108", + "integrations/codex-plugin/lib/repo-scope.mjs": "b89eb707f495d458c449e20b36384284bc34261139bd60545aa7b93dea582f1e", "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "63ed14793cf0fb6a1df0df9e70652e86a76c95114c3003fe83bdba48e2e7a12e", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc",