diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 7acc7737a6c..f529f31b5b2 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). @@ -55,9 +55,12 @@ 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), and once more at the Stop of a + session that ran no test since its last code change, for the files it changed. With + `LOOM_TEST_GATE=block` the outline goes at Stop only, for the files the session changed, + or for the whole uncommitted tree when the client gives no transcript. A diff's outline, up to 200,000 characters, is its file paths, its hunk line ranges and, in a code file, the last identifier before the first `(` of each hunk header's context, usually the enclosing function's name. Git takes that context from a line above the hunk in the old file, @@ -185,8 +188,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: @@ -391,11 +394,24 @@ 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 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 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 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 `--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 @@ -471,13 +487,14 @@ 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 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` | | UserPromptSubmit | `loom-record.mjs` | the prompt's one process: runs `loom-prompt-pack` and `loom-prompt-recall` in the hook and prints their context as one answer, writes the run's begin to the session's run state, and hands the prompt's recording scripts (`loom-run`, the namespace audit) to a detached process | each script's own | | 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` | for changes this session made, blocks "done" once with the tests `code.test_gate` says the change obliges, unless a test runner ran since the last code change or your latest prompt ends with "Do not run the tests"; with `LOOM_TEST_GATE=block`, unless pytest ran the named tests to its summary line and nothing was edited or run since ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | | Stop | `loom-validate-gate.mjs` | blocks once when `namespace.validate` finds errors or warnings on the memory keys this session wrote | `LOOM_VALIDATE_GATE=off` | | Stop | `loom-namespace-health.mjs` | one line when `namespace.audit` finds a critical misuse of the namespace, pointing at the `loom-optimize` skill; the audit is asked once per session, by the first prompt's detached process, and told at a Stop | `LOOM_NAMESPACE_HEALTH=off` | | Stop, PreCompact | `loom-working-memory.mjs` | refreshes the working-memory note (`session:`): goal, git status, files edited, last reply | `LOOM_WORKING_MEMORY=off` | @@ -491,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. @@ -584,6 +601,7 @@ Beyond the off switches in the table: | `LOOM_PROMPT_PACK_MIN_CONF` | unset | a `retrieval_confidence` gate for search pointers (low risk is 0.7 up); unset, that label | | `LOOM_FILE_CONTEXT_TTL_MIN` | `30` | minutes before the same file's context is fetched again | | `LOOM_BLAST_DEPTH` | `1` | `code.impact` depth for the blast-radius line | +| `LOOM_TEST_GATE` | unset | `block`: no line at edit time, and a stop passes only on the named tests; `off`: no gate | | `LOOM_TEST_GATE_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 | @@ -592,6 +610,47 @@ 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 comes back with one extra +line when Loom has a test to name for it: + +```text +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 + 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. +- **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. A file is asked about at + its first change only, so a function changed later in the same file is not named. A + test that shell command itself runs is not named on its own result. +- **At the end of the session.** A session that ran no test since its last code change + is held once per distinct change, with the tests the change obliges and the functions + the index links no test to. A held stop costs the session one more model request, so + any test run since that change lets the stop pass: a shell command that starts a test + runner and finished no earlier than the newest write among the code files the session + changed. A documentation or prose file (`.md`, `.rst`, `.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**. + +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 Inside an indexed checkout, `loom-code-shunt.mjs` denies a bulk read and puts the diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 390a5e5325e..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.68", + "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 512c30f85b6..1ed41fb2295 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 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. @@ -142,36 +142,41 @@ the duplicate, run `claude mcp remove -s user`. ## What it wires -| Lifecycle event | Script | What it does | -| --------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `UserPromptSubmit` | `loom-record.mjs` | The prompt's one process. Runs the two lookups the prompt waits for (`loom-prompt-pack`, `loom-prompt-recall`) in the hook itself and prints what they found as one `additionalContext`; writes the run's begin to the session's run state and hands the prompt's recording scripts (`loom-run`, `loom-namespace-health`'s audit) to a detached process and exits, as after a tool call. | -| `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. `LOOM_BLAST_RADIUS=off` disables. | -| `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-validate-gate.mjs` | **Compile green before done**: collects the memory keys this session wrote from the transcript, asks `namespace.validate` for a report scoped to exactly those keys, and blocks the stop **once** per distinct key set with the error and warning findings that name them (a conflict you opened, a fact whose `valid_to` has passed, an attestation your edit made stale) and each check's remedy. `info` findings never block; the second stop on the same keys passes. `LOOM_VALIDATE_GATE=off` disables. | -| `Stop` | `loom-namespace-health.mjs` | **The store tells you when the namespace is misused**: once per session, one `namespace.audit` over the last day (no samples) for the session's namespace, asked by the first prompt's detached process so that a stop does not wait for it (a stop asks in place only when that process died before its answer); when it carries a critical finding — exact-key reads dwarfing searches, double-encoded values, rows the embedder gave up on, leases in the memory plane — you get **one line** naming the codes and `/loom-optimize`, once per session, at the first stop that finds the verdict, as a block-once reason (the one channel a Stop hook has to the model). Healthy namespace, no token, slow or down server: nothing. The same summary rides `context.pack` as the `namespace_health` section at session start. `LOOM_NAMESPACE_HEALTH=off` disables. | -| `Stop` | `loom-usage.mjs` | Posts the session's own model usage (input, cache read, cache creation by TTL, output; deduped by message id, sidechains skipped) to `cost.record_turns`; the **server** prices it into `loom.agent_turn_usage` from the same table it prices its own upstream spend with. Turns "did loom make this session cheaper" into a standing series instead of a hand-run paired experiment. Needs a writer token. `LOOM_USAGE=off` disables. | -| `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 prompt does not wait for that answer, so the SessionStart primer, the prompt's recall and a first tool observation 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 | +| --------------------------------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `UserPromptSubmit` | `loom-record.mjs` | The prompt's one process. Runs the two lookups the prompt waits for (`loom-prompt-pack`, `loom-prompt-recall`) in the hook itself and prints what they found as one `additionalContext`; writes the run's begin to the session's run state and hands the prompt's recording scripts (`loom-run`, `loom-namespace-health`'s audit) to a detached process and exits, as after a tool call. | +| `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**: once per session, one `namespace.audit` over the last day (no samples) for the session's namespace, asked by the first prompt's detached process so that a stop does not wait for it (a stop asks in place only when that process died before its answer); when it carries a critical finding — exact-key reads dwarfing searches, double-encoded values, rows the embedder gave up on, leases in the memory plane — you get **one line** naming the codes and `/loom-optimize`, once per session, at the first stop that finds the verdict, as a block-once reason (the one channel a Stop hook has to the model). Healthy namespace, no token, slow or down server: nothing. The same summary rides `context.pack` as the `namespace_health` section at session start. `LOOM_NAMESPACE_HEALTH=off` disables. | +| `Stop` | `loom-usage.mjs` | Posts the session's own model usage (input, cache read, cache creation by TTL, output; deduped by message id, sidechains skipped) to `cost.record_turns`; the **server** prices it into `loom.agent_turn_usage` from the same table it prices its own upstream spend with. Turns "did loom make this session cheaper" into a standing series instead of a hand-run paired experiment. Needs a writer token. `LOOM_USAGE=off` disables. | +| `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 prompt does not wait for that answer, so the SessionStart primer, the prompt's recall and a first tool observation 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. -**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 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. -**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. +**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. + +**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 3fc255ed70a..73ac562d1cc 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -100,7 +100,8 @@ receives on stdout. | PreToolUse Read\|Grep\|Bash | loom-code-shunt | tool_name, tool_input, cwd | JSON permission decision | code.repos; one code.outline, code.symbol or tracker.duplicate_check before a deny; 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 (`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 | @@ -109,7 +110,7 @@ receives on stdout. | Stop, detached | loom-capture | session_id | none | observe.crystallize | no token | | Stop, detached | loom-conversation | transcript, last_assistant_message | none | conversation.append via the flusher | `LOOM_CAPTURE_CONVERSATIONS=false` | | Stop, detached | loom-usage | transcript | none | cost.record_turns | `LOOM_USAGE=off` | -| Stop | loom-test-gate | transcript, cwd | JSON block once | code.test_gate | `LOOM_TEST_GATE=off` | +| Stop | loom-test-gate | transcript, cwd | JSON block once | code.test_gate, when the transcript shows no test run since the last code change (`testedSince`); with LOOM_TEST_GATE=block, unless the named tests ran | `LOOM_TEST_GATE=off` | | Stop | loom-validate-gate | transcript | JSON block once | namespace.validate | `LOOM_VALIDATE_GATE=off` | | Stop | loom-namespace-health | cwd, session_id | JSON block once | none: tells the stored verdict once (namespace.audit is asked here by a wiring with no detached process, on the first Stop, and when the prompt's ask is overdue) | `LOOM_NAMESPACE_HEALTH=off` | | Stop, detached | loom-working-memory | transcript, cwd | none | working_memory.set when the note changed | `LOOM_WORKING_MEMORY=off` | @@ -251,7 +252,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 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); @@ -322,15 +326,45 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). prompt. A wiring that starts the script at Stop only (Codex, a hand-wired client) asks on the first Stop and waits for the answer. Later stops make no call. -- **loom-test-gate.** 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 of a changed file, and holds the + stop of a session that ran no test since its last code change. By default it names + them when the file changes: after a Bash or + PowerShell command (and, through loom-blast-radius, after an edit tool) + it takes the dirty paths the call named or targeted that were written + since the session's first row, asks code.test_gate about each one not + 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 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; 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. By default a stop passes, and asks the server nothing, when + the transcript holds a shell command that starts a test runner and + finished no earlier than the newest write among the changed code files, + documentation and prose left out by name + (`testedSince`, `lastCodeChange`): the command's text is read for a + runner's name only, not for which tests ran or how they went, so a run + that failed, was piped or ran between `git stash` and `git stash pop` + 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 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 fd63e065eba..1002267c3e7 100644 --- a/integrations/claude-code-plugin/hooks/hooks.json +++ b/integrations/claude-code-plugin/hooks/hooks.json @@ -65,6 +65,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..e77f1a8c5dc 100644 --- a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs @@ -8,11 +8,19 @@ // 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` for the file's tests and names +// their command (lib/test-gate.mjs), in place of the radius's own count of +// 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. 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 +43,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, adviceLines, 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 +97,34 @@ 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 ? adviceLines(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); + // 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 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.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 013b96f64e3..deecee88c48 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -1,30 +1,47 @@ #!/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` 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, 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. +// +// 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 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 +// 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. -// LOOM_TEST_GATE=off disables; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. +// 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 fs from "node:fs"; -import path from "node:path"; import crypto from "node:crypto"; import { git, gitToplevel, - pathUnder, + normalizeToolName, postBounded, readStdinJson, DIFF_ARGS, @@ -32,30 +49,54 @@ import { resolveServerUrl, resolveToken, scheduleExit, - envSwitch, } 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, + adviceLines, + advicePayload, checkoutPython, commentOnlyDiff, decideBlock, + gateDepth, + gateMode, gatePayload, gateSignature, + lastCodeChange, newestChange, renderGate, runAnswered, sessionScope, sessionStart, + testedSince, + 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 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 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"); +} async function main() { - if (!ENABLED) { + if (MODE === "off" || (AFTER_TOOL && MODE === "block")) { scheduleExit(0); return; } @@ -65,6 +106,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); @@ -93,6 +139,11 @@ async function main() { scheduleExit(0); return; } + // The default holds the stop of a session whose transcript shows no test run since its last code change. + if (MODE === "advise" && (!transcript || testedSince(rows, lastCodeChange(root, changed)))) { + scheduleExit(0); + return; + } const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); if (!repo.indexed) { scheduleExit(0); @@ -127,16 +178,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/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 6a9521efd71..8b1ea2ebe66 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1,7 +1,16 @@ -// 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 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, or with the changed functions +// the index links no test to when it has no test to name; once per file per +// session (`adviceFiles`, `adviceLines`). +// +// At Stop it holds a session that ran no test since its last code change. +// When the agent is about to stop with uncommitted changes in a +// loom-indexed repo, it asks +// `code.test_gate` what the change obliges: the tests that reach // it (evidence-ordered, with a run command when derivable) and the touched // functions no test reaches. If either list is non-empty and this exact // change has not been gated yet this session, block the stop ONCE with a @@ -9,8 +18,14 @@ // 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 last write to a changed code file lets the stop pass before +// anything is asked (`testedSince`, `lastCodeChange`): which tests it ran +// and how they went is the agent's to +// judge, and a hook that reads shell text to decide it blocks sessions that +// ran them. With LOOM_TEST_GATE=block nothing is named at edit time and the +// stop passes only when the transcript shows the named tests ran on the tree +// as it stands (`runAnswered`). // // The change is the session's, not the tree's: `sessionScope` keeps only // the dirty paths the transcript shows this session edited or named in a @@ -21,10 +36,45 @@ 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 and holds the stop of a session that + * ran no test since its last code change (unset, or any on-word); "block" names + * nothing and holds the stop until the named tests ran; "off" does neither. */ +export function gateMode(env = process.env) { + if ( + String(env.LOOM_TEST_GATE ?? "") + .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 +112,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; @@ -85,15 +131,12 @@ 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. 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 +147,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 +159,66 @@ 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 }) { + 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 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 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`): 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, 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. */ @@ -239,6 +342,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 +456,135 @@ 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 }; +} + +/** `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; +} + +/** Adds `keys` to the session's test-advice map `field` (`seen`: files asked + * 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. */ +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 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, 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 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() } = {}) { + 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 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 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; + 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 && 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; + 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 // 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 @@ -373,6 +619,106 @@ 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 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. */ +function rolloutCommand(call) { + let input = call.input ?? call.arguments; + if (typeof input === "string") { + try { + input = JSON.parse(input); + } catch { + return input; + } + } + return commandText(input) || (typeof input === "string" ? input : ""); +} + +/** + * True when the transcript holds a shell command that starts a test runner + * (`RUNNER`) and finished at or after `since` (epoch ms), or has no dated + * result: Claude Code rows and Codex rollout calls, sidechains skipped. Its + * output is not read, so a run that failed, was piped into `grep` or ran + * between `git stash` and `git stash pop` counts. + */ +export function testedSince(objs, since) { + const done = new Map(); + const runs = []; + for (const o of objs || []) { + const at = Date.parse((o && o.timestamp) || ""); + if (o?.type === "response_item") { + const call = o.payload || {}; + if (/_output$/.test(call.type)) done.set(call.call_id, at); + else if (rolloutShell(call.name) && RUNNER.test(rolloutCommand(call))) { + runs.push(call.call_id); + } + continue; + } + const content = o && !o.isSidechain && o.message && o.message.content; + for (const b of Array.isArray(content) ? content : []) { + if (o.type === "user" && b?.type === "tool_result") done.set(b.tool_use_id, at); + else if ( + o.type === "assistant" && + b?.type === "tool_use" && + ["Bash", "PowerShell"].includes(normalizeToolName(b.name)) && + RUNNER.test(commandText(b.input)) + ) { + runs.push(b.id); + } + } + } + return runs.some((id) => !(done.get(id) < since)); +} + +// Documentation and prose by name: a test run answers no change to one. +// `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 { + last = Math.max(last, fs.statSync(path.join(root, file)).mtimeMs); + } catch { + // A deleted file has no time of its own. + } + } + return last; +} + // pytest's last line, whose order is fixed: failed, passed, skipped, // deselected, xfailed, xpassed, warnings, errors. A whole line starts at // "failed" or "passed" and names nothing deselected, so a -k subset is not diff --git a/integrations/claude-code-plugin/tests/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 b44660413d8..500048e31a1 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 that takes only a run of the named tests as an answer. +const BLOCKING = { LOOM_TEST_GATE: "block" }; + const HOOK_NAMES = [ "loom-code-shunt.mjs", "loom-file-context.mjs", @@ -126,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}`); + } } } }); @@ -162,6 +170,10 @@ test("no token: nothing is asked of the server and nothing is printed", async () 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, []); }); }); @@ -334,6 +346,41 @@ 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 more", 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: 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; + assert.equal((await 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 +485,25 @@ 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 }); }); - 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 at the Stop of a session that ran no test. + 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 883495fa660..f059e61dfd4 100644 --- a/integrations/claude-code-plugin/tests/hooks-json.test.mjs +++ b/integrations/claude-code-plugin/tests/hooks-json.test.mjs @@ -45,6 +45,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..27bedb39d70 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -5,10 +5,15 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { + advicePayload, + adviceTests, checkoutPython, decideBlock, + gateMode, gatePayload, gateSignature, + printedTests, + renderAdvice, renderGate, sessionScope, sessionStart, @@ -32,6 +37,79 @@ 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", adviceTests("src/a.py", GATE), { python: ".venv/bin/python" }); + assert.equal( + 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", + ); + // 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 }, + }); +}); + +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(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( + 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(line("src/a.py", none), ""); + } + 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`, + why: "graph_hop", + run: `pytest tests/test_${n}.py`, + })); + assert.equal( + 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", () => { assert.equal(gateSignature(["b.py", "a.py"], "h1"), gateSignature(["a.py", "b.py"], "h1")); assert.notEqual(gateSignature(["a.py"], "h1"), gateSignature(["a.py"], "h2")); @@ -433,8 +511,8 @@ 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 { cachePathFor } from "../lib/repo-scope.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"; const said = (content, extra = {}) => ({ type: "user", message: { content }, ...extra }); @@ -828,10 +906,122 @@ 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("any test run that finished since the change counts, whatever it ran and however it went", () => { + const since = Date.parse(edit()[0].timestamp); + for (const command of [ + SUITE, + "git stash; pytest tests; git stash pop", + "pytest tests/test_other.py -x 2>&1 | grep FAILED", + "sed -i s/1/2/ src/a.py && .venv/bin/python -m unittest discover", + "npx vitest run src/a.test.ts", + "go test ./pkg/...", + "go test ./...", + "make test-unit", + "npm run test", + "node --test", + "node --test tests/a.test.mjs", + "gradle :app:test", + "./gradlew testDebugUnitTest", + "make unit-tests", + "cargo nextest run", + "tests/clickhouse-test 01234_x", + ]) { + 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; + // 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", + "npm install @testing-library/react", + "go get github.com/stretchr/testify", + ]) { + assert.equal(testedSince(bash(command, ""), since), false, command); + } + assert.equal(testedSince(call("Read", { command: SUITE }), since), false); + assert.equal(testedSince(bash(SUITE, PASSED, { isSidechain: true }), since), false); + // A row of another type that copies the call is not the session's call. + assert.equal(testedSince([{ ...bash(SUITE, PASSED)[0], type: "api-request-blob" }], since), false); + // A run that finished before the change does not count; one with no dated result does. + const before = bash(SUITE, PASSED); + assert.equal(testedSince(before, Date.parse(before[1].timestamp) + 1), false); + assert.equal(testedSince(before.slice(0, 1), Date.parse(before[1].timestamp) + 1), true); + // A Codex rollout's shell call counts by its output row's time. + const item = (payload, ms) => ({ type: "response_item", timestamp: new Date(ms).toISOString(), payload }); + const rollout = [ + item( + { type: "function_call", name: "shell", call_id: "c1", arguments: '{"command":["pytest","tests","-q"]}' }, + 1e12, + ), + item({ type: "function_call_output", call_id: "c1", output: "3 passed in 0.10s" }, 1e12 + 1000), + ]; + assert.equal(testedSince(rollout, 1e12 + 500), true); + assert.equal(testedSince(rollout, 1e12 + 1500), false); + // Its arguments hold an argv, a shell wrapper's script or one string. + const shell = (args) => [item({ type: "function_call", name: "shell", call_id: "c2", arguments: args }, 1e12)]; + for (const args of [ + '{"command":["go","test","./..."]}', + '{"command":["npm","test"]}', + '{"command":["bash","-lc","make test-unit"]}', + '{"cmd":"npm run test"}', + "go test ./...", + ]) { + assert.equal(testedSince(shell(args), 1e12), true, args); + } + assert.equal(testedSince(shell('{"command":["npm","install","x@latest"]}'), 1e12), false); + // The shell tool counts under each name the client gives it; another tool that names a runner does not. + const named = (name) => [ + item({ type: "function_call", name, call_id: "c3", arguments: '{"command":"pytest -q"}' }, 1e12), + ]; + for (const name of ["exec", "exec_command", "shell", "shell_command", "local_shell", "container.exec"]) { + assert.equal(testedSince(named(name), 1e12), true, name); + } + assert.equal(testedSince(named("apply_patch"), 1e12), false); + assert.equal(testedSince([], 0), false); +}); + +test("the last code change is the most recently written code file that can be read", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-last-code-")); + try { + for (const [file, at] of [ + ["a.py", 1e12], + ["b.py", 1e12 + 5000], + ["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(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 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"); } @@ -843,6 +1033,7 @@ test("the hook blocks a change whose tests never ran and lets an answered one st 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); @@ -851,13 +1042,15 @@ test("the hook blocks a change whose tests never ran and lets an answered one st 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( @@ -874,6 +1067,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", + ...(mode ? { LOOM_TEST_GATE: mode } : {}), }), stdio: ["pipe", "pipe", "ignore"], }); @@ -885,6 +1079,29 @@ test("the hook blocks a change whose tests never ran and lets an answered one st try { const ran = [change, bash(SUITE, PASSED)]; const no = [said("Fix f. Do not run the test suite."), change]; + // The default: a change with no test run since it is held once, with the tests to run. + assert.match(await stop("d-never-ran", [change], ""), /"decision":"block".*pytest tests\/test_a\.py/); + assert.equal(await stop("d-never-ran", [change], ""), ""); + assert.match(await stop("d-ran-before", [ranBefore, change], ""), /"decision":"block"/); + assert.match(await stop("d-only-read", [change, bash("cat tests/test_a.py", "")], ""), /"decision":"block"/); + // Any run since the change passes: one that failed, ran another file, or was followed by more commands. + const asked = requests.length; + assert.equal(await stop("d-ran", ran, ""), ""); + assert.equal(await stop("d-failed", [change, bash("pytest tests/test_b.py -x | grep FAILED", "")], ""), ""); + assert.equal(await stop("d-then-more", [...ran, bash("rm src/helper.py", ""), bash("git diff", "")], ""), ""); + // A documentation file written after the run is not a code change. + const later = (file) => { + const edited = call("Edit", { file_path: path.join(dir, file) }, "updated"); + fs.appendFileSync(path.join(dir, file), "def h():\n return 3\n"); + touch(file, new Date(edited[1].timestamp)); + return edited; + }; + assert.equal(await stop("d-doc-after-run", [...ran, later("docs/guide.md")], ""), ""); + assert.equal(requests.length, asked, "a stop that passes on a test run asks the server nothing"); + // A second code file written after the run is: the run saw the first one only. + assert.match(await stop("d-run-between", [...ran, later("src/b.py")], ""), /"decision":"block"/); + execFileSync("git", ["checkout", "-q", "--", "src/b.py", "docs/guide.md"], { cwd: dir }); + assert.equal(await stop("d-ruled-out", no, ""), ""); assert.match(await stop("never-ran", [change]), /"decision":"block".*pytest tests\/test_a\.py/); assert.equal(await stop("never-ran", [change]), ""); // An untracked file whose name git would quote or a trim would cut does not hide the tree's age. @@ -920,3 +1137,272 @@ 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 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", 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/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"); + } + 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 = []; + // 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": { + 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: stem.length ? [{ 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, 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 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. + 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 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( + 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); + // 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 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 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(", ")); + // This transcript shows no tool call, so the stop has no change of the session's to hold. + assert.equal(await run("loom-test-gate", "Stop", {}), null); + // LOOM_TEST_GATE=block: nothing at edit time, the radius counts its tests, the stop is held. + const blocking = { LOOM_TEST_GATE: "block" }; + write("src/a.py", "def h():\n return 3\n"); + 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), /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( + 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 6c43be1ebb1..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.68", + "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/hooks.json b/integrations/codex-plugin/hooks/hooks.json index 5cd56a7d935..7f4965786e9 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..e77f1a8c5dc 100644 --- a/integrations/codex-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/codex-plugin/hooks/loom-blast-radius.mjs @@ -8,11 +8,19 @@ // 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` for the file's tests and names +// their command (lib/test-gate.mjs), in place of the radius's own count of +// 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. 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 +43,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, adviceLines, 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 +97,34 @@ 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 ? adviceLines(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); + // 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 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.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 013b96f64e3..deecee88c48 100644 --- a/integrations/codex-plugin/hooks/loom-test-gate.mjs +++ b/integrations/codex-plugin/hooks/loom-test-gate.mjs @@ -1,30 +1,47 @@ #!/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` 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, 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. +// +// 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 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 +// 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. -// LOOM_TEST_GATE=off disables; LOOM_TEST_GATE_DEPTH (1-3) sets the hops. +// 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 fs from "node:fs"; -import path from "node:path"; import crypto from "node:crypto"; import { git, gitToplevel, - pathUnder, + normalizeToolName, postBounded, readStdinJson, DIFF_ARGS, @@ -32,30 +49,54 @@ import { resolveServerUrl, resolveToken, scheduleExit, - envSwitch, } 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, + adviceLines, + advicePayload, checkoutPython, commentOnlyDiff, decideBlock, + gateDepth, + gateMode, gatePayload, gateSignature, + lastCodeChange, newestChange, renderGate, runAnswered, sessionScope, sessionStart, + testedSince, + 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 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 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"); +} async function main() { - if (!ENABLED) { + if (MODE === "off" || (AFTER_TOOL && MODE === "block")) { scheduleExit(0); return; } @@ -65,6 +106,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); @@ -93,6 +139,11 @@ async function main() { scheduleExit(0); return; } + // The default holds the stop of a session whose transcript shows no test run since its last code change. + if (MODE === "advise" && (!transcript || testedSince(rows, lastCodeChange(root, changed)))) { + scheduleExit(0); + return; + } const repo = await resolveIndexedRepo(root, { consumer: "claude-code-testgate" }); if (!repo.indexed) { scheduleExit(0); @@ -127,16 +178,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/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 6a9521efd71..8b1ea2ebe66 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1,7 +1,16 @@ -// 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 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, or with the changed functions +// the index links no test to when it has no test to name; once per file per +// session (`adviceFiles`, `adviceLines`). +// +// At Stop it holds a session that ran no test since its last code change. +// When the agent is about to stop with uncommitted changes in a +// loom-indexed repo, it asks +// `code.test_gate` what the change obliges: the tests that reach // it (evidence-ordered, with a run command when derivable) and the touched // functions no test reaches. If either list is non-empty and this exact // change has not been gated yet this session, block the stop ONCE with a @@ -9,8 +18,14 @@ // 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 last write to a changed code file lets the stop pass before +// anything is asked (`testedSince`, `lastCodeChange`): which tests it ran +// and how they went is the agent's to +// judge, and a hook that reads shell text to decide it blocks sessions that +// ran them. With LOOM_TEST_GATE=block nothing is named at edit time and the +// stop passes only when the transcript shows the named tests ran on the tree +// as it stands (`runAnswered`). // // The change is the session's, not the tree's: `sessionScope` keeps only // the dirty paths the transcript shows this session edited or named in a @@ -21,10 +36,45 @@ 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 and holds the stop of a session that + * ran no test since its last code change (unset, or any on-word); "block" names + * nothing and holds the stop until the named tests ran; "off" does neither. */ +export function gateMode(env = process.env) { + if ( + String(env.LOOM_TEST_GATE ?? "") + .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 +112,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; @@ -85,15 +131,12 @@ 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. 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 +147,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 +159,66 @@ 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 }) { + 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 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 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`): 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, 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. */ @@ -239,6 +342,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 +456,135 @@ 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 }; +} + +/** `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; +} + +/** Adds `keys` to the session's test-advice map `field` (`seen`: files asked + * 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. */ +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 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, 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 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() } = {}) { + 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 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 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; + 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 && 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; + 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 // 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 @@ -373,6 +619,106 @@ 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 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. */ +function rolloutCommand(call) { + let input = call.input ?? call.arguments; + if (typeof input === "string") { + try { + input = JSON.parse(input); + } catch { + return input; + } + } + return commandText(input) || (typeof input === "string" ? input : ""); +} + +/** + * True when the transcript holds a shell command that starts a test runner + * (`RUNNER`) and finished at or after `since` (epoch ms), or has no dated + * result: Claude Code rows and Codex rollout calls, sidechains skipped. Its + * output is not read, so a run that failed, was piped into `grep` or ran + * between `git stash` and `git stash pop` counts. + */ +export function testedSince(objs, since) { + const done = new Map(); + const runs = []; + for (const o of objs || []) { + const at = Date.parse((o && o.timestamp) || ""); + if (o?.type === "response_item") { + const call = o.payload || {}; + if (/_output$/.test(call.type)) done.set(call.call_id, at); + else if (rolloutShell(call.name) && RUNNER.test(rolloutCommand(call))) { + runs.push(call.call_id); + } + continue; + } + const content = o && !o.isSidechain && o.message && o.message.content; + for (const b of Array.isArray(content) ? content : []) { + if (o.type === "user" && b?.type === "tool_result") done.set(b.tool_use_id, at); + else if ( + o.type === "assistant" && + b?.type === "tool_use" && + ["Bash", "PowerShell"].includes(normalizeToolName(b.name)) && + RUNNER.test(commandText(b.input)) + ) { + runs.push(b.id); + } + } + } + return runs.some((id) => !(done.get(id) < since)); +} + +// Documentation and prose by name: a test run answers no change to one. +// `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 { + last = Math.max(last, fs.statSync(path.join(root, file)).mtimeMs); + } catch { + // A deleted file has no time of its own. + } + } + return last; +} + // pytest's last line, whose order is fixed: failed, passed, skipped, // deselected, xfailed, xpassed, warnings, errors. A whole line starts at // "failed" or "passed" and names nothing deselected, so a -k subset is not diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 5a52f977574..6901196c780 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",