From 2e900ba6ae4620def76e52ab37de06e440e8dba7 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 16:19:04 +0530 Subject: [PATCH 01/24] A bug report's pointers carry what a whole run of a slow test file costs in the repository A session that does not know what a whole run of a data-driven test file costs runs the whole file to check a change, where a -k selection of its cases answers in seconds. The plugin's pytest result file holds the case count and the run's seconds, and nothing kept them. The test report hook now notes them for a shell command that is one pytest run of one test file, in the session's private state. The session's end hands one memory row a repository to the flusher for a whole run of 60 s or more, and the prompt hook reads that row beside a bug report's search and prints one line under the pointers. The read is never waited for past the search's answer. Code-only mode notes, stores and prints nothing. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 158 +++-- .../.claude-plugin/plugin.json | 4 +- integrations/claude-code-plugin/README.md | 83 ++- .../claude-code-plugin/hooks/HOOKS.md | 182 +++-- .../hooks/loom-prompt-pack.mjs | 35 +- .../claude-code-plugin/hooks/loom-record.mjs | 16 +- .../hooks/loom-session-memory.mjs | 19 +- .../hooks/loom-test-report.mjs | 19 +- .../claude-code-plugin/lib/test-cost.mjs | 251 +++++++ .../claude-code-plugin/lib/test-gate.mjs | 41 ++ .../claude-code-plugin/lib/test-report.mjs | 53 +- .../tests/test-cost.test.mjs | 665 ++++++++++++++++++ .../codex-plugin/.codex-plugin/plugin.json | 2 +- .../codex-plugin/hooks/loom-prompt-pack.mjs | 35 +- .../codex-plugin/hooks/loom-record.mjs | 16 +- .../hooks/loom-session-memory.mjs | 19 +- .../codex-plugin/hooks/loom-test-report.mjs | 19 +- integrations/codex-plugin/lib/test-cost.mjs | 251 +++++++ integrations/codex-plugin/lib/test-gate.mjs | 41 ++ integrations/codex-plugin/lib/test-report.mjs | 53 +- tests/unit/session_content_senders.json | 14 +- 21 files changed, 1785 insertions(+), 191 deletions(-) create mode 100644 integrations/claude-code-plugin/lib/test-cost.mjs create mode 100644 integrations/claude-code-plugin/tests/test-cost.test.mjs create mode 100644 integrations/codex-plugin/lib/test-cost.mjs diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 497bdd45751..f990a3f0e92 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -90,6 +90,12 @@ end of this section are the exceptions. The plugin sends: definitions its changed lines are in, at most four of 120 characters each, read from the hunk headers and the added definition lines of `git diff -U0` (`LOOM_SESSION_MEMORY=off` stops all of it); +- for a pytest run of one test file that passed and took a minute or more, the file's + path, the number of cases it collected and the seconds it and a filtered run of it + took, to `memory.set` at the session's end, as one memory row a repository; a session + that has the test report reads that row with one `memory.get` at its first bug report + ([what a whole run costs](#what-a-whole-run-costs); `LOOM_TEST_REPORT=off` stops both, + `LOOM_SESSION_MEMORY=off` the write; Claude Code only); - a run record (the first prompt as its goal, the last reply) and a working-memory note (goal, git status, files edited, last reply); - a session brief at each compaction and at session end: the client's compaction summary @@ -121,7 +127,8 @@ end of this section are the exceptions. The plugin sends: The plugin's [mode](#modes) narrows the list. In `code` mode the hooks send no tool call's input, output or error, no chat turn, no session turns for extraction and no list of -changed files, no working-memory note and no brief, and fetch no recalled memory. They +changed files, no test run's cost, no working-memory note and no brief, and fetch no +recalled memory. They still send each prompt's text as a code-index search where the checkout is indexed (`code.search`; `prompt_pack=off` stops it), the run record (the first prompt and the last reply; `LOOM_RUN_LEDGER=off` stops it), token usage and the model name (`LOOM_USAGE=off` stops @@ -166,8 +173,9 @@ the result of the session's last pytest run as pytest writes it (test names, fai messages and tracebacks): the plugin adds its result-file option to `PYTEST_ADDOPTS` for the session's shell commands so that pytest writes it. The file is sent nowhere and is removed when the session ends; a digest of at most 700 characters, redacted, goes to the model after a -failing run whose output was cut ([the test report](#the-test-report); -`LOOM_TEST_REPORT=off` stops it). +failing run whose output was cut, and what a slow whole run of one test file cost goes to +memory, as listed above ([the test report](#the-test-report); `LOOM_TEST_REPORT=off` +stops both). Where the code plane is on and `LOOM_MCP_CODE_SCOPE` is not off, Claude Code's SessionStart also writes `loom-mcp-project-.json` in the system temp directory @@ -264,16 +272,16 @@ Install either this plugin or `loom-code-skill`, not both; the plugin already sh `loom-code` skill. Update with `claude plugin update loom@loom`: hooks ship with the plugin, not the server. -| Option | Default | Meaning | -| ---------------- | -------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `server_url` | `$LOOM_BASE_URL/mcp?toolset=coding&schema_profile=plugin`, else `http://localhost:7777/mcp?toolset=coding&schema_profile=plugin` | Full MCP endpoint; include the proxy prefix and desired toolset. The default is used as written, so set `LOOM_BASE_URL` with no trailing slash | -| `token` | empty | a writer JWT, stored as a sensitive value | -| `local_first` | `false` | `true` stands the code shunt down (same as `LOOM_CODE_LOCAL_FIRST=on`) | -| `prompt_pack` | `auto` | `auto`, `on` or `off`: the code index's pointers for a prompt, at `auto` where this Loom holds the checkout's own repository (same as `LOOM_PROMPT_PACK`; [below](#what-a-prompt-gets)) | -| `prompt_recall` | `first` | `first`, `on` or `off`: the memory recall for a prompt (same as `LOOM_PROMPT_RECALL`) | -| `prompt_context` | `true` | `false` stops everything the plugin adds to a prompt, code pointers and memory recall (same as `LOOM_PROMPT_CONTEXT=off`) | -| `stop_test_gate` | `false` | `true` holds the end of a session that changed code and ran no test since, once (same as `LOOM_TEST_GATE=stop`; [the test gate](#the-test-gate)) | -| `test_report` | `true` | `false` stops the result-file option the plugin adds to `PYTEST_ADDOPTS` and the failure digest (same as `LOOM_TEST_REPORT=off`; [the test report](#the-test-report)) | +| Option | Default | Meaning | +| ---------------- | -------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `server_url` | `$LOOM_BASE_URL/mcp?toolset=coding&schema_profile=plugin`, else `http://localhost:7777/mcp?toolset=coding&schema_profile=plugin` | Full MCP endpoint; include the proxy prefix and desired toolset. The default is used as written, so set `LOOM_BASE_URL` with no trailing slash | +| `token` | empty | a writer JWT, stored as a sensitive value | +| `local_first` | `false` | `true` stands the code shunt down (same as `LOOM_CODE_LOCAL_FIRST=on`) | +| `prompt_pack` | `auto` | `auto`, `on` or `off`: the code index's pointers for a prompt, at `auto` where this Loom holds the checkout's own repository (same as `LOOM_PROMPT_PACK`; [below](#what-a-prompt-gets)) | +| `prompt_recall` | `first` | `first`, `on` or `off`: the memory recall for a prompt (same as `LOOM_PROMPT_RECALL`) | +| `prompt_context` | `true` | `false` stops everything the plugin adds to a prompt, code pointers and memory recall (same as `LOOM_PROMPT_CONTEXT=off`) | +| `stop_test_gate` | `false` | `true` holds the end of a session that changed code and ran no test since, once (same as `LOOM_TEST_GATE=stop`; [the test gate](#the-test-gate)) | +| `test_report` | `true` | `false` stops the result-file option the plugin adds to `PYTEST_ADDOPTS`, the failure digest and the test cost note (same as `LOOM_TEST_REPORT=off`; [the test report](#the-test-report)) | The endpoint query chooses the listing, for example `?toolset=coding+tracker`, and [mode](#modes). Without a recognized toolset the server chooses its configured default. @@ -1055,32 +1063,32 @@ See [code index overview](../code-index/overview.md) and the The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. -| Event | Script | Effect | Off switch | -| ------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | -| SessionStart | `loom-session-start.mjs` | one budgeted `context.pack` primer (working-memory note, profile, the session's memory stack, recent runs with `LOOM_CONTEXT_RUNS`; and the memories, decisions and procedures a search for the project finds or, where a new or cleared conversation's prompts get the recall, the pinned and newest ones, listed), one line naming an indexed checkout's code namespace and the repository's memory tag (left out in a new session whose MCP connection carries the checkout: the server then applies both), a line naming the project's saved session briefs, a task-inbox line (`task.counts`), a few lines naming the collections the token can read (`collection.list`), and a line for a checkout without [the instruction block](#the-instruction-block) | `LOOM_INJECT_CONTEXT=false`, `LOOM_CODE_MAP=false`, `LOOM_TASK_INBOX_LINE=off`, `LOOM_COLLECTIONS_LINE=off`, `LOOM_SETUP_LINE=off` | -| UserPromptSubmit | `loom-prompt-pack.mjs` | no request with `prompt_pack` off; at its default no prompt text unless this Loom holds the checkout's own repository ([what a prompt gets](#what-a-prompt-gets)); otherwise up to three `code.search` pointers for the prompt, only when the index rates its answer low-risk (or it reaches `LOOM_PROMPT_PACK_MIN_CONF`) and then only the answer's places to edit, one pointer per place: a definition, a unit of a file the hook does not hold to definitions, a document or a test when the prompt names it or asks for documentation or tests, a Python migration or a release script only if named, and module-level code when it asks for tests; below them the test line for a pointer whose definition the prompt names ([the test gate](#the-test-gate)) | off unless `prompt_pack` or `LOOM_PROMPT_PACK=on`; `LOOM_PROMPT_CONTEXT=off` | -| UserPromptSubmit | `loom-prompt-recall.mjs` | one bounded `context.pack` recall for the prompt (memories, decisions, procedures), injected only when memory does not abstain: whole records, and none of code as it was before a commit the checkout already has; of a record linked to a file of the checkout that the prompt does not name, one line: its key and the file | `LOOM_PROMPT_RECALL=first` (default) / `on` / `off`; `LOOM_PROMPT_CONTEXT=off` | -| UserPromptSubmit | `loom-run.mjs` | opens the session's run (`run.begin`, `run_id = cc-`, goal = the first prompt); the prompt does not wait for it | `LOOM_RUN_LEDGER=off` | -| PreToolUse (Read, Grep; Bash for a command that runs `gh`) | `loom-code-shunt.mjs` | the code shunt and the tracker shunt ([next section](#the-code-shunt)) | `LOOM_CODE_SHUNT=off`, `LOOM_TRACKER_SHUNT=off` | -| PostToolUse (Read, Grep, Bash) | `loom-file-context.mjs` | what Loom knows about each file the call read (`memory.for_file`): your rules and the repository's shared rules and design decisions, on the read's result; once per file per session and agent context, without the records the session already holds | `LOOM_FILE_CONTEXT=off` | -| PreToolUse (Edit, Write, MultiEdit, NotebookEdit) | `loom-file-context.mjs` | the same block before an edit of a file not shown yet in this agent context, or shown more than 30 min ago | `LOOM_FILE_CONTEXT=off` | -| PostToolUse (Loom tools) | `loom-mentor-hint.mjs` | lifts a result's `hint` into context, once per hint code per session | `LOOM_MENTOR_HINTS=off` | -| PostToolUse (Edit, Write, MultiEdit) | `loom-blast-radius.mjs` | one line from `code.impact`: callers, tests reaching the change, co-change files not yet touched; on a file's first edit, the test gate's line beside it in place of the tests | `LOOM_BLAST_RADIUS=off` | -| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | for a file the command changed that has a test of its own, that test's command and what the index knows of it (`code.test_gate`); once per file and per test per session, on the tool result; nothing for a file with no such test or after a command that only reads ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | -| PostToolUse, PostToolUseFailure (Bash) | `loom-test-report.mjs` | after a test command whose output names no failure's reason, a digest of the result file its pytest run wrote: totals and failures grouped by message; no request ([the test report](#the-test-report)) | `LOOM_TEST_REPORT=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, PreCompact, Stop, SessionEnd | `loom-record.mjs` | the event's one process: runs the scripts the session waits for in the hook (the PostToolUse rows above, each for its tools, the test report after a failed call too, and the Stop gates below) and prints their answers as one, and runs the event's recording scripts (the other rows for those events) in one process: detached after a tool call the capture script records something of, at Stop and at SessionEnd, so the session does not wait for their requests and the client cannot cancel them, and in the hook itself before a compaction | 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` | off unless the install turns it on (`stop_test_gate`, or `LOOM_TEST_GATE=stop`): 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; the primer of a new conversation on another branch than the note names leaves it out | `LOOM_WORKING_MEMORY=off` | -| Stop, PreCompact, SessionEnd | `loom-capture.mjs` | crystallises the session (`observe.crystallize`) | none | -| PreCompact, SessionEnd | `loom-session-brief.mjs` | revises the branch's session brief (`session.brief_save`, key `auto//`) | `LOOM_SESSION_BRIEF=off` | -| SessionEnd | `loom-run.mjs` | closes the run (`run.complete`, `outcome: none`, the last reply as the final response) | `LOOM_RUN_LEDGER=off` | -| SessionEnd | `loom-session-memory.mjs` | hands the session's turns to `memory.set_from_messages(defer=true)`, which extracts facts and writes the session summary; a session with under 40 bytes (UTF-8) of user and assistant text is not sent and gets neither | `LOOM_SESSION_MEMORY=off` | +| Event | Script | Effect | Off switch | +| ------------------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| SessionStart | `loom-session-start.mjs` | one budgeted `context.pack` primer (working-memory note, profile, the session's memory stack, recent runs with `LOOM_CONTEXT_RUNS`; and the memories, decisions and procedures a search for the project finds or, where a new or cleared conversation's prompts get the recall, the pinned and newest ones, listed), one line naming an indexed checkout's code namespace and the repository's memory tag (left out in a new session whose MCP connection carries the checkout: the server then applies both), a line naming the project's saved session briefs, a task-inbox line (`task.counts`), a few lines naming the collections the token can read (`collection.list`), and a line for a checkout without [the instruction block](#the-instruction-block) | `LOOM_INJECT_CONTEXT=false`, `LOOM_CODE_MAP=false`, `LOOM_TASK_INBOX_LINE=off`, `LOOM_COLLECTIONS_LINE=off`, `LOOM_SETUP_LINE=off` | +| UserPromptSubmit | `loom-prompt-pack.mjs` | no request with `prompt_pack` off; at its default no prompt text unless this Loom holds the checkout's own repository ([what a prompt gets](#what-a-prompt-gets)); otherwise up to three `code.search` pointers for the prompt, only when the index rates its answer low-risk (or it reaches `LOOM_PROMPT_PACK_MIN_CONF`) and then only the answer's places to edit, one pointer per place: a definition, a unit of a file the hook does not hold to definitions, a document or a test when the prompt names it or asks for documentation or tests, a Python migration or a release script only if named, and module-level code when it asks for tests; below them the test line for a pointer whose definition the prompt names ([the test gate](#the-test-gate)), and under a bug report's pointers the repository's test cost line, from one `memory.get` a session ([what a whole run costs](#what-a-whole-run-costs)) | off unless `prompt_pack` or `LOOM_PROMPT_PACK=on`; `LOOM_PROMPT_CONTEXT=off` | +| UserPromptSubmit | `loom-prompt-recall.mjs` | one bounded `context.pack` recall for the prompt (memories, decisions, procedures), injected only when memory does not abstain: whole records, and none of code as it was before a commit the checkout already has; of a record linked to a file of the checkout that the prompt does not name, one line: its key and the file | `LOOM_PROMPT_RECALL=first` (default) / `on` / `off`; `LOOM_PROMPT_CONTEXT=off` | +| UserPromptSubmit | `loom-run.mjs` | opens the session's run (`run.begin`, `run_id = cc-`, goal = the first prompt); the prompt does not wait for it | `LOOM_RUN_LEDGER=off` | +| PreToolUse (Read, Grep; Bash for a command that runs `gh`) | `loom-code-shunt.mjs` | the code shunt and the tracker shunt ([next section](#the-code-shunt)) | `LOOM_CODE_SHUNT=off`, `LOOM_TRACKER_SHUNT=off` | +| PostToolUse (Read, Grep, Bash) | `loom-file-context.mjs` | what Loom knows about each file the call read (`memory.for_file`): your rules and the repository's shared rules and design decisions, on the read's result; once per file per session and agent context, without the records the session already holds | `LOOM_FILE_CONTEXT=off` | +| PreToolUse (Edit, Write, MultiEdit, NotebookEdit) | `loom-file-context.mjs` | the same block before an edit of a file not shown yet in this agent context, or shown more than 30 min ago | `LOOM_FILE_CONTEXT=off` | +| PostToolUse (Loom tools) | `loom-mentor-hint.mjs` | lifts a result's `hint` into context, once per hint code per session | `LOOM_MENTOR_HINTS=off` | +| PostToolUse (Edit, Write, MultiEdit) | `loom-blast-radius.mjs` | one line from `code.impact`: callers, tests reaching the change, co-change files not yet touched; on a file's first edit, the test gate's line beside it in place of the tests | `LOOM_BLAST_RADIUS=off` | +| PostToolUse (Bash, PowerShell) | `loom-test-gate.mjs` | for a file the command changed that has a test of its own, that test's command and what the index knows of it (`code.test_gate`); once per file and per test per session, on the tool result; nothing for a file with no such test or after a command that only reads ([the test gate](#the-test-gate)) | `LOOM_TEST_GATE=off` | +| PostToolUse, PostToolUseFailure (Bash) | `loom-test-report.mjs` | after a test command whose output names no failure's reason, a digest of the result file its pytest run wrote: totals and failures grouped by message; no request; it notes what a pytest run of one test file cost for the session's end ([the test report](#the-test-report)) | `LOOM_TEST_REPORT=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, PreCompact, Stop, SessionEnd | `loom-record.mjs` | the event's one process: runs the scripts the session waits for in the hook (the PostToolUse rows above, each for its tools, the test report after a failed call too, and the Stop gates below) and prints their answers as one, and runs the event's recording scripts (the other rows for those events) in one process: detached after a tool call the capture script records something of, at Stop and at SessionEnd, so the session does not wait for their requests and the client cannot cancel them, and in the hook itself before a compaction | 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` | off unless the install turns it on (`stop_test_gate`, or `LOOM_TEST_GATE=stop`): 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; the primer of a new conversation on another branch than the note names leaves it out | `LOOM_WORKING_MEMORY=off` | +| Stop, PreCompact, SessionEnd | `loom-capture.mjs` | crystallises the session (`observe.crystallize`) | none | +| PreCompact, SessionEnd | `loom-session-brief.mjs` | revises the branch's session brief (`session.brief_save`, key `auto//`) | `LOOM_SESSION_BRIEF=off` | +| SessionEnd | `loom-run.mjs` | closes the run (`run.complete`, `outcome: none`, the last reply as the final response) | `LOOM_RUN_LEDGER=off` | +| SessionEnd | `loom-session-memory.mjs` | hands the session's turns to `memory.set_from_messages(defer=true)`, which extracts facts and writes the session summary, and with them one `memory.set` of what a slow whole run of one test file cost ([what a whole run costs](#what-a-whole-run-costs)); a session with under 40 bytes (UTF-8) of user and assistant text is not sent and gets neither | `LOOM_SESSION_MEMORY=off` | The plugin's hooks and its MCP header helper (the script that adds the token to Loom's MCP requests) run `node`, `git` and `grep` on your machine: `git` reads the checkout's @@ -1409,7 +1417,7 @@ Beyond the off switches in the table: | `LOOM_BLAST_DEPTH` | `1` | `code.impact` depth for the blast-radius line | | `LOOM_TEST_GATE` | unset | `stop`: also hold a stop with no test run since the last code change (the `stop_test_gate` option); `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_TEST_REPORT` | `on` | `off`: no result-file option in `PYTEST_ADDOPTS` and no failure digest after a cut pytest run (the `test_report` option) | +| `LOOM_TEST_REPORT` | `on` | `off`: no result-file option in `PYTEST_ADDOPTS`, no failure digest after a cut pytest run and no test cost noted or printed (the `test_report` option) | | `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 | | `LOOM_PLUGIN_SCRATCHPAD` | unset | `1` appends each turn's one-line conclusion to the run's `scratchpad` working-memory block | @@ -1545,8 +1553,10 @@ the gate off. A session that pipes pytest into `tail` sees the totals and not why a test failed, and spends a model request on running the same tests again to read it. The plugin has pytest write a result file on every run of the session, and after a test command whose output was -cut it adds the failure reasons to that command's result. It sends no request and stores -nothing in Loom. It is pytest only. +cut it adds the failure reasons to that command's result. The digest sends no request and +nothing of it is stored in Loom; from the same file the plugin keeps what a slow whole run +of one test file costs, as one memory row a repository +([what a whole run costs](#what-a-whole-run-costs)). It is pytest only. **Loom adds its result-file option to `PYTEST_ADDOPTS` for the session's shell commands**: `--junitxml= -o junit_family=xunit1`, where the file is the session's own, mode @@ -1633,6 +1643,70 @@ session's next start. The file is removed when the session ends, and a day after write if the session has not ended by then: a session that runs no pytest for a day gets no option and no digest after that. +### What a whole run costs + +A session that does not know what a whole run of a data-driven test file costs runs it to +check a change where a `-k` selection of its cases answers in seconds. With the memory +plane on, the test report also notes what a pytest run cost, and a later session in the +repository is told before it chooses. + +**What is noted.** After a shell command that holds one pytest run, started in the +checkout, that names one test file and nothing else to run, the hook reads the number of +cases and the seconds pytest writes at the head of the result file, and keeps them in the +session's private state: + +- a whole run counts when no case failed, and the costliest one is kept; +- a run of a selection of the file (`-k`, `-m`, a node id, `--lf`, `--sw`, `--deselect`) + counts as filtered, and the middle of the session's filtered runs of the file is kept; +- a command with two pytest runs or two paths, and a run that only collects or prints + (`--collect-only`, `--fixtures`), count as neither. + +The result file is the command's when the command's output shows pytest's summary line +and the file's first case is in the test file the command names. A run that outlives its +shell call writes the file after the hook ran: it is read when the session ends, where no +other test command followed it. + +**What is stored.** When the session ends, a whole run of 60 s or more becomes one memory +row for the repository, written with the session's turns (`memory.set`, key +`repo:/test-cost/pytest`, in the session's namespace): + +```text +A whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. +``` + +A session that read a row whose seconds are within a quarter of its own writes nothing. A +row for another test file is replaced only by a run over a quarter longer. The write +revises the row the session read and is create-only for a session that read none, so it +replaces no row the session did not see. Of the run, the path as pytest names it from its +root, the number of cases and the seconds are sent; an absolute path, a path that leaves +the checkout and one the secret redaction would change are not noted. + +**What a prompt gets.** A prompt that reads as a bug report and gets code pointers +([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: + +```text +Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the 120 s limit of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. +``` + +The clause about the limit is printed for a run over 120 s, and the middle sentence where +a filtered run was measured. The row is read with one `memory.get` a session, sent beside +the prompt's search and never waited for past its answer: a read that fails or is slow +adds nothing, and the pointers are printed as they are. The line is made of the row's +path and numbers, so a value someone rewrote is neither printed nor overwritten. + +What it does not do: + +- it is one row a repository and names one test file, the costliest one a session ran + whole; +- a run that outlives its shell call is noted only when no other test command follows it + in the session; +- two repositories' rows in one namespace read alike, so the server's conflict check can + mark one `conflicted`; both are still read by key; +- it is pytest under Claude Code only: Codex names no file for the result-file option. + +`LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, +and [`code` mode](#modes) all three. `memory.delete` on the row's key removes it. + ## 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 712961a18ec..f3ff54f72fc 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.176", + "version": "1.2.179", "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" @@ -71,7 +71,7 @@ "test_report": { "type": "boolean", "title": "Failure reasons after a cut pytest run", - "description": "On by default. In a checkout that configures pytest, the plugin adds its result-file option to PYTEST_ADDOPTS for the session's shell commands (--junitxml, to a private file in the temp directory, with -o junit_family=xunit1), and after a test command whose visible output names no failure's reason it adds a digest of that file to the tool result, at most 700 characters. pytest names the file in one line of its summary on a run that is not quiet (-q). No request is sent and nothing is stored. Off: no option and no digest, from the session's next start (LOOM_TEST_REPORT=off does the same).", + "description": "On by default. In a checkout that configures pytest, the plugin adds its result-file option to PYTEST_ADDOPTS for the session's shell commands (--junitxml, to a private file in the temp directory, with -o junit_family=xunit1), and after a test command whose visible output names no failure's reason it adds a digest of that file to the tool result, at most 700 characters. pytest names the file in one line of its summary on a run that is not quiet (-q). No request is sent for the digest and nothing of it is stored. With the memory plane on, what a whole pytest run of one test file cost (its path, the number of cases and the seconds) is kept as one memory row a repository when it took a minute or more, and a later bug report in that repository carries it as one line under its code pointers. Off: no option, no digest and no test cost, from the session's next start (LOOM_TEST_REPORT=off does the same).", "default": true }, "code_repo": { diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index e248c48a7db..2930e1357e9 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -133,6 +133,10 @@ space on the server that your token writes to. The hooks and scripts send: of the files the session changed, each with the time it was last written and the names of the definitions its changed lines are in (`LOOM_SESSION_MEMORY=off` stops it); +- for a pytest run of one test file that passed and took a minute or more, the + file's path, the number of cases it collected and the seconds it and a + filtered run of it took, kept as one memory row a repository + (`LOOM_TEST_REPORT=off` or `LOOM_SESSION_MEMORY=off` stops it); - the file paths and diff outlines of uncommitted changes (a diff's outline is its file paths, hunk line ranges and usually the enclosing function's name; no other part of a changed line is sent), a record of the session's first prompt @@ -147,8 +151,8 @@ space on the server that your token writes to. The hooks and scripts send: that identity token and `LOOM_CLIENT_ID`, exchanged for a Loom token. The endpoint's mode narrows the list ([modes](#modes)). In `code` mode the hooks send no -tool call's input or output, no chat turn, no brief, no note and no session for the -server to extract facts from. They still send each prompt's text as a code-index search +tool call's input or output, no chat turn, no brief, no note, no test run's cost and no +session for the server to extract facts from. They still send each prompt's text as a code-index search where the checkout is indexed (`--config prompt_pack=off` stops that), the record of the session's first prompt and last reply with token usage and the model name (`LOOM_RUN_LEDGER=off` and `LOOM_USAGE=off` stop those), and the code-index items above: @@ -209,7 +213,8 @@ In a checkout that configures pytest, one more file in that directory, mode option to `PYTEST_ADDOPTS` for the session's shell commands so that pytest writes it. The file is sent nowhere and is removed when the session ends; a digest of at most 700 characters, redacted, goes to the model after a failing run whose output was -cut (**The test report**, below; `LOOM_TEST_REPORT=off` stops it). +cut, and what a slow whole run of one test file cost goes to memory, as listed +above (**The test report**, below; `LOOM_TEST_REPORT=off` stops both). Where the code plane is on and `LOOM_MCP_CODE_SCOPE` is not off, Claude Code's SessionStart also writes `loom-mcp-project-.json` in the system temp directory @@ -271,33 +276,33 @@ 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`, `PreCompact`, `Stop`, `SessionEnd` | `loom-record.mjs` | The event's one process. Runs the scripts whose answer the session waits for in the hook itself, each for the tools its row below names and only where the [mode](#modes) runs its plane: after a tool call `loom-file-context`, `loom-mentor-hint`, `loom-blast-radius`, `loom-test-gate` (only after a shell command that may have written a file) and `loom-test-report` (only after one that starts a test runner), at `Stop` the gates the install runs. It prints their answers as one, each script's text on a line of its own: a file's memory and then its test line as one `additionalContext`, the gates' reasons as one block. 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 `loom-capture` records something of, at `Stop` and at `SessionEnd` that process is detached, so the session does not wait for their requests and the client, which ends a SessionEnd hook after 1.5 s, cannot cancel them. Before a compaction it is the hook itself, which exits when they have returned: the compaction's primer reads the note they write. | -| `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 via `context.pack`: the project's working-memory note, the profile, the session's memory stack and a few memories. In a new or cleared conversation whose prompts get the recall (`loom-prompt-recall.mjs`, which this plugin and Codex's wire, where it is on) the primer runs no memory search: the memories are the namespace's pinned rows and then its newest, five at most, and the recall searches with the prompt. Any other row arrives only when a prompt's recall finds it: a session whose recall abstains gets none. A resumed or compacted session, a session with `LOOM_PROMPT_RECALL=off` or `LOOM_PROMPT_CONTEXT=off` and a hand-wired client get the memories, decisions and procedures a search for the project finds instead. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index is read: no checkout, no remote, no answer, a repository this Loom does not index, one the session's principal is not a reader of, or one whose namespace the token does not name; an index still being built says so too. A new session whose MCP connection carries the checkout is told neither: the header helper sent the namespace, the server applies it to every `loom_code_*` call and adds the tag to a save, and a session with nothing else to hear starts with no text from the hook. 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. | -| `PostToolUse` (Read / Grep / Bash), `PreCompact` | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about a file the call read (its files facet) and attaches the rendered block to the read's result, at no model request: the first local read of a file in the checkout — `Read`, a `Grep` of one file, or a shell `cat` / `sed -n` / `head` / `tail` / `grep pattern file` — brings its memory, so a session that only reads, or that edits through the shell, gets it too. One lookup per session, agent context and file (a subagent's read does not use up the main agent's block); a compaction clears what was shown. A record the session already holds, given whole with the prompt or printed with the same line in another file's block, is left out, and a block with nothing new is not attached; a team rule, a decision and a constraint are printed under every file they name. A file with no memory adds nothing. Reads ask about at most three files per call and 40 per session, give the request 1 s and the call 2 s in all, and stop asking after three unanswered lookups. Where the mode runs the code index, a read or an edit that asks first renews a repository lookup that is ten minutes old, which brings the repository's shared rules; a read that this takes past its 2 s leaves the file for its next read or its edit. | -| `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Before an edit of a file this agent context has not been shown, the same lookup and block — a constraint arrives **before** the edit, not as a review comment. A file shown more than 30 min ago is asked about again, and a record handed more than 30 min ago is printed again; a team rule, a decision and a constraint are printed with every block. 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 test, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | -| `PostToolUse` (Bash / PowerShell) | `loom-test-gate.mjs` | **A changed file's own test is 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, for a file that has a test of its own, attaches its command and what the index knows of it: `Loom test for src/router.py: .venv/bin/python -m pytest -q -rf tests/test_router.py`, then `It is the one test file named for that file.` and what the checkout proves of the command. 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, a runner the checkout does not configure, a comment-only change and a prompt that ruled a test run out get nothing, and a command that only reads (`grep`, `cat`, `sed -n`, `git diff`) starts no git process and asks nothing (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | -| `PostToolUse`, `PostToolUseFailure` (Bash) | `loom-test-report.mjs` | **Why a test failed, on the run whose output was cut.** In a checkout that configures pytest, SessionStart adds its result-file option to `PYTEST_ADDOPTS` for the session's shell commands, so every pytest run writes a private result file. After a test command whose visible output names no failure's reason (`pytest ... \| tail -3`), the hook adds a digest of that file to the tool result: the totals, up to three groups of failures by message, each with its first test and where it was raised; at most 700 characters. No request and nothing stored (**The test report**, below). `LOOM_TEST_REPORT=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` (or the install option `prompt_recall`) for every prompt, `off` to disable; `LOOM_PROMPT_CONTEXT=off` disables it too ([what a prompt gets](#what-a-prompt-gets)). One `context.pack` per prompt restricted to `memories`, `decisions`, `procedures` with the prompt as the query; injects the records the session has not seen (each plane's under its tag; memories that answer alone under none), only when memory is not abstaining and `retrieval_confidence ≥ 0.5`, whole records within 1,600 chars (`LOOM_PROMPT_RECALL_MAX_CHARS`; one that does not fit is left out; a block's only record that the pack cut, or the first when none fits, is cut at its last whole sentence and names the call that reads it whole, the one the server's mark on the line names, or else the key to read it whole by). A record of code as it was before a commit the checkout's `HEAD` already has is left out, and a fix record whose commit it has is added as one line that names the commit. A record linked to a file of the checkout is added as one line, its key and that file, unless the prompt names the file or the definition, or asks memory: `loom-file-context` adds the record's own line after a local read of the file or before an edit of it. With `LOOM_FILE_CONTEXT=off`, or outside a checkout of a repository this Loom indexes, the prompt gets the record whole. 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` | Runs where the Loom the session talks to holds the checkout's own repository in its code index (`LOOM_PROMPT_PACK=off` stops it; [what a prompt gets](#what-a-prompt-gets)). One bounded lookup: `code.symbol`, `code.callers` or `code.impact` for an explicit named question, otherwise `code.search` (top 3, no bodies). The repository lookup and the answer share one bound (`LOOM_PROMPT_PACK_TIMEOUT_MS`, 2.5 s; a searched bug report asks for the server's pick and has 6 s): what comes later is skipped. 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), without abstention, and sends only the answer's places to edit, one pointer per place: a definition, a unit of a file the hook does not hold to definitions, a document or a test when the prompt names it or asks for documentation or tests, a Python migration or a release script only if named, and module-level code when it asks for tests; 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. Below the pointers of a search answer goes the test gate's line (**Tests at edit time**, below) when a pointer's definition is named in the prompt and its Python file has exactly one test file named after it, in a checkout that configures pytest; it adds no request and a session gets a test once. | -| `Stop` | `loom-test-gate.mjs` | **Off by default; with the `stop_test_gate` option (or `LOOM_TEST_GATE=stop`), holds a session that ran no test since its last code change.** A held stop costs the session at least one more model request, so it is yours to turn on. Then, 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 to run, in evidence order with a `run` command when the harness is derivable, and the touched definitions a coverage run measured unexecuted — and blocks the stop **once** per distinct change with a reason that names them. The second stop on the same change passes. 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 the gate at both events. | -| `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. A new or cleared conversation whose checkout is on another branch than the note names gets its primer without the note. 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. The body also names the files the session changed in its checkout (each path and the time it was last written, never its content), which decide the session's fix record whatever tool wrote them, and `HEAD` as the commit that holds them, when its history has a commit of the session's that touches every file its edit tool wrote (the tag `change:`). 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`, `PreCompact`, `Stop`, `SessionEnd` | `loom-record.mjs` | The event's one process. Runs the scripts whose answer the session waits for in the hook itself, each for the tools its row below names and only where the [mode](#modes) runs its plane: after a tool call `loom-file-context`, `loom-mentor-hint`, `loom-blast-radius`, `loom-test-gate` (only after a shell command that may have written a file) and `loom-test-report` (only after one that starts a test runner), at `Stop` the gates the install runs. It prints their answers as one, each script's text on a line of its own: a file's memory and then its test line as one `additionalContext`, the gates' reasons as one block. 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 `loom-capture` records something of, at `Stop` and at `SessionEnd` that process is detached, so the session does not wait for their requests and the client, which ends a SessionEnd hook after 1.5 s, cannot cancel them. Before a compaction it is the hook itself, which exits when they have returned: the compaction's primer reads the note they write. | +| `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 via `context.pack`: the project's working-memory note, the profile, the session's memory stack and a few memories. In a new or cleared conversation whose prompts get the recall (`loom-prompt-recall.mjs`, which this plugin and Codex's wire, where it is on) the primer runs no memory search: the memories are the namespace's pinned rows and then its newest, five at most, and the recall searches with the prompt. Any other row arrives only when a prompt's recall finds it: a session whose recall abstains gets none. A resumed or compacted session, a session with `LOOM_PROMPT_RECALL=off` or `LOOM_PROMPT_CONTEXT=off` and a hand-wired client get the memories, decisions and procedures a search for the project finds instead. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index is read: no checkout, no remote, no answer, a repository this Loom does not index, one the session's principal is not a reader of, or one whose namespace the token does not name; an index still being built says so too. A new session whose MCP connection carries the checkout is told neither: the header helper sent the namespace, the server applies it to every `loom_code_*` call and adds the tag to a save, and a session with nothing else to hear starts with no text from the hook. 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. | +| `PostToolUse` (Read / Grep / Bash), `PreCompact` | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about a file the call read (its files facet) and attaches the rendered block to the read's result, at no model request: the first local read of a file in the checkout — `Read`, a `Grep` of one file, or a shell `cat` / `sed -n` / `head` / `tail` / `grep pattern file` — brings its memory, so a session that only reads, or that edits through the shell, gets it too. One lookup per session, agent context and file (a subagent's read does not use up the main agent's block); a compaction clears what was shown. A record the session already holds, given whole with the prompt or printed with the same line in another file's block, is left out, and a block with nothing new is not attached; a team rule, a decision and a constraint are printed under every file they name. A file with no memory adds nothing. Reads ask about at most three files per call and 40 per session, give the request 1 s and the call 2 s in all, and stop asking after three unanswered lookups. Where the mode runs the code index, a read or an edit that asks first renews a repository lookup that is ten minutes old, which brings the repository's shared rules; a read that this takes past its 2 s leaves the file for its next read or its edit. | +| `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Before an edit of a file this agent context has not been shown, the same lookup and block — a constraint arrives **before** the edit, not as a review comment. A file shown more than 30 min ago is asked about again, and a record handed more than 30 min ago is printed again; a team rule, a decision and a constraint are printed with every block. 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 test, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | +| `PostToolUse` (Bash / PowerShell) | `loom-test-gate.mjs` | **A changed file's own test is 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, for a file that has a test of its own, attaches its command and what the index knows of it: `Loom test for src/router.py: .venv/bin/python -m pytest -q -rf tests/test_router.py`, then `It is the one test file named for that file.` and what the checkout proves of the command. 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, a runner the checkout does not configure, a comment-only change and a prompt that ruled a test run out get nothing, and a command that only reads (`grep`, `cat`, `sed -n`, `git diff`) starts no git process and asks nothing (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | +| `PostToolUse`, `PostToolUseFailure` (Bash) | `loom-test-report.mjs` | **Why a test failed, on the run whose output was cut.** In a checkout that configures pytest, SessionStart adds its result-file option to `PYTEST_ADDOPTS` for the session's shell commands, so every pytest run writes a private result file. After a test command whose visible output names no failure's reason (`pytest ... \| tail -3`), the hook adds a digest of that file to the tool result: the totals, up to three groups of failures by message, each with its first test and where it was raised; at most 700 characters. The hook sends no request; it notes what a pytest run of one test file cost, which the session's end stores for a slow whole run (**The test report**, below). `LOOM_TEST_REPORT=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` (or the install option `prompt_recall`) for every prompt, `off` to disable; `LOOM_PROMPT_CONTEXT=off` disables it too ([what a prompt gets](#what-a-prompt-gets)). One `context.pack` per prompt restricted to `memories`, `decisions`, `procedures` with the prompt as the query; injects the records the session has not seen (each plane's under its tag; memories that answer alone under none), only when memory is not abstaining and `retrieval_confidence ≥ 0.5`, whole records within 1,600 chars (`LOOM_PROMPT_RECALL_MAX_CHARS`; one that does not fit is left out; a block's only record that the pack cut, or the first when none fits, is cut at its last whole sentence and names the call that reads it whole, the one the server's mark on the line names, or else the key to read it whole by). A record of code as it was before a commit the checkout's `HEAD` already has is left out, and a fix record whose commit it has is added as one line that names the commit. A record linked to a file of the checkout is added as one line, its key and that file, unless the prompt names the file or the definition, or asks memory: `loom-file-context` adds the record's own line after a local read of the file or before an edit of it. With `LOOM_FILE_CONTEXT=off`, or outside a checkout of a repository this Loom indexes, the prompt gets the record whole. 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` | Runs where the Loom the session talks to holds the checkout's own repository in its code index (`LOOM_PROMPT_PACK=off` stops it; [what a prompt gets](#what-a-prompt-gets)). One bounded lookup: `code.symbol`, `code.callers` or `code.impact` for an explicit named question, otherwise `code.search` (top 3, no bodies). The repository lookup and the answer share one bound (`LOOM_PROMPT_PACK_TIMEOUT_MS`, 2.5 s; a searched bug report asks for the server's pick and has 6 s): what comes later is skipped. 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), without abstention, and sends only the answer's places to edit, one pointer per place: a definition, a unit of a file the hook does not hold to definitions, a document or a test when the prompt names it or asks for documentation or tests, a Python migration or a release script only if named, and module-level code when it asks for tests; 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. Below the pointers of a search answer goes the test gate's line (**Tests at edit time**, below) when a pointer's definition is named in the prompt and its Python file has exactly one test file named after it, in a checkout that configures pytest; it adds no request and a session gets a test once. Below a bug report's pointers goes the repository's test cost line where an earlier session stored one (**The test report**, below, **What a whole run costs**): one `memory.get` a session, never waited for past the search. | +| `Stop` | `loom-test-gate.mjs` | **Off by default; with the `stop_test_gate` option (or `LOOM_TEST_GATE=stop`), holds a session that ran no test since its last code change.** A held stop costs the session at least one more model request, so it is yours to turn on. Then, 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 to run, in evidence order with a `run` command when the harness is derivable, and the touched definitions a coverage run measured unexecuted — and blocks the stop **once** per distinct change with a reason that names them. The second stop on the same change passes. 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 the gate at both events. | +| `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. A new or cleared conversation whose checkout is on another branch than the note names gets its primer without the note. 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. The body also names the files the session changed in its checkout (each path and the time it was last written, never its content), which decide the session's fix record whatever tool wrote them, and `HEAD` as the commit that holds them, when its history has a commit of the session's that touches every file its edit tool wrote (the tag `change:`). 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. With the turns goes one `memory.set` of what a slow whole run of one test file cost, where the session measured one (**The test report**, above). `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 names 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. On a server whose default scope is `all_mine`, the request of a checkout with a remote is also answered with the rows you wrote in your other namespaces; such a row reads ` (namespace ""): …`. 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. @@ -315,10 +320,24 @@ Loom test report, the session's last pytest run: 16 failed, 8 passed. raised in shop/totals.py:57 ``` -Failures that share a message are one group, the most frequent first, at most three, with the group's first test and, for a file of the checkout, the last `path:line` of its traceback; the digest is at most 700 characters and is redacted before it is cut. It reaches the model only: no request is sent and nothing is stored in Loom. +Failures that share a message are one group, the most frequent first, at most three, with the group's first test and, for a file of the checkout, the last `path:line` of its traceback; the digest is at most 700 characters and is redacted before it is cut. The digest reaches the model only: no request is sent for it and nothing of it is stored in Loom. Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run of a selection of the file (`-k`, `-m`, a node id, `--lf`, `--sw`, `--deselect`) counts as filtered. A command with two pytest runs or two paths and a run that only collects count as neither. A run that outlives its shell call is read when the session ends, where no other test command followed it. At the session's end a whole run of 60 s or more becomes the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace), unless the row the session read is within a quarter of it: + +```text +A whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. +``` + +Of the run, only the path as pytest names it from its root, the number of cases and the seconds are sent; an absolute path, or one the secret redaction would change, is not noted. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: + +```text +Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the 120 s limit of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. +``` + +The clause about the limit is printed for a run over 120 s, and the middle sentence where a filtered run was measured. The row is read once a session, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, and `code` mode all three. The row is an ordinary memory: `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. + **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. **Unlinked and untested definitions.** The index's call graph is a floor: a test may reach a definition the graph holds no edge to, through a fixture, a string-dispatched entry point or a public API. The reason of a held stop therefore lists a touched definition with no linked test as the index's view, `the index links no test to: … (the tests named here may still reach it)`, and such a definition alone holds no stop and asks for no test. Only a definition an imported coverage run measured unexecuted reads `measured unexecuted at : …` and asks for a test. @@ -658,7 +677,7 @@ path. | `LOOM_FILE_CONTEXT` | `on` | `off` disables the file-context injection, after a read and before an edit. | | `LOOM_FILE_CONTEXT_TOKENS` | `300` | Budget per file for the block's rows other than decisions and constraints, which print whole. | | `LOOM_FILE_CONTEXT_TTL_MIN` | `30` | Before an edit, re-inject for the same file after this many minutes. | -| `LOOM_TEST_REPORT` | `on` | `off`: no result-file option in `PYTEST_ADDOPTS` and no failure digest after a cut pytest run (the `test_report` option). | +| `LOOM_TEST_REPORT` | `on` | `off`: no result-file option in `PYTEST_ADDOPTS`, no failure digest after a cut pytest run and no test cost noted or printed (the `test_report` option). | | `LOOM_HOOK_EXIT_MS` | derived (= the request bound) | Hard exit grace after dispatch. Unref'd, so a hook exits as soon as its request settles; the grace is the ceiling. A shorter grace loses every fire-and-forget capture to a remote server whose TLS handshake alone takes ~570 ms. | | `LOOM_SESSION_END_WAIT` | `off` | `on`: the SessionEnd hook sends the session's close itself and returns when the run's close is answered, instead of handing it to a detached process. For a host torn down the moment the client exits (a container whose entrypoint is the client, a CI runner), which would end that process first. | | `LOOM_WORKING_MEMORY` | `on` | `off` disables the Stop/PreCompact working-memory note. | diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 5dec2810003..85c40a24cb6 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -144,39 +144,39 @@ wrong type is dropped. Timeouts are the host's default unless noted. "Output" is what the host receives on stdout. -| Event | Script | Reads | Output | Side effects | Off | -| ------------------------------------------------------------- | --------------------- | ---------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------- | -| SessionStart | loom-session-start | cwd, session_id, source | primer text | context.pack, code.repos/index_status/map, task.counts, namespace.get, session.brief_list, collection.list; GET /v1/health: its round trip is cached as the RTT bound, its `version` feeds the server version warning; in a checkout that configures pytest, one line in the file `CLAUDE_ENV_FILE` names and an empty result file | `LOOM_INJECT_CONTEXT=false` | -| UserPromptSubmit | loom-record | the payload | JSON additionalContext | keeps the run's begin in the run state; starts one detached process, which runs the event's `detached` rows; runs the event's `in loom-record` rows itself and prints their context as one answer | each script's own | -| UserPromptSubmit, in loom-record | loom-prompt-pack | prompt, cwd, session_id | its context | code.search, or code.symbol, code.callers or code.impact for a named definition; no request with the pointers off; under `auto` none of those unless the server holds the checkout's own repository, and one code.repos where no lookup has answered; for a test line one `git ls-files`, and the test is noted in the test gate's session state | `LOOM_PROMPT_PACK=off` | -| UserPromptSubmit, in loom-record | loom-prompt-recall | prompt, cwd, session_id | its context | context.pack | `LOOM_PROMPT_RECALL=off` | -| UserPromptSubmit, detached | loom-run | prompt, session_id | none | run.begin on the first prompt; appends the turn journal | `LOOM_RUN_LEDGER=off` | -| UserPromptSubmit, detached | loom-namespace-health | cwd, session_id | none | namespace.audit, once per session; the verdict goes to the session's state file | `LOOM_NAMESPACE_HEALTH=off` | -| PreToolUse Read\|Grep, and Bash for a command that runs `gh` | 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, agent_id | JSON additionalContext | memory.for_file, unless this agent context was shown the file in the last 30 min | `LOOM_FILE_CONTEXT=off` | -| PostToolUse Read\|Grep\|Bash, in loom-record | loom-file-context | tool_*, cwd, session_id, agent_id | JSON additionalContext | memory.for_file for each file of the checkout the call read that this agent context has not been shown: at most three per call, 40 per session | `LOOM_FILE_CONTEXT=off` | -| PostToolUse loom tools, in loom-record | loom-mentor-hint | tool_name, tool_response | JSON additionalContext | none | `LOOM_MENTOR_HINTS=off` | -| PostToolUse Edit\|Write\|MultiEdit, in loom-record | loom-blast-radius | tool_input, cwd, transcript | 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, in loom-record | loom-test-gate | tool_input, cwd, transcript | JSON additionalContext | code.test_gate for each changed file the command names, once per file; not loaded for a command that only reads | `LOOM_TEST_GATE=off` or `block` | -| PostToolUse, PostToolUseFailure Bash, in loom-record | loom-test-report | tool_input, tool_response, error | JSON additionalContext | none: reads the result file a pytest run of the command wrote for the session, at most 2 MB; not loaded for a command that starts no test runner | `LOOM_TEST_REPORT=off` | -| PostToolUse, PostToolUseFailure, PreCompact, Stop, SessionEnd | loom-record | the payload | the one answer of the event's `in loom-record` rows | starts one detached process for the event's `detached` rows, after a tool call only where loom-capture records something of the call, and runs the event's `in loom-record` rows itself; before a compaction, it runs all of them itself; at SessionEnd it removes the session's test report | each script's own | -| PostToolUse, PostToolUseFailure, detached | loom-capture | tool_*, session_id, cwd | none | observe.record; code.outcome; the recalled-keys stash; started only for a call it records something of | no token | -| PreCompact, in loom-record | loom-capture | session_id | none | observe.crystallize | no token | -| PreCompact, in loom-record | loom-working-memory | transcript, cwd | none | working_memory.set | `LOOM_WORKING_MEMORY=off` | -| PreCompact, in loom-record | loom-session-brief | transcript, cwd | none | session.brief_save via the flusher | `LOOM_SESSION_BRIEF=off` | -| PreCompact, in loom-record | loom-file-context | session_id | none | none: forgets which files the session was shown and which records it was handed | `LOOM_FILE_CONTEXT=off` | -| 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, in loom-record | loom-test-gate | transcript, cwd | JSON block once | only with the `stop_test_gate` option or LOOM_TEST_GATE=stop: 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 | off unless asked for | -| Stop, in loom-record | loom-validate-gate | transcript | JSON block once | namespace.validate | `LOOM_VALIDATE_GATE=off` | -| Stop, in loom-record | 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` | -| SessionEnd, detached | loom-capture | session_id | none | observe.crystallize | no token | -| SessionEnd, detached | loom-conversation | transcript | none | the turns since the last Stop | as Stop | -| SessionEnd, detached | loom-run | transcript, reason | none | run.complete, awaited | `LOOM_RUN_LEDGER=off` | -| SessionEnd, detached | loom-session-memory | transcript, cwd | none | memory.set_from_messages via the flusher | `LOOM_SESSION_MEMORY=off` | -| SessionEnd, detached | loom-session-brief | transcript, cwd | none | session.brief_save via the flusher | `LOOM_SESSION_BRIEF=off` | +| Event | Script | Reads | Output | Side effects | Off | +| ------------------------------------------------------------- | --------------------- | ---------------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | +| SessionStart | loom-session-start | cwd, session_id, source | primer text | context.pack, code.repos/index_status/map, task.counts, namespace.get, session.brief_list, collection.list; GET /v1/health: its round trip is cached as the RTT bound, its `version` feeds the server version warning; in a checkout that configures pytest, one line in the file `CLAUDE_ENV_FILE` names and an empty result file | `LOOM_INJECT_CONTEXT=false` | +| UserPromptSubmit | loom-record | the payload | JSON additionalContext | keeps the run's begin in the run state; starts one detached process, which runs the event's `detached` rows; runs the event's `in loom-record` rows itself and prints their context as one answer | each script's own | +| UserPromptSubmit, in loom-record | loom-prompt-pack | prompt, cwd, session_id | its context | code.search, or code.symbol, code.callers or code.impact for a named definition; no request with the pointers off; under `auto` none of those unless the server holds the checkout's own repository, and one code.repos where no lookup has answered; for a test line one `git ls-files`, and the test is noted in the test gate's session state; under a bug report's pointers, in a session that has the test report, one memory.get of the repository's test cost row, once a session | `LOOM_PROMPT_PACK=off` | +| UserPromptSubmit, in loom-record | loom-prompt-recall | prompt, cwd, session_id | its context | context.pack | `LOOM_PROMPT_RECALL=off` | +| UserPromptSubmit, detached | loom-run | prompt, session_id | none | run.begin on the first prompt; appends the turn journal | `LOOM_RUN_LEDGER=off` | +| UserPromptSubmit, detached | loom-namespace-health | cwd, session_id | none | namespace.audit, once per session; the verdict goes to the session's state file | `LOOM_NAMESPACE_HEALTH=off` | +| PreToolUse Read\|Grep, and Bash for a command that runs `gh` | 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, agent_id | JSON additionalContext | memory.for_file, unless this agent context was shown the file in the last 30 min | `LOOM_FILE_CONTEXT=off` | +| PostToolUse Read\|Grep\|Bash, in loom-record | loom-file-context | tool_*, cwd, session_id, agent_id | JSON additionalContext | memory.for_file for each file of the checkout the call read that this agent context has not been shown: at most three per call, 40 per session | `LOOM_FILE_CONTEXT=off` | +| PostToolUse loom tools, in loom-record | loom-mentor-hint | tool_name, tool_response | JSON additionalContext | none | `LOOM_MENTOR_HINTS=off` | +| PostToolUse Edit\|Write\|MultiEdit, in loom-record | loom-blast-radius | tool_input, cwd, transcript | 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, in loom-record | loom-test-gate | tool_input, cwd, transcript | JSON additionalContext | code.test_gate for each changed file the command names, once per file; not loaded for a command that only reads | `LOOM_TEST_GATE=off` or `block` | +| PostToolUse, PostToolUseFailure Bash, in loom-record | loom-test-report | tool_input, tool_response, error | JSON additionalContext | none: reads the result file a pytest run of the command wrote for the session, at most 2 MB, and notes in the session's state what a run of one test file cost; not loaded for a command that starts no test runner | `LOOM_TEST_REPORT=off` | +| PostToolUse, PostToolUseFailure, PreCompact, Stop, SessionEnd | loom-record | the payload | the one answer of the event's `in loom-record` rows | starts one detached process for the event's `detached` rows, after a tool call only where loom-capture records something of the call, and runs the event's `in loom-record` rows itself; before a compaction, it runs all of them itself; at SessionEnd it reads the session's test report once more, for the cost of a run that outlived its command, and removes it | each script's own | +| PostToolUse, PostToolUseFailure, detached | loom-capture | tool_*, session_id, cwd | none | observe.record; code.outcome; the recalled-keys stash; started only for a call it records something of | no token | +| PreCompact, in loom-record | loom-capture | session_id | none | observe.crystallize | no token | +| PreCompact, in loom-record | loom-working-memory | transcript, cwd | none | working_memory.set | `LOOM_WORKING_MEMORY=off` | +| PreCompact, in loom-record | loom-session-brief | transcript, cwd | none | session.brief_save via the flusher | `LOOM_SESSION_BRIEF=off` | +| PreCompact, in loom-record | loom-file-context | session_id | none | none: forgets which files the session was shown and which records it was handed | `LOOM_FILE_CONTEXT=off` | +| 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, in loom-record | loom-test-gate | transcript, cwd | JSON block once | only with the `stop_test_gate` option or LOOM_TEST_GATE=stop: 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 | off unless asked for | +| Stop, in loom-record | loom-validate-gate | transcript | JSON block once | namespace.validate | `LOOM_VALIDATE_GATE=off` | +| Stop, in loom-record | 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` | +| SessionEnd, detached | loom-capture | session_id | none | observe.crystallize | no token | +| SessionEnd, detached | loom-conversation | transcript | none | the turns since the last Stop | as Stop | +| SessionEnd, detached | loom-run | transcript, reason | none | run.complete, awaited | `LOOM_RUN_LEDGER=off` | +| SessionEnd, detached | loom-session-memory | transcript, cwd | none | memory.set_from_messages and, for a slow whole run of one test file, one memory.set, via the flusher | `LOOM_SESSION_MEMORY=off` | +| SessionEnd, detached | loom-session-brief | transcript, cwd | none | session.brief_save via the flusher | `LOOM_SESSION_BRIEF=off` | A `detached` row runs in the process `loom-record` starts and an `in loom-record` row in `loom-record` itself, not as a hook of its own, and @@ -254,28 +254,28 @@ record: the run and its usage counters. ignores it and lists both planes; the hooks follow the mode either way. The Codex plugin's entry is fixed and lists what it always did. -| Script | Plane | -| --------------------- | ----------------------------------------------------------------------------------- | -| loom-blast-radius | code | -| loom-capture | memory (observations, crystallize, recalled keys); code (`code.outcome`) | -| loom-code-shunt | code; its `gh` issue-search redirect asks the tracker and runs with memory too | -| loom-conversation | memory | -| loom-file-context | memory; where code runs, a read or an edit renews a lapsed repository entry | -| loom-flush | memory: every job it delivers is a memory script's | -| loom-mentor-hint | memory and code together: a hint names the plane a session is not using | -| loom-namespace-health | memory | -| loom-prompt-pack | code | -| loom-prompt-recall | memory; where code runs, a prompt naming a definition is left to the code index | -| loom-record | ledger (keeps the run's begin); each script it starts checks its own plane | -| loom-run | ledger | -| loom-session-brief | memory | -| loom-session-memory | memory | -| loom-session-start | memory (pack, tag, task, brief, collections and recording lines); code (scope, map) | -| loom-test-gate | code | -| loom-test-report | ledger: reads the session's own test report in every mode and sends nothing | -| loom-usage | ledger | -| loom-validate-gate | memory | -| loom-working-memory | memory | +| Script | Plane | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| loom-blast-radius | code | +| loom-capture | memory (observations, crystallize, recalled keys); code (`code.outcome`) | +| loom-code-shunt | code; its `gh` issue-search redirect asks the tracker and runs with memory too | +| loom-conversation | memory | +| loom-file-context | memory; where code runs, a read or an edit renews a lapsed repository entry | +| loom-flush | memory: every job it delivers is a memory script's | +| loom-mentor-hint | memory and code together: a hint names the plane a session is not using | +| loom-namespace-health | memory | +| loom-prompt-pack | code; memory for the test cost line under a bug report's pointers | +| loom-prompt-recall | memory; where code runs, a prompt naming a definition is left to the code index | +| loom-record | ledger (keeps the run's begin); memory (reads a late run's cost from the test report at SessionEnd); each script it starts checks its own plane | +| loom-run | ledger | +| loom-session-brief | memory | +| loom-session-memory | memory | +| loom-session-start | memory (pack, tag, task, brief, collections and recording lines); code (scope, map) | +| loom-test-gate | code | +| loom-test-report | ledger: reads the session's own test report in every mode and sends nothing; memory: notes what a run of one test file cost | +| loom-usage | ledger | +| loom-validate-gate | memory | +| loom-working-memory | memory | ## What a prompt gets @@ -935,6 +935,26 @@ in. session state, so neither a later prompt nor the edit of the file names it again. The line is the test gate's: LOOM_TEST_GATE=off or block sends none. + **The test cost line.** Below those, a prompt that reads as a bug report + and gets pointers from its search carries one more line where an earlier + session stored what a whole run of a slow test file costs in the + repository (**loom-test-report**, below, **The cost of a run**): + `Test cost in this repository (measured in earlier sessions): a whole run +of collects about cases and takes about s, longer than the +120 s limit of a shell call. A run filtered with -k takes about s. +Check a change with -k selections of the cases it affects.` The clause + about the + limit is printed for a run over 120 s, and the middle sentence where a + filtered run was measured (`renderCost` in lib/test-cost.mjs). The hook + reads the row by its key with one `memory.get`, sent beside the search + and inside its bound, and never waits for it past the search's answer: an + answer that has not come by then, an error and a miss print nothing, and + the pointers are the same bytes with or without the line. The row as it + was read, a miss too, is kept in the session's state, so a session asks + once; a read that failed or came late is asked again at the next bug + report. The line is made of the row's path and numbers and never of its + text: a value that is not the stored sentence prints nothing. It needs + the memory plane and a session that has the test report. **The listwise pick.** For a request that reads as a bug report (twelve words or more, or the vocabulary of a failure, as the search reads it) the search carries `rerank: "builtin:pick"`. On a server that names a pick @@ -1216,8 +1236,9 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that totals and not why a test failed, and runs the tests again to read it. So the plugin has pytest write a result file on every run of the session and adds a digest of it to the result of a test command whose output was - cut (lib/test-report.mjs). No request is sent and nothing is stored in - Loom. + cut (lib/test-report.mjs). The hook sends no request, and nothing of the + digest is stored in Loom; what a slow whole run of one test file cost is + stored at the session's end (**The cost of a run**, below). - **The option.** At SessionStart, in a checkout that configures pytest (`configuresPytest` in lib/test-gate.mjs: one of pytest's settings files with its section, or a `conftest.py`, at the root or in `tests` @@ -1305,8 +1326,53 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that files a day after its last write; so is a running session's, which then gets no option and no digest, and so is a refusal's note, after which a start of that session sets the report up again. + - **The cost of a run.** A session that does not know what a whole run + of a data-driven test file costs runs it to check a change where a + selection of its cases answers in seconds. Where the memory plane is + on, the hook notes what a shell command's pytest run cost when the + command holds one pytest run, started in the checkout, that names one + test file and nothing else to run (`fileRun` in lib/test-gate.mjs): the + case count and the seconds of the report's first `testsuite` + (`runCost`, read from the file's first 4,096 bytes, also for a file + over the 2 MB bound). The session's private state keeps the costliest + whole run in which no case failed, and the seconds of each run of a + selection of a file (`-k`, `-m`, a node id, `--lf`, `--sw`, + `--deselect`). A run that only collects or prints is neither, and a + command with two pytest runs or two paths is noted as nothing + (lib/test-cost.mjs). + The report is the command's when the command's visible output shows + pytest's summary line and the report's first case is in the file the + command names. A run whose output shows no summary has not ended: one + that outlives its shell call writes the file after the hook ran. It is + kept as the session's pending run, and the launcher reads the report + once more at SessionEnd, before it removes the file. Any other test + command in between drops the pending run, since the next report could + be either's. + At SessionEnd `loom-session-memory` hands one `memory.set` to the + flusher, with the session's turns, when the whole run took 60 s or + more and the session read no row, or read one whose seconds differ + from it by more than a quarter. A row for another file is replaced + only by a run over a quarter longer, and a row with no time for a + selected run gets the middle of the session's. The key is + `repo:/test-cost/pytest`, one row a repository in the session's + namespace, tagged `repo:`, `source:` and `test-cost`, with + `files: []`, so that no file's memory serves it, and + `source_class: "external"`. The value is one sentence: + `A whole run of collects about cases and takes about s; +a run of it filtered with -k takes about s.` The write revises the row + the session read at a prompt (`if_match_sha256`) and is create-only + (`absent`) for a session that read none, so it replaces no row the + session did not see; a value that is not that sentence is left as it + is. + What leaves the machine is the path as pytest names it from its root, + the case count and the seconds. A path that is absolute, leaves the + checkout, holds a character outside letters, digits and `._/-`, is over + 160 characters or is changed by the secret redaction is not noted. + `loom-prompt-pack` prints the row under a bug report's pointers (**The + test cost line**, above). `LOOM_SESSION_MEMORY=off` stops the write, and + a session in code-only mode notes, stores and prints nothing. - LOOM_TEST_REPORT=off, or the `test_report` option set to false, stops - both from the session's next start. + all of it from the session's next start. - **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/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index a14d9cfbd25..88979bed0ec 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -42,6 +42,15 @@ // is said about tests, and nothing where LOOM_TEST_GATE says off or block: // the line is the test gate's. // +// Below those goes one test cost line, for a bug report (as the next paragraph +// reads one) in a session that has the test report, where the memory plane +// runs and an earlier session stored what a whole run of a slow test file +// costs in this repository (lib/test-cost.mjs): the file, its case count and +// seconds, the seconds of a run filtered with -k, and to check a change with +// -k selections. The row is read by its key once a session, beside the search +// and inside the prompt's bound, and the line is sent only when that read has +// answered by the time the search has: it never holds the pointers back. +// // A search whose query reads as a bug report (twelve words or more, or a word // such as `error` or `crash`) asks the server's pick model // (LOOM_CODE_SEARCH_PICK_MODEL) to choose the pointers. It carries what is left @@ -88,6 +97,7 @@ import { postBounded, promptPointersMode, readStdinJson, + resolveScope, resolveServerUrl, resolveToken, runHookMain, @@ -122,6 +132,8 @@ const TOP_K = Math.round(envNumber("LOOM_PROMPT_PACK_TOP_K", 3, { min: 1, max: 5 const PICK_TIMEOUT_MS = Math.round(envNumber("LOOM_PROMPT_PACK_PICK_TIMEOUT_MS", 6000, { min: 200 })); // The test line is the test gate's: sent in the modes that name a test at edit time. const TEST_LINE = gateAdvises(); +// The test cost line is read from memory: only where that plane runs too. +const COST_LINE = planeEnabled("memory"); const CONSUMER = "claude-code-prompt-pack"; // The lookups a session makes as it starts: SessionStart's, and the MCP headers helper's. @@ -207,6 +219,15 @@ async function testLine(pointers, prompt, root, payload, until) { return check.text; } +/** The test cost line of the session's repository, or "" (`costLine` in + * lib/test-cost.mjs, loaded only for a bug report). Never rejects: nothing + * waits for it when the search answers first. */ +function costNote(payload, cwd, options) { + return import("../lib/test-cost.mjs") + .then(({ costLine }) => costLine(payload.session_id, () => resolveScope(cwd), options)) + .catch(() => ""); +} + async function main() { if (POINTERS === "off") { scheduleExit(0); @@ -253,18 +274,20 @@ async function main() { // The server skips a pick it cannot finish by the deadline, cuts one that runs past it, // and answers with the ranking it has: without a deadline a late pick is no answer at all. if (pick) body.deadline_ms = pickDeadline(left); - const res = await requestLookup(lookup.op, body, { - token, - serverUrl: resolveServerUrl(), - timeoutMs: left, - }); + const options = { token, serverUrl: resolveServerUrl(), timeoutMs: left }; + const asked = requestLookup(lookup.op, body, options); + // Started beside the search, once that is sent, and not waited for after it. + const cost = COST_LINE && pick && payload.session_id ? costNote(payload, cwd, options) : null; + const res = await asked; // A search answer sends its places to edit, and the test line reads the same ones. const sent = lookup.op === "code.search" ? pointerBlock(body, res, prompt, { topK: TOP_K, minConfidence: MIN_CONF }) : null; const text = sent ? sent.text : renderLookup(lookup, body, res, repo); const check = TEST_LINE && text && sent ? await testLine(sent.pointers, prompt, root, payload, until) : ""; + // What the read has answered by now, or nothing: a settled promise wins the race. + const note = cost && text && sent ? await Promise.race([cost, Promise.resolve("")]) : ""; scheduleExit(0); - return text ? packPayload(check ? `${text}\n${check}` : text) : undefined; + return text ? packPayload([text, check, note].filter(Boolean).join("\n")) : undefined; } runHookMain(main); diff --git a/integrations/claude-code-plugin/hooks/loom-record.mjs b/integrations/claude-code-plugin/hooks/loom-record.mjs index 7e04f7e2a16..86e4dd01ebb 100644 --- a/integrations/claude-code-plugin/hooks/loom-record.mjs +++ b/integrations/claude-code-plugin/hooks/loom-record.mjs @@ -55,8 +55,9 @@ // Each script checks the install's mode and its own switch itself // (`planeEnabled`, `promptPointersMode`, `promptRecallMode`, `gateMode`); the // launcher reads the planes and switches of the scripts the host waits for -// (WAITED) only to leave one unloaded. What the launcher does itself, keeping -// the run's begin, is the ledger's. +// (WAITED) only to leave one unloaded. What the launcher does itself is the +// ledger's, keeping the run's begin, and memory's, reading the test report +// at SessionEnd for the cost of a run that outlived its command. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -79,6 +80,7 @@ import { import { keepRunBegin, runLedgerEnabled } from "../lib/run-hook.mjs"; import { readsOnly } from "../lib/shell-command.mjs"; import { useHooksServer } from "../lib/plugin-options.mjs"; +import { settleRun } from "../lib/test-cost.mjs"; import { startsRunner } from "../lib/test-gate.mjs"; import { endReport, reportPath, showsRefusal, testReportOn, visibleOutput } from "../lib/test-report.mjs"; import { readPrivateFile, removeFile } from "../lib/tmp-state.mjs"; @@ -229,8 +231,14 @@ async function hook(script, event, client) { // An invalid endpoint throws here, before a job file is written or a copy started. resolveServerUrl(); const raw = await readStdinText(); - // The session's test report goes with the session, whatever else is recorded. - if (event === "SessionEnd") endReport(parsePayload(raw).session_id); + // The session's test report goes with the session, whatever else is recorded. A + // run that had not ended when its command returned wrote the report since: what + // it cost is read first, for the session's hand-off to memory. + if (event === "SessionEnd") { + const sessionId = parsePayload(raw).session_id; + if (planeEnabled("memory") && testReportOn()) settleRun(sessionId); + endReport(sessionId); + } if (recordedInHook(event)) { // Left open, a stdin its host never closes would hold this process // through the exit grace after the records are sent. diff --git a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs index 03bf03840b2..190b45f6d27 100644 --- a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs @@ -5,6 +5,11 @@ // the turns as the facts' source evidence; the hook itself runs no model (see // lib/session-memory.mjs). // +// With the turns goes what the session's test runs cost: one memory.set of +// the repository's test cost row, when the session saw a slow whole run of a +// test file or can add a missing time to the row (lib/test-cost.mjs; +// LOOM_TEST_REPORT=off stops it). +// // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget // through the detached flusher so the agent never waits on the request. @@ -25,7 +30,9 @@ import { sessionToolEchoes, transcriptTurns, } from "../lib/session-memory.mjs"; +import { costPost } from "../lib/test-cost.mjs"; import { sessionStart } from "../lib/test-gate.mjs"; +import { testReportOn } from "../lib/test-report.mjs"; import { editedFiles } from "../lib/working-memory.mjs"; import { readRecalledStash, recalledStashPath } from "../lib/run-hook.mjs"; import { fileSize, parseLines, readTail } from "../lib/transcript.mjs"; @@ -46,11 +53,18 @@ async function main() { const journal = readJournal(sid); removeFile(recalledStashPath(sid)); if (planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken()) { - await handOff(payload, journal, recalledKeys); + const posts = [ + await handOff(payload, journal, recalledKeys), + testReportOn() ? costPost(sid, () => resolveScope(payload.cwd)) : null, + ].filter(Boolean); + // Spawn failure: nothing is lost that the next session cannot say again. + if (posts.length) dispatchFlush({ posts }); } scheduleExit(0); } +/** The flusher's post of the session's turns, or none for a session with + * nothing to extract. */ async function handOff(payload, journal, recalledKeys) { const transcript = payload.transcript_path || ""; // The transcript's turns when the client names one this script can read; @@ -76,8 +90,7 @@ async function handOff(payload, journal, recalledKeys) { // session's own that touches every file its edit tool wrote. const commit = changed && changed.length ? await changeCommit(payload.cwd || process.cwd(), began, edited) : ""; if (commit) body.extra_tags.push(`change:${commit}`); - // Spawn failure: nothing is lost that the next session cannot say again. - dispatchFlush({ posts: [{ op: "memory.set_from_messages", body }] }); + return { op: "memory.set_from_messages", body }; } runHookMain(main); diff --git a/integrations/claude-code-plugin/hooks/loom-test-report.mjs b/integrations/claude-code-plugin/hooks/loom-test-report.mjs index da8bcbd2e51..7967c414374 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-report.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-report.mjs @@ -21,9 +21,14 @@ // notes the refusal, so no later command and no later start of the session // gets the option. // -// No request, nothing stored in Loom, a bounded read of one private file, and -// silence on every error. It reads the session's own record of its test runs -// and sends nothing, so it runs in every mode. +// Where the memory plane runs, the hook also notes what a pytest run of one +// test file cost, from the report's head, in the session's private state +// (lib/test-cost.mjs): the session's end hands the cost of a slow whole run +// to memory, and a later session's prompt carries it. +// +// No request, a bounded read of one private file, and silence on every +// error. It reads the session's own record of its test runs and sends +// nothing, so it runs in every mode. // // LOOM_TEST_REPORT=off disable (or the `test_report` install option) @@ -36,6 +41,8 @@ import { runHookMain, scheduleExit, } from "../lib/loom-client.mjs"; +import { noteCommand } from "../lib/test-cost.mjs"; +import { fileRun } from "../lib/test-gate.mjs"; import { digest, newReport, @@ -50,6 +57,8 @@ import { } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); +// What a run cost is memory's: noted only where that plane runs. +const COST = planeEnabled("memory"); // True of a command the option did not reach too (one run in the sandbox). const REFUSED = "Loom: this command's pytest does not accept the report option Loom added (`--junitxml`), and a run that got it ended with `unrecognized arguments`. The option is removed for the rest of this session: run the command again if it ended that way."; @@ -60,12 +69,14 @@ function answer(payload) { const seen = sessionId ? seenReport(sessionId) : null; if (!seen) return null; const output = visibleOutput(payload); - if (rejectsOption(commandText(payload.tool_input), output, reportPath(sessionId))) { + const command = commandText(payload.tool_input); + if (rejectsOption(command, output, reportPath(sessionId))) { refuseReport(sessionId); return reportContext(payload, REFUSED); } // Read whatever the output shows: a report left unread would be the next command's. const report = newReport(sessionId, seen); + if (COST) noteCommand(sessionId, fileRun(command, output), report ? report.head : null); if (!report || shownAlready(output)) return null; const cwd = payload.cwd || process.cwd(); return reportContext(payload, digest(report.xml, { root: gitToplevel(cwd) || cwd, cwd, redact: redactSecrets })); diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs new file mode 100644 index 00000000000..1c39ad2fb9c --- /dev/null +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -0,0 +1,251 @@ +// What a whole run of a slow test file costs in this repository, told to a +// session before it chooses how to check a change. A session that does not +// know the cost runs the whole file where a selection of it answers in +// seconds. +// +// The number is in the result file the test report has pytest write +// (lib/test-report.mjs): its first testsuite holds the case count and the +// run's seconds. hooks/loom-test-report.mjs notes them for a command that is +// one pytest run of one test file (`noteCommand`), in the session's private +// state: the costliest whole run that passed, and the times of the runs of a +// selection of each file. A run that outlives its shell call writes the file +// after that call's hook ran, so the launcher reads it once more before it +// removes the file at the session's end (`settleRun`). +// +// At the session's end hooks/loom-session-memory.mjs hands one memory row a +// repository to the flusher (`costPost`): a whole run of 60 s or more, where +// the session read no row, or one whose seconds differ by more than a +// quarter. hooks/loom-prompt-pack.mjs reads the row by its key beside a bug +// report's search and prints one line under the pointers (`costLine`). +// +// What leaves the machine is the file's path as pytest names it, a case +// count and seconds, under the repository's id. A path that is absolute, +// leaves the checkout, holds a character outside letters, digits and `._/-`, +// is over 160 characters or is changed by the secret redaction is not noted. + +import { hookClient, postBounded, redactSecrets } from "./loom-client.mjs"; +import { newReport, runCost, seenReport } from "./test-report.mjs"; +import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; + +// A whole run shorter than this is not worth a line in a prompt. +export const MIN_WHOLE_SECONDS = 60; +// The default limit of one shell call under Claude Code. +const CALL_LIMIT_SECONDS = 120; +const MAX_PATH = 160; +// The files whose selected runs a session's state holds, and the runs of each. +const MAX_FILES = 8; +const MAX_SAMPLES = 15; + +// The session's runs: `{ pending, whole, filtered }`. +const RUNS = "test-cost"; +// The repository's row as the session read it: `{ read, row }`. +const ROW = "test-cost-row"; + +/** `file` when it may be sent, else "". */ +function sendable(file) { + const p = String(file || ""); + const plain = p.length <= MAX_PATH && /^(?!\/)[\w./-]+\.py$/.test(p) && !p.split("/").includes(".."); + return plain && redactSecrets(p) === p ? p : ""; +} + +/** Whether a report's `file` (from pytest's root) is the file a command + * names as `path` (from the folder the command ran in). */ +function sameFile(file, path) { + const named = path.replace(/^\.\//, ""); + return file === named || file.endsWith(`/${named}`) || named.endsWith(`/${file}`); +} + +/** Add what `run` cost to `state`, from the head of the report it wrote. A + * report whose first case is in another file is another run's. A whole run + * counts when no case failed: one that stopped at a failure took less. */ +function add(state, run, head) { + const cost = runCost(head); + const file = sendable(cost?.file); + if (!file || !sameFile(file, run.path)) return; + if (run.whole) { + if (!cost.failed && cost.seconds > (state.whole?.seconds ?? -1)) { + state.whole = { path: file, tests: cost.tests, seconds: cost.seconds }; + } + return; + } + const filtered = { ...state.filtered }; + filtered[file] = [...(filtered[file] || []), cost.seconds].slice(-MAX_SAMPLES); + state.filtered = Object.fromEntries(Object.entries(filtered).slice(-MAX_FILES)); +} + +/** + * Note the shell command the test report was read for. `run` is the + * command's one-file pytest run (`fileRun` in lib/test-gate.mjs) or null, and + * `head` the head of the report when a run wrote it since the session's last + * read, else null. + * + * The report is this command's when its output shows pytest's summary. A + * run whose output shows none has not ended: it is kept as the session's + * pending run, and a report that comes with a later command of the same run + * (the same file, whole or selected alike) is counted as that run's. Any + * other command drops the pending run: a report after it could be either's. + */ +export function noteCommand(sessionId, run, head) { + try { + const state = readSessionState(RUNS, sessionId); + const pending = state.pending; + if (!run && !pending) return; + const open = Boolean(run && !run.ended); + const again = Boolean(open && pending && pending.path === run.path && pending.whole === run.whole); + if (head && run && (run.ended || again)) add(state, run, head); + state.pending = open && (!pending || again) ? { path: run.path, whole: run.whole } : undefined; + writeSessionState(RUNS, sessionId, state); + } catch { + /* nothing noted */ + } +} + +/** At the session's end, before its report is removed: a report written + * since the session's last read is the pending run's. One bounded read of + * the session's own file. */ +export function settleRun(sessionId) { + try { + const state = readSessionState(RUNS, sessionId); + if (!state.pending) return; + const seen = seenReport(sessionId); + const report = seen && newReport(sessionId, seen); + if (report) add(state, state.pending, report.head); + state.pending = undefined; + writeSessionState(RUNS, sessionId, state); + } catch { + /* nothing noted */ + } +} + +/** The row's value: one plain-text claim. */ +export function claim({ path, tests, seconds, filtered }) { + const whole = `A whole run of ${path} collects about ${tests} cases and takes about ${seconds} s`; + return filtered ? `${whole}; a run of it filtered with -k takes about ${filtered} s.` : `${whole}.`; +} + +const CLAIM = + /^A whole run of ([\w./-]+\.py) collects about (\d{1,9}) cases and takes about (\d{1,6}) s(?:; a run of it filtered with -k takes about (\d{1,6}) s)?\.$/; + +/** What a row's value claims, `{ path, tests, seconds, filtered? }`; null for + * a value that is not `claim`'s text. */ +export function parseClaim(value) { + const found = typeof value === "string" ? CLAIM.exec(value) : null; + if (!found || !sendable(found[1])) return null; + const filtered = found[4] ? { filtered: Number(found[4]) } : {}; + return { path: found[1], tests: Number(found[2]), seconds: Number(found[3]), ...filtered }; +} + +/** The line a prompt carries. It is made of the claim's parts and never of + * the stored text, so a row written by another hand adds no sentence. */ +export function renderCost({ path, tests, seconds, filtered }) { + const limit = seconds > CALL_LIMIT_SECONDS ? `, longer than the ${CALL_LIMIT_SECONDS} s limit of a shell call` : ""; + return ( + `Test cost in this repository (measured in earlier sessions): a whole run of ${path} collects about ${tests} ` + + `cases and takes about ${seconds} s${limit}.` + + (filtered ? ` A run filtered with -k takes about ${filtered} s.` : "") + + " Check a change with -k selections of the cases it affects." + ); +} + +/** The key of the row of the repository of `scope` (`resolveScope`), "" for a + * checkout with no remote: `//`, the runner as the id. */ +export const costKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/test-cost/pytest` : ""); + +const identity = (scope) => ({ + org: scope.org, + namespace: scope.namespace, + agent: scope.agent, + memory_key: costKey(scope), +}); + +/** + * The line for a prompt of a session that has the test report, or "": the + * repository's row, read once a session (`memory.get` by key, bounded by + * `options.timeoutMs`) and kept in the session's state, a miss too. + * `scopeOf()` is asked only for that read. An answer that does not come, an + * error and a row that is not `claim`'s text give no line; a later prompt + * asks again only after the first two. + */ +export async function costLine(sessionId, scopeOf, options) { + try { + if (!seenReport(sessionId)) return ""; + let held = readSessionState(ROW, sessionId); + if (!held.read) { + const scope = scopeOf(); + if (!costKey(scope)) return ""; + const res = await postBounded("memory.get", { ...identity(scope), fields: ["value", "content_sha256"] }, options); + if (!res) return ""; + const row = res.found ? { ...parseClaim(res.value), sha: String(res.content_sha256 || "") } : null; + held = { read: true, row }; + writeSessionState(ROW, sessionId, held); + } + return held.row?.path ? renderCost(held.row) : ""; + } catch { + return ""; + } +} + +/** The middle of `seconds`, a second at least; undefined for none. */ +function median(seconds) { + const sorted = [...(seconds || [])].sort((a, b) => a - b); + if (!sorted.length) return undefined; + return Math.max(1, Math.round((sorted[(sorted.length - 1) >> 1] + sorted[sorted.length >> 1]) / 2)); +} + +/** + * The claim to store after a session whose runs are `state`, or null for + * none. `row` is the repository's row as the session read it: undefined for + * no read, null for a miss, `{ sha }` for a value that is not `claim`'s text, + * which is left as it is. + * + * The session's costliest whole run is stored when it took + * `MIN_WHOLE_SECONDS` or more and there is no row, the row's seconds for the + * same file differ from it by more than a quarter, or the row is another + * file's and this one took over a quarter longer. Otherwise a row with no + * time for a selected run gets the session's, when it has one for the row's + * file. + */ +export function revised(state, row) { + if (row && !row.path) return null; + const whole = state.whole; + if (whole && whole.seconds >= MIN_WHOLE_SECONDS) { + const apart = row && Math.abs(whole.seconds - row.seconds) > row.seconds / 4; + if (!row || (whole.path === row.path ? apart : whole.seconds > row.seconds * 1.25)) { + const filtered = median(state.filtered?.[whole.path]) ?? (row?.path === whole.path ? row.filtered : undefined); + return { ...whole, ...(filtered ? { filtered } : {}) }; + } + } + const filtered = row && !row.filtered ? median(state.filtered?.[row.path]) : undefined; + return filtered ? { path: row.path, tests: row.tests, seconds: row.seconds, filtered } : null; +} + +/** + * The flusher's post that stores what the session measured, or null; the + * session's cost state is removed either way. One `memory.set` of the + * repository's key: a revision of the row the session read + * (`if_match_sha256`), else a first row (`absent`, which a session that read + * none sends too, and the server refuses where a row is there). The value + * names no file to the server (`files: []`), and its class says a tool + * measured it. + */ +export function costPost(sessionId, scopeOf) { + try { + const state = readSessionState(RUNS, sessionId); + const held = readSessionState(ROW, sessionId); + for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); + const next = revised(state, held.read ? held.row : undefined); + const scope = next ? scopeOf() : null; + if (!costKey(scope)) return null; + const body = { + ...identity(scope), + value: claim(next), + tags: [`repo:${scope.repo.id}`, `source:${hookClient()}`, "test-cost"], + files: [], + source_class: "external", + if_match_sha256: held.row?.sha || "absent", + }; + return { op: "memory.set", body }; + } catch { + return null; + } +} diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 4c24d67e5b4..bbdca463a82 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1352,6 +1352,47 @@ function allRan(output, runs) { ); } +// The options of `PARTIAL` that run a selection of what the paths name. The +// others run no test. +const SELECTS = /^(?:-[km]|--(?:lf|last-failed|sw|stepwise|deselect)\b)/; +// A run that names its own result file, or turns the result file off, +// does not write the session's. +const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; + +/** + * The pytest run of `command` when it is the command's one pytest run, + * started in this checkout (`ranHere`), and names one test file and nothing + * else to run: `{ path, whole, ended }`, else null. `path` is the file as the + * command spells it. `whole` is false for a run of a part of the file: a node + * id after the path, or an option that selects (`SELECTS`). `ended` says the + * visible `output` holds pytest's summary line, so the run finished inside + * the call. A run that prints what pytest knows and exits, or only collects + * (the rest of `PARTIAL`), is none, and so is one that does not write the + * session's result file (`OWN_REPORT`). The word after a flag that may take a + * value is that value and no path (`BARE`); a short flag written with its + * value (`-rf`, `-kparse`, `-n4`) takes none after it. + */ +export function fileRun(command, output = "") { + const text = String(command || "").replace(/\\\n/g, ""); + const runs = [...text.matchAll(PYTEST)]; + if (runs.length !== 1 || !ranHere(text.slice(0, runs[0].index))) return null; + const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); + const named = []; + let value = false; + for (const word of words) { + const flag = word.startsWith("-"); + if (!flag && !value) named.push(word); + value = flag && !word.includes("=") && !BARE.test(word) && !/^-[^-]./.test(word); + } + const file = named.length === 1 ? /^([^\s:]+\.py)(::\S*)?$/.exec(named[0]) : null; + const partial = words.filter((word) => PARTIAL.test(word)); + if (!file || !partial.every((word) => SELECTS.test(word)) || words.some((word) => OWN_REPORT.test(word))) return null; + const ended = String(output || "") + .split(/\r?\n/) + .some((line) => line.length < 300 && SUMMARY.test(line)); + return { path: file[1], whole: !file[2] && !partial.length, ended }; +} + /** * The repo-relative files and directories pytest ran to its summary on the * tree as it stands, read in transcript order (Claude Code rows; sidechains diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index d803e04c828..a73a4fc7e4f 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -6,9 +6,10 @@ // session's shell, and hooks/loom-test-report.mjs adds a digest of that file // to the result of the command that wrote it. // -// Nothing is sent to the server and nothing is stored in Loom. The result -// file is the session's own, owner-only, in the temp folder the hooks keep -// their state in. +// The digest sends nothing to the server. The result file is the session's +// own, owner-only, in the temp folder the hooks keep their state in. What a +// run cost is read from the file's head (`runCost`); lib/test-cost.mjs keeps +// it for the session and hands it to memory at the session's end. import fs from "node:fs"; import path from "node:path"; @@ -19,8 +20,10 @@ import { readSessionState, removeFile, sessionStatePath, writePrivateFile, write /** What marks the line the plugin wrote in the session's shell file. */ const MARKER = "# loom test report"; -// A larger report is not read: a hook's read is bounded. +// A larger report is not read past its head: a hook's read is bounded. const MAX_REPORT_BYTES = 2 * 1024 * 1024; +// The head holds the first testsuite's tag and the first testcase's. +const HEAD_BYTES = 4096; const MAX_GROUPS = 3; const MAX_REASON = 200; const MAX_ID = 160; @@ -115,9 +118,9 @@ export function seenReport(sessionId) { } /** The session's report when a run wrote it since the session saw it as - * `seen`: `{ xml }`, with "" for a report over the read bound, and the file - * noted as seen. null when no run wrote it, or the file is not this user's - * regular file. */ + * `seen`: `{ xml, head }`, with "" as `xml` for a report over the read + * bound and its first `HEAD_BYTES` as `head`, and the file noted as seen. + * null when no run wrote it, or the file is not this user's regular file. */ export function newReport(sessionId, seen) { let fd; try { @@ -128,9 +131,10 @@ export function newReport(sessionId, seen) { if (typeof process.getuid === "function" && st.uid !== process.getuid()) return null; if (st.mtimeMs === seen.mtimeMs && st.size === seen.size) return null; writeSessionState("test-report", sessionId, { mtimeMs: st.mtimeMs, size: st.size }); - if (st.size > MAX_REPORT_BYTES) return { xml: "" }; - const buf = Buffer.alloc(st.size); - return { xml: buf.toString("utf8", 0, fs.readSync(fd, buf, 0, buf.length, 0)) }; + const large = st.size > MAX_REPORT_BYTES; + const buf = Buffer.alloc(large ? HEAD_BYTES : st.size); + const text = buf.toString("utf8", 0, fs.readSync(fd, buf, 0, buf.length, 0)); + return { xml: large ? "" : text, head: text.slice(0, HEAD_BYTES) }; } catch { return null; } finally { @@ -285,6 +289,35 @@ function scan(xml) { return { totals, failed }; } +/** What the run that wrote a result file cost, from the file's `head`: the + * first testsuite's case count, its seconds to the nearest one, how many + * cases failed or ended in an error, and the file of its first testcase, + * which pytest names in the family the option sets ("" where the head holds + * none). null for a head with no whole testsuite tag, no case or no time. */ +export function runCost(head) { + const first = (text, name) => { + try { + return startTags(text, name).next().value; + } catch { + return undefined; + } + }; + const xml = String(head ?? ""); + const suite = first(xml, "testsuite"); + if (!suite) return null; + const has = attributes(suite.attrs); + const tests = Number(has.tests); + const seconds = Number(has.time); + if (!Number.isInteger(tests) || tests < 1 || !has.time || !Number.isFinite(seconds) || seconds < 0) return null; + const testcase = first(xml.slice(suite.end), "testcase"); + return { + tests, + seconds: Math.round(seconds), + failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), + file: testcase ? attributes(testcase.attrs).file || "" : "", + }; +} + /** `text` as one line: its lines trimmed and joined by `; `, by a space after * one that ends in a colon. */ function oneLine(text) { diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs new file mode 100644 index 00000000000..837de38038a --- /dev/null +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -0,0 +1,665 @@ +// The test cost note: what a pytest run of one test file cost, read from the +// head of the session's result file; the row a session's end hands to memory +// for a slow whole run; and the line a later bug report carries under its +// pointers. +import "./temp-home.mjs"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync, spawn } from "node:child_process"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { fileURLToPath } from "node:url"; +import { removeSandbox } from "./hook-sandbox.mjs"; +import { hostEnv, withTmpdir } from "./host-env.mjs"; +import { repoIdentity } from "../lib/loom-client.mjs"; +import { cachePathFor } from "../lib/repo-scope.mjs"; +import { claim, costKey, noteCommand, parseClaim, renderCost, revised, settleRun } from "../lib/test-cost.mjs"; +import { fileRun } from "../lib/test-gate.mjs"; +import { newReport, reportPath, runCost } from "../lib/test-report.mjs"; +import { readJsonFile, sessionStatePath, writeJsonFile, writePrivateFile } from "../lib/tmp-state.mjs"; + +const root = path.join(path.dirname(fileURLToPath(import.meta.url)), ".."); +const WINDOWS = process.platform === "win32"; +const SESSION = "cost-session-1"; +const FILE = "tests/test_big.py"; +const ORIGIN = "https://github.com/example/app.git"; +const KEY = `repo:${repoIdentity(ORIGIN).id}/test-cost/pytest`; + +/** A result file as pytest writes it in the family the option sets, which + * names each case's file: one suite of `tests` cases that took `time`. */ +function report({ tests, time, file = FILE, failures = 0 }) { + return ( + `` + + `` + + `` + ); +} + +const WHOLE = report({ tests: 8000, time: "140.2" }); +const WHOLE_COMMAND = `python -m pytest ${FILE} -q 2>&1 | tail -3`; +const WHOLE_OUTPUT = "8000 passed in 140.21s (0:02:20)"; +const FILTERED = report({ tests: 12, time: "2.3" }); +const FILTERED_COMMAND = `python -m pytest ${FILE} -k "parse and not slow" -q`; +const FILTERED_OUTPUT = "12 passed, 7988 deselected in 2.31s"; +const BOTH = `A whole run of ${FILE} collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s.`; + +// --- the parts ---------------------------------------------------------------- + +test("the head of a report gives the run's case count and its seconds", () => { + assert.deepEqual(runCost(WHOLE.slice(0, 4096)), { tests: 8000, seconds: 140, failed: 0, file: FILE }); + assert.deepEqual(runCost(report({ tests: 3, time: "0.4", failures: 2 })), { + tests: 3, + seconds: 0, + failed: 2, + file: FILE, + }); + // A head cut inside the first case still holds the suite's totals. + const cut = WHOLE.slice(0, WHOLE.indexOf("", + WHOLE.slice(0, WHOLE.indexOf("tests=")), + report({ tests: 0, time: "0.1" }), + WHOLE.replace(' time="140.2"', ""), + WHOLE.replace('time="140.2"', 'time="soon"'), + ]) { + assert.equal(runCost(head), null, head.slice(-40)); + } +}); + +test("a report over the read bound is read for its head", { skip: WINDOWS }, (t) => { + const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-test-cost-"))); + t.after(() => fs.rmSync(tmp, { recursive: true, force: true })); + withTmpdir(tmp, () => { + writePrivateFile(reportPath(SESSION), `${WHOLE}${" ".repeat(2 * 1024 * 1024)}`); + const read = newReport(SESSION, { mtimeMs: 1, size: 0 }); + assert.equal(read.xml, ""); + assert.equal(read.head.length, 4096); + assert.deepEqual(runCost(read.head), { tests: 8000, seconds: 140, failed: 0, file: FILE }); + }); +}); + +test("a command's one pytest run of one test file is whole or a selection of it", () => { + const whole = { path: FILE, whole: true, ended: false }; + for (const command of [ + `pytest ${FILE}`, + `python -m pytest ${FILE} -q`, + `.venv/bin/python -m pytest -x -q ${FILE} 2>&1 | tail -5`, + `cd pkg && uv run pytest ${FILE} -n auto --tb=short > /tmp/out.txt 2>&1`, + `timeout 600 pytest ${FILE} -p no:cacheprovider`, + // A short flag written with its value takes none after it. + `pytest -rf -n4 ${FILE}`, + ]) { + assert.deepEqual(fileRun(command), whole, command); + } + const part = { path: FILE, whole: false, ended: false }; + for (const command of [ + `pytest ${FILE} -k parse`, + `pytest ${FILE} -k "parse and not slow" -q`, + `pytest -kparse ${FILE}`, + `pytest -m "not slow" ${FILE}`, + `pytest ${FILE}::TestParse::test_empty`, + `pytest "${FILE}::test_case[a-b]" -q`, + `pytest ${FILE} --lf`, + `pytest ${FILE} --deselect ${FILE}::test_slow`, + ]) { + assert.deepEqual(fileRun(command), part, command); + } + // The run ended inside the call when the output holds pytest's summary. + assert.equal(fileRun(`pytest ${FILE} -q`, "........\n8000 passed in 140.21s (0:02:20)").ended, true); + assert.equal(fileRun(`pytest ${FILE} -k parse`, "12 passed, 7988 deselected in 2.31s").ended, true); + assert.equal(fileRun(`pytest ${FILE} -q`, "Command running in background with ID: bash_1").ended, false); +}); + +test("a command with two pytest runs, two paths, no file or no run of its own is no file run", () => { + for (const command of [ + `pytest ${FILE} -q; pytest ${FILE} -k parse`, + `pytest ${FILE} tests/test_small.py`, + `pytest tests ${FILE}`, + "pytest tests/", + "pytest -q", + // The word after a flag that may take a value is that value. + `pytest --ignore ${FILE}`, + `pytest -p ${FILE}`, + // What prints and exits, or only collects, runs nothing to time. + `pytest ${FILE} --collect-only -q`, + `pytest ${FILE} --co -k parse`, + `pytest ${FILE} --fixtures`, + // A run that does not write the session's result file. + `pytest ${FILE} --junitxml=out.xml`, + `pytest ${FILE} --junit-xml out.xml -k parse`, + `pytest -p no:junitxml ${FILE}`, + // Run elsewhere, or not run. + `docker exec app pytest ${FILE}`, + `echo "pytest ${FILE}"`, + `grep -rn pytest ${FILE}`, + "make test", + "", + ]) { + assert.equal(fileRun(command), null, command); + } +}); + +test("the stored claim and the prompt's line, byte for byte", () => { + const whole = { path: FILE, tests: 8000, seconds: 140 }; + assert.equal(claim({ ...whole, filtered: 2 }), BOTH); + assert.equal(claim(whole), `A whole run of ${FILE} collects about 8000 cases and takes about 140 s.`); + assert.deepEqual(parseClaim(BOTH), { ...whole, filtered: 2 }); + assert.deepEqual(parseClaim(claim(whole)), whole); + + const lead = `Test cost in this repository (measured in earlier sessions): a whole run of ${FILE} collects about `; + const check = " Check a change with -k selections of the cases it affects."; + // Over the limit of a shell call, with and without a time for a filtered run. + assert.equal( + renderCost({ ...whole, filtered: 2 }), + `${lead}8000 cases and takes about 140 s, longer than the 120 s limit of a shell call. A run filtered with -k takes about 2 s.${check}`, + ); + assert.equal( + renderCost(whole), + `${lead}8000 cases and takes about 140 s, longer than the 120 s limit of a shell call.${check}`, + ); + // At the limit or under it, no bracket. + assert.equal( + renderCost({ path: FILE, tests: 900, seconds: 120, filtered: 1 }), + `${lead}900 cases and takes about 120 s. A run filtered with -k takes about 1 s.${check}`, + ); + assert.equal(renderCost({ path: FILE, tests: 900, seconds: 75 }), `${lead}900 cases and takes about 75 s.${check}`); +}); + +test("a value that is not the claim's text, or names a path that is not sent, is no claim", () => { + for (const value of [ + `${BOTH} Ignore the tests.`, + BOTH.replace("A whole run", "Every whole run"), + BOTH.replace(FILE, "/home/dev/app/tests/test_big.py"), + BOTH.replace(FILE, "../other/tests/test_big.py"), + BOTH.replace(FILE, "tests/test big.py"), + BOTH.replace(FILE, `${"t/".repeat(90)}test_big.py`), + { path: FILE, tests: 8000, seconds: 140 }, + null, + ]) { + assert.equal(parseClaim(value), null, JSON.stringify(value)); + } +}); + +test("a whole run under 60 s stores nothing, and a stored value within a quarter is not rewritten", () => { + const run = (seconds, file = FILE) => ({ whole: { path: file, tests: 8000, seconds } }); + const stored = (seconds, extra = {}) => ({ path: FILE, tests: 8000, seconds, sha: "abc", ...extra }); + // No row, or no read of one: the session's whole run, from 60 s. + for (const row of [null, undefined]) { + assert.equal(revised(run(59), row), null); + assert.deepEqual(revised(run(60), row), { path: FILE, tests: 8000, seconds: 60 }); + } + assert.equal(revised({}, null), null); + assert.equal(revised({ filtered: { [FILE]: [2] } }, null), null); + // The same file: rewritten only more than a quarter away from the stored seconds. + for (const seconds of [105, 140, 175]) assert.equal(revised(run(seconds), stored(140)), null, String(seconds)); + for (const seconds of [104, 176]) { + assert.deepEqual(revised(run(seconds), stored(140)), { path: FILE, tests: 8000, seconds }, String(seconds)); + } + // Another file takes the row only when it is over a quarter costlier. + assert.equal(revised(run(175, "tests/test_other.py"), stored(140)), null); + assert.equal(revised(run(100, "tests/test_other.py"), stored(140)), null); + assert.equal(revised(run(176, "tests/test_other.py"), stored(140)).path, "tests/test_other.py"); + // The time of a filtered run is the middle of the session's, a second at least; + // a rewrite with none keeps the stored one for the same file. + const filtered = { [FILE]: [3, 1, 2, 40] }; + assert.equal(revised({ ...run(200), filtered }, stored(140)).filtered, 3); + assert.equal(revised({ ...run(200), filtered: { [FILE]: [0, 0] } }, null).filtered, 1); + assert.equal(revised(run(200), stored(140, { filtered: 2 })).filtered, 2); + assert.equal(revised(run(200, "tests/test_other.py"), stored(140, { filtered: 2 })).filtered, undefined); + // A row with no such time gets the session's, with no whole run of its own. + assert.deepEqual(revised({ filtered }, stored(140)), { path: FILE, tests: 8000, seconds: 140, filtered: 3 }); + assert.equal(revised({ filtered }, stored(140, { filtered: 2 })), null); + assert.equal(revised({ filtered: { "tests/test_other.py": [2] } }, stored(140)), null); + // A value another hand wrote is left as it is. + assert.equal(revised({ ...run(300), filtered }, { sha: "abc" }), null); +}); + +test("the key is the repository's, and a checkout with no remote has none", () => { + assert.equal(costKey({ repo: repoIdentity(ORIGIN) }), KEY); + assert.match(KEY, /^repo:[0-9a-f]{10}\/test-cost\/pytest$/); + assert.equal(costKey({ repo: null }), ""); +}); + +// --- the session's state -------------------------------------------------------- + +/** Run `fn` with this process's temp folder a fresh one, removed after the test. */ +function inTmp(t, fn) { + const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-test-cost-"))); + t.after(() => fs.rmSync(tmp, { recursive: true, force: true })); + return withTmpdir(tmp, () => fn(tmp)); +} +const runs = () => readJsonFile(sessionStatePath("test-cost", SESSION), null); +const head = (xml) => xml.slice(0, 4096); +const ran = (command, output) => fileRun(command, output); + +test("a report is the command's whose output shows the summary", { skip: WINDOWS }, (t) => { + inTmp(t, () => { + noteCommand(SESSION, ran(WHOLE_COMMAND, WHOLE_OUTPUT), head(WHOLE)); + assert.deepEqual(runs(), { whole: { path: FILE, tests: 8000, seconds: 140 } }); + noteCommand(SESSION, ran(FILTERED_COMMAND, FILTERED_OUTPUT), head(FILTERED)); + noteCommand(SESSION, ran(FILTERED_COMMAND, FILTERED_OUTPUT), head(report({ tests: 30, time: "3.6" }))); + assert.deepEqual(runs(), { whole: { path: FILE, tests: 8000, seconds: 140 }, filtered: { [FILE]: [2, 4] } }); + // The costliest whole run stays; one that failed took less than the file costs. + noteCommand(SESSION, ran(WHOLE_COMMAND, "8000 passed in 90.00s"), head(report({ tests: 8000, time: "90.0" }))); + noteCommand( + SESSION, + ran(WHOLE_COMMAND, "1 failed, 7999 passed in 300.00s"), + head(report({ tests: 8000, time: "300.0", failures: 1 })), + ); + assert.equal(runs().whole.seconds, 140); + // A command that names the file from another folder, and a report of another file. + noteCommand( + SESSION, + ran("cd tests && pytest test_big.py -q", "8000 passed in 150.00s"), + head(report({ tests: 8000, time: "150.0" })), + ); + assert.equal(runs().whole.seconds, 150); + noteCommand( + SESSION, + ran(WHOLE_COMMAND, "9000 passed in 900.00s"), + head(report({ tests: 9000, time: "900.0", file: "tests/test_other.py" })), + ); + assert.equal(runs().whole.seconds, 150); + }); +}); + +test("a command that is no file run, with no run pending, leaves no state", { skip: WINDOWS }, (t) => { + inTmp(t, () => { + noteCommand(SESSION, ran("make test", "8000 passed in 140.21s"), head(WHOLE)); + noteCommand(SESSION, ran(`pytest ${FILE} -q; pytest ${FILE} -k parse`, WHOLE_OUTPUT), head(WHOLE)); + noteCommand(SESSION, ran(`pytest ${FILE} tests/test_small.py`, WHOLE_OUTPUT), head(WHOLE)); + assert.equal(runs(), null); + }); +}); + +test("a run that outlives its call is pending, and the report at the session's end is its", { skip: WINDOWS }, (t) => { + inTmp(t, () => { + const started = "Command running in background with ID: bash_1"; + writePrivateFile(reportPath(SESSION), ""); + writeJsonFile(sessionStatePath("test-report", SESSION), { mtimeMs: 1, size: 0 }); + noteCommand(SESSION, ran(`pytest ${FILE} -q`, started), null); + assert.deepEqual(runs(), { pending: { path: FILE, whole: true } }); + // The same run started again: a report that came since is counted as that run's. + noteCommand(SESSION, ran(`pytest ${FILE} -q`, started), head(report({ tests: 8000, time: "130.0" }))); + assert.deepEqual(runs(), { + pending: { path: FILE, whole: true }, + whole: { path: FILE, tests: 8000, seconds: 130 }, + }); + fs.writeFileSync(reportPath(SESSION), WHOLE); + settleRun(SESSION); + assert.deepEqual(runs(), { whole: { path: FILE, tests: 8000, seconds: 140 } }); + // Nothing pending: the session's end reads nothing. + fs.writeFileSync(reportPath(SESSION), report({ tests: 8000, time: "999.0" })); + settleRun(SESSION); + assert.equal(runs().whole.seconds, 140); + }); +}); + +test("a report that could be another run's is counted for none", { skip: WINDOWS }, (t) => { + inTmp(t, () => { + const started = "Command running in background with ID: bash_1"; + const pending = () => noteCommand(SESSION, ran(`pytest ${FILE} -q`, started), null); + // Another command that starts a runner: the next report could be its. + pending(); + noteCommand(SESSION, null, null); + assert.deepEqual(runs(), {}); + // A selection of the file started while the whole run is open. + pending(); + noteCommand(SESSION, ran(`pytest ${FILE} -k parse`, started), head(WHOLE)); + assert.deepEqual(runs(), {}); + // A run whose summary is in sight takes the report; the open run's is lost. + pending(); + noteCommand(SESSION, ran(FILTERED_COMMAND, FILTERED_OUTPUT), head(FILTERED)); + assert.deepEqual(runs(), { filtered: { [FILE]: [2] } }); + }); +}); + +// --- the hooks, started as the host starts them ---------------------------------- + +const SEARCH = { + abstain: false, + retrieval_confidence: 0.8, + retrieval_risk: "low", + results: [{ path: "src/parser.py", start_line: 10, end_line: 14, symbol: "combine", kind: "function" }], +}; +const BLOCK = + "Loom index pointers for this prompt, candidates: Read a line range to check one, search if none fits:\n" + + "- src/parser.py:10-14 combine"; +const LINE = renderCost({ path: FILE, tests: 8000, seconds: 140, filtered: 2 }); +// Reads as a bug report: the prompt hook asks for the pick, and for the cost line. +const BUG = "Nested record prefixes raise an error before validation when the parser is given an empty prefix."; + +/** A stub Loom server. `get` is what memory.get answers, or a status for a + * failure; `getStall` holds that answer back. A search answers after 300 ms, + * as one that embeds its query does. */ +async function loom(t, { get = { found: false }, getStall = 0 } = {}) { + const requests = []; + const server = http.createServer((req, res) => { + let raw = ""; + req.on("data", (chunk) => (raw += chunk)); + req.on("end", () => { + const op = (req.url || "").replace(/^\/v1\//, ""); + let body = {}; + try { + body = JSON.parse(raw || "{}"); + } catch { + /* answered as an empty body */ + } + requests.push({ op, body, headers: req.headers }); + const failed = op === "memory.get" && typeof get === "number"; + const answer = + op === "code.search" ? SEARCH : op === "memory.get" ? get : op === "run.begin" ? { run_id: body.run_id } : {}; + res.writeHead(failed ? get : 200, { "content-type": "application/json" }); + const wait = op === "code.search" ? 300 : op === "memory.get" ? getStall : 0; + // Unreferenced: an answer still held back when the test ends does not keep the run open. + setTimeout(() => res.end(JSON.stringify(failed ? {} : answer)), wait).unref(); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + t.after(async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + }); + const sent = (op) => requests.filter((r) => r.op === op); + return { url: `http://127.0.0.1:${server.address().port}`, requests, sent }; +} + +/** A checkout of ORIGIN that configures pytest, a home and a temp folder, in + * a session that has the test report; `server` holds the checkout's index. */ +function sandbox(t, server) { + const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-test-cost-hook-"))); + const box = { dir, home: path.join(dir, "home"), tmp: path.join(dir, "tmp"), cwd: path.join(dir, "work") }; + for (const d of [box.home, box.tmp, box.cwd]) fs.mkdirSync(d); + fs.writeFileSync(path.join(box.cwd, "pytest.ini"), "[pytest]\n"); + const git = (...a) => execFileSync("git", a, { cwd: box.cwd, stdio: "ignore" }); + git("init", "-q", "-b", "main"); + git("remote", "add", "origin", ORIGIN); + box.report = reportPath(SESSION, { tmp: box.tmp }); + box.runs = sessionStatePath("test-cost", SESSION, { tmp: box.tmp }); + box.row = sessionStatePath("test-cost-row", SESSION, { tmp: box.tmp }); + writePrivateFile(box.report, ""); + writeJsonFile(sessionStatePath("test-report", SESSION, { tmp: box.tmp }), { mtimeMs: 1, size: 0 }); + fs.writeFileSync( + cachePathFor(box.cwd, box.tmp, { serverUrl: server.url, token: "t" }), + JSON.stringify({ + ts: Date.now(), + indexed: true, + own: true, + matchedVia: "origin", + org: "o", + namespace: "code-app", + repo: "example/app", + prefixes: [], + }), + ); + box.env = (extra = {}) => + hostEnv({ + PATH: process.env.PATH, + HOME: box.home, + TMPDIR: box.tmp, + LOOM_BASE_URL: server.url, + LOOM_API_KEY: "t", + LOOM_AUTO_SIGNUP: "off", + LOOM_PROMPT_RECALL: "off", + LOOM_HOOK_DEBUG: "on", + ...extra, + }); + t.after(() => removeSandbox(box)); + return box; +} + +function run(script, event, env, payload) { + return new Promise((resolve) => { + const child = spawn(process.execPath, [path.join(root, "hooks", script), event], { env, cwd: os.tmpdir() }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (c) => (stdout += c)); + child.stderr.on("data", (c) => (stderr += c)); + child.on("close", (code) => resolve({ code, stdout, stderr })); + child.stdin.end(JSON.stringify({ hook_event_name: event, session_id: SESSION, ...payload })); + }); +} + +/** The launcher after a shell command of the session whose pytest wrote `xml`. */ +function afterCommand(box, command, output, xml, extra) { + if (xml !== undefined) fs.writeFileSync(box.report, xml); + return run("loom-record.mjs", "PostToolUse", box.env(extra), { + cwd: box.cwd, + tool_name: "Bash", + tool_input: { command }, + tool_response: { stdout: output, stderr: "" }, + }); +} + +const endSession = (box, extra) => + run("loom-record.mjs", "SessionEnd", box.env(extra), { cwd: box.cwd, reason: "exit" }); + +/** The prompt hook on `prompt`: alone, or in the launcher as Claude Code runs it. */ +const ask = (box, { prompt = BUG, extra, launcher = false } = {}) => + run(launcher ? "loom-record.mjs" : "loom-prompt-pack.mjs", "UserPromptSubmit", box.env(extra), { + cwd: box.cwd, + prompt, + }); +const context = (r) => JSON.parse(r.stdout).hookSpecificOutput.additionalContext; + +/** Wait until the server has `op`, and every detached job is done. */ +async function arrived(server, box, op) { + const deadline = Date.now() + 45000; + while (!server.sent(op).length) { + if (Date.now() > deadline) throw new Error(`${op} did not arrive`); + await delay(25); + } + await settled(box); +} + +/** Every detached job of the sandbox is done. */ +async function settled(box) { + const deadline = Date.now() + 45000; + while (fs.readdirSync(box.tmp).some((name) => /^loom-(?:flush|record-[A-Za-z]+)-\d+-\d+\.json$/.test(name))) { + if (Date.now() > deadline) throw new Error("the session's jobs did not finish"); + await delay(25); + } +} + +test("a slow whole run and a filtered one are noted, and the session's end stores one row", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + const quiet = { code: 0, stdout: "", stderr: "" }; + assert.deepEqual(await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE), quiet); + assert.deepEqual(await afterCommand(box, FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED), quiet); + assert.deepEqual(readJsonFile(box.runs, null), { + whole: { path: FILE, tests: 8000, seconds: 140 }, + filtered: { [FILE]: [2] }, + }); + await settled(box); + // Nothing of it has left the machine before the session ends. + assert.deepEqual(server.sent("memory.set"), []); + assert.deepEqual(server.sent("memory.get"), []); + + assert.deepEqual(await endSession(box), quiet); + await arrived(server, box, "memory.set"); + const [stored] = server.sent("memory.set"); + assert.equal(server.sent("memory.set").length, 1); + assert.deepEqual(stored.body, { + org: "default", + namespace: "coding", + agent: "claude-code", + memory_key: KEY, + value: BOTH, + tags: [`repo:${repoIdentity(ORIGIN).id}`, "source:claude-code", "test-cost"], + files: [], + source_class: "external", + // The session read no row: the server writes only where there is none. + if_match_sha256: "absent", + }); + assert.equal(stored.headers["x-loom-session-protection"], undefined); + // The session's cost state went with the hand-off. + assert.equal(fs.existsSync(box.runs), false); +}); + +test("a whole run that outlived its call is stored from the report it wrote before the session's end", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await afterCommand(box, `python -m pytest ${FILE} -q`, "Command running in background with ID: bash_1"); + assert.deepEqual(readJsonFile(box.runs, null), { pending: { path: FILE, whole: true } }); + // The run ends after its command's hook ran, and no test command follows it. + fs.writeFileSync(box.report, WHOLE); + await endSession(box); + await arrived(server, box, "memory.set"); + assert.equal( + server.sent("memory.set")[0].body.value, + `A whole run of ${FILE} collects about 8000 cases and takes about 140 s.`, + ); + assert.equal(fs.existsSync(box.report), false); +}); + +test("nothing is stored for a whole run under 60 s, a command of two runs or two paths, or with a switch off", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const cases = [ + // Under 60 s. + [`python -m pytest ${FILE} -q`, "8000 passed in 59.40s", report({ tests: 8000, time: "59.4" }), {}], + // Two runs, and two paths: nothing is noted. + [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}], + [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}], + // The session hands nothing to memory, or has no test report. + [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }], + [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_TEST_REPORT: "off" }], + ]; + for (const [command, output, xml, extra] of cases) { + const box = sandbox(t, server); + await afterCommand(box, command, output, xml, extra); + await endSession(box, extra); + await settled(box); + } + assert.deepEqual(server.sent("memory.set"), []); + assert.deepEqual(server.sent("memory.get"), []); +}); + +test("code-only mode notes nothing, stores nothing and prints no line", { skip: WINDOWS }, async (t) => { + const server = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" } }); + const box = sandbox(t, server); + const code = { LOOM_MODE: "code" }; + await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, code); + assert.equal(fs.existsSync(box.runs), false); + assert.equal(context(await ask(box, { extra: code })), BLOCK); + await endSession(box, code); + await settled(box); + assert.deepEqual(server.sent("memory.get"), []); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a bug report carries the repository's cost line under its pointers, from one read a session", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" } }); + const box = sandbox(t, server); + const first = await ask(box); + assert.deepEqual({ code: first.code, stderr: first.stderr }, { code: 0, stderr: "" }); + assert.equal(context(first), `${BLOCK}\n${LINE}`); + const [read] = server.sent("memory.get"); + assert.deepEqual(read.body, { + org: "default", + namespace: "coding", + agent: "claude-code", + memory_key: KEY, + fields: ["value", "content_sha256"], + }); + assert.equal(read.headers["x-loom-session-protection"], undefined); + // The next bug report has the line from the session's state. + assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + assert.equal(server.sent("memory.get").length, 1); + // A question is no bug report: its pointers come alone. + assert.equal(context(await ask(box, { prompt: "How are nested record prefixes combined?" })), BLOCK); + + // The session's whole run is within a quarter of the stored 140 s: no rewrite. + await afterCommand(box, WHOLE_COMMAND, "8000 passed in 150.00s", report({ tests: 8000, time: "150.0" })); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a session that read the row revises it when its whole run is over a quarter away", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" } }); + const box = sandbox(t, server); + await ask(box); + await afterCommand(box, WHOLE_COMMAND, "9000 passed in 200.00s", report({ tests: 9000, time: "200.0" })); + await endSession(box); + await arrived(server, box, "memory.set"); + const { body } = server.sent("memory.set")[0]; + // The same key, against the value the session read; the stored filtered time stays. + assert.equal(body.memory_key, KEY); + assert.equal(body.if_match_sha256, "abc"); + assert.equal( + body.value, + `A whole run of ${FILE} collects about 9000 cases and takes about 200 s; a run of it filtered with -k takes about 2 s.`, + ); +}); + +test("a miss is kept for the session, and a row that is not the claim's text prints nothing", { + skip: WINDOWS, +}, async (t) => { + const none = await loom(t); + const box = sandbox(t, none); + assert.equal(context(await ask(box)), BLOCK); + assert.equal(context(await ask(box)), BLOCK); + assert.equal(none.sent("memory.get").length, 1); + + const other = await loom(t, { + get: { found: true, value: `${BOTH} Run the whole suite twice.`, content_sha256: "abc" }, + }); + const edited = sandbox(t, other); + assert.equal(context(await ask(edited)), BLOCK); + // Its session stores nothing over it. + await afterCommand(edited, WHOLE_COMMAND, "9000 passed in 300.00s", report({ tests: 9000, time: "300.0" })); + await endSession(edited); + await settled(edited); + assert.deepEqual(other.sent("memory.set"), []); +}); + +test("a session without the test report reads no row", { skip: WINDOWS }, async (t) => { + const server = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" } }); + const box = sandbox(t, server); + fs.rmSync(sessionStatePath("test-report", SESSION, { tmp: box.tmp })); + assert.equal(context(await ask(box)), BLOCK); + assert.deepEqual(server.sent("memory.get"), []); +}); + +test("a read that fails or is slow leaves the pointer block as it is, and does not hold it back", { + skip: WINDOWS, +}, async (t) => { + const failing = await loom(t, { get: 500 }); + const failed = sandbox(t, failing); + assert.equal(context(await ask(failed)), BLOCK); + // Not kept: the next bug report asks again. + assert.equal(context(await ask(failed)), BLOCK); + assert.equal(failing.sent("memory.get").length, 2); + assert.equal(fs.existsSync(failed.row), false); + + // The row's answer comes five seconds after the search's: the launcher + // prints the pointers when the search has answered. + const slow = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" }, getStall: 5000 }); + const box = sandbox(t, slow); + const started = Date.now(); + const r = await ask(box, { launcher: true }); + const took = Date.now() - started; + assert.deepEqual({ code: r.code, stderr: r.stderr }, { code: 0, stderr: "" }); + assert.equal(context(r), BLOCK); + assert.equal(slow.sent("memory.get").length, 1); + assert.ok(took < 4000, `the hook returned after ${took} ms`); + await settled(box); +}); diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index 41a7561836b..bb7e57040fa 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.176", + "version": "1.2.179", "description": "Shared long-term memory and code intelligence for Codex, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs index a14d9cfbd25..88979bed0ec 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -42,6 +42,15 @@ // is said about tests, and nothing where LOOM_TEST_GATE says off or block: // the line is the test gate's. // +// Below those goes one test cost line, for a bug report (as the next paragraph +// reads one) in a session that has the test report, where the memory plane +// runs and an earlier session stored what a whole run of a slow test file +// costs in this repository (lib/test-cost.mjs): the file, its case count and +// seconds, the seconds of a run filtered with -k, and to check a change with +// -k selections. The row is read by its key once a session, beside the search +// and inside the prompt's bound, and the line is sent only when that read has +// answered by the time the search has: it never holds the pointers back. +// // A search whose query reads as a bug report (twelve words or more, or a word // such as `error` or `crash`) asks the server's pick model // (LOOM_CODE_SEARCH_PICK_MODEL) to choose the pointers. It carries what is left @@ -88,6 +97,7 @@ import { postBounded, promptPointersMode, readStdinJson, + resolveScope, resolveServerUrl, resolveToken, runHookMain, @@ -122,6 +132,8 @@ const TOP_K = Math.round(envNumber("LOOM_PROMPT_PACK_TOP_K", 3, { min: 1, max: 5 const PICK_TIMEOUT_MS = Math.round(envNumber("LOOM_PROMPT_PACK_PICK_TIMEOUT_MS", 6000, { min: 200 })); // The test line is the test gate's: sent in the modes that name a test at edit time. const TEST_LINE = gateAdvises(); +// The test cost line is read from memory: only where that plane runs too. +const COST_LINE = planeEnabled("memory"); const CONSUMER = "claude-code-prompt-pack"; // The lookups a session makes as it starts: SessionStart's, and the MCP headers helper's. @@ -207,6 +219,15 @@ async function testLine(pointers, prompt, root, payload, until) { return check.text; } +/** The test cost line of the session's repository, or "" (`costLine` in + * lib/test-cost.mjs, loaded only for a bug report). Never rejects: nothing + * waits for it when the search answers first. */ +function costNote(payload, cwd, options) { + return import("../lib/test-cost.mjs") + .then(({ costLine }) => costLine(payload.session_id, () => resolveScope(cwd), options)) + .catch(() => ""); +} + async function main() { if (POINTERS === "off") { scheduleExit(0); @@ -253,18 +274,20 @@ async function main() { // The server skips a pick it cannot finish by the deadline, cuts one that runs past it, // and answers with the ranking it has: without a deadline a late pick is no answer at all. if (pick) body.deadline_ms = pickDeadline(left); - const res = await requestLookup(lookup.op, body, { - token, - serverUrl: resolveServerUrl(), - timeoutMs: left, - }); + const options = { token, serverUrl: resolveServerUrl(), timeoutMs: left }; + const asked = requestLookup(lookup.op, body, options); + // Started beside the search, once that is sent, and not waited for after it. + const cost = COST_LINE && pick && payload.session_id ? costNote(payload, cwd, options) : null; + const res = await asked; // A search answer sends its places to edit, and the test line reads the same ones. const sent = lookup.op === "code.search" ? pointerBlock(body, res, prompt, { topK: TOP_K, minConfidence: MIN_CONF }) : null; const text = sent ? sent.text : renderLookup(lookup, body, res, repo); const check = TEST_LINE && text && sent ? await testLine(sent.pointers, prompt, root, payload, until) : ""; + // What the read has answered by now, or nothing: a settled promise wins the race. + const note = cost && text && sent ? await Promise.race([cost, Promise.resolve("")]) : ""; scheduleExit(0); - return text ? packPayload(check ? `${text}\n${check}` : text) : undefined; + return text ? packPayload([text, check, note].filter(Boolean).join("\n")) : undefined; } runHookMain(main); diff --git a/integrations/codex-plugin/hooks/loom-record.mjs b/integrations/codex-plugin/hooks/loom-record.mjs index 7e04f7e2a16..86e4dd01ebb 100644 --- a/integrations/codex-plugin/hooks/loom-record.mjs +++ b/integrations/codex-plugin/hooks/loom-record.mjs @@ -55,8 +55,9 @@ // Each script checks the install's mode and its own switch itself // (`planeEnabled`, `promptPointersMode`, `promptRecallMode`, `gateMode`); the // launcher reads the planes and switches of the scripts the host waits for -// (WAITED) only to leave one unloaded. What the launcher does itself, keeping -// the run's begin, is the ledger's. +// (WAITED) only to leave one unloaded. What the launcher does itself is the +// ledger's, keeping the run's begin, and memory's, reading the test report +// at SessionEnd for the cost of a run that outlived its command. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -79,6 +80,7 @@ import { import { keepRunBegin, runLedgerEnabled } from "../lib/run-hook.mjs"; import { readsOnly } from "../lib/shell-command.mjs"; import { useHooksServer } from "../lib/plugin-options.mjs"; +import { settleRun } from "../lib/test-cost.mjs"; import { startsRunner } from "../lib/test-gate.mjs"; import { endReport, reportPath, showsRefusal, testReportOn, visibleOutput } from "../lib/test-report.mjs"; import { readPrivateFile, removeFile } from "../lib/tmp-state.mjs"; @@ -229,8 +231,14 @@ async function hook(script, event, client) { // An invalid endpoint throws here, before a job file is written or a copy started. resolveServerUrl(); const raw = await readStdinText(); - // The session's test report goes with the session, whatever else is recorded. - if (event === "SessionEnd") endReport(parsePayload(raw).session_id); + // The session's test report goes with the session, whatever else is recorded. A + // run that had not ended when its command returned wrote the report since: what + // it cost is read first, for the session's hand-off to memory. + if (event === "SessionEnd") { + const sessionId = parsePayload(raw).session_id; + if (planeEnabled("memory") && testReportOn()) settleRun(sessionId); + endReport(sessionId); + } if (recordedInHook(event)) { // Left open, a stdin its host never closes would hold this process // through the exit grace after the records are sent. diff --git a/integrations/codex-plugin/hooks/loom-session-memory.mjs b/integrations/codex-plugin/hooks/loom-session-memory.mjs index 03bf03840b2..190b45f6d27 100644 --- a/integrations/codex-plugin/hooks/loom-session-memory.mjs +++ b/integrations/codex-plugin/hooks/loom-session-memory.mjs @@ -5,6 +5,11 @@ // the turns as the facts' source evidence; the hook itself runs no model (see // lib/session-memory.mjs). // +// With the turns goes what the session's test runs cost: one memory.set of +// the repository's test cost row, when the session saw a slow whole run of a +// test file or can add a missing time to the row (lib/test-cost.mjs; +// LOOM_TEST_REPORT=off stops it). +// // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget // through the detached flusher so the agent never waits on the request. @@ -25,7 +30,9 @@ import { sessionToolEchoes, transcriptTurns, } from "../lib/session-memory.mjs"; +import { costPost } from "../lib/test-cost.mjs"; import { sessionStart } from "../lib/test-gate.mjs"; +import { testReportOn } from "../lib/test-report.mjs"; import { editedFiles } from "../lib/working-memory.mjs"; import { readRecalledStash, recalledStashPath } from "../lib/run-hook.mjs"; import { fileSize, parseLines, readTail } from "../lib/transcript.mjs"; @@ -46,11 +53,18 @@ async function main() { const journal = readJournal(sid); removeFile(recalledStashPath(sid)); if (planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken()) { - await handOff(payload, journal, recalledKeys); + const posts = [ + await handOff(payload, journal, recalledKeys), + testReportOn() ? costPost(sid, () => resolveScope(payload.cwd)) : null, + ].filter(Boolean); + // Spawn failure: nothing is lost that the next session cannot say again. + if (posts.length) dispatchFlush({ posts }); } scheduleExit(0); } +/** The flusher's post of the session's turns, or none for a session with + * nothing to extract. */ async function handOff(payload, journal, recalledKeys) { const transcript = payload.transcript_path || ""; // The transcript's turns when the client names one this script can read; @@ -76,8 +90,7 @@ async function handOff(payload, journal, recalledKeys) { // session's own that touches every file its edit tool wrote. const commit = changed && changed.length ? await changeCommit(payload.cwd || process.cwd(), began, edited) : ""; if (commit) body.extra_tags.push(`change:${commit}`); - // Spawn failure: nothing is lost that the next session cannot say again. - dispatchFlush({ posts: [{ op: "memory.set_from_messages", body }] }); + return { op: "memory.set_from_messages", body }; } runHookMain(main); diff --git a/integrations/codex-plugin/hooks/loom-test-report.mjs b/integrations/codex-plugin/hooks/loom-test-report.mjs index da8bcbd2e51..7967c414374 100644 --- a/integrations/codex-plugin/hooks/loom-test-report.mjs +++ b/integrations/codex-plugin/hooks/loom-test-report.mjs @@ -21,9 +21,14 @@ // notes the refusal, so no later command and no later start of the session // gets the option. // -// No request, nothing stored in Loom, a bounded read of one private file, and -// silence on every error. It reads the session's own record of its test runs -// and sends nothing, so it runs in every mode. +// Where the memory plane runs, the hook also notes what a pytest run of one +// test file cost, from the report's head, in the session's private state +// (lib/test-cost.mjs): the session's end hands the cost of a slow whole run +// to memory, and a later session's prompt carries it. +// +// No request, a bounded read of one private file, and silence on every +// error. It reads the session's own record of its test runs and sends +// nothing, so it runs in every mode. // // LOOM_TEST_REPORT=off disable (or the `test_report` install option) @@ -36,6 +41,8 @@ import { runHookMain, scheduleExit, } from "../lib/loom-client.mjs"; +import { noteCommand } from "../lib/test-cost.mjs"; +import { fileRun } from "../lib/test-gate.mjs"; import { digest, newReport, @@ -50,6 +57,8 @@ import { } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); +// What a run cost is memory's: noted only where that plane runs. +const COST = planeEnabled("memory"); // True of a command the option did not reach too (one run in the sandbox). const REFUSED = "Loom: this command's pytest does not accept the report option Loom added (`--junitxml`), and a run that got it ended with `unrecognized arguments`. The option is removed for the rest of this session: run the command again if it ended that way."; @@ -60,12 +69,14 @@ function answer(payload) { const seen = sessionId ? seenReport(sessionId) : null; if (!seen) return null; const output = visibleOutput(payload); - if (rejectsOption(commandText(payload.tool_input), output, reportPath(sessionId))) { + const command = commandText(payload.tool_input); + if (rejectsOption(command, output, reportPath(sessionId))) { refuseReport(sessionId); return reportContext(payload, REFUSED); } // Read whatever the output shows: a report left unread would be the next command's. const report = newReport(sessionId, seen); + if (COST) noteCommand(sessionId, fileRun(command, output), report ? report.head : null); if (!report || shownAlready(output)) return null; const cwd = payload.cwd || process.cwd(); return reportContext(payload, digest(report.xml, { root: gitToplevel(cwd) || cwd, cwd, redact: redactSecrets })); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs new file mode 100644 index 00000000000..1c39ad2fb9c --- /dev/null +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -0,0 +1,251 @@ +// What a whole run of a slow test file costs in this repository, told to a +// session before it chooses how to check a change. A session that does not +// know the cost runs the whole file where a selection of it answers in +// seconds. +// +// The number is in the result file the test report has pytest write +// (lib/test-report.mjs): its first testsuite holds the case count and the +// run's seconds. hooks/loom-test-report.mjs notes them for a command that is +// one pytest run of one test file (`noteCommand`), in the session's private +// state: the costliest whole run that passed, and the times of the runs of a +// selection of each file. A run that outlives its shell call writes the file +// after that call's hook ran, so the launcher reads it once more before it +// removes the file at the session's end (`settleRun`). +// +// At the session's end hooks/loom-session-memory.mjs hands one memory row a +// repository to the flusher (`costPost`): a whole run of 60 s or more, where +// the session read no row, or one whose seconds differ by more than a +// quarter. hooks/loom-prompt-pack.mjs reads the row by its key beside a bug +// report's search and prints one line under the pointers (`costLine`). +// +// What leaves the machine is the file's path as pytest names it, a case +// count and seconds, under the repository's id. A path that is absolute, +// leaves the checkout, holds a character outside letters, digits and `._/-`, +// is over 160 characters or is changed by the secret redaction is not noted. + +import { hookClient, postBounded, redactSecrets } from "./loom-client.mjs"; +import { newReport, runCost, seenReport } from "./test-report.mjs"; +import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; + +// A whole run shorter than this is not worth a line in a prompt. +export const MIN_WHOLE_SECONDS = 60; +// The default limit of one shell call under Claude Code. +const CALL_LIMIT_SECONDS = 120; +const MAX_PATH = 160; +// The files whose selected runs a session's state holds, and the runs of each. +const MAX_FILES = 8; +const MAX_SAMPLES = 15; + +// The session's runs: `{ pending, whole, filtered }`. +const RUNS = "test-cost"; +// The repository's row as the session read it: `{ read, row }`. +const ROW = "test-cost-row"; + +/** `file` when it may be sent, else "". */ +function sendable(file) { + const p = String(file || ""); + const plain = p.length <= MAX_PATH && /^(?!\/)[\w./-]+\.py$/.test(p) && !p.split("/").includes(".."); + return plain && redactSecrets(p) === p ? p : ""; +} + +/** Whether a report's `file` (from pytest's root) is the file a command + * names as `path` (from the folder the command ran in). */ +function sameFile(file, path) { + const named = path.replace(/^\.\//, ""); + return file === named || file.endsWith(`/${named}`) || named.endsWith(`/${file}`); +} + +/** Add what `run` cost to `state`, from the head of the report it wrote. A + * report whose first case is in another file is another run's. A whole run + * counts when no case failed: one that stopped at a failure took less. */ +function add(state, run, head) { + const cost = runCost(head); + const file = sendable(cost?.file); + if (!file || !sameFile(file, run.path)) return; + if (run.whole) { + if (!cost.failed && cost.seconds > (state.whole?.seconds ?? -1)) { + state.whole = { path: file, tests: cost.tests, seconds: cost.seconds }; + } + return; + } + const filtered = { ...state.filtered }; + filtered[file] = [...(filtered[file] || []), cost.seconds].slice(-MAX_SAMPLES); + state.filtered = Object.fromEntries(Object.entries(filtered).slice(-MAX_FILES)); +} + +/** + * Note the shell command the test report was read for. `run` is the + * command's one-file pytest run (`fileRun` in lib/test-gate.mjs) or null, and + * `head` the head of the report when a run wrote it since the session's last + * read, else null. + * + * The report is this command's when its output shows pytest's summary. A + * run whose output shows none has not ended: it is kept as the session's + * pending run, and a report that comes with a later command of the same run + * (the same file, whole or selected alike) is counted as that run's. Any + * other command drops the pending run: a report after it could be either's. + */ +export function noteCommand(sessionId, run, head) { + try { + const state = readSessionState(RUNS, sessionId); + const pending = state.pending; + if (!run && !pending) return; + const open = Boolean(run && !run.ended); + const again = Boolean(open && pending && pending.path === run.path && pending.whole === run.whole); + if (head && run && (run.ended || again)) add(state, run, head); + state.pending = open && (!pending || again) ? { path: run.path, whole: run.whole } : undefined; + writeSessionState(RUNS, sessionId, state); + } catch { + /* nothing noted */ + } +} + +/** At the session's end, before its report is removed: a report written + * since the session's last read is the pending run's. One bounded read of + * the session's own file. */ +export function settleRun(sessionId) { + try { + const state = readSessionState(RUNS, sessionId); + if (!state.pending) return; + const seen = seenReport(sessionId); + const report = seen && newReport(sessionId, seen); + if (report) add(state, state.pending, report.head); + state.pending = undefined; + writeSessionState(RUNS, sessionId, state); + } catch { + /* nothing noted */ + } +} + +/** The row's value: one plain-text claim. */ +export function claim({ path, tests, seconds, filtered }) { + const whole = `A whole run of ${path} collects about ${tests} cases and takes about ${seconds} s`; + return filtered ? `${whole}; a run of it filtered with -k takes about ${filtered} s.` : `${whole}.`; +} + +const CLAIM = + /^A whole run of ([\w./-]+\.py) collects about (\d{1,9}) cases and takes about (\d{1,6}) s(?:; a run of it filtered with -k takes about (\d{1,6}) s)?\.$/; + +/** What a row's value claims, `{ path, tests, seconds, filtered? }`; null for + * a value that is not `claim`'s text. */ +export function parseClaim(value) { + const found = typeof value === "string" ? CLAIM.exec(value) : null; + if (!found || !sendable(found[1])) return null; + const filtered = found[4] ? { filtered: Number(found[4]) } : {}; + return { path: found[1], tests: Number(found[2]), seconds: Number(found[3]), ...filtered }; +} + +/** The line a prompt carries. It is made of the claim's parts and never of + * the stored text, so a row written by another hand adds no sentence. */ +export function renderCost({ path, tests, seconds, filtered }) { + const limit = seconds > CALL_LIMIT_SECONDS ? `, longer than the ${CALL_LIMIT_SECONDS} s limit of a shell call` : ""; + return ( + `Test cost in this repository (measured in earlier sessions): a whole run of ${path} collects about ${tests} ` + + `cases and takes about ${seconds} s${limit}.` + + (filtered ? ` A run filtered with -k takes about ${filtered} s.` : "") + + " Check a change with -k selections of the cases it affects." + ); +} + +/** The key of the row of the repository of `scope` (`resolveScope`), "" for a + * checkout with no remote: `//`, the runner as the id. */ +export const costKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/test-cost/pytest` : ""); + +const identity = (scope) => ({ + org: scope.org, + namespace: scope.namespace, + agent: scope.agent, + memory_key: costKey(scope), +}); + +/** + * The line for a prompt of a session that has the test report, or "": the + * repository's row, read once a session (`memory.get` by key, bounded by + * `options.timeoutMs`) and kept in the session's state, a miss too. + * `scopeOf()` is asked only for that read. An answer that does not come, an + * error and a row that is not `claim`'s text give no line; a later prompt + * asks again only after the first two. + */ +export async function costLine(sessionId, scopeOf, options) { + try { + if (!seenReport(sessionId)) return ""; + let held = readSessionState(ROW, sessionId); + if (!held.read) { + const scope = scopeOf(); + if (!costKey(scope)) return ""; + const res = await postBounded("memory.get", { ...identity(scope), fields: ["value", "content_sha256"] }, options); + if (!res) return ""; + const row = res.found ? { ...parseClaim(res.value), sha: String(res.content_sha256 || "") } : null; + held = { read: true, row }; + writeSessionState(ROW, sessionId, held); + } + return held.row?.path ? renderCost(held.row) : ""; + } catch { + return ""; + } +} + +/** The middle of `seconds`, a second at least; undefined for none. */ +function median(seconds) { + const sorted = [...(seconds || [])].sort((a, b) => a - b); + if (!sorted.length) return undefined; + return Math.max(1, Math.round((sorted[(sorted.length - 1) >> 1] + sorted[sorted.length >> 1]) / 2)); +} + +/** + * The claim to store after a session whose runs are `state`, or null for + * none. `row` is the repository's row as the session read it: undefined for + * no read, null for a miss, `{ sha }` for a value that is not `claim`'s text, + * which is left as it is. + * + * The session's costliest whole run is stored when it took + * `MIN_WHOLE_SECONDS` or more and there is no row, the row's seconds for the + * same file differ from it by more than a quarter, or the row is another + * file's and this one took over a quarter longer. Otherwise a row with no + * time for a selected run gets the session's, when it has one for the row's + * file. + */ +export function revised(state, row) { + if (row && !row.path) return null; + const whole = state.whole; + if (whole && whole.seconds >= MIN_WHOLE_SECONDS) { + const apart = row && Math.abs(whole.seconds - row.seconds) > row.seconds / 4; + if (!row || (whole.path === row.path ? apart : whole.seconds > row.seconds * 1.25)) { + const filtered = median(state.filtered?.[whole.path]) ?? (row?.path === whole.path ? row.filtered : undefined); + return { ...whole, ...(filtered ? { filtered } : {}) }; + } + } + const filtered = row && !row.filtered ? median(state.filtered?.[row.path]) : undefined; + return filtered ? { path: row.path, tests: row.tests, seconds: row.seconds, filtered } : null; +} + +/** + * The flusher's post that stores what the session measured, or null; the + * session's cost state is removed either way. One `memory.set` of the + * repository's key: a revision of the row the session read + * (`if_match_sha256`), else a first row (`absent`, which a session that read + * none sends too, and the server refuses where a row is there). The value + * names no file to the server (`files: []`), and its class says a tool + * measured it. + */ +export function costPost(sessionId, scopeOf) { + try { + const state = readSessionState(RUNS, sessionId); + const held = readSessionState(ROW, sessionId); + for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); + const next = revised(state, held.read ? held.row : undefined); + const scope = next ? scopeOf() : null; + if (!costKey(scope)) return null; + const body = { + ...identity(scope), + value: claim(next), + tags: [`repo:${scope.repo.id}`, `source:${hookClient()}`, "test-cost"], + files: [], + source_class: "external", + if_match_sha256: held.row?.sha || "absent", + }; + return { op: "memory.set", body }; + } catch { + return null; + } +} diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 4c24d67e5b4..bbdca463a82 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1352,6 +1352,47 @@ function allRan(output, runs) { ); } +// The options of `PARTIAL` that run a selection of what the paths name. The +// others run no test. +const SELECTS = /^(?:-[km]|--(?:lf|last-failed|sw|stepwise|deselect)\b)/; +// A run that names its own result file, or turns the result file off, +// does not write the session's. +const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; + +/** + * The pytest run of `command` when it is the command's one pytest run, + * started in this checkout (`ranHere`), and names one test file and nothing + * else to run: `{ path, whole, ended }`, else null. `path` is the file as the + * command spells it. `whole` is false for a run of a part of the file: a node + * id after the path, or an option that selects (`SELECTS`). `ended` says the + * visible `output` holds pytest's summary line, so the run finished inside + * the call. A run that prints what pytest knows and exits, or only collects + * (the rest of `PARTIAL`), is none, and so is one that does not write the + * session's result file (`OWN_REPORT`). The word after a flag that may take a + * value is that value and no path (`BARE`); a short flag written with its + * value (`-rf`, `-kparse`, `-n4`) takes none after it. + */ +export function fileRun(command, output = "") { + const text = String(command || "").replace(/\\\n/g, ""); + const runs = [...text.matchAll(PYTEST)]; + if (runs.length !== 1 || !ranHere(text.slice(0, runs[0].index))) return null; + const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); + const named = []; + let value = false; + for (const word of words) { + const flag = word.startsWith("-"); + if (!flag && !value) named.push(word); + value = flag && !word.includes("=") && !BARE.test(word) && !/^-[^-]./.test(word); + } + const file = named.length === 1 ? /^([^\s:]+\.py)(::\S*)?$/.exec(named[0]) : null; + const partial = words.filter((word) => PARTIAL.test(word)); + if (!file || !partial.every((word) => SELECTS.test(word)) || words.some((word) => OWN_REPORT.test(word))) return null; + const ended = String(output || "") + .split(/\r?\n/) + .some((line) => line.length < 300 && SUMMARY.test(line)); + return { path: file[1], whole: !file[2] && !partial.length, ended }; +} + /** * The repo-relative files and directories pytest ran to its summary on the * tree as it stands, read in transcript order (Claude Code rows; sidechains diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index d803e04c828..a73a4fc7e4f 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -6,9 +6,10 @@ // session's shell, and hooks/loom-test-report.mjs adds a digest of that file // to the result of the command that wrote it. // -// Nothing is sent to the server and nothing is stored in Loom. The result -// file is the session's own, owner-only, in the temp folder the hooks keep -// their state in. +// The digest sends nothing to the server. The result file is the session's +// own, owner-only, in the temp folder the hooks keep their state in. What a +// run cost is read from the file's head (`runCost`); lib/test-cost.mjs keeps +// it for the session and hands it to memory at the session's end. import fs from "node:fs"; import path from "node:path"; @@ -19,8 +20,10 @@ import { readSessionState, removeFile, sessionStatePath, writePrivateFile, write /** What marks the line the plugin wrote in the session's shell file. */ const MARKER = "# loom test report"; -// A larger report is not read: a hook's read is bounded. +// A larger report is not read past its head: a hook's read is bounded. const MAX_REPORT_BYTES = 2 * 1024 * 1024; +// The head holds the first testsuite's tag and the first testcase's. +const HEAD_BYTES = 4096; const MAX_GROUPS = 3; const MAX_REASON = 200; const MAX_ID = 160; @@ -115,9 +118,9 @@ export function seenReport(sessionId) { } /** The session's report when a run wrote it since the session saw it as - * `seen`: `{ xml }`, with "" for a report over the read bound, and the file - * noted as seen. null when no run wrote it, or the file is not this user's - * regular file. */ + * `seen`: `{ xml, head }`, with "" as `xml` for a report over the read + * bound and its first `HEAD_BYTES` as `head`, and the file noted as seen. + * null when no run wrote it, or the file is not this user's regular file. */ export function newReport(sessionId, seen) { let fd; try { @@ -128,9 +131,10 @@ export function newReport(sessionId, seen) { if (typeof process.getuid === "function" && st.uid !== process.getuid()) return null; if (st.mtimeMs === seen.mtimeMs && st.size === seen.size) return null; writeSessionState("test-report", sessionId, { mtimeMs: st.mtimeMs, size: st.size }); - if (st.size > MAX_REPORT_BYTES) return { xml: "" }; - const buf = Buffer.alloc(st.size); - return { xml: buf.toString("utf8", 0, fs.readSync(fd, buf, 0, buf.length, 0)) }; + const large = st.size > MAX_REPORT_BYTES; + const buf = Buffer.alloc(large ? HEAD_BYTES : st.size); + const text = buf.toString("utf8", 0, fs.readSync(fd, buf, 0, buf.length, 0)); + return { xml: large ? "" : text, head: text.slice(0, HEAD_BYTES) }; } catch { return null; } finally { @@ -285,6 +289,35 @@ function scan(xml) { return { totals, failed }; } +/** What the run that wrote a result file cost, from the file's `head`: the + * first testsuite's case count, its seconds to the nearest one, how many + * cases failed or ended in an error, and the file of its first testcase, + * which pytest names in the family the option sets ("" where the head holds + * none). null for a head with no whole testsuite tag, no case or no time. */ +export function runCost(head) { + const first = (text, name) => { + try { + return startTags(text, name).next().value; + } catch { + return undefined; + } + }; + const xml = String(head ?? ""); + const suite = first(xml, "testsuite"); + if (!suite) return null; + const has = attributes(suite.attrs); + const tests = Number(has.tests); + const seconds = Number(has.time); + if (!Number.isInteger(tests) || tests < 1 || !has.time || !Number.isFinite(seconds) || seconds < 0) return null; + const testcase = first(xml.slice(suite.end), "testcase"); + return { + tests, + seconds: Math.round(seconds), + failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), + file: testcase ? attributes(testcase.attrs).file || "" : "", + }; +} + /** `text` as one line: its lines trimmed and joined by `; `, by a space after * one that ends in a colon. */ function oneLine(text) { diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 8df74dd9087..5942e32d4a5 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -77,6 +77,10 @@ "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." }, + "integrations/claude-code-plugin/lib/test-cost.mjs:memory.get:c16ad269d7fdfb5f894a:1": { + "category": "reference", + "reason": "Reads the repository's test cost row by its key, which is built from the repository's id, with the scoped identity and a fixed field list; no prompt, transcript, path or file content is sent." + }, "integrations/codex-plugin/hooks/loom-code-shunt.mjs:code.repos:983653c27b6d99198a73:1": { "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." @@ -153,6 +157,10 @@ "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." }, + "integrations/codex-plugin/lib/test-cost.mjs:memory.get:c16ad269d7fdfb5f894a:1": { + "category": "reference", + "reason": "Reads the repository's test cost row by its key, which is built from the repository's id, with the scoped identity and a fixed field list; no prompt, transcript, path or file content is sent." + }, "integrations/cursor/cursor-session-hook.sh::d26a86f07b41aa77289e:0": { "category": "delivery", "reason": "Delegates transcript ingestion to the separately scanned CLI entry point." @@ -390,7 +398,7 @@ "integrations/claude-code-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/claude-code-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/claude-code-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "b4fc5dc1bf717beae23ee0d26e7d1544f2ed1a44a200e310f11c58e515f0fc86", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "f941d1e83d8266834ce224625aa8dc95fb5adfabf374b017b46de7f1fcc3965a", "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "65a0e04dba5319c703c7d267179bb1739014a16d133f6eb6c504ef5c12e596fc", "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/claude-code-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -402,10 +410,11 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", + "integrations/claude-code-plugin/lib/test-cost.mjs": "521211877ccd370f6d922b3b66ab874e944ce70cff110b6964301f5b86756a58", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "b4fc5dc1bf717beae23ee0d26e7d1544f2ed1a44a200e310f11c58e515f0fc86", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "f941d1e83d8266834ce224625aa8dc95fb5adfabf374b017b46de7f1fcc3965a", "integrations/codex-plugin/hooks/loom-session-start.mjs": "65a0e04dba5319c703c7d267179bb1739014a16d133f6eb6c504ef5c12e596fc", "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -417,6 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", + "integrations/codex-plugin/lib/test-cost.mjs": "521211877ccd370f6d922b3b66ab874e944ce70cff110b6964301f5b86756a58", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 5ec3afc76697c8214d0da2bdcc2d65eaae816ccc Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 17:31:22 +0530 Subject: [PATCH 02/24] The test cost row follows its file, and only a -k run counts as filtered A row could not be lowered or replaced once its file got faster, was renamed or was removed, and the prompt kept printing it. The session now keeps its runs by file: the row's own file is revised by a whole run more than a quarter away, down as well as up, another file takes the row with a run over a quarter longer, and any slow run takes a row whose file the checkout no longer holds. The prompt prints no row under 60 s or for a file that is not there. The path is the file's in the checkout, resolved from the command's folder. --lf, --sw, --deselect and -m may run every case, so only a -k run that ran fewer cases than the whole file is a filtered time, and a stored one more than a quarter and two seconds from the session's is replaced. A report is a command's only when its seconds are the ones the command's summary shows: a run the option did not reach writes none. A command that names a runner and starts none keeps the pending run and credits it the report that came. The launcher at SessionEnd no longer resolves a token while it reads the pending run's report: the redaction check runs in the detached copy, before the path is sent, so an agent's hook starts no token exchange. Only a session whose prompt read the row writes, under the agent that wrote the row, so no row is written where no prompt can read it and a revision is not refused for another agent's row. The stored sentence names the repository by its tag, since recall can serve the row in another repository of the namespace. The line says "the default 120 s timeout", which a call can raise. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 88 ++-- integrations/claude-code-plugin/README.md | 20 +- .../claude-code-plugin/hooks/HOOKS.md | 111 ++-- .../hooks/loom-prompt-pack.mjs | 9 +- .../hooks/loom-session-memory.mjs | 6 +- .../hooks/loom-test-report.mjs | 5 +- .../claude-code-plugin/lib/test-cost.mjs | 297 +++++++---- .../claude-code-plugin/lib/test-gate.mjs | 69 ++- .../tests/test-cost.test.mjs | 497 +++++++++++++----- .../codex-plugin/hooks/loom-prompt-pack.mjs | 9 +- .../hooks/loom-session-memory.mjs | 6 +- .../codex-plugin/hooks/loom-test-report.mjs | 5 +- integrations/codex-plugin/lib/test-cost.mjs | 297 +++++++---- integrations/codex-plugin/lib/test-gate.mjs | 69 ++- tests/unit/session_content_senders.json | 12 +- 15 files changed, 979 insertions(+), 521 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index f990a3f0e92..60ae02a4902 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -90,10 +90,11 @@ end of this section are the exceptions. The plugin sends: definitions its changed lines are in, at most four of 120 characters each, read from the hunk headers and the added definition lines of `git diff -U0` (`LOOM_SESSION_MEMORY=off` stops all of it); -- for a pytest run of one test file that passed and took a minute or more, the file's - path, the number of cases it collected and the seconds it and a filtered run of it - took, to `memory.set` at the session's end, as one memory row a repository; a session - that has the test report reads that row with one `memory.get` at its first bug report +- for a whole pytest run of one test file that passed, the file's path in the checkout, + the number of cases it collected and the seconds it and a filtered run of it took, to + `memory.set` at the session's end, as one memory row a repository, which a run of a + minute or more starts; a session that has the test report reads that row with one + `memory.get` at its first bug report ([what a whole run costs](#what-a-whole-run-costs); `LOOM_TEST_REPORT=off` stops both, `LOOM_SESSION_MEMORY=off` the write; Claude Code only); - a run record (the first prompt as its goal, the last reply) and a working-memory note @@ -1653,54 +1654,77 @@ repository is told before it chooses. **What is noted.** After a shell command that holds one pytest run, started in the checkout, that names one test file and nothing else to run, the hook reads the number of cases and the seconds pytest writes at the head of the result file, and keeps them in the -session's private state: +session's private state, by the file: -- a whole run counts when no case failed, and the costliest one is kept; -- a run of a selection of the file (`-k`, `-m`, a node id, `--lf`, `--sw`, `--deselect`) - counts as filtered, and the middle of the session's filtered runs of the file is kept; -- a command with two pytest runs or two paths, and a run that only collects or prints - (`--collect-only`, `--fixtures`), count as neither. +- a whole run counts when no case failed, and the costliest one of each file is kept; +- a run filtered with `-k` counts as filtered, and a file's filtered time is the middle + of the session's filtered runs of it that ran fewer cases than the whole file; +- a run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a + command with two pytest runs or two paths, and a run that only collects or prints + (`--collect-only`, `--fixtures`) count as neither. The result file is the command's when the command's output shows pytest's summary line -and the file's first case is in the test file the command names. A run that outlives its -shell call writes the file after the hook ran: it is read when the session ends, where no -other test command followed it. - -**What is stored.** When the session ends, a whole run of 60 s or more becomes one memory -row for the repository, written with the session's turns (`memory.set`, key +with the seconds the file holds (within a second, or a twentieth of them), and the file's +first case is in the test file the command names. A run that outlives its shell call +writes the file after the hook ran: it is read after the next shell command that names a +test runner and starts none (`pgrep -f pytest`), or when the session ends. A command that +starts another test run in between drops it, since the next result file could be +either's. + +**What is stored.** When the session ends, what it measured goes to the repository's one +memory row, written with the session's turns (`memory.set`, key `repo:/test-cost/pytest`, in the session's namespace): ```text -A whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. +In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. ``` -A session that read a row whose seconds are within a quarter of its own writes nothing. A -row for another test file is replaced only by a run over a quarter longer. The write -revises the row the session read and is create-only for a session that read none, so it -replaces no row the session did not see. Of the run, the path as pytest names it from its -root, the number of cases and the seconds are sent; an absolute path, a path that leaves -the checkout and one the secret redaction would change are not noted. +The sentence names the repository by the tag a session is told at its start, because +recall can serve the row in another repository of the namespace. Only a session whose +bug report read the row writes, a miss included, so it knows what it replaces: + +- with no row, the session's costliest whole run is stored when it took 60 s or more; +- the row's own file is revised by the session's whole run of it when that is more than + a quarter away from the stored seconds, down as well as up, and by its filtered time + when the row has none or the session's is more than a quarter and two seconds away; +- another file takes the row with a whole run of 60 s or more that is over a quarter + longer than the row's file takes, and any such run takes a row whose file the checkout + no longer holds. + +The write names the value the session read (`if_match_sha256`), is create-only after a +miss, and goes under the agent that wrote the row, so it replaces no row the session did +not see. Of the run, the file's path in the checkout, the number of cases and the seconds +are sent; a path that holds a character outside letters, digits and `._/-`, is over 160 +characters or would be changed by the secret redaction is not sent. **What a prompt gets.** A prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: ```text -Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the 120 s limit of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. +Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the limit is printed for a run over 120 s, and the middle sentence where -a filtered run was measured. The row is read with one `memory.get` a session, sent beside -the prompt's search and never waited for past its answer: a read that fails or is slow -adds nothing, and the pointers are printed as they are. The line is made of the row's -path and numbers, so a value someone rewrote is neither printed nor overwritten. +The clause about the timeout is printed for a run over 120 s, the default of a shell call +under Claude Code, and the middle sentence where a filtered run was measured. The row is +read with one `memory.get` a session, sent beside the prompt's search and never waited +for past its answer: a read that fails or is slow adds nothing, and the pointers are +printed as they are. The line is made of the row's path and numbers, so a value someone +rewrote is neither printed nor overwritten. A row whose whole run is under 60 s, or whose +file the checkout does not hold, prints nothing. What it does not do: - it is one row a repository and names one test file, the costliest one a session ran whole; -- a run that outlives its shell call is noted only when no other test command follows it - in the session; -- two repositories' rows in one namespace read alike, so the server's conflict check can +- a session none of whose prompts read the row stores nothing: one with no bug report, + and every session in `memory` mode, with the prompt pointers off or in a repository + this Loom does not index; +- a run that outlives its shell call is noted only where no command that starts another + test run follows it in the session; +- a row whose file was removed stays, unprinted, until a session measures a slow whole + run of another file; +- the row is an ordinary memory row, so recall can serve its sentence, and two + repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key; - it is pytest under Claude Code only: Codex names no file for the result-file option. diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 2930e1357e9..21ffdbe2585 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -133,10 +133,10 @@ space on the server that your token writes to. The hooks and scripts send: of the files the session changed, each with the time it was last written and the names of the definitions its changed lines are in (`LOOM_SESSION_MEMORY=off` stops it); -- for a pytest run of one test file that passed and took a minute or more, the - file's path, the number of cases it collected and the seconds it and a - filtered run of it took, kept as one memory row a repository - (`LOOM_TEST_REPORT=off` or `LOOM_SESSION_MEMORY=off` stops it); +- for a whole pytest run of one test file that passed, the file's path in the + checkout, the number of cases it collected and the seconds it and a filtered + run of it took, kept as one memory row a repository, which a run of a minute + or more starts (`LOOM_TEST_REPORT=off` or `LOOM_SESSION_MEMORY=off` stops it); - the file paths and diff outlines of uncommitted changes (a diff's outline is its file paths, hunk line ranges and usually the enclosing function's name; no other part of a changed line is sent), a record of the session's first prompt @@ -301,7 +301,7 @@ the duplicate, run `claude mcp remove -s user`. | `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. A new or cleared conversation whose checkout is on another branch than the note names gets its primer without the note. 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. The body also names the files the session changed in its checkout (each path and the time it was last written, never its content), which decide the session's fix record whatever tool wrote them, and `HEAD` as the commit that holds them, when its history has a commit of the session's that touches every file its edit tool wrote (the tag `change:`). 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. With the turns goes one `memory.set` of what a slow whole run of one test file cost, where the session measured one (**The test report**, above). `LOOM_SESSION_MEMORY=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. The body also names the files the session changed in its checkout (each path and the time it was last written, never its content), which decide the session's fix record whatever tool wrote them, and `HEAD` as the commit that holds them, when its history has a commit of the session's that touches every file its edit tool wrote (the tag `change:`). 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. With the turns goes one `memory.set` of what a slow whole run of one test file cost, where the session measured one and its bug report read the repository's row (**The test report**, above). `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 names 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. On a server whose default scope is `all_mine`, the request of a checkout with a remote is also answered with the rows you wrote in your other namespaces; such a row reads ` (namespace ""): …`. 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. @@ -324,19 +324,19 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run of a selection of the file (`-k`, `-m`, a node id, `--lf`, `--sw`, `--deselect`) counts as filtered. A command with two pytest runs or two paths and a run that only collects count as neither. A run that outlives its shell call is read when the session ends, where no other test command followed it. At the session's end a whole run of 60 s or more becomes the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace), unless the row the session read is within a quarter of it: +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner and starts none (`pgrep -f pytest`), or when the session ends, where no command that starts another test run followed it. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text -A whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. +In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. ``` -Of the run, only the path as pytest names it from its root, the number of cases and the seconds are sent; an absolute path, or one the secret redaction would change, is not noted. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: +Only a session whose bug report read the row writes, a miss included. With no row, its costliest whole run is stored when it took 60 s or more. The row's own file is revised when the session's whole run of it is more than a quarter away from the stored seconds, down as well as up, or its filtered time is. Another file takes the row with a whole run of 60 s or more that is over a quarter longer, and any such run takes a row whose file the checkout no longer holds. The write names the value the session read and goes under the agent that wrote the row. Of the run, only the file's path in the checkout, the number of cases and the seconds are sent; a path the secret redaction would change is not sent. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: ```text -Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the 120 s limit of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. +Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the limit is printed for a run over 120 s, and the middle sentence where a filtered run was measured. The row is read once a session, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, and `code` mode all three. The row is an ordinary memory: `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, and `code` mode all three; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 85c40a24cb6..f911b6949fb 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -941,20 +941,22 @@ in. repository (**loom-test-report**, below, **The cost of a run**): `Test cost in this repository (measured in earlier sessions): a whole run of collects about cases and takes about s, longer than the -120 s limit of a shell call. A run filtered with -k takes about s. -Check a change with -k selections of the cases it affects.` The clause - about the - limit is printed for a run over 120 s, and the middle sentence where a - filtered run was measured (`renderCost` in lib/test-cost.mjs). The hook - reads the row by its key with one `memory.get`, sent beside the search - and inside its bound, and never waits for it past the search's answer: an - answer that has not come by then, an error and a miss print nothing, and - the pointers are the same bytes with or without the line. The row as it - was read, a miss too, is kept in the session's state, so a session asks - once; a read that failed or came late is asked again at the next bug - report. The line is made of the row's path and numbers and never of its - text: a value that is not the stored sentence prints nothing. It needs - the memory plane and a session that has the test report. +default 120 s timeout of a shell call. A run filtered with -k takes about + s. Check a change with -k selections of the cases it affects.` The + clause about the timeout is printed for a run over 120 s, the default of + a shell call under Claude Code, and the middle sentence where a filtered + run was measured (`renderCost` in lib/test-cost.mjs). The hook reads the + row by its key with one `memory.get`, sent beside the search and inside + its bound, and never waits for it past the search's answer: an answer + that has not come by then, an error and a miss print nothing, and the + pointers are the same bytes with or without the line. The row as it was + read, a miss too, is kept in the session's state with its hash and the + agent that wrote it, so a session asks once; a read that failed or came + late is asked again at the next bug report. The line is made of the row's + path and numbers and never of its text: a value that is not the stored + sentence prints nothing. Nor does a row whose whole run is under 60 s, or + whose file the checkout does not hold. It needs the memory plane and a + session that has the test report. **The listwise pick.** For a request that reads as a bug report (twelve words or more, or the vocabulary of a failure, as the search reads it) the search carries `rerank: "builtin:pick"`. On a server that names a pick @@ -1334,40 +1336,57 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that test file and nothing else to run (`fileRun` in lib/test-gate.mjs): the case count and the seconds of the report's first `testsuite` (`runCost`, read from the file's first 4,096 bytes, also for a file - over the 2 MB bound). The session's private state keeps the costliest - whole run in which no case failed, and the seconds of each run of a - selection of a file (`-k`, `-m`, a node id, `--lf`, `--sw`, - `--deselect`). A run that only collects or prints is neither, and a - command with two pytest runs or two paths is noted as nothing - (lib/test-cost.mjs). + over the 2 MB bound). The session's private state keeps, for each of + the eight files it ran last, the costliest whole run in which no case + failed and the case count and seconds of each run filtered with `-k`. + A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, + `--deselect`, which may run every case), a run that only collects or + prints, and a command with two pytest runs or two paths are noted as + nothing (lib/test-cost.mjs). The file is the one the command names, + from the payload's folder and the command's one `cd`, where it is + there. The report is the command's when the command's visible output shows - pytest's summary line and the report's first case is in the file the - command names. A run whose output shows no summary has not ended: one - that outlives its shell call writes the file after the hook ran. It is - kept as the session's pending run, and the launcher reads the report - once more at SessionEnd, before it removes the file. Any other test - command in between drops the pending run, since the next report could - be either's. + pytest's summary line with the seconds the report holds, within a + second or a twentieth of them, and the report's first case is in the + file the command names: a run the option did not reach writes no + report, and the one read after it is an earlier run's. A run whose + output shows no summary has not ended: one that outlives its shell + call writes the file after the hook ran. It is kept as the session's + pending run. A report that comes with a later command is its own when + that command names a test runner and starts none (`pgrep -f pytest`, + `mayRunTests` in lib/test-gate.mjs), and the launcher reads the report + once more at SessionEnd, before it removes the file, without reading a + token. A command that starts another test run in between drops the + pending run, since the next report could be either's. At SessionEnd `loom-session-memory` hands one `memory.set` to the - flusher, with the session's turns, when the whole run took 60 s or - more and the session read no row, or read one whose seconds differ - from it by more than a quarter. A row for another file is replaced - only by a run over a quarter longer, and a row with no time for a - selected run gets the middle of the session's. The key is - `repo:/test-cost/pytest`, one row a repository in the session's - namespace, tagged `repo:`, `source:` and `test-cost`, with - `files: []`, so that no file's memory serves it, and - `source_class: "external"`. The value is one sentence: - `A whole run of collects about cases and takes about s; -a run of it filtered with -k takes about s.` The write revises the row - the session read at a prompt (`if_match_sha256`) and is create-only - (`absent`) for a session that read none, so it replaces no row the - session did not see; a value that is not that sentence is left as it - is. - What leaves the machine is the path as pytest names it from its root, - the case count and the seconds. A path that is absolute, leaves the - checkout, holds a character outside letters, digits and `._/-`, is over - 160 characters or is changed by the secret redaction is not noted. + flusher, with the session's turns, where a prompt of the session read + the row, a miss included, and its runs say something the row does not + (`revised`). With no row, the costliest whole run is stored when it + took 60 s or more. The row's own file is revised by the session's + whole run of it when that is more than a quarter away from the stored + seconds, down as well as up, and by the middle of its filtered runs + that ran fewer cases than the whole file, when the row has no such time + or one more than a quarter and two seconds away. Another file takes the + row with a whole run of 60 s or more that is over a quarter longer than + the row's file takes, and any such run takes a row whose file the + checkout no longer holds. The key is `repo:/test-cost/pytest`, one + row a repository in the session's namespace, tagged `repo:`, + `source:` and `test-cost`, with `files: []`, so that no file's + memory serves it, and `source_class: "external"`. The value is one + sentence, which names the repository by its tag because recall can + serve the row in another repository of the namespace: + `In the repository tagged repo:, a whole run of collects +about cases and takes about s; a run of it filtered with -k takes +about s.` The write revises the row the session read + (`if_match_sha256`), under the agent that wrote it, and is create-only + (`absent`) after a miss, so it replaces no row the session did not + see; a value that is not that sentence is left as it is. A session + none of whose prompts read the row stores nothing. + What leaves the machine is the file's path in the checkout, the case + count and the seconds. A path that holds a character outside letters, + digits and `._/-`, is over 160 characters or is changed by the secret + redaction is not sent, and neither is a file that is gone by the + session's end. `loom-prompt-pack` prints the row under a bug report's pointers (**The test cost line**, above). `LOOM_SESSION_MEMORY=off` stops the write, and a session in code-only mode notes, stores and prints nothing. diff --git a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index 88979bed0ec..487bdd9c985 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -49,7 +49,8 @@ // seconds, the seconds of a run filtered with -k, and to check a change with // -k selections. The row is read by its key once a session, beside the search // and inside the prompt's bound, and the line is sent only when that read has -// answered by the time the search has: it never holds the pointers back. +// answered by the time the search has: it never holds the pointers back. A +// row whose file the checkout does not hold prints nothing. // // A search whose query reads as a bug report (twelve words or more, or a word // such as `error` or `crash`) asks the server's pick model @@ -222,9 +223,9 @@ async function testLine(pointers, prompt, root, payload, until) { /** The test cost line of the session's repository, or "" (`costLine` in * lib/test-cost.mjs, loaded only for a bug report). Never rejects: nothing * waits for it when the search answers first. */ -function costNote(payload, cwd, options) { +function costNote(payload, root, cwd, options) { return import("../lib/test-cost.mjs") - .then(({ costLine }) => costLine(payload.session_id, () => resolveScope(cwd), options)) + .then(({ costLine }) => costLine(payload.session_id, root, () => resolveScope(cwd), options)) .catch(() => ""); } @@ -277,7 +278,7 @@ async function main() { const options = { token, serverUrl: resolveServerUrl(), timeoutMs: left }; const asked = requestLookup(lookup.op, body, options); // Started beside the search, once that is sent, and not waited for after it. - const cost = COST_LINE && pick && payload.session_id ? costNote(payload, cwd, options) : null; + const cost = COST_LINE && pick && payload.session_id ? costNote(payload, root, cwd, options) : null; const res = await asked; // A search answer sends its places to edit, and the test line reads the same ones. const sent = diff --git a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs index 190b45f6d27..0107f4563d2 100644 --- a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs @@ -6,8 +6,8 @@ // lib/session-memory.mjs). // // With the turns goes what the session's test runs cost: one memory.set of -// the repository's test cost row, when the session saw a slow whole run of a -// test file or can add a missing time to the row (lib/test-cost.mjs; +// the repository's test cost row, where the session's runs of a test file say +// something the row one of its prompts read does not (lib/test-cost.mjs; // LOOM_TEST_REPORT=off stops it). // // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget @@ -55,7 +55,7 @@ async function main() { if (planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken()) { const posts = [ await handOff(payload, journal, recalledKeys), - testReportOn() ? costPost(sid, () => resolveScope(payload.cwd)) : null, + testReportOn() ? costPost(sid, payload.cwd, () => resolveScope(payload.cwd)) : null, ].filter(Boolean); // Spawn failure: nothing is lost that the next session cannot say again. if (posts.length) dispatchFlush({ posts }); diff --git a/integrations/claude-code-plugin/hooks/loom-test-report.mjs b/integrations/claude-code-plugin/hooks/loom-test-report.mjs index 7967c414374..c21d7559d69 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-report.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-report.mjs @@ -42,7 +42,6 @@ import { scheduleExit, } from "../lib/loom-client.mjs"; import { noteCommand } from "../lib/test-cost.mjs"; -import { fileRun } from "../lib/test-gate.mjs"; import { digest, newReport, @@ -76,9 +75,9 @@ function answer(payload) { } // Read whatever the output shows: a report left unread would be the next command's. const report = newReport(sessionId, seen); - if (COST) noteCommand(sessionId, fileRun(command, output), report ? report.head : null); - if (!report || shownAlready(output)) return null; const cwd = payload.cwd || process.cwd(); + if (COST) noteCommand(sessionId, { command, output, head: report ? report.head : null, cwd }); + if (!report || shownAlready(output)) return null; return reportContext(payload, digest(report.xml, { root: gitToplevel(cwd) || cwd, cwd, redact: redactSecrets })); } diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 1c39ad2fb9c..943e5437363 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -7,93 +7,118 @@ // (lib/test-report.mjs): its first testsuite holds the case count and the // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private -// state: the costliest whole run that passed, and the times of the runs of a -// selection of each file. A run that outlives its shell call writes the file -// after that call's hook ran, so the launcher reads it once more before it -// removes the file at the session's end (`settleRun`). +// state: for each file, the costliest whole run that passed and the runs +// filtered with -k. A run that outlives its shell call writes the file after +// that call's hook ran, so the launcher reads it once more before it removes +// the file at the session's end (`settleRun`). // -// At the session's end hooks/loom-session-memory.mjs hands one memory row a -// repository to the flusher (`costPost`): a whole run of 60 s or more, where -// the session read no row, or one whose seconds differ by more than a -// quarter. hooks/loom-prompt-pack.mjs reads the row by its key beside a bug -// report's search and prints one line under the pointers (`costLine`). +// hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key +// beside a bug report's search and prints one line under the pointers +// (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the +// row to the flusher (`costPost`), where the session's runs say something +// the row it read does not (`revised`). // -// What leaves the machine is the file's path as pytest names it, a case -// count and seconds, under the repository's id. A path that is absolute, -// leaves the checkout, holds a character outside letters, digits and `._/-`, -// is over 160 characters or is changed by the secret redaction is not noted. +// What leaves the machine is the file's path in the checkout, a case count +// and seconds, under the repository's id. A path that holds a character +// outside letters, digits and `._/-`, is over 160 characters or is changed by +// the secret redaction is not sent. -import { hookClient, postBounded, redactSecrets } from "./loom-client.mjs"; +import fs from "node:fs"; +import path from "node:path"; +import { gitToplevel, hookClient, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; +import { fileRun, mayRunTests } from "./test-gate.mjs"; import { newReport, runCost, seenReport } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; // A whole run shorter than this is not worth a line in a prompt. -export const MIN_WHOLE_SECONDS = 60; -// The default limit of one shell call under Claude Code. -const CALL_LIMIT_SECONDS = 120; +const MIN_WHOLE_SECONDS = 60; +// The default timeout of one shell call under Claude Code. +const CALL_TIMEOUT_SECONDS = 120; const MAX_PATH = 160; -// The files whose selected runs a session's state holds, and the runs of each. +// The files whose runs a session's state holds, and the filtered runs of each. const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, whole, filtered }`. +// The session's runs: `{ pending, files }`, by each file's absolute path. const RUNS = "test-cost"; // The repository's row as the session read it: `{ read, row }`. const ROW = "test-cost-row"; -/** `file` when it may be sent, else "". */ +const isFile = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isFile()); + +/** `file`, a path in the checkout, when it may be sent, else "". */ function sendable(file) { const p = String(file || ""); const plain = p.length <= MAX_PATH && /^(?!\/)[\w./-]+\.py$/.test(p) && !p.split("/").includes(".."); return plain && redactSecrets(p) === p ? p : ""; } -/** Whether a report's `file` (from pytest's root) is the file a command - * names as `path` (from the folder the command ran in). */ -function sameFile(file, path) { - const named = path.replace(/^\.\//, ""); - return file === named || file.endsWith(`/${named}`) || named.endsWith(`/${file}`); +/** Two measures of one thing, in whole seconds, differ by more than a + * quarter of the stored one, and by more than their rounding. */ +const apart = (seen, stored) => Math.abs(seen - stored) > Math.max(stored / 4, 2); + +/** `run` (`fileRun`) with `file`, the absolute path of the file it names, or + * null where the command names none that is there. The payload's `cwd` is + * the session's folder before the command or after it, so the run's own + * `cd` is tried first and then left out. */ +function located(run, cwd) { + if (!run) return null; + const file = [path.resolve(cwd, run.dir, run.path), path.resolve(cwd, run.path)].find(isFile); + return file ? { ...run, file } : null; } /** Add what `run` cost to `state`, from the head of the report it wrote. A - * report whose first case is in another file is another run's. A whole run - * counts when no case failed: one that stopped at a failure took less. */ + * report whose first case is in another file is another run's (pytest names + * the file from its root, a folder at or above the file's). A whole run + * counts when no case failed: one that stopped at a failure took less. The + * file is put last, so the bound drops the one least recently run. */ function add(state, run, head) { const cost = runCost(head); - const file = sendable(cost?.file); - if (!file || !sameFile(file, run.path)) return; - if (run.whole) { - if (!cost.failed && cost.seconds > (state.whole?.seconds ?? -1)) { - state.whole = { path: file, tests: cost.tests, seconds: cost.seconds }; - } - return; - } - const filtered = { ...state.filtered }; - filtered[file] = [...(filtered[file] || []), cost.seconds].slice(-MAX_SAMPLES); - state.filtered = Object.fromEntries(Object.entries(filtered).slice(-MAX_FILES)); + if (!cost?.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; + const { [run.file]: seen = {}, ...files } = state.files || {}; + const whole = run.whole && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); + const next = { + ...seen, + ...(whole ? { whole: { tests: cost.tests, seconds: cost.seconds } } : {}), + ...(run.whole ? {} : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), + }; + if (next.whole || next.filtered) files[run.file] = next; + state.files = Object.fromEntries(Object.entries(files).slice(-MAX_FILES)); } /** - * Note the shell command the test report was read for. `run` is the - * command's one-file pytest run (`fileRun` in lib/test-gate.mjs) or null, and - * `head` the head of the report when a run wrote it since the session's last - * read, else null. + * Note a shell command the test report was read for: its text, its visible + * `output`, the `head` of the report when a run wrote it since the session's + * last read (else null), and the payload's `cwd`. * - * The report is this command's when its output shows pytest's summary. A - * run whose output shows none has not ended: it is kept as the session's - * pending run, and a report that comes with a later command of the same run - * (the same file, whole or selected alike) is counted as that run's. Any - * other command drops the pending run: a report after it could be either's. + * The report is the command's when the command is one pytest run of one test + * file (`fileRun`) and its output shows pytest's summary with the seconds + * the report holds: a run the option did not reach writes no report, and the + * one read after it is an earlier run's. A run whose output shows no summary + * has not ended: it is kept as the session's pending run. A report that + * comes with a later command is the pending run's when that command starts + * the same run again, or starts no test run at all (`mayRunTests`), as a + * command that only names a runner does. Any other command drops the pending + * run: a report after it could be either's. */ -export function noteCommand(sessionId, run, head) { +export function noteCommand(sessionId, { command, output, head, cwd }) { try { + const run = located(fileRun(command, output), cwd || process.cwd()); const state = readSessionState(RUNS, sessionId); const pending = state.pending; if (!run && !pending) return; - const open = Boolean(run && !run.ended); - const again = Boolean(open && pending && pending.path === run.path && pending.whole === run.whole); - if (head && run && (run.ended || again)) add(state, run, head); - state.pending = open && (!pending || again) ? { path: run.path, whole: run.whole } : undefined; + if (!run && !mayRunTests(command)) { + if (!head) return; + add(state, pending, head); + state.pending = undefined; + } else { + const open = Boolean(run && run.seconds === null); + const again = Boolean(open && pending && pending.file === run.file && pending.whole === run.whole); + // The summary's seconds and the report's are two clocks on one run. + const ended = run && !open && Math.abs(run.seconds - runCost(head)?.seconds) <= Math.max(1, run.seconds / 20); + if (head && (again || ended)) add(state, run, head); + state.pending = open && (!pending || again) ? { file: run.file, whole: run.whole } : undefined; + } writeSessionState(RUNS, sessionId, state); } catch { /* nothing noted */ @@ -102,7 +127,7 @@ export function noteCommand(sessionId, run, head) { /** At the session's end, before its report is removed: a report written * since the session's last read is the pending run's. One bounded read of - * the session's own file. */ + * the session's own file, and no token is read. */ export function settleRun(sessionId) { try { const state = readSessionState(RUNS, sessionId); @@ -117,31 +142,36 @@ export function settleRun(sessionId) { } } -/** The row's value: one plain-text claim. */ -export function claim({ path, tests, seconds, filtered }) { - const whole = `A whole run of ${path} collects about ${tests} cases and takes about ${seconds} s`; +/** The row's value for the repository whose id is `repo`: one plain-text + * claim. It names the repository by the tag a session is told at its start, + * so recall in another repository of the namespace does not serve it as + * that repository's. */ +export function claim(repo, { path: file, tests, seconds, filtered }) { + const whole = `In the repository tagged repo:${repo}, a whole run of ${file} collects about ${tests} cases and takes about ${seconds} s`; return filtered ? `${whole}; a run of it filtered with -k takes about ${filtered} s.` : `${whole}.`; } const CLAIM = - /^A whole run of ([\w./-]+\.py) collects about (\d{1,9}) cases and takes about (\d{1,6}) s(?:; a run of it filtered with -k takes about (\d{1,6}) s)?\.$/; + /^In the repository tagged repo:(\w+), a whole run of ([\w./-]+\.py) collects about (\d{1,9}) cases and takes about (\d{1,6}) s(?:; a run of it filtered with -k takes about (\d{1,6}) s)?\.$/; -/** What a row's value claims, `{ path, tests, seconds, filtered? }`; null for - * a value that is not `claim`'s text. */ -export function parseClaim(value) { +/** What a row's value claims of the repository whose id is `repo`, + * `{ path, tests, seconds, filtered? }`; null for a value that is not + * `claim`'s text. */ +export function parseClaim(repo, value) { const found = typeof value === "string" ? CLAIM.exec(value) : null; - if (!found || !sendable(found[1])) return null; - const filtered = found[4] ? { filtered: Number(found[4]) } : {}; - return { path: found[1], tests: Number(found[2]), seconds: Number(found[3]), ...filtered }; + if (!found || found[1] !== repo || !sendable(found[2])) return null; + const filtered = found[5] ? { filtered: Number(found[5]) } : {}; + return { path: found[2], tests: Number(found[3]), seconds: Number(found[4]), ...filtered }; } /** The line a prompt carries. It is made of the claim's parts and never of * the stored text, so a row written by another hand adds no sentence. */ -export function renderCost({ path, tests, seconds, filtered }) { - const limit = seconds > CALL_LIMIT_SECONDS ? `, longer than the ${CALL_LIMIT_SECONDS} s limit of a shell call` : ""; +export function renderCost({ path: file, tests, seconds, filtered }) { + const slow = + seconds > CALL_TIMEOUT_SECONDS ? `, longer than the default ${CALL_TIMEOUT_SECONDS} s timeout of a shell call` : ""; return ( - `Test cost in this repository (measured in earlier sessions): a whole run of ${path} collects about ${tests} ` + - `cases and takes about ${seconds} s${limit}.` + + `Test cost in this repository (measured in earlier sessions): a whole run of ${file} collects about ${tests} ` + + `cases and takes about ${seconds} s${slow}.` + (filtered ? ` A run filtered with -k takes about ${filtered} s.` : "") + " Check a change with -k selections of the cases it affects." ); @@ -151,98 +181,137 @@ export function renderCost({ path, tests, seconds, filtered }) { * checkout with no remote: `//`, the runner as the id. */ export const costKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/test-cost/pytest` : ""); -const identity = (scope) => ({ +/** The row's identity: under the agent that wrote the row, where the session + * read one. A read finds another agent's row, and a write names its own. */ +const identity = (scope, agent) => ({ org: scope.org, namespace: scope.namespace, - agent: scope.agent, + agent: agent || scope.agent, memory_key: costKey(scope), }); /** - * The line for a prompt of a session that has the test report, or "": the - * repository's row, read once a session (`memory.get` by key, bounded by - * `options.timeoutMs`) and kept in the session's state, a miss too. - * `scopeOf()` is asked only for that read. An answer that does not come, an - * error and a row that is not `claim`'s text give no line; a later prompt - * asks again only after the first two. + * The line for a prompt of a session that has the test report, in the + * checkout at `root`, or "": the repository's row, read once a session + * (`memory.get` by key, bounded by `options.timeoutMs`) and kept in the + * session's state, a miss too, with the agent that wrote it. `scopeOf()` is + * asked only for that read. An answer that does not come and an error give no + * line, and a later prompt asks again. A row gives none whose value is not + * `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose + * file the checkout does not hold. */ -export async function costLine(sessionId, scopeOf, options) { +export async function costLine(sessionId, root, scopeOf, options) { try { if (!seenReport(sessionId)) return ""; let held = readSessionState(ROW, sessionId); if (!held.read) { const scope = scopeOf(); if (!costKey(scope)) return ""; - const res = await postBounded("memory.get", { ...identity(scope), fields: ["value", "content_sha256"] }, options); + const fields = ["value", "content_sha256", "agent"]; + const res = await postBounded("memory.get", { ...identity(scope), fields }, options); if (!res) return ""; - const row = res.found ? { ...parseClaim(res.value), sha: String(res.content_sha256 || "") } : null; - held = { read: true, row }; + const found = { sha: String(res.content_sha256 || ""), agent: String(res.agent || "") }; + held = { read: true, row: res.found ? { ...parseClaim(scope.repo.id, res.value), ...found } : null }; writeSessionState(ROW, sessionId, held); } - return held.row?.path ? renderCost(held.row) : ""; + const row = held.row; + const printed = row?.path && row.seconds >= MIN_WHOLE_SECONDS && isFile(path.join(root, row.path)); + return printed ? renderCost(row) : ""; } catch { return ""; } } -/** The middle of `seconds`, a second at least; undefined for none. */ -function median(seconds) { - const sorted = [...(seconds || [])].sort((a, b) => a - b); +/** The middle of the seconds of the `samples` (`[tests, seconds]`) that ran + * fewer cases than the `tests` of the whole file, a second at least; + * undefined for none. A -k run that left no case out is no selection. */ +function median(samples, tests) { + const sorted = (samples || []) + .filter((sample) => sample[0] < tests) + .map((sample) => sample[1]) + .sort((a, b) => a - b); if (!sorted.length) return undefined; return Math.max(1, Math.round((sorted[(sorted.length - 1) >> 1] + sorted[sorted.length >> 1]) / 2)); } /** - * The claim to store after a session whose runs are `state`, or null for - * none. `row` is the repository's row as the session read it: undefined for - * no read, null for a miss, `{ sha }` for a value that is not `claim`'s text, - * which is left as it is. + * The claim to store after a session, or null for none. `runs` holds what + * the session measured, by each file's path in the checkout: `{ whole, + * filtered }`. `row` is the repository's row: null for none, `{ sha }` for a + * value that is not `claim`'s text, which is left as it is, and a claim with + * `gone` set where the checkout no longer holds its file, which any slow + * whole run then replaces. * - * The session's costliest whole run is stored when it took - * `MIN_WHOLE_SECONDS` or more and there is no row, the row's seconds for the - * same file differ from it by more than a quarter, or the row is another - * file's and this one took over a quarter longer. Otherwise a row with no - * time for a selected run gets the session's, when it has one for the row's - * file. + * The row's own file is revised by the session's runs of it: its whole run, + * where that is more than a quarter away from the stored seconds, down as + * well as up, and the middle of its filtered runs, where the row has none or + * one more than a quarter away. Another file takes the row with a whole run + * of `MIN_WHOLE_SECONDS` or more that is over a quarter longer than the + * row's file takes. */ -export function revised(state, row) { +export function revised(runs, row) { if (row && !row.path) return null; - const whole = state.whole; - if (whole && whole.seconds >= MIN_WHOLE_SECONDS) { - const apart = row && Math.abs(whole.seconds - row.seconds) > row.seconds / 4; - if (!row || (whole.path === row.path ? apart : whole.seconds > row.seconds * 1.25)) { - const filtered = median(state.filtered?.[whole.path]) ?? (row?.path === whole.path ? row.filtered : undefined); - return { ...whole, ...(filtered ? { filtered } : {}) }; - } + const stored = row && !row.gone ? row : null; + let next = null; + if (stored) { + const own = runs[stored.path] || {}; + const whole = own.whole && apart(own.whole.seconds, stored.seconds) ? own.whole : stored; + const filtered = median(own.filtered, whole.tests); + const kept = filtered && (!stored.filtered || apart(filtered, stored.filtered)) ? filtered : stored.filtered; + next = { path: stored.path, tests: whole.tests, seconds: whole.seconds, ...(kept ? { filtered: kept } : {}) }; + } + const [file, seen] = + Object.entries(runs) + .filter(([other, run]) => other !== stored?.path && run.whole) + .sort((a, b) => b[1].whole.seconds - a[1].whole.seconds)[0] || []; + if (seen && seen.whole.seconds >= MIN_WHOLE_SECONDS && !(next && seen.whole.seconds <= next.seconds * 1.25)) { + const filtered = median(seen.filtered, seen.whole.tests); + next = { path: file, ...seen.whole, ...(filtered ? { filtered } : {}) }; + } + const same = stored && ["path", "tests", "seconds", "filtered"].every((part) => next[part] === stored[part]); + return same ? null : next; +} + +/** What the session measured, by each file's path in the checkout at + * `root`, for the files that are still there and may be sent. */ +function measured(state, root) { + const runs = {}; + for (const [file, seen] of Object.entries(state.files || {})) { + const rel = isFile(file) ? sendable(pathUnder(root, file)) : ""; + if (rel) runs[rel] = seen; } - const filtered = row && !row.filtered ? median(state.filtered?.[row.path]) : undefined; - return filtered ? { path: row.path, tests: row.tests, seconds: row.seconds, filtered } : null; + return runs; } /** * The flusher's post that stores what the session measured, or null; the - * session's cost state is removed either way. One `memory.set` of the - * repository's key: a revision of the row the session read - * (`if_match_sha256`), else a first row (`absent`, which a session that read - * none sends too, and the server refuses where a row is there). The value - * names no file to the server (`files: []`), and its class says a tool - * measured it. + * session's cost state is removed either way. Only a session whose prompt + * read the row stores, a miss included: it knows what it replaces, and where + * no prompt can read the row no session writes one. One `memory.set` of the + * repository's key follows where `revised` has a claim: a revision of the + * row as read (`if_match_sha256`, under the row's agent), else a first row + * (`absent`). The value names no file to the server (`files: []`), and its + * class says a tool measured it. */ -export function costPost(sessionId, scopeOf) { +export function costPost(sessionId, cwd, scopeOf) { try { const state = readSessionState(RUNS, sessionId); const held = readSessionState(ROW, sessionId); for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); - const next = revised(state, held.read ? held.row : undefined); + const root = held.read && state.files ? gitToplevel(cwd) : ""; + const runs = root ? measured(state, root) : {}; + if (!Object.keys(runs).length) return null; + const row = held.row?.path ? { ...held.row, gone: !isFile(path.join(root, held.row.path)) } : held.row; + const next = revised(runs, row); const scope = next ? scopeOf() : null; if (!costKey(scope)) return null; const body = { - ...identity(scope), - value: claim(next), + ...identity(scope, row?.agent), + value: claim(scope.repo.id, next), tags: [`repo:${scope.repo.id}`, `source:${hookClient()}`, "test-cost"], files: [], source_class: "external", - if_match_sha256: held.row?.sha || "absent", + if_match_sha256: row?.sha || "absent", }; return { op: "memory.set", body }; } catch { diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index bbdca463a82..26d02f4c102 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1352,9 +1352,11 @@ function allRan(output, runs) { ); } -// The options of `PARTIAL` that run a selection of what the paths name. The -// others run no test. -const SELECTS = /^(?:-[km]|--(?:lf|last-failed|sw|stepwise|deselect)\b)/; +// A name expression: the one option with which a run counts as a filtered run +// of its file. +const BY_NAME = /^-k/; +// A cluster of short flags that may hold `-k` or `-m` (`-qk parse`). +const CLUSTER = /^-[A-Za-z]+[km]/; // A run that names its own result file, or turns the result file off, // does not write the session's. const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; @@ -1362,20 +1364,32 @@ const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, whole, ended }`, else null. `path` is the file as the - * command spells it. `whole` is false for a run of a part of the file: a node - * id after the path, or an option that selects (`SELECTS`). `ended` says the - * visible `output` holds pytest's summary line, so the run finished inside - * the call. A run that prints what pytest knows and exits, or only collects - * (the rest of `PARTIAL`), is none, and so is one that does not write the - * session's result file (`OWN_REPORT`). The word after a flag that may take a - * value is that value and no path (`BARE`); a short flag written with its - * value (`-rf`, `-kparse`, `-n4`) takes none after it. + * else to run: `{ path, dir, whole, seconds }`, else null. `path` is the file + * as the command spells it and `dir` the folder of the one `cd` before the + * run, "" for none. `whole` is false for a run filtered with `-k`. `seconds` + * is what pytest's summary line in the visible `output` shows, null where + * the output holds none: the run did not finish inside the call. + * + * A run of another part of the file is none: a node id after the path, any + * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run + * every case; the rest run none), or a cluster of short flags that may hold + * one. Nor is a run that does not write the session's result file + * (`OWN_REPORT`), or one after a move the reader cannot follow (a second + * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder the shell + * expands). The word after a flag that may take a value is that value and no + * path (`BARE`); a short flag written with its value (`-rf`, `-kparse`, + * `-n4`) takes none after it. */ export function fileRun(command, output = "") { const text = String(command || "").replace(/\\\n/g, ""); const runs = [...text.matchAll(PYTEST)]; - if (runs.length !== 1 || !ranHere(text.slice(0, runs[0].index))) return null; + const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; + if (runs.length !== 1 || !ranHere(head)) return null; + const cd = [...head.matchAll(CD)]; + const followed = + cd.length < 2 && + (head.match(MOVE) || []).length === cd.length && + cd.every((m) => !/^-$|[$~`*?]/.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; let value = false; @@ -1384,13 +1398,30 @@ export function fileRun(command, output = "") { if (!flag && !value) named.push(word); value = flag && !word.includes("=") && !BARE.test(word) && !/^-[^-]./.test(word); } - const file = named.length === 1 ? /^([^\s:]+\.py)(::\S*)?$/.exec(named[0]) : null; - const partial = words.filter((word) => PARTIAL.test(word)); - if (!file || !partial.every((word) => SELECTS.test(word)) || words.some((word) => OWN_REPORT.test(word))) return null; - const ended = String(output || "") + const other = (word) => !BY_NAME.test(word) && (PARTIAL.test(word) || CLUSTER.test(word) || OWN_REPORT.test(word)); + if (!followed || named.length !== 1 || !/^[^\s:]+\.py$/.test(named[0]) || words.some(other)) return null; + const summary = String(output || "") .split(/\r?\n/) - .some((line) => line.length < 300 && SUMMARY.test(line)); - return { path: file[1], whole: !file[2] && !partial.length, ended }; + .findLast((line) => line.length < 300 && SUMMARY.test(line)); + return { + path: named[0], + dir: cd.length ? unquoted(cd[0][1]) : "", + whole: !words.some((word) => BY_NAME.test(word)), + seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, + }; +} + +// The name of pytest where a command only mentions it. +const PYTEST_NAME = /(? ranHere(text.slice(0, run.index)))) return true; + return startsRunner(text.replace(PYTEST_NAME, " ")); } /** diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 837de38038a..1ae5ff1e0d9 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -17,7 +17,7 @@ import { hostEnv, withTmpdir } from "./host-env.mjs"; import { repoIdentity } from "../lib/loom-client.mjs"; import { cachePathFor } from "../lib/repo-scope.mjs"; import { claim, costKey, noteCommand, parseClaim, renderCost, revised, settleRun } from "../lib/test-cost.mjs"; -import { fileRun } from "../lib/test-gate.mjs"; +import { fileRun, mayRunTests } from "../lib/test-gate.mjs"; import { newReport, reportPath, runCost } from "../lib/test-report.mjs"; import { readJsonFile, sessionStatePath, writeJsonFile, writePrivateFile } from "../lib/tmp-state.mjs"; @@ -26,7 +26,8 @@ const WINDOWS = process.platform === "win32"; const SESSION = "cost-session-1"; const FILE = "tests/test_big.py"; const ORIGIN = "https://github.com/example/app.git"; -const KEY = `repo:${repoIdentity(ORIGIN).id}/test-cost/pytest`; +const REPO = repoIdentity(ORIGIN).id; +const KEY = `repo:${REPO}/test-cost/pytest`; /** A result file as pytest writes it in the family the option sets, which * names each case's file: one suite of `tests` cases that took `time`. */ @@ -45,7 +46,7 @@ const WHOLE_OUTPUT = "8000 passed in 140.21s (0:02:20)"; const FILTERED = report({ tests: 12, time: "2.3" }); const FILTERED_COMMAND = `python -m pytest ${FILE} -k "parse and not slow" -q`; const FILTERED_OUTPUT = "12 passed, 7988 deselected in 2.31s"; -const BOTH = `A whole run of ${FILE} collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s.`; +const BOTH = `In the repository tagged repo:${REPO}, a whole run of ${FILE} collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s.`; // --- the parts ---------------------------------------------------------------- @@ -85,39 +86,38 @@ test("a report over the read bound is read for its head", { skip: WINDOWS }, (t) }); }); -test("a command's one pytest run of one test file is whole or a selection of it", () => { - const whole = { path: FILE, whole: true, ended: false }; +test("a command's one pytest run of one test file is whole or filtered with -k", () => { + const whole = { path: FILE, dir: "", whole: true, seconds: null }; for (const command of [ `pytest ${FILE}`, `python -m pytest ${FILE} -q`, `.venv/bin/python -m pytest -x -q ${FILE} 2>&1 | tail -5`, - `cd pkg && uv run pytest ${FILE} -n auto --tb=short > /tmp/out.txt 2>&1`, `timeout 600 pytest ${FILE} -p no:cacheprovider`, // A short flag written with its value takes none after it. `pytest -rf -n4 ${FILE}`, ]) { assert.deepEqual(fileRun(command), whole, command); } - const part = { path: FILE, whole: false, ended: false }; + const part = { ...whole, whole: false }; for (const command of [ `pytest ${FILE} -k parse`, `pytest ${FILE} -k "parse and not slow" -q`, `pytest -kparse ${FILE}`, - `pytest -m "not slow" ${FILE}`, - `pytest ${FILE}::TestParse::test_empty`, - `pytest "${FILE}::test_case[a-b]" -q`, - `pytest ${FILE} --lf`, - `pytest ${FILE} --deselect ${FILE}::test_slow`, ]) { assert.deepEqual(fileRun(command), part, command); } - // The run ended inside the call when the output holds pytest's summary. - assert.equal(fileRun(`pytest ${FILE} -q`, "........\n8000 passed in 140.21s (0:02:20)").ended, true); - assert.equal(fileRun(`pytest ${FILE} -k parse`, "12 passed, 7988 deselected in 2.31s").ended, true); - assert.equal(fileRun(`pytest ${FILE} -q`, "Command running in background with ID: bash_1").ended, false); + // The folder of the one `cd` before the run. + assert.deepEqual(fileRun(`cd pkg && uv run pytest ${FILE} -n auto --tb=short > /tmp/out.txt 2>&1`), { + ...whole, + dir: "pkg", + }); + // The seconds of pytest's summary, where the output holds it: the run ended inside the call. + assert.equal(fileRun(`pytest ${FILE} -q`, "........\n8000 passed in 140.21s (0:02:20)").seconds, 140.21); + assert.equal(fileRun(`pytest ${FILE} -k parse`, "12 passed, 7988 deselected in 2.31s").seconds, 2.31); + assert.equal(fileRun(`pytest ${FILE} -q`, "Command running in background with ID: bash_1").seconds, null); }); -test("a command with two pytest runs, two paths, no file or no run of its own is no file run", () => { +test("a command with two pytest runs, two paths, another selection or no run of its own is no file run", () => { for (const command of [ `pytest ${FILE} -q; pytest ${FILE} -k parse`, `pytest ${FILE} tests/test_small.py`, @@ -127,6 +127,14 @@ test("a command with two pytest runs, two paths, no file or no run of its own is // The word after a flag that may take a value is that value. `pytest --ignore ${FILE}`, `pytest -p ${FILE}`, + // A selection that may run every case of the file, or is not by name. + `pytest ${FILE} --lf`, + `pytest ${FILE} --sw -q`, + `pytest ${FILE} --deselect ${FILE}::test_slow`, + `pytest -m "not slow" ${FILE}`, + `pytest ${FILE} -qk parse`, + `pytest ${FILE}::TestParse::test_empty`, + `pytest "${FILE}::test_case[a-b]" -q`, // What prints and exits, or only collects, runs nothing to time. `pytest ${FILE} --collect-only -q`, `pytest ${FILE} --co -k parse`, @@ -135,6 +143,11 @@ test("a command with two pytest runs, two paths, no file or no run of its own is `pytest ${FILE} --junitxml=out.xml`, `pytest ${FILE} --junit-xml out.xml -k parse`, `pytest -p no:junitxml ${FILE}`, + // A move the reader cannot follow. + `cd a && cd b && pytest ${FILE}`, + `pushd pkg && pytest ${FILE}`, + `(cd pkg && make build); pytest ${FILE}`, + `cd "$PKG" && pytest ${FILE}`, // Run elsewhere, or not run. `docker exec app pytest ${FILE}`, `echo "pytest ${FILE}"`, @@ -146,25 +159,49 @@ test("a command with two pytest runs, two paths, no file or no run of its own is } }); +test("a command that only names pytest starts no test run", () => { + for (const command of [ + "ps aux | grep pytest", + "pgrep -f pytest", + "tail -5 /tmp/pytest/out.log", + 'git commit -m "fix pytest flake"', + `echo "pytest ${FILE}"`, + `docker exec app pytest ${FILE}`, + ]) { + assert.equal(mayRunTests(command), false, command); + } + for (const command of [ + `pytest ${FILE} -k parse`, + "cd pkg && python -m pytest tests", + "make test", + "tox -e py312", + "ps aux | grep pytest; npm test", + "./runtests.py", + ]) { + assert.equal(mayRunTests(command), true, command); + } +}); + test("the stored claim and the prompt's line, byte for byte", () => { const whole = { path: FILE, tests: 8000, seconds: 140 }; - assert.equal(claim({ ...whole, filtered: 2 }), BOTH); - assert.equal(claim(whole), `A whole run of ${FILE} collects about 8000 cases and takes about 140 s.`); - assert.deepEqual(parseClaim(BOTH), { ...whole, filtered: 2 }); - assert.deepEqual(parseClaim(claim(whole)), whole); + assert.equal(claim(REPO, { ...whole, filtered: 2 }), BOTH); + assert.equal( + claim(REPO, whole), + `In the repository tagged repo:${REPO}, a whole run of ${FILE} collects about 8000 cases and takes about 140 s.`, + ); + assert.deepEqual(parseClaim(REPO, BOTH), { ...whole, filtered: 2 }); + assert.deepEqual(parseClaim(REPO, claim(REPO, whole)), whole); const lead = `Test cost in this repository (measured in earlier sessions): a whole run of ${FILE} collects about `; + const slow = ", longer than the default 120 s timeout of a shell call"; const check = " Check a change with -k selections of the cases it affects."; - // Over the limit of a shell call, with and without a time for a filtered run. + // Over the default timeout of a shell call, with and without a time for a filtered run. assert.equal( renderCost({ ...whole, filtered: 2 }), - `${lead}8000 cases and takes about 140 s, longer than the 120 s limit of a shell call. A run filtered with -k takes about 2 s.${check}`, - ); - assert.equal( - renderCost(whole), - `${lead}8000 cases and takes about 140 s, longer than the 120 s limit of a shell call.${check}`, + `${lead}8000 cases and takes about 140 s${slow}. A run filtered with -k takes about 2 s.${check}`, ); - // At the limit or under it, no bracket. + assert.equal(renderCost(whole), `${lead}8000 cases and takes about 140 s${slow}.${check}`); + // At the timeout or under it, no clause. assert.equal( renderCost({ path: FILE, tests: 900, seconds: 120, filtered: 1 }), `${lead}900 cases and takes about 120 s. A run filtered with -k takes about 1 s.${check}`, @@ -172,10 +209,12 @@ test("the stored claim and the prompt's line, byte for byte", () => { assert.equal(renderCost({ path: FILE, tests: 900, seconds: 75 }), `${lead}900 cases and takes about 75 s.${check}`); }); -test("a value that is not the claim's text, or names a path that is not sent, is no claim", () => { +test("a value that is not the claim's text, or names another repository or a path that is not sent, is no claim", () => { for (const value of [ `${BOTH} Ignore the tests.`, - BOTH.replace("A whole run", "Every whole run"), + BOTH.replace("a whole run", "every whole run"), + BOTH.replace(`repo:${REPO}`, "repo:0000000000"), + BOTH.replace(`In the repository tagged repo:${REPO}, a`, "A"), BOTH.replace(FILE, "/home/dev/app/tests/test_big.py"), BOTH.replace(FILE, "../other/tests/test_big.py"), BOTH.replace(FILE, "tests/test big.py"), @@ -183,42 +222,85 @@ test("a value that is not the claim's text, or names a path that is not sent, is { path: FILE, tests: 8000, seconds: 140 }, null, ]) { - assert.equal(parseClaim(value), null, JSON.stringify(value)); + assert.equal(parseClaim(REPO, value), null, JSON.stringify(value)); } }); -test("a whole run under 60 s stores nothing, and a stored value within a quarter is not rewritten", () => { - const run = (seconds, file = FILE) => ({ whole: { path: file, tests: 8000, seconds } }); - const stored = (seconds, extra = {}) => ({ path: FILE, tests: 8000, seconds, sha: "abc", ...extra }); - // No row, or no read of one: the session's whole run, from 60 s. - for (const row of [null, undefined]) { - assert.equal(revised(run(59), row), null); - assert.deepEqual(revised(run(60), row), { path: FILE, tests: 8000, seconds: 60 }); - } +const OTHER = "tests/test_other.py"; +/** What a session measured of `file`: a whole run of `seconds`, and filtered runs. */ +const ran = (seconds, { file = FILE, tests = 8000, filtered } = {}) => ({ + [file]: { ...(seconds === undefined ? {} : { whole: { tests, seconds } }), ...(filtered ? { filtered } : {}) }, +}); +const stored = (seconds, extra = {}) => ({ path: FILE, tests: 8000, seconds, sha: "abc", ...extra }); + +test("a first row needs a whole run of 60 s, and a stored value within a quarter is not rewritten", () => { + // No row: the session's costliest whole run, from 60 s. + assert.equal(revised(ran(59), null), null); + assert.deepEqual(revised(ran(60), null), { path: FILE, tests: 8000, seconds: 60 }); + assert.equal(revised({ ...ran(100), ...ran(110, { file: OTHER }) }, null).path, OTHER); assert.equal(revised({}, null), null); - assert.equal(revised({ filtered: { [FILE]: [2] } }, null), null); + assert.equal(revised(ran(undefined, { filtered: [[12, 2]] }), null), null); // The same file: rewritten only more than a quarter away from the stored seconds. - for (const seconds of [105, 140, 175]) assert.equal(revised(run(seconds), stored(140)), null, String(seconds)); + for (const seconds of [105, 140, 175]) assert.equal(revised(ran(seconds), stored(140)), null, String(seconds)); for (const seconds of [104, 176]) { - assert.deepEqual(revised(run(seconds), stored(140)), { path: FILE, tests: 8000, seconds }, String(seconds)); + assert.deepEqual(revised(ran(seconds), stored(140)), { path: FILE, tests: 8000, seconds }, String(seconds)); } // Another file takes the row only when it is over a quarter costlier. - assert.equal(revised(run(175, "tests/test_other.py"), stored(140)), null); - assert.equal(revised(run(100, "tests/test_other.py"), stored(140)), null); - assert.equal(revised(run(176, "tests/test_other.py"), stored(140)).path, "tests/test_other.py"); - // The time of a filtered run is the middle of the session's, a second at least; - // a rewrite with none keeps the stored one for the same file. - const filtered = { [FILE]: [3, 1, 2, 40] }; - assert.equal(revised({ ...run(200), filtered }, stored(140)).filtered, 3); - assert.equal(revised({ ...run(200), filtered: { [FILE]: [0, 0] } }, null).filtered, 1); - assert.equal(revised(run(200), stored(140, { filtered: 2 })).filtered, 2); - assert.equal(revised(run(200, "tests/test_other.py"), stored(140, { filtered: 2 })).filtered, undefined); - // A row with no such time gets the session's, with no whole run of its own. - assert.deepEqual(revised({ filtered }, stored(140)), { path: FILE, tests: 8000, seconds: 140, filtered: 3 }); - assert.equal(revised({ filtered }, stored(140, { filtered: 2 })), null); - assert.equal(revised({ filtered: { "tests/test_other.py": [2] } }, stored(140)), null); + assert.equal(revised(ran(175, { file: OTHER }), stored(140)), null); + assert.equal(revised(ran(100, { file: OTHER }), stored(140)), null); + assert.equal(revised(ran(176, { file: OTHER }), stored(140)).path, OTHER); + assert.equal(revised(ran(176, { file: OTHER }), stored(140, { filtered: 2 })).filtered, undefined); // A value another hand wrote is left as it is. - assert.equal(revised({ ...run(300), filtered }, { sha: "abc" }), null); + assert.equal(revised(ran(300, { filtered: [[12, 2]] }), { sha: "abc" }), null); +}); + +test("a file that got faster lowers its row, under 60 s too, and a row whose file is gone is replaced", () => { + // The file was split: its whole run is more than a quarter below the stored one. + assert.deepEqual(revised(ran(40, { tests: 2000 }), stored(140, { filtered: 2 })), { + path: FILE, + tests: 2000, + seconds: 40, + filtered: 2, + }); + // The lowered row is no longer in another file's way. + assert.equal(revised({ ...ran(40), ...ran(70, { file: OTHER }) }, stored(140)).path, OTHER); + assert.equal(revised(ran(70, { file: OTHER }), stored(40)).path, OTHER); + // The checkout no longer holds the row's file: any whole run of 60 s takes the row. + assert.deepEqual(revised(ran(100, { file: OTHER }), stored(140, { gone: true })), { + path: OTHER, + tests: 8000, + seconds: 100, + }); + assert.equal(revised(ran(59, { file: OTHER }), stored(140, { gone: true })), null); + assert.equal(revised({}, stored(140, { gone: true })), null); +}); + +test("the time of a filtered run is the middle of the session's runs that left cases out", () => { + const filtered = [ + [12, 3], + [12, 1], + [30, 2], + [40, 40], + ]; + assert.equal(revised(ran(200, { filtered }), stored(140)).filtered, 3); + assert.equal(revised(ran(200, { filtered: [[5, 0]] }), null).filtered, 1); + // A -k run that ran every case of the file is no selection of it. + assert.equal(revised(ran(200, { filtered: [[8000, 139]] }), null).filtered, undefined); + assert.equal(revised(ran(undefined, { filtered: [[8000, 139]] }), stored(140)), null); + // A rewrite with none keeps the stored one for the same file. + assert.equal(revised(ran(200), stored(140, { filtered: 2 })).filtered, 2); + // A row with no such time gets the session's, with no whole run of its own. + assert.deepEqual(revised(ran(undefined, { filtered }), stored(140)), { + path: FILE, + tests: 8000, + seconds: 140, + filtered: 3, + }); + assert.equal(revised(ran(undefined, { file: OTHER, filtered }), stored(140)), null); + // A stored time is replaced when the session's is more than a quarter and two seconds away. + assert.equal(revised(ran(undefined, { filtered }), stored(140, { filtered: 139 })).filtered, 3); + assert.equal(revised(ran(undefined, { filtered }), stored(140, { filtered: 5 })), null); + assert.equal(revised(ran(undefined, { filtered }), stored(140, { filtered: 2 })), null); }); test("the key is the repository's, and a checkout with no remote has none", () => { @@ -229,95 +311,145 @@ test("the key is the repository's, and a checkout with no remote has none", () = // --- the session's state -------------------------------------------------------- -/** Run `fn` with this process's temp folder a fresh one, removed after the test. */ +/** Run `fn(cwd, file)` with this process's temp folder a fresh one, removed + * after the test: `cwd` is a folder in it that holds FILE, at `file`. */ function inTmp(t, fn) { const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-test-cost-"))); t.after(() => fs.rmSync(tmp, { recursive: true, force: true })); - return withTmpdir(tmp, () => fn(tmp)); + const cwd = path.join(tmp, "work"); + fs.mkdirSync(path.join(cwd, "tests"), { recursive: true }); + fs.writeFileSync(path.join(cwd, FILE), ""); + return withTmpdir(tmp, () => fn(cwd, path.join(cwd, FILE))); } const runs = () => readJsonFile(sessionStatePath("test-cost", SESSION), null); -const head = (xml) => xml.slice(0, 4096); -const ran = (command, output) => fileRun(command, output); - -test("a report is the command's whose output shows the summary", { skip: WINDOWS }, (t) => { - inTmp(t, () => { - noteCommand(SESSION, ran(WHOLE_COMMAND, WHOLE_OUTPUT), head(WHOLE)); - assert.deepEqual(runs(), { whole: { path: FILE, tests: 8000, seconds: 140 } }); - noteCommand(SESSION, ran(FILTERED_COMMAND, FILTERED_OUTPUT), head(FILTERED)); - noteCommand(SESSION, ran(FILTERED_COMMAND, FILTERED_OUTPUT), head(report({ tests: 30, time: "3.6" }))); - assert.deepEqual(runs(), { whole: { path: FILE, tests: 8000, seconds: 140 }, filtered: { [FILE]: [2, 4] } }); +const head = (xml) => (xml === null ? null : xml.slice(0, 4096)); +const STARTED = "Command running in background with ID: bash_1"; + +test("a report is the command's whose output shows the summary with the report's seconds", { + skip: WINDOWS, +}, (t) => { + inTmp(t, (cwd, file) => { + const note = (command, output, xml) => noteCommand(SESSION, { command, output, head: head(xml), cwd }); + const whole = (seconds) => ({ tests: 8000, seconds }); + note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + assert.deepEqual(runs(), { files: { [file]: { whole: whole(140) } } }); + note(FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED); + note(FILTERED_COMMAND, "30 passed, 7970 deselected in 3.61s", report({ tests: 30, time: "3.6" })); + const filtered = [ + [12, 2], + [30, 4], + ]; + assert.deepEqual(runs(), { files: { [file]: { whole: whole(140), filtered } } }); // The costliest whole run stays; one that failed took less than the file costs. - noteCommand(SESSION, ran(WHOLE_COMMAND, "8000 passed in 90.00s"), head(report({ tests: 8000, time: "90.0" }))); - noteCommand( - SESSION, - ran(WHOLE_COMMAND, "1 failed, 7999 passed in 300.00s"), - head(report({ tests: 8000, time: "300.0", failures: 1 })), - ); - assert.equal(runs().whole.seconds, 140); + note(WHOLE_COMMAND, "8000 passed in 90.00s", report({ tests: 8000, time: "90.0" })); + note(WHOLE_COMMAND, "1 failed, 7999 passed in 300.00s", report({ tests: 8000, time: "300.0", failures: 1 })); + assert.deepEqual(runs().files[file].whole, whole(140)); // A command that names the file from another folder, and a report of another file. - noteCommand( - SESSION, - ran("cd tests && pytest test_big.py -q", "8000 passed in 150.00s"), - head(report({ tests: 8000, time: "150.0" })), - ); - assert.equal(runs().whole.seconds, 150); - noteCommand( - SESSION, - ran(WHOLE_COMMAND, "9000 passed in 900.00s"), - head(report({ tests: 9000, time: "900.0", file: "tests/test_other.py" })), - ); - assert.equal(runs().whole.seconds, 150); + note("cd tests && pytest test_big.py -q", "8000 passed in 150.00s", report({ tests: 8000, time: "150.0" })); + assert.deepEqual(runs().files[file].whole, whole(150)); + note(WHOLE_COMMAND, "9000 passed in 900.00s", report({ tests: 9000, time: "900.0", file: "tests/test_other.py" })); + assert.deepEqual(runs().files[file].whole, whole(150)); + // A run the option did not reach wrote no report: the one read after it is an + // earlier run's, and its seconds are not the summary's. + note(`PYTEST_ADDOPTS=-q pytest ${FILE} -k parse`, FILTERED_OUTPUT, report({ tests: 8000, time: "600.0" })); + note(WHOLE_COMMAND, "8000 passed in 2.31s", report({ tests: 8000, time: "600.0" })); + assert.deepEqual(runs(), { files: { [file]: { whole: whole(150), filtered } } }); }); }); -test("a command that is no file run, with no run pending, leaves no state", { skip: WINDOWS }, (t) => { - inTmp(t, () => { - noteCommand(SESSION, ran("make test", "8000 passed in 140.21s"), head(WHOLE)); - noteCommand(SESSION, ran(`pytest ${FILE} -q; pytest ${FILE} -k parse`, WHOLE_OUTPUT), head(WHOLE)); - noteCommand(SESSION, ran(`pytest ${FILE} tests/test_small.py`, WHOLE_OUTPUT), head(WHOLE)); +test("a command that is no file run, or names a file that is not there, leaves no state", { + skip: WINDOWS, +}, (t) => { + inTmp(t, (cwd) => { + const note = (command, output) => noteCommand(SESSION, { command, output, head: head(WHOLE), cwd }); + note("make test", "8000 passed in 140.21s"); + note(`pytest ${FILE} -q; pytest ${FILE} -k parse`, WHOLE_OUTPUT); + note(`pytest ${FILE} tests/test_small.py`, WHOLE_OUTPUT); + note(`pytest ${FILE} --lf -q`, WHOLE_OUTPUT); + note("pytest tests/test_gone.py -q", WHOLE_OUTPUT); + note(`cd elsewhere && pytest ${FILE.replace("big", "gone")} -q`, WHOLE_OUTPUT); assert.equal(runs(), null); }); }); +test("the files a session's state holds are the eight it ran last", { skip: WINDOWS }, (t) => { + inTmp(t, (cwd, file) => { + const note = (name) => { + fs.writeFileSync(path.join(cwd, name), ""); + const xml = report({ tests: 12, time: "2.3", file: name }); + noteCommand(SESSION, { command: `pytest ${name} -k parse -q`, output: FILTERED_OUTPUT, head: head(xml), cwd }); + }; + note(FILE); + for (let i = 0; i < 7; i++) note(`tests/test_${i}.py`); + // Run again, the first file is the one run last: the next file drops another. + note(FILE); + note("tests/test_7.py"); + const held = Object.keys(runs().files); + assert.equal(held.length, 8); + assert.equal(held.includes(file), true); + assert.equal(held.includes(path.join(cwd, "tests/test_0.py")), false); + assert.deepEqual(runs().files[file].filtered, [ + [12, 2], + [12, 2], + ]); + }); +}); + test("a run that outlives its call is pending, and the report at the session's end is its", { skip: WINDOWS }, (t) => { - inTmp(t, () => { - const started = "Command running in background with ID: bash_1"; + inTmp(t, (cwd, file) => { + const note = (xml) => noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, head: head(xml), cwd }); writePrivateFile(reportPath(SESSION), ""); writeJsonFile(sessionStatePath("test-report", SESSION), { mtimeMs: 1, size: 0 }); - noteCommand(SESSION, ran(`pytest ${FILE} -q`, started), null); - assert.deepEqual(runs(), { pending: { path: FILE, whole: true } }); + note(null); + assert.deepEqual(runs(), { pending: { file, whole: true } }); // The same run started again: a report that came since is counted as that run's. - noteCommand(SESSION, ran(`pytest ${FILE} -q`, started), head(report({ tests: 8000, time: "130.0" }))); + note(report({ tests: 8000, time: "130.0" })); assert.deepEqual(runs(), { - pending: { path: FILE, whole: true }, - whole: { path: FILE, tests: 8000, seconds: 130 }, + pending: { file, whole: true }, + files: { [file]: { whole: { tests: 8000, seconds: 130 } } }, }); fs.writeFileSync(reportPath(SESSION), WHOLE); settleRun(SESSION); - assert.deepEqual(runs(), { whole: { path: FILE, tests: 8000, seconds: 140 } }); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); // Nothing pending: the session's end reads nothing. fs.writeFileSync(reportPath(SESSION), report({ tests: 8000, time: "999.0" })); settleRun(SESSION); - assert.equal(runs().whole.seconds, 140); + assert.equal(runs().files[file].whole.seconds, 140); + }); +}); + +test("a command that only names a runner keeps the pending run, and a report that came with it is that run's", { + skip: WINDOWS, +}, (t) => { + inTmp(t, (cwd, file) => { + const note = (command, output, xml) => noteCommand(SESSION, { command, output, head: head(xml), cwd }); + note(`pytest ${FILE} -q`, STARTED, null); + // The session looks for its run from the shell: nothing is dropped. + note("ps aux | grep pytest", "dev 4242 python -m pytest", null); + note("tail -5 /tmp/pytest/out.log", "....", null); + assert.deepEqual(runs(), { pending: { file, whole: true } }); + // The run has ended by the next look. + note("pgrep -f pytest", "", WHOLE); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); }); }); test("a report that could be another run's is counted for none", { skip: WINDOWS }, (t) => { - inTmp(t, () => { - const started = "Command running in background with ID: bash_1"; - const pending = () => noteCommand(SESSION, ran(`pytest ${FILE} -q`, started), null); + inTmp(t, (cwd, file) => { + const note = (command, output, xml) => noteCommand(SESSION, { command, output, head: head(xml), cwd }); + const pending = () => note(`pytest ${FILE} -q`, STARTED, null); // Another command that starts a runner: the next report could be its. pending(); - noteCommand(SESSION, null, null); + note("make test", "ok", null); assert.deepEqual(runs(), {}); // A selection of the file started while the whole run is open. pending(); - noteCommand(SESSION, ran(`pytest ${FILE} -k parse`, started), head(WHOLE)); + note(`pytest ${FILE} -k parse`, STARTED, WHOLE); assert.deepEqual(runs(), {}); // A run whose summary is in sight takes the report; the open run's is lost. pending(); - noteCommand(SESSION, ran(FILTERED_COMMAND, FILTERED_OUTPUT), head(FILTERED)); - assert.deepEqual(runs(), { filtered: { [FILE]: [2] } }); + note(FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED); + assert.deepEqual(runs(), { files: { [file]: { filtered: [[12, 2]] } } }); }); }); @@ -336,10 +468,14 @@ const LINE = renderCost({ path: FILE, tests: 8000, seconds: 140, filtered: 2 }); // Reads as a bug report: the prompt hook asks for the pick, and for the cost line. const BUG = "Nested record prefixes raise an error before validation when the parser is given an empty prefix."; +/** The repository's row as memory.get answers it. */ +const row = (value = BOTH, agent = "claude-code") => ({ found: true, value, content_sha256: "abc", agent }); + /** A stub Loom server. `get` is what memory.get answers, or a status for a * failure; `getStall` holds that answer back. A search answers after 300 ms, - * as one that embeds its query does. */ -async function loom(t, { get = { found: false }, getStall = 0 } = {}) { + * as one that embeds its query does. Each request is kept with what + * `mark()` says of the moment it came. */ +async function loom(t, { get = { found: false }, getStall = 0, mark = () => ({}) } = {}) { const requests = []; const server = http.createServer((req, res) => { let raw = ""; @@ -352,7 +488,7 @@ async function loom(t, { get = { found: false }, getStall = 0 } = {}) { } catch { /* answered as an empty body */ } - requests.push({ op, body, headers: req.headers }); + requests.push({ op, body, headers: req.headers, ...mark() }); const failed = op === "memory.get" && typeof get === "number"; const answer = op === "code.search" ? SEARCH : op === "memory.get" ? get : op === "run.begin" ? { run_id: body.run_id } : {}; @@ -371,13 +507,17 @@ async function loom(t, { get = { found: false }, getStall = 0 } = {}) { return { url: `http://127.0.0.1:${server.address().port}`, requests, sent }; } -/** A checkout of ORIGIN that configures pytest, a home and a temp folder, in - * a session that has the test report; `server` holds the checkout's index. */ +/** A checkout of ORIGIN that configures pytest and holds FILE, a home and a + * temp folder, in a session that has the test report; `server` holds the + * checkout's index. */ function sandbox(t, server) { const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-test-cost-hook-"))); const box = { dir, home: path.join(dir, "home"), tmp: path.join(dir, "tmp"), cwd: path.join(dir, "work") }; for (const d of [box.home, box.tmp, box.cwd]) fs.mkdirSync(d); fs.writeFileSync(path.join(box.cwd, "pytest.ini"), "[pytest]\n"); + box.file = path.join(box.cwd, FILE); + fs.mkdirSync(path.dirname(box.file)); + fs.writeFileSync(box.file, ""); const git = (...a) => execFileSync("git", a, { cwd: box.cwd, stdio: "ignore" }); git("init", "-q", "-b", "main"); git("remote", "add", "origin", ORIGIN); @@ -474,16 +614,17 @@ test("a slow whole run and a filtered one are noted, and the session's end store const server = await loom(t); const box = sandbox(t, server); const quiet = { code: 0, stdout: "", stderr: "" }; + // The session's bug report finds no row. + assert.equal(context(await ask(box)), BLOCK); assert.deepEqual(await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE), quiet); assert.deepEqual(await afterCommand(box, FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED), quiet); assert.deepEqual(readJsonFile(box.runs, null), { - whole: { path: FILE, tests: 8000, seconds: 140 }, - filtered: { [FILE]: [2] }, + files: { [box.file]: { whole: { tests: 8000, seconds: 140 }, filtered: [[12, 2]] } }, }); await settled(box); // Nothing of it has left the machine before the session ends. assert.deepEqual(server.sent("memory.set"), []); - assert.deepEqual(server.sent("memory.get"), []); + assert.equal(server.sent("memory.get").length, 1); assert.deepEqual(await endSession(box), quiet); await arrived(server, box, "memory.set"); @@ -495,14 +636,28 @@ test("a slow whole run and a filtered one are noted, and the session's end store agent: "claude-code", memory_key: KEY, value: BOTH, - tags: [`repo:${repoIdentity(ORIGIN).id}`, "source:claude-code", "test-cost"], + tags: [`repo:${REPO}`, "source:claude-code", "test-cost"], files: [], source_class: "external", - // The session read no row: the server writes only where there is none. + // The session's read was a miss: the server writes only where there is no row. if_match_sha256: "absent", }); assert.equal(stored.headers["x-loom-session-protection"], undefined); - // The session's cost state went with the hand-off. + // The session's cost state went with the hand-off, and nothing was read again. + assert.equal(fs.existsSync(box.runs), false); + assert.equal(server.sent("memory.get").length, 1); +}); + +test("a session whose prompts read no row stores nothing", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + // A question is no bug report: it reads no row. + assert.equal(context(await ask(box, { prompt: "How are nested record prefixes combined?" })), BLOCK); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.get"), []); + assert.deepEqual(server.sent("memory.set"), []); assert.equal(fs.existsSync(box.runs), false); }); @@ -511,19 +666,41 @@ test("a whole run that outlived its call is stored from the report it wrote befo }, async (t) => { const server = await loom(t); const box = sandbox(t, server); - await afterCommand(box, `python -m pytest ${FILE} -q`, "Command running in background with ID: bash_1"); - assert.deepEqual(readJsonFile(box.runs, null), { pending: { path: FILE, whole: true } }); + await ask(box); + await afterCommand(box, `python -m pytest ${FILE} -q`, STARTED); + assert.deepEqual(readJsonFile(box.runs, null), { pending: { file: box.file, whole: true } }); // The run ends after its command's hook ran, and no test command follows it. fs.writeFileSync(box.report, WHOLE); await endSession(box); await arrived(server, box, "memory.set"); - assert.equal( - server.sent("memory.set")[0].body.value, - `A whole run of ${FILE} collects about 8000 cases and takes about 140 s.`, - ); + assert.equal(server.sent("memory.set")[0].body.value, claim(REPO, { path: FILE, tests: 8000, seconds: 140 })); assert.equal(fs.existsSync(box.report), false); }); +test("the launcher at an agent's SessionEnd reads the pending run's report and exchanges no token", { + skip: WINDOWS, +}, async (t) => { + const probe = { report: "" }; + const server = await loom(t, { mark: () => ({ report: fs.existsSync(probe.report) }) }); + const box = sandbox(t, server); + probe.report = box.report; + await afterCommand(box, `python -m pytest ${FILE} -q`, STARTED); + await settled(box); + fs.writeFileSync(box.report, WHOLE); + // An agent whose token is due: the exchange is a child process the caller waits for. + await endSession(box, { LOOM_API_KEY: "", LOOM_CLIENT_ID: "ci", LOOM_WORKLOAD_TOKEN: "workload-proof" }); + await settled(box); + assert.deepEqual(readJsonFile(box.runs, null), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); + // The launcher removes the report before it starts the copy: an exchange that + // found the report there was the launcher's own. + const exchanges = server.sent("/oauth/token"); + assert.ok(exchanges.length > 0, "the detached copy asked for a token"); + assert.deepEqual( + exchanges.map((r) => r.report), + exchanges.map(() => false), + ); +}); + test("nothing is stored for a whole run under 60 s, a command of two runs or two paths, or with a switch off", { skip: WINDOWS, }, async (t) => { @@ -531,25 +708,26 @@ test("nothing is stored for a whole run under 60 s, a command of two runs or two const cases = [ // Under 60 s. [`python -m pytest ${FILE} -q`, "8000 passed in 59.40s", report({ tests: 8000, time: "59.4" }), {}], - // Two runs, and two paths: nothing is noted. + // Two runs, two paths, and a selection that is not by name: nothing is noted. [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}], [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}], + [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}], // The session hands nothing to memory, or has no test report. [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }], [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_TEST_REPORT: "off" }], ]; for (const [command, output, xml, extra] of cases) { const box = sandbox(t, server); + await ask(box, { extra }); await afterCommand(box, command, output, xml, extra); await endSession(box, extra); await settled(box); } assert.deepEqual(server.sent("memory.set"), []); - assert.deepEqual(server.sent("memory.get"), []); }); test("code-only mode notes nothing, stores nothing and prints no line", { skip: WINDOWS }, async (t) => { - const server = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" } }); + const server = await loom(t, { get: row() }); const box = sandbox(t, server); const code = { LOOM_MODE: "code" }; await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, code); @@ -564,7 +742,7 @@ test("code-only mode notes nothing, stores nothing and prints no line", { skip: test("a bug report carries the repository's cost line under its pointers, from one read a session", { skip: WINDOWS, }, async (t) => { - const server = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" } }); + const server = await loom(t, { get: row() }); const box = sandbox(t, server); const first = await ask(box); assert.deepEqual({ code: first.code, stderr: first.stderr }, { code: 0, stderr: "" }); @@ -575,7 +753,7 @@ test("a bug report carries the repository's cost line under its pointers, from o namespace: "coding", agent: "claude-code", memory_key: KEY, - fields: ["value", "content_sha256"], + fields: ["value", "content_sha256", "agent"], }); assert.equal(read.headers["x-loom-session-protection"], undefined); // The next bug report has the line from the session's state. @@ -591,23 +769,62 @@ test("a bug report carries the repository's cost line under its pointers, from o assert.deepEqual(server.sent("memory.set"), []); }); -test("a session that read the row revises it when its whole run is over a quarter away", { +test("a row prints no line when its file is not in the checkout or its whole run is under 60 s", { skip: WINDOWS, }, async (t) => { - const server = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" } }); + const gone = await loom(t, { get: row() }); + const box = sandbox(t, gone); + fs.rmSync(box.file); + assert.equal(context(await ask(box)), BLOCK); + assert.equal(gone.sent("memory.get").length, 1); + + const fast = await loom(t, { get: row(claim(REPO, { path: FILE, tests: 2000, seconds: 40, filtered: 2 })) }); + assert.equal(context(await ask(sandbox(t, fast))), BLOCK); + assert.equal(fast.sent("memory.get").length, 1); +}); + +test("a session that read the row revises it, under the agent that wrote it", { skip: WINDOWS }, async (t) => { + const server = await loom(t, { get: row(BOTH, "team-bot") }); const box = sandbox(t, server); await ask(box); await afterCommand(box, WHOLE_COMMAND, "9000 passed in 200.00s", report({ tests: 9000, time: "200.0" })); await endSession(box); await arrived(server, box, "memory.set"); const { body } = server.sent("memory.set")[0]; - // The same key, against the value the session read; the stored filtered time stays. + // The same key and agent, against the value the session read; the stored filtered time stays. assert.equal(body.memory_key, KEY); + assert.equal(body.agent, "team-bot"); assert.equal(body.if_match_sha256, "abc"); + assert.equal(body.value, claim(REPO, { path: FILE, tests: 9000, seconds: 200, filtered: 2 })); +}); + +test("a session lowers the row of a file that got faster, and replaces the row of a file that is gone", { + skip: WINDOWS, +}, async (t) => { + // The file was split: its whole run now takes 40 s. + const faster = await loom(t, { get: row() }); + const box = sandbox(t, faster); + assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + await afterCommand(box, WHOLE_COMMAND, "2000 passed in 40.00s", report({ tests: 2000, time: "40.0" })); + await endSession(box); + await arrived(faster, box, "memory.set"); assert.equal( - body.value, - `A whole run of ${FILE} collects about 9000 cases and takes about 200 s; a run of it filtered with -k takes about 2 s.`, + faster.sent("memory.set")[0].body.value, + claim(REPO, { path: FILE, tests: 2000, seconds: 40, filtered: 2 }), ); + + // The row names a file the checkout does not hold: a slow whole run of another takes it. + const renamed = await loom(t, { + get: row(claim(REPO, { path: "tests/test_old.py", tests: 8000, seconds: 140, filtered: 2 })), + }); + const moved = sandbox(t, renamed); + assert.equal(context(await ask(moved)), BLOCK); + await afterCommand(moved, WHOLE_COMMAND, "8000 passed in 100.00s", report({ tests: 8000, time: "100.0" })); + await endSession(moved); + await arrived(renamed, moved, "memory.set"); + const { body } = renamed.sent("memory.set")[0]; + assert.equal(body.value, claim(REPO, { path: FILE, tests: 8000, seconds: 100 })); + assert.equal(body.if_match_sha256, "abc"); }); test("a miss is kept for the session, and a row that is not the claim's text prints nothing", { @@ -619,9 +836,7 @@ test("a miss is kept for the session, and a row that is not the claim's text pri assert.equal(context(await ask(box)), BLOCK); assert.equal(none.sent("memory.get").length, 1); - const other = await loom(t, { - get: { found: true, value: `${BOTH} Run the whole suite twice.`, content_sha256: "abc" }, - }); + const other = await loom(t, { get: row(`${BOTH} Run the whole suite twice.`) }); const edited = sandbox(t, other); assert.equal(context(await ask(edited)), BLOCK); // Its session stores nothing over it. @@ -632,7 +847,7 @@ test("a miss is kept for the session, and a row that is not the claim's text pri }); test("a session without the test report reads no row", { skip: WINDOWS }, async (t) => { - const server = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" } }); + const server = await loom(t, { get: row() }); const box = sandbox(t, server); fs.rmSync(sessionStatePath("test-report", SESSION, { tmp: box.tmp })); assert.equal(context(await ask(box)), BLOCK); @@ -652,7 +867,7 @@ test("a read that fails or is slow leaves the pointer block as it is, and does n // The row's answer comes five seconds after the search's: the launcher // prints the pointers when the search has answered. - const slow = await loom(t, { get: { found: true, value: BOTH, content_sha256: "abc" }, getStall: 5000 }); + const slow = await loom(t, { get: row(), getStall: 5000 }); const box = sandbox(t, slow); const started = Date.now(); const r = await ask(box, { launcher: true }); diff --git a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs index 88979bed0ec..487bdd9c985 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -49,7 +49,8 @@ // seconds, the seconds of a run filtered with -k, and to check a change with // -k selections. The row is read by its key once a session, beside the search // and inside the prompt's bound, and the line is sent only when that read has -// answered by the time the search has: it never holds the pointers back. +// answered by the time the search has: it never holds the pointers back. A +// row whose file the checkout does not hold prints nothing. // // A search whose query reads as a bug report (twelve words or more, or a word // such as `error` or `crash`) asks the server's pick model @@ -222,9 +223,9 @@ async function testLine(pointers, prompt, root, payload, until) { /** The test cost line of the session's repository, or "" (`costLine` in * lib/test-cost.mjs, loaded only for a bug report). Never rejects: nothing * waits for it when the search answers first. */ -function costNote(payload, cwd, options) { +function costNote(payload, root, cwd, options) { return import("../lib/test-cost.mjs") - .then(({ costLine }) => costLine(payload.session_id, () => resolveScope(cwd), options)) + .then(({ costLine }) => costLine(payload.session_id, root, () => resolveScope(cwd), options)) .catch(() => ""); } @@ -277,7 +278,7 @@ async function main() { const options = { token, serverUrl: resolveServerUrl(), timeoutMs: left }; const asked = requestLookup(lookup.op, body, options); // Started beside the search, once that is sent, and not waited for after it. - const cost = COST_LINE && pick && payload.session_id ? costNote(payload, cwd, options) : null; + const cost = COST_LINE && pick && payload.session_id ? costNote(payload, root, cwd, options) : null; const res = await asked; // A search answer sends its places to edit, and the test line reads the same ones. const sent = diff --git a/integrations/codex-plugin/hooks/loom-session-memory.mjs b/integrations/codex-plugin/hooks/loom-session-memory.mjs index 190b45f6d27..0107f4563d2 100644 --- a/integrations/codex-plugin/hooks/loom-session-memory.mjs +++ b/integrations/codex-plugin/hooks/loom-session-memory.mjs @@ -6,8 +6,8 @@ // lib/session-memory.mjs). // // With the turns goes what the session's test runs cost: one memory.set of -// the repository's test cost row, when the session saw a slow whole run of a -// test file or can add a missing time to the row (lib/test-cost.mjs; +// the repository's test cost row, where the session's runs of a test file say +// something the row one of its prompts read does not (lib/test-cost.mjs; // LOOM_TEST_REPORT=off stops it). // // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget @@ -55,7 +55,7 @@ async function main() { if (planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken()) { const posts = [ await handOff(payload, journal, recalledKeys), - testReportOn() ? costPost(sid, () => resolveScope(payload.cwd)) : null, + testReportOn() ? costPost(sid, payload.cwd, () => resolveScope(payload.cwd)) : null, ].filter(Boolean); // Spawn failure: nothing is lost that the next session cannot say again. if (posts.length) dispatchFlush({ posts }); diff --git a/integrations/codex-plugin/hooks/loom-test-report.mjs b/integrations/codex-plugin/hooks/loom-test-report.mjs index 7967c414374..c21d7559d69 100644 --- a/integrations/codex-plugin/hooks/loom-test-report.mjs +++ b/integrations/codex-plugin/hooks/loom-test-report.mjs @@ -42,7 +42,6 @@ import { scheduleExit, } from "../lib/loom-client.mjs"; import { noteCommand } from "../lib/test-cost.mjs"; -import { fileRun } from "../lib/test-gate.mjs"; import { digest, newReport, @@ -76,9 +75,9 @@ function answer(payload) { } // Read whatever the output shows: a report left unread would be the next command's. const report = newReport(sessionId, seen); - if (COST) noteCommand(sessionId, fileRun(command, output), report ? report.head : null); - if (!report || shownAlready(output)) return null; const cwd = payload.cwd || process.cwd(); + if (COST) noteCommand(sessionId, { command, output, head: report ? report.head : null, cwd }); + if (!report || shownAlready(output)) return null; return reportContext(payload, digest(report.xml, { root: gitToplevel(cwd) || cwd, cwd, redact: redactSecrets })); } diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 1c39ad2fb9c..943e5437363 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -7,93 +7,118 @@ // (lib/test-report.mjs): its first testsuite holds the case count and the // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private -// state: the costliest whole run that passed, and the times of the runs of a -// selection of each file. A run that outlives its shell call writes the file -// after that call's hook ran, so the launcher reads it once more before it -// removes the file at the session's end (`settleRun`). +// state: for each file, the costliest whole run that passed and the runs +// filtered with -k. A run that outlives its shell call writes the file after +// that call's hook ran, so the launcher reads it once more before it removes +// the file at the session's end (`settleRun`). // -// At the session's end hooks/loom-session-memory.mjs hands one memory row a -// repository to the flusher (`costPost`): a whole run of 60 s or more, where -// the session read no row, or one whose seconds differ by more than a -// quarter. hooks/loom-prompt-pack.mjs reads the row by its key beside a bug -// report's search and prints one line under the pointers (`costLine`). +// hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key +// beside a bug report's search and prints one line under the pointers +// (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the +// row to the flusher (`costPost`), where the session's runs say something +// the row it read does not (`revised`). // -// What leaves the machine is the file's path as pytest names it, a case -// count and seconds, under the repository's id. A path that is absolute, -// leaves the checkout, holds a character outside letters, digits and `._/-`, -// is over 160 characters or is changed by the secret redaction is not noted. +// What leaves the machine is the file's path in the checkout, a case count +// and seconds, under the repository's id. A path that holds a character +// outside letters, digits and `._/-`, is over 160 characters or is changed by +// the secret redaction is not sent. -import { hookClient, postBounded, redactSecrets } from "./loom-client.mjs"; +import fs from "node:fs"; +import path from "node:path"; +import { gitToplevel, hookClient, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; +import { fileRun, mayRunTests } from "./test-gate.mjs"; import { newReport, runCost, seenReport } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; // A whole run shorter than this is not worth a line in a prompt. -export const MIN_WHOLE_SECONDS = 60; -// The default limit of one shell call under Claude Code. -const CALL_LIMIT_SECONDS = 120; +const MIN_WHOLE_SECONDS = 60; +// The default timeout of one shell call under Claude Code. +const CALL_TIMEOUT_SECONDS = 120; const MAX_PATH = 160; -// The files whose selected runs a session's state holds, and the runs of each. +// The files whose runs a session's state holds, and the filtered runs of each. const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, whole, filtered }`. +// The session's runs: `{ pending, files }`, by each file's absolute path. const RUNS = "test-cost"; // The repository's row as the session read it: `{ read, row }`. const ROW = "test-cost-row"; -/** `file` when it may be sent, else "". */ +const isFile = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isFile()); + +/** `file`, a path in the checkout, when it may be sent, else "". */ function sendable(file) { const p = String(file || ""); const plain = p.length <= MAX_PATH && /^(?!\/)[\w./-]+\.py$/.test(p) && !p.split("/").includes(".."); return plain && redactSecrets(p) === p ? p : ""; } -/** Whether a report's `file` (from pytest's root) is the file a command - * names as `path` (from the folder the command ran in). */ -function sameFile(file, path) { - const named = path.replace(/^\.\//, ""); - return file === named || file.endsWith(`/${named}`) || named.endsWith(`/${file}`); +/** Two measures of one thing, in whole seconds, differ by more than a + * quarter of the stored one, and by more than their rounding. */ +const apart = (seen, stored) => Math.abs(seen - stored) > Math.max(stored / 4, 2); + +/** `run` (`fileRun`) with `file`, the absolute path of the file it names, or + * null where the command names none that is there. The payload's `cwd` is + * the session's folder before the command or after it, so the run's own + * `cd` is tried first and then left out. */ +function located(run, cwd) { + if (!run) return null; + const file = [path.resolve(cwd, run.dir, run.path), path.resolve(cwd, run.path)].find(isFile); + return file ? { ...run, file } : null; } /** Add what `run` cost to `state`, from the head of the report it wrote. A - * report whose first case is in another file is another run's. A whole run - * counts when no case failed: one that stopped at a failure took less. */ + * report whose first case is in another file is another run's (pytest names + * the file from its root, a folder at or above the file's). A whole run + * counts when no case failed: one that stopped at a failure took less. The + * file is put last, so the bound drops the one least recently run. */ function add(state, run, head) { const cost = runCost(head); - const file = sendable(cost?.file); - if (!file || !sameFile(file, run.path)) return; - if (run.whole) { - if (!cost.failed && cost.seconds > (state.whole?.seconds ?? -1)) { - state.whole = { path: file, tests: cost.tests, seconds: cost.seconds }; - } - return; - } - const filtered = { ...state.filtered }; - filtered[file] = [...(filtered[file] || []), cost.seconds].slice(-MAX_SAMPLES); - state.filtered = Object.fromEntries(Object.entries(filtered).slice(-MAX_FILES)); + if (!cost?.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; + const { [run.file]: seen = {}, ...files } = state.files || {}; + const whole = run.whole && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); + const next = { + ...seen, + ...(whole ? { whole: { tests: cost.tests, seconds: cost.seconds } } : {}), + ...(run.whole ? {} : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), + }; + if (next.whole || next.filtered) files[run.file] = next; + state.files = Object.fromEntries(Object.entries(files).slice(-MAX_FILES)); } /** - * Note the shell command the test report was read for. `run` is the - * command's one-file pytest run (`fileRun` in lib/test-gate.mjs) or null, and - * `head` the head of the report when a run wrote it since the session's last - * read, else null. + * Note a shell command the test report was read for: its text, its visible + * `output`, the `head` of the report when a run wrote it since the session's + * last read (else null), and the payload's `cwd`. * - * The report is this command's when its output shows pytest's summary. A - * run whose output shows none has not ended: it is kept as the session's - * pending run, and a report that comes with a later command of the same run - * (the same file, whole or selected alike) is counted as that run's. Any - * other command drops the pending run: a report after it could be either's. + * The report is the command's when the command is one pytest run of one test + * file (`fileRun`) and its output shows pytest's summary with the seconds + * the report holds: a run the option did not reach writes no report, and the + * one read after it is an earlier run's. A run whose output shows no summary + * has not ended: it is kept as the session's pending run. A report that + * comes with a later command is the pending run's when that command starts + * the same run again, or starts no test run at all (`mayRunTests`), as a + * command that only names a runner does. Any other command drops the pending + * run: a report after it could be either's. */ -export function noteCommand(sessionId, run, head) { +export function noteCommand(sessionId, { command, output, head, cwd }) { try { + const run = located(fileRun(command, output), cwd || process.cwd()); const state = readSessionState(RUNS, sessionId); const pending = state.pending; if (!run && !pending) return; - const open = Boolean(run && !run.ended); - const again = Boolean(open && pending && pending.path === run.path && pending.whole === run.whole); - if (head && run && (run.ended || again)) add(state, run, head); - state.pending = open && (!pending || again) ? { path: run.path, whole: run.whole } : undefined; + if (!run && !mayRunTests(command)) { + if (!head) return; + add(state, pending, head); + state.pending = undefined; + } else { + const open = Boolean(run && run.seconds === null); + const again = Boolean(open && pending && pending.file === run.file && pending.whole === run.whole); + // The summary's seconds and the report's are two clocks on one run. + const ended = run && !open && Math.abs(run.seconds - runCost(head)?.seconds) <= Math.max(1, run.seconds / 20); + if (head && (again || ended)) add(state, run, head); + state.pending = open && (!pending || again) ? { file: run.file, whole: run.whole } : undefined; + } writeSessionState(RUNS, sessionId, state); } catch { /* nothing noted */ @@ -102,7 +127,7 @@ export function noteCommand(sessionId, run, head) { /** At the session's end, before its report is removed: a report written * since the session's last read is the pending run's. One bounded read of - * the session's own file. */ + * the session's own file, and no token is read. */ export function settleRun(sessionId) { try { const state = readSessionState(RUNS, sessionId); @@ -117,31 +142,36 @@ export function settleRun(sessionId) { } } -/** The row's value: one plain-text claim. */ -export function claim({ path, tests, seconds, filtered }) { - const whole = `A whole run of ${path} collects about ${tests} cases and takes about ${seconds} s`; +/** The row's value for the repository whose id is `repo`: one plain-text + * claim. It names the repository by the tag a session is told at its start, + * so recall in another repository of the namespace does not serve it as + * that repository's. */ +export function claim(repo, { path: file, tests, seconds, filtered }) { + const whole = `In the repository tagged repo:${repo}, a whole run of ${file} collects about ${tests} cases and takes about ${seconds} s`; return filtered ? `${whole}; a run of it filtered with -k takes about ${filtered} s.` : `${whole}.`; } const CLAIM = - /^A whole run of ([\w./-]+\.py) collects about (\d{1,9}) cases and takes about (\d{1,6}) s(?:; a run of it filtered with -k takes about (\d{1,6}) s)?\.$/; + /^In the repository tagged repo:(\w+), a whole run of ([\w./-]+\.py) collects about (\d{1,9}) cases and takes about (\d{1,6}) s(?:; a run of it filtered with -k takes about (\d{1,6}) s)?\.$/; -/** What a row's value claims, `{ path, tests, seconds, filtered? }`; null for - * a value that is not `claim`'s text. */ -export function parseClaim(value) { +/** What a row's value claims of the repository whose id is `repo`, + * `{ path, tests, seconds, filtered? }`; null for a value that is not + * `claim`'s text. */ +export function parseClaim(repo, value) { const found = typeof value === "string" ? CLAIM.exec(value) : null; - if (!found || !sendable(found[1])) return null; - const filtered = found[4] ? { filtered: Number(found[4]) } : {}; - return { path: found[1], tests: Number(found[2]), seconds: Number(found[3]), ...filtered }; + if (!found || found[1] !== repo || !sendable(found[2])) return null; + const filtered = found[5] ? { filtered: Number(found[5]) } : {}; + return { path: found[2], tests: Number(found[3]), seconds: Number(found[4]), ...filtered }; } /** The line a prompt carries. It is made of the claim's parts and never of * the stored text, so a row written by another hand adds no sentence. */ -export function renderCost({ path, tests, seconds, filtered }) { - const limit = seconds > CALL_LIMIT_SECONDS ? `, longer than the ${CALL_LIMIT_SECONDS} s limit of a shell call` : ""; +export function renderCost({ path: file, tests, seconds, filtered }) { + const slow = + seconds > CALL_TIMEOUT_SECONDS ? `, longer than the default ${CALL_TIMEOUT_SECONDS} s timeout of a shell call` : ""; return ( - `Test cost in this repository (measured in earlier sessions): a whole run of ${path} collects about ${tests} ` + - `cases and takes about ${seconds} s${limit}.` + + `Test cost in this repository (measured in earlier sessions): a whole run of ${file} collects about ${tests} ` + + `cases and takes about ${seconds} s${slow}.` + (filtered ? ` A run filtered with -k takes about ${filtered} s.` : "") + " Check a change with -k selections of the cases it affects." ); @@ -151,98 +181,137 @@ export function renderCost({ path, tests, seconds, filtered }) { * checkout with no remote: `//`, the runner as the id. */ export const costKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/test-cost/pytest` : ""); -const identity = (scope) => ({ +/** The row's identity: under the agent that wrote the row, where the session + * read one. A read finds another agent's row, and a write names its own. */ +const identity = (scope, agent) => ({ org: scope.org, namespace: scope.namespace, - agent: scope.agent, + agent: agent || scope.agent, memory_key: costKey(scope), }); /** - * The line for a prompt of a session that has the test report, or "": the - * repository's row, read once a session (`memory.get` by key, bounded by - * `options.timeoutMs`) and kept in the session's state, a miss too. - * `scopeOf()` is asked only for that read. An answer that does not come, an - * error and a row that is not `claim`'s text give no line; a later prompt - * asks again only after the first two. + * The line for a prompt of a session that has the test report, in the + * checkout at `root`, or "": the repository's row, read once a session + * (`memory.get` by key, bounded by `options.timeoutMs`) and kept in the + * session's state, a miss too, with the agent that wrote it. `scopeOf()` is + * asked only for that read. An answer that does not come and an error give no + * line, and a later prompt asks again. A row gives none whose value is not + * `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose + * file the checkout does not hold. */ -export async function costLine(sessionId, scopeOf, options) { +export async function costLine(sessionId, root, scopeOf, options) { try { if (!seenReport(sessionId)) return ""; let held = readSessionState(ROW, sessionId); if (!held.read) { const scope = scopeOf(); if (!costKey(scope)) return ""; - const res = await postBounded("memory.get", { ...identity(scope), fields: ["value", "content_sha256"] }, options); + const fields = ["value", "content_sha256", "agent"]; + const res = await postBounded("memory.get", { ...identity(scope), fields }, options); if (!res) return ""; - const row = res.found ? { ...parseClaim(res.value), sha: String(res.content_sha256 || "") } : null; - held = { read: true, row }; + const found = { sha: String(res.content_sha256 || ""), agent: String(res.agent || "") }; + held = { read: true, row: res.found ? { ...parseClaim(scope.repo.id, res.value), ...found } : null }; writeSessionState(ROW, sessionId, held); } - return held.row?.path ? renderCost(held.row) : ""; + const row = held.row; + const printed = row?.path && row.seconds >= MIN_WHOLE_SECONDS && isFile(path.join(root, row.path)); + return printed ? renderCost(row) : ""; } catch { return ""; } } -/** The middle of `seconds`, a second at least; undefined for none. */ -function median(seconds) { - const sorted = [...(seconds || [])].sort((a, b) => a - b); +/** The middle of the seconds of the `samples` (`[tests, seconds]`) that ran + * fewer cases than the `tests` of the whole file, a second at least; + * undefined for none. A -k run that left no case out is no selection. */ +function median(samples, tests) { + const sorted = (samples || []) + .filter((sample) => sample[0] < tests) + .map((sample) => sample[1]) + .sort((a, b) => a - b); if (!sorted.length) return undefined; return Math.max(1, Math.round((sorted[(sorted.length - 1) >> 1] + sorted[sorted.length >> 1]) / 2)); } /** - * The claim to store after a session whose runs are `state`, or null for - * none. `row` is the repository's row as the session read it: undefined for - * no read, null for a miss, `{ sha }` for a value that is not `claim`'s text, - * which is left as it is. + * The claim to store after a session, or null for none. `runs` holds what + * the session measured, by each file's path in the checkout: `{ whole, + * filtered }`. `row` is the repository's row: null for none, `{ sha }` for a + * value that is not `claim`'s text, which is left as it is, and a claim with + * `gone` set where the checkout no longer holds its file, which any slow + * whole run then replaces. * - * The session's costliest whole run is stored when it took - * `MIN_WHOLE_SECONDS` or more and there is no row, the row's seconds for the - * same file differ from it by more than a quarter, or the row is another - * file's and this one took over a quarter longer. Otherwise a row with no - * time for a selected run gets the session's, when it has one for the row's - * file. + * The row's own file is revised by the session's runs of it: its whole run, + * where that is more than a quarter away from the stored seconds, down as + * well as up, and the middle of its filtered runs, where the row has none or + * one more than a quarter away. Another file takes the row with a whole run + * of `MIN_WHOLE_SECONDS` or more that is over a quarter longer than the + * row's file takes. */ -export function revised(state, row) { +export function revised(runs, row) { if (row && !row.path) return null; - const whole = state.whole; - if (whole && whole.seconds >= MIN_WHOLE_SECONDS) { - const apart = row && Math.abs(whole.seconds - row.seconds) > row.seconds / 4; - if (!row || (whole.path === row.path ? apart : whole.seconds > row.seconds * 1.25)) { - const filtered = median(state.filtered?.[whole.path]) ?? (row?.path === whole.path ? row.filtered : undefined); - return { ...whole, ...(filtered ? { filtered } : {}) }; - } + const stored = row && !row.gone ? row : null; + let next = null; + if (stored) { + const own = runs[stored.path] || {}; + const whole = own.whole && apart(own.whole.seconds, stored.seconds) ? own.whole : stored; + const filtered = median(own.filtered, whole.tests); + const kept = filtered && (!stored.filtered || apart(filtered, stored.filtered)) ? filtered : stored.filtered; + next = { path: stored.path, tests: whole.tests, seconds: whole.seconds, ...(kept ? { filtered: kept } : {}) }; + } + const [file, seen] = + Object.entries(runs) + .filter(([other, run]) => other !== stored?.path && run.whole) + .sort((a, b) => b[1].whole.seconds - a[1].whole.seconds)[0] || []; + if (seen && seen.whole.seconds >= MIN_WHOLE_SECONDS && !(next && seen.whole.seconds <= next.seconds * 1.25)) { + const filtered = median(seen.filtered, seen.whole.tests); + next = { path: file, ...seen.whole, ...(filtered ? { filtered } : {}) }; + } + const same = stored && ["path", "tests", "seconds", "filtered"].every((part) => next[part] === stored[part]); + return same ? null : next; +} + +/** What the session measured, by each file's path in the checkout at + * `root`, for the files that are still there and may be sent. */ +function measured(state, root) { + const runs = {}; + for (const [file, seen] of Object.entries(state.files || {})) { + const rel = isFile(file) ? sendable(pathUnder(root, file)) : ""; + if (rel) runs[rel] = seen; } - const filtered = row && !row.filtered ? median(state.filtered?.[row.path]) : undefined; - return filtered ? { path: row.path, tests: row.tests, seconds: row.seconds, filtered } : null; + return runs; } /** * The flusher's post that stores what the session measured, or null; the - * session's cost state is removed either way. One `memory.set` of the - * repository's key: a revision of the row the session read - * (`if_match_sha256`), else a first row (`absent`, which a session that read - * none sends too, and the server refuses where a row is there). The value - * names no file to the server (`files: []`), and its class says a tool - * measured it. + * session's cost state is removed either way. Only a session whose prompt + * read the row stores, a miss included: it knows what it replaces, and where + * no prompt can read the row no session writes one. One `memory.set` of the + * repository's key follows where `revised` has a claim: a revision of the + * row as read (`if_match_sha256`, under the row's agent), else a first row + * (`absent`). The value names no file to the server (`files: []`), and its + * class says a tool measured it. */ -export function costPost(sessionId, scopeOf) { +export function costPost(sessionId, cwd, scopeOf) { try { const state = readSessionState(RUNS, sessionId); const held = readSessionState(ROW, sessionId); for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); - const next = revised(state, held.read ? held.row : undefined); + const root = held.read && state.files ? gitToplevel(cwd) : ""; + const runs = root ? measured(state, root) : {}; + if (!Object.keys(runs).length) return null; + const row = held.row?.path ? { ...held.row, gone: !isFile(path.join(root, held.row.path)) } : held.row; + const next = revised(runs, row); const scope = next ? scopeOf() : null; if (!costKey(scope)) return null; const body = { - ...identity(scope), - value: claim(next), + ...identity(scope, row?.agent), + value: claim(scope.repo.id, next), tags: [`repo:${scope.repo.id}`, `source:${hookClient()}`, "test-cost"], files: [], source_class: "external", - if_match_sha256: held.row?.sha || "absent", + if_match_sha256: row?.sha || "absent", }; return { op: "memory.set", body }; } catch { diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index bbdca463a82..26d02f4c102 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1352,9 +1352,11 @@ function allRan(output, runs) { ); } -// The options of `PARTIAL` that run a selection of what the paths name. The -// others run no test. -const SELECTS = /^(?:-[km]|--(?:lf|last-failed|sw|stepwise|deselect)\b)/; +// A name expression: the one option with which a run counts as a filtered run +// of its file. +const BY_NAME = /^-k/; +// A cluster of short flags that may hold `-k` or `-m` (`-qk parse`). +const CLUSTER = /^-[A-Za-z]+[km]/; // A run that names its own result file, or turns the result file off, // does not write the session's. const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; @@ -1362,20 +1364,32 @@ const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, whole, ended }`, else null. `path` is the file as the - * command spells it. `whole` is false for a run of a part of the file: a node - * id after the path, or an option that selects (`SELECTS`). `ended` says the - * visible `output` holds pytest's summary line, so the run finished inside - * the call. A run that prints what pytest knows and exits, or only collects - * (the rest of `PARTIAL`), is none, and so is one that does not write the - * session's result file (`OWN_REPORT`). The word after a flag that may take a - * value is that value and no path (`BARE`); a short flag written with its - * value (`-rf`, `-kparse`, `-n4`) takes none after it. + * else to run: `{ path, dir, whole, seconds }`, else null. `path` is the file + * as the command spells it and `dir` the folder of the one `cd` before the + * run, "" for none. `whole` is false for a run filtered with `-k`. `seconds` + * is what pytest's summary line in the visible `output` shows, null where + * the output holds none: the run did not finish inside the call. + * + * A run of another part of the file is none: a node id after the path, any + * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run + * every case; the rest run none), or a cluster of short flags that may hold + * one. Nor is a run that does not write the session's result file + * (`OWN_REPORT`), or one after a move the reader cannot follow (a second + * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder the shell + * expands). The word after a flag that may take a value is that value and no + * path (`BARE`); a short flag written with its value (`-rf`, `-kparse`, + * `-n4`) takes none after it. */ export function fileRun(command, output = "") { const text = String(command || "").replace(/\\\n/g, ""); const runs = [...text.matchAll(PYTEST)]; - if (runs.length !== 1 || !ranHere(text.slice(0, runs[0].index))) return null; + const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; + if (runs.length !== 1 || !ranHere(head)) return null; + const cd = [...head.matchAll(CD)]; + const followed = + cd.length < 2 && + (head.match(MOVE) || []).length === cd.length && + cd.every((m) => !/^-$|[$~`*?]/.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; let value = false; @@ -1384,13 +1398,30 @@ export function fileRun(command, output = "") { if (!flag && !value) named.push(word); value = flag && !word.includes("=") && !BARE.test(word) && !/^-[^-]./.test(word); } - const file = named.length === 1 ? /^([^\s:]+\.py)(::\S*)?$/.exec(named[0]) : null; - const partial = words.filter((word) => PARTIAL.test(word)); - if (!file || !partial.every((word) => SELECTS.test(word)) || words.some((word) => OWN_REPORT.test(word))) return null; - const ended = String(output || "") + const other = (word) => !BY_NAME.test(word) && (PARTIAL.test(word) || CLUSTER.test(word) || OWN_REPORT.test(word)); + if (!followed || named.length !== 1 || !/^[^\s:]+\.py$/.test(named[0]) || words.some(other)) return null; + const summary = String(output || "") .split(/\r?\n/) - .some((line) => line.length < 300 && SUMMARY.test(line)); - return { path: file[1], whole: !file[2] && !partial.length, ended }; + .findLast((line) => line.length < 300 && SUMMARY.test(line)); + return { + path: named[0], + dir: cd.length ? unquoted(cd[0][1]) : "", + whole: !words.some((word) => BY_NAME.test(word)), + seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, + }; +} + +// The name of pytest where a command only mentions it. +const PYTEST_NAME = /(? ranHere(text.slice(0, run.index)))) return true; + return startsRunner(text.replace(PYTEST_NAME, " ")); } /** diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 5942e32d4a5..e169d283940 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -77,7 +77,7 @@ "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." }, - "integrations/claude-code-plugin/lib/test-cost.mjs:memory.get:c16ad269d7fdfb5f894a:1": { + "integrations/claude-code-plugin/lib/test-cost.mjs:memory.get:b24b4138da905c52ed4a:1": { "category": "reference", "reason": "Reads the repository's test cost row by its key, which is built from the repository's id, with the scoped identity and a fixed field list; no prompt, transcript, path or file content is sent." }, @@ -157,7 +157,7 @@ "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." }, - "integrations/codex-plugin/lib/test-cost.mjs:memory.get:c16ad269d7fdfb5f894a:1": { + "integrations/codex-plugin/lib/test-cost.mjs:memory.get:b24b4138da905c52ed4a:1": { "category": "reference", "reason": "Reads the repository's test cost row by its key, which is built from the repository's id, with the scoped identity and a fixed field list; no prompt, transcript, path or file content is sent." }, @@ -398,7 +398,7 @@ "integrations/claude-code-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/claude-code-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/claude-code-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "f941d1e83d8266834ce224625aa8dc95fb5adfabf374b017b46de7f1fcc3965a", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "02d39ad9db1f1882a115bee950e11eb0248424c0a911e56705c38fa97493b20b", "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "65a0e04dba5319c703c7d267179bb1739014a16d133f6eb6c504ef5c12e596fc", "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/claude-code-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -410,11 +410,11 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "521211877ccd370f6d922b3b66ab874e944ce70cff110b6964301f5b86756a58", + "integrations/claude-code-plugin/lib/test-cost.mjs": "a048dd09f6e714ae0d0e7c6da268b58bb1c6fdc1e7c89cc910a34f234c77c2cb", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "f941d1e83d8266834ce224625aa8dc95fb5adfabf374b017b46de7f1fcc3965a", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "02d39ad9db1f1882a115bee950e11eb0248424c0a911e56705c38fa97493b20b", "integrations/codex-plugin/hooks/loom-session-start.mjs": "65a0e04dba5319c703c7d267179bb1739014a16d133f6eb6c504ef5c12e596fc", "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "521211877ccd370f6d922b3b66ab874e944ce70cff110b6964301f5b86756a58", + "integrations/codex-plugin/lib/test-cost.mjs": "a048dd09f6e714ae0d0e7c6da268b58bb1c6fdc1e7c89cc910a34f234c77c2cb", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 6a96217a9195f153e0f6ad3e3ee230332483dae2 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 18:10:38 +0530 Subject: [PATCH 03/24] A pending test run counts only the report of a run that began before its command returned A run whose output shows no summary is kept as the session's pending run. Its report was told from a later run's by reading the later command: one that names a runner and starts none left the report to the pending run. `time pytest`, `nohup`, `bash -c "pytest"` and a script no hook is run for all read as starting none, so a -k run's count and seconds were stored as the file's whole run. The report now says whose it is. pytest began the run that wrote it at the time the file was written less the seconds of its testsuite. The pending run keeps the time its command returned, and a report counts for it only when its run began by then: a run any later command started began after it. `mayRunTests` is removed. A run put in the background before pytest began is no longer counted. A word after a long flag that names a Python file or a folder makes a run no run of one file: the flag may take no value (`--no-header tests`). The row a session read is kept with the checkout it was read in, so a session whose folder moves to another checkout reads and writes that repository's row. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 26 +- integrations/claude-code-plugin/README.md | 4 +- .../claude-code-plugin/hooks/HOOKS.md | 35 ++- .../hooks/loom-prompt-pack.mjs | 8 +- .../hooks/loom-test-report.mjs | 2 +- .../claude-code-plugin/lib/test-cost.mjs | 129 +++++---- .../claude-code-plugin/lib/test-gate.mjs | 46 ++-- .../claude-code-plugin/lib/test-report.mjs | 19 +- .../tests/test-cost.test.mjs | 251 +++++++++++++----- .../codex-plugin/hooks/loom-prompt-pack.mjs | 8 +- .../codex-plugin/hooks/loom-test-report.mjs | 2 +- integrations/codex-plugin/lib/test-cost.mjs | 129 +++++---- integrations/codex-plugin/lib/test-gate.mjs | 46 ++-- integrations/codex-plugin/lib/test-report.mjs | 19 +- tests/unit/session_content_senders.json | 8 +- 15 files changed, 445 insertions(+), 287 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 60ae02a4902..895d8875daa 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1661,15 +1661,18 @@ session's private state, by the file: of the session's filtered runs of it that ran fewer cases than the whole file; - a run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, and a run that only collects or prints - (`--collect-only`, `--fixtures`) count as neither. + (`--collect-only`, `--fixtures`) count as neither. The word after a long flag is a + second path where the flag takes no value (`--no-header tests`): a run with such a word + that names a Python file or a folder counts as neither too. The result file is the command's when the command's output shows pytest's summary line with the seconds the file holds (within a second, or a twentieth of them), and the file's first case is in the test file the command names. A run that outlives its shell call writes the file after the hook ran: it is read after the next shell command that names a -test runner and starts none (`pgrep -f pytest`), or when the session ends. A command that -starts another test run in between drops it, since the next result file could be -either's. +test runner, or when the session ends. That file is the run's when pytest began the run +that wrote it before the run's own command returned (the time the file was written, less +the seconds it holds): a run that any later command started began after that, and its +file counts for no run. **What is stored.** When the session ends, what it measured goes to the repository's one memory row, written with the session's turns (`memory.set`, key @@ -1706,11 +1709,11 @@ Test cost in this repository (measured in earlier sessions): a whole run of test The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. The row is -read with one `memory.get` a session, sent beside the prompt's search and never waited -for past its answer: a read that fails or is slow adds nothing, and the pointers are -printed as they are. The line is made of the row's path and numbers, so a value someone -rewrote is neither printed nor overwritten. A row whose whole run is under 60 s, or whose -file the checkout does not hold, prints nothing. +read with one `memory.get` a session and checkout, sent beside the prompt's search and +never waited for past its answer: a read that fails or is slow adds nothing, and the +pointers are printed as they are. The line is made of the row's path and numbers, so a +value someone rewrote is neither printed nor overwritten. A row whose whole run is under +60 s, or whose file the checkout does not hold, prints nothing. What it does not do: @@ -1719,8 +1722,9 @@ What it does not do: - a session none of whose prompts read the row stores nothing: one with no bug report, and every session in `memory` mode, with the prompt pointers off or in a repository this Loom does not index; -- a run that outlives its shell call is noted only where no command that starts another - test run follows it in the session; +- a run that outlives its shell call is noted when it began before that call returned: a + run put in the background at once, before pytest began, is not, and neither is one + that was open together with a run of another kind of the same file; - a row whose file was removed stays, unprinted, until a session measures a slow whole run of another file; - the row is an ordinary memory row, so recall can serve its sentence, and two diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 21ffdbe2585..b866b92f4f2 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner and starts none (`pgrep -f pytest`), or when the session ends, where no command that starts another test run followed it. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. @@ -336,7 +336,7 @@ Only a session whose bug report read the row writes, a miss included. With no ro Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, and `code` mode all three; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session and checkout, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, and `code` mode all three; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index f911b6949fb..f5d4f8bdfbc 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -950,9 +950,10 @@ default 120 s timeout of a shell call. A run filtered with -k takes about its bound, and never waits for it past the search's answer: an answer that has not come by then, an error and a miss print nothing, and the pointers are the same bytes with or without the line. The row as it was - read, a miss too, is kept in the session's state with its hash and the - agent that wrote it, so a session asks once; a read that failed or came - late is asked again at the next bug report. The line is made of the row's + read, a miss too, is kept in the session's state with its hash, the + agent that wrote it and the checkout it was read in, so a session asks + once in a checkout; a read that failed or came late is asked again at + the next bug report. The line is made of the row's path and numbers and never of its text: a value that is not the stored sentence prints nothing. Nor does a row whose whole run is under 60 s, or whose file the checkout does not hold. It needs the memory plane and a @@ -1342,22 +1343,28 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`, which may run every case), a run that only collects or prints, and a command with two pytest runs or two paths are noted as - nothing (lib/test-cost.mjs). The file is the one the command names, - from the payload's folder and the command's one `cd`, where it is - there. + nothing (lib/test-cost.mjs). The word after a long flag is a second + path where the flag takes no value (`--no-header tests`), so a run + with such a word that names a Python file or a folder is noted as + nothing too. The file is the one the command names, from the payload's + folder and the command's one `cd`, where it is there. The report is the command's when the command's visible output shows pytest's summary line with the seconds the report holds, within a second or a twentieth of them, and the report's first case is in the file the command names: a run the option did not reach writes no report, and the one read after it is an earlier run's. A run whose - output shows no summary has not ended: one that outlives its shell - call writes the file after the hook ran. It is kept as the session's - pending run. A report that comes with a later command is its own when - that command names a test runner and starts none (`pgrep -f pytest`, - `mayRunTests` in lib/test-gate.mjs), and the launcher reads the report - once more at SessionEnd, before it removes the file, without reading a - token. A command that starts another test run in between drops the - pending run, since the next report could be either's. + output shows no summary may not have ended: one that outlives its + shell call writes the file after the hook ran. It is kept as the + session's pending run, with the time its command returned. Any other + report the hook reads is the pending run's when the run that wrote it + began by that time, and no run's otherwise: pytest began it at the + time the file was written less the seconds of its `testsuite`, and a + run that a later command started, by any launcher and whether or not + a hook ran for that command, began after it. The launcher reads the + report once more at SessionEnd, before it removes the file, without + reading a token. A run of another kind left open while one is pending + drops both, since one would be counted as the other. A run put in the + background at once returns before pytest began, and is not counted. At SessionEnd `loom-session-memory` hands one `memory.set` to the flusher, with the session's turns, where a prompt of the session read the row, a miss included, and its runs say something the row does not diff --git a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index 487bdd9c985..f6bc9ad0243 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -47,10 +47,10 @@ // runs and an earlier session stored what a whole run of a slow test file // costs in this repository (lib/test-cost.mjs): the file, its case count and // seconds, the seconds of a run filtered with -k, and to check a change with -// -k selections. The row is read by its key once a session, beside the search -// and inside the prompt's bound, and the line is sent only when that read has -// answered by the time the search has: it never holds the pointers back. A -// row whose file the checkout does not hold prints nothing. +// -k selections. The row is read by its key once a session and checkout, +// beside the search and inside the prompt's bound, and the line is sent only +// when that read has answered by the time the search has: it never holds the +// pointers back. A row whose file the checkout does not hold prints nothing. // // A search whose query reads as a bug report (twelve words or more, or a word // such as `error` or `crash`) asks the server's pick model diff --git a/integrations/claude-code-plugin/hooks/loom-test-report.mjs b/integrations/claude-code-plugin/hooks/loom-test-report.mjs index c21d7559d69..274e67a77f3 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-report.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-report.mjs @@ -76,7 +76,7 @@ function answer(payload) { // Read whatever the output shows: a report left unread would be the next command's. const report = newReport(sessionId, seen); const cwd = payload.cwd || process.cwd(); - if (COST) noteCommand(sessionId, { command, output, head: report ? report.head : null, cwd }); + if (COST) noteCommand(sessionId, { command, output, report, cwd }); if (!report || shownAlready(output)) return null; return reportContext(payload, digest(report.xml, { root: gitToplevel(cwd) || cwd, cwd, redact: redactSecrets })); } diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 943e5437363..0e183f0ce06 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -9,8 +9,9 @@ // one pytest run of one test file (`noteCommand`), in the session's private // state: for each file, the costliest whole run that passed and the runs // filtered with -k. A run that outlives its shell call writes the file after -// that call's hook ran, so the launcher reads it once more before it removes -// the file at the session's end (`settleRun`). +// that call's hook ran: a report read later is its when pytest began the run +// that wrote it before that call returned, and the launcher reads the file +// once more before it removes it at the session's end (`settleRun`). // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -26,7 +27,7 @@ import fs from "node:fs"; import path from "node:path"; import { gitToplevel, hookClient, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; -import { fileRun, mayRunTests } from "./test-gate.mjs"; +import { fileRun } from "./test-gate.mjs"; import { newReport, runCost, seenReport } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; @@ -41,10 +42,12 @@ const MAX_SAMPLES = 15; // The session's runs: `{ pending, files }`, by each file's absolute path. const RUNS = "test-cost"; -// The repository's row as the session read it: `{ read, row }`. +// The repository's row as the session read it in the checkout at `root`: +// `{ read, root, row }`. const ROW = "test-cost-row"; const isFile = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isFile()); +const isFolder = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isDirectory()); /** `file`, a path in the checkout, when it may be sent, else "". */ function sendable(file) { @@ -60,21 +63,24 @@ const apart = (seen, stored) => Math.abs(seen - stored) > Math.max(stored / 4, 2 /** `run` (`fileRun`) with `file`, the absolute path of the file it names, or * null where the command names none that is there. The payload's `cwd` is * the session's folder before the command or after it, so the run's own - * `cd` is tried first and then left out. */ + * `cd` is tried first and then left out. A run is none either when a word + * after a long flag names a folder there: pytest ran it too, where the flag + * takes no value. */ function located(run, cwd) { if (!run) return null; - const file = [path.resolve(cwd, run.dir, run.path), path.resolve(cwd, run.path)].find(isFile); - return file ? { ...run, file } : null; + const from = [path.resolve(cwd, run.dir), path.resolve(cwd)].find((dir) => isFile(path.resolve(dir, run.path))); + if (!from || run.values.some((word) => isFolder(path.resolve(from, word)))) return null; + return { ...run, file: path.resolve(from, run.path) }; } -/** Add what `run` cost to `state`, from the head of the report it wrote. A - * report whose first case is in another file is another run's (pytest names - * the file from its root, a folder at or above the file's). A whole run - * counts when no case failed: one that stopped at a failure took less. The - * file is put last, so the bound drops the one least recently run. */ -function add(state, run, head) { - const cost = runCost(head); - if (!cost?.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; +/** Add what `run` cost to `state`: `cost` is `runCost` of the head of the + * report it wrote. A report whose first case is in another file is another + * run's (pytest names the file from its root, a folder at or above the + * file's). A whole run counts when no case failed: one that stopped at a + * failure took less. The file is put last, so the bound drops the one least + * recently run. */ +function add(state, run, cost) { + if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; const whole = run.whole && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); const next = { @@ -86,38 +92,49 @@ function add(state, run, head) { state.files = Object.fromEntries(Object.entries(files).slice(-MAX_FILES)); } +/** Count `report` (`newReport`) for the session's pending run when the run + * that wrote it began before the pending run's command returned: pytest + * began it at the time the file was written less the suite's seconds. A + * command that came later, whatever it is and whether or not a hook saw it, + * began its run after that. The pending run is then settled. */ +function settle(state, report) { + const cost = report ? runCost(report.head) : null; + if (!cost || !state.pending || report.mtimeMs - cost.time * 1000 > state.pending.at) return; + add(state, state.pending, cost); + state.pending = undefined; +} + /** * Note a shell command the test report was read for: its text, its visible - * `output`, the `head` of the report when a run wrote it since the session's - * last read (else null), and the payload's `cwd`. + * `output`, the `report` when a run wrote it since the session's last read + * (`newReport`, else null), and the payload's `cwd`. * * The report is the command's when the command is one pytest run of one test * file (`fileRun`) and its output shows pytest's summary with the seconds * the report holds: a run the option did not reach writes no report, and the * one read after it is an earlier run's. A run whose output shows no summary - * has not ended: it is kept as the session's pending run. A report that - * comes with a later command is the pending run's when that command starts - * the same run again, or starts no test run at all (`mayRunTests`), as a - * command that only names a runner does. Any other command drops the pending - * run: a report after it could be either's. + * may not have ended: it is kept as the session's pending run, with the time + * its command returned. Any other report is the pending run's when its run + * began by that time (`settle`), and no run's otherwise. So a run that was + * put in the background before pytest began is not counted. An open run of + * another kind than the pending one drops both: one of the two would be + * counted as the other. */ -export function noteCommand(sessionId, { command, output, head, cwd }) { +export function noteCommand(sessionId, { command, output, report, cwd }) { try { const run = located(fileRun(command, output), cwd || process.cwd()); const state = readSessionState(RUNS, sessionId); - const pending = state.pending; - if (!run && !pending) return; - if (!run && !mayRunTests(command)) { - if (!head) return; - add(state, pending, head); - state.pending = undefined; - } else { - const open = Boolean(run && run.seconds === null); - const again = Boolean(open && pending && pending.file === run.file && pending.whole === run.whole); - // The summary's seconds and the report's are two clocks on one run. - const ended = run && !open && Math.abs(run.seconds - runCost(head)?.seconds) <= Math.max(1, run.seconds / 20); - if (head && (again || ended)) add(state, run, head); - state.pending = open && (!pending || again) ? { file: run.file, whole: run.whole } : undefined; + if (!run && !state.pending) return; + const cost = report ? runCost(report.head) : null; + const open = Boolean(run && run.seconds === null); + // The summary's seconds and the report's are two clocks on one run. + const own = run && !open && cost && Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); + if (own) add(state, run, cost); + else settle(state, report); + if (open) { + const pending = state.pending; + const free = !pending || (pending.file === run.file && pending.whole === run.whole); + state.pending = free ? { file: run.file, whole: run.whole, at: Date.now() } : undefined; } writeSessionState(RUNS, sessionId, state); } catch { @@ -126,15 +143,14 @@ export function noteCommand(sessionId, { command, output, head, cwd }) { } /** At the session's end, before its report is removed: a report written - * since the session's last read is the pending run's. One bounded read of - * the session's own file, and no token is read. */ + * since the session's last read is counted for the pending run (`settle`). + * One bounded read of the session's own file, and no token is read. */ export function settleRun(sessionId) { try { const state = readSessionState(RUNS, sessionId); if (!state.pending) return; const seen = seenReport(sessionId); - const report = seen && newReport(sessionId, seen); - if (report) add(state, state.pending, report.head); + settle(state, seen && newReport(sessionId, seen)); state.pending = undefined; writeSessionState(RUNS, sessionId, state); } catch { @@ -192,26 +208,27 @@ const identity = (scope, agent) => ({ /** * The line for a prompt of a session that has the test report, in the - * checkout at `root`, or "": the repository's row, read once a session - * (`memory.get` by key, bounded by `options.timeoutMs`) and kept in the - * session's state, a miss too, with the agent that wrote it. `scopeOf()` is - * asked only for that read. An answer that does not come and an error give no - * line, and a later prompt asks again. A row gives none whose value is not - * `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose - * file the checkout does not hold. + * checkout at `root`, or "": the repository's row, read once a session and + * checkout (`memory.get` by key, bounded by `options.timeoutMs`) and kept in + * the session's state, a miss too, with the agent that wrote it and the + * checkout it was read in: a session whose folder moved to another checkout + * reads that one's row. `scopeOf()` is asked only for that read. An answer + * that does not come and an error give no line, and a later prompt asks + * again. A row gives none whose value is not `claim`'s text, whose whole run + * is under `MIN_WHOLE_SECONDS`, or whose file the checkout does not hold. */ export async function costLine(sessionId, root, scopeOf, options) { try { if (!seenReport(sessionId)) return ""; let held = readSessionState(ROW, sessionId); - if (!held.read) { + if (!held.read || held.root !== root) { const scope = scopeOf(); if (!costKey(scope)) return ""; const fields = ["value", "content_sha256", "agent"]; const res = await postBounded("memory.get", { ...identity(scope), fields }, options); if (!res) return ""; const found = { sha: String(res.content_sha256 || ""), agent: String(res.agent || "") }; - held = { read: true, row: res.found ? { ...parseClaim(scope.repo.id, res.value), ...found } : null }; + held = { read: true, root, row: res.found ? { ...parseClaim(scope.repo.id, res.value), ...found } : null }; writeSessionState(ROW, sessionId, held); } const row = held.row; @@ -286,12 +303,12 @@ function measured(state, root) { /** * The flusher's post that stores what the session measured, or null; the * session's cost state is removed either way. Only a session whose prompt - * read the row stores, a miss included: it knows what it replaces, and where - * no prompt can read the row no session writes one. One `memory.set` of the - * repository's key follows where `revised` has a claim: a revision of the - * row as read (`if_match_sha256`, under the row's agent), else a first row - * (`absent`). The value names no file to the server (`files: []`), and its - * class says a tool measured it. + * read the row in the checkout of `cwd` stores, a miss included: it knows + * what it replaces, and where no prompt can read the row no session writes + * one. One `memory.set` of the repository's key follows where `revised` has + * a claim: a revision of the row as read (`if_match_sha256`, under the row's + * agent), else a first row (`absent`). The value names no file to the server + * (`files: []`), and its class says a tool measured it. */ export function costPost(sessionId, cwd, scopeOf) { try { @@ -299,7 +316,7 @@ export function costPost(sessionId, cwd, scopeOf) { const held = readSessionState(ROW, sessionId); for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); const root = held.read && state.files ? gitToplevel(cwd) : ""; - const runs = root ? measured(state, root) : {}; + const runs = root && held.root === root ? measured(state, root) : {}; if (!Object.keys(runs).length) return null; const row = held.row?.path ? { ...held.row, gone: !isFile(path.join(root, held.row.path)) } : held.row; const next = revised(runs, row); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 26d02f4c102..3e1673c1970 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1360,15 +1360,17 @@ const CLUSTER = /^-[A-Za-z]+[km]/; // A run that names its own result file, or turns the result file off, // does not write the session's. const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; +// A Python file, or a test in one, as a word of a pytest command. +const PYTHON_FILE = /\.py(?:::|$)/; /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, dir, whole, seconds }`, else null. `path` is the file - * as the command spells it and `dir` the folder of the one `cd` before the - * run, "" for none. `whole` is false for a run filtered with `-k`. `seconds` - * is what pytest's summary line in the visible `output` shows, null where - * the output holds none: the run did not finish inside the call. + * else to run: `{ path, dir, whole, seconds, values }`, else null. `path` is + * the file as the command spells it and `dir` the folder of the one `cd` + * before the run, "" for none. `whole` is false for a run filtered with `-k`. + * `seconds` is what pytest's summary line in the visible `output` shows, null + * where the output holds none: the run did not finish inside the call. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1378,7 +1380,10 @@ const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder the shell * expands). The word after a flag that may take a value is that value and no * path (`BARE`); a short flag written with its value (`-rf`, `-kparse`, - * `-n4`) takes none after it. + * `-n4`) takes none after it. A long flag may take none (`--no-header`), and + * the word after it is then a second path: a run with such a word that names + * a Python file is none, and the others are `values`, for a reader that can + * tell a folder (`--cov src` from `--no-header tests`). */ export function fileRun(command, output = "") { const text = String(command || "").replace(/\\\n/g, ""); @@ -1392,14 +1397,21 @@ export function fileRun(command, output = "") { cd.every((m) => !/^-$|[$~`*?]/.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; - let value = false; + const values = []; + // The flag before a word, where the word may be its value. + let flag = ""; for (const word of words) { - const flag = word.startsWith("-"); - if (!flag && !value) named.push(word); - value = flag && !word.includes("=") && !BARE.test(word) && !/^-[^-]./.test(word); + if (word.startsWith("-")) { + flag = !word.includes("=") && !BARE.test(word) && !/^-[^-]./.test(word) ? word : ""; + continue; + } + if (!flag) named.push(word); + else if (flag.startsWith("--") || PYTHON_FILE.test(word)) values.push(word); + flag = ""; } const other = (word) => !BY_NAME.test(word) && (PARTIAL.test(word) || CLUSTER.test(word) || OWN_REPORT.test(word)); if (!followed || named.length !== 1 || !/^[^\s:]+\.py$/.test(named[0]) || words.some(other)) return null; + if (values.some((word) => PYTHON_FILE.test(word))) return null; const summary = String(output || "") .split(/\r?\n/) .findLast((line) => line.length < 300 && SUMMARY.test(line)); @@ -1408,22 +1420,10 @@ export function fileRun(command, output = "") { dir: cd.length ? unquoted(cd[0][1]) : "", whole: !words.some((word) => BY_NAME.test(word)), seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, + values, }; } -// The name of pytest where a command only mentions it. -const PYTEST_NAME = /(? ranHere(text.slice(0, run.index)))) return true; - return startsRunner(text.replace(PYTEST_NAME, " ")); -} - /** * The repo-relative files and directories pytest ran to its summary on the * tree as it stands, read in transcript order (Claude Code rows; sidechains diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index a73a4fc7e4f..35583b194ed 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -118,9 +118,10 @@ export function seenReport(sessionId) { } /** The session's report when a run wrote it since the session saw it as - * `seen`: `{ xml, head }`, with "" as `xml` for a report over the read - * bound and its first `HEAD_BYTES` as `head`, and the file noted as seen. - * null when no run wrote it, or the file is not this user's regular file. */ + * `seen`: `{ xml, head, mtimeMs }`, with "" as `xml` for a report over the + * read bound, its first `HEAD_BYTES` as `head` and the time it was written, + * and the file noted as seen. null when no run wrote it, or the file is not + * this user's regular file. */ export function newReport(sessionId, seen) { let fd; try { @@ -134,7 +135,7 @@ export function newReport(sessionId, seen) { const large = st.size > MAX_REPORT_BYTES; const buf = Buffer.alloc(large ? HEAD_BYTES : st.size); const text = buf.toString("utf8", 0, fs.readSync(fd, buf, 0, buf.length, 0)); - return { xml: large ? "" : text, head: text.slice(0, HEAD_BYTES) }; + return { xml: large ? "" : text, head: text.slice(0, HEAD_BYTES), mtimeMs: st.mtimeMs }; } catch { return null; } finally { @@ -290,10 +291,11 @@ function scan(xml) { } /** What the run that wrote a result file cost, from the file's `head`: the - * first testsuite's case count, its seconds to the nearest one, how many - * cases failed or ended in an error, and the file of its first testcase, - * which pytest names in the family the option sets ("" where the head holds - * none). null for a head with no whole testsuite tag, no case or no time. */ + * first testsuite's case count, its seconds to the nearest one and as + * written (`time`), how many cases failed or ended in an error, and the file + * of its first testcase, which pytest names in the family the option sets + * ("" where the head holds none). null for a head with no whole testsuite + * tag, no case or no time. */ export function runCost(head) { const first = (text, name) => { try { @@ -313,6 +315,7 @@ export function runCost(head) { return { tests, seconds: Math.round(seconds), + time: seconds, failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), file: testcase ? attributes(testcase.attrs).file || "" : "", }; diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 1ae5ff1e0d9..e662b3ed9ab 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -17,7 +17,7 @@ import { hostEnv, withTmpdir } from "./host-env.mjs"; import { repoIdentity } from "../lib/loom-client.mjs"; import { cachePathFor } from "../lib/repo-scope.mjs"; import { claim, costKey, noteCommand, parseClaim, renderCost, revised, settleRun } from "../lib/test-cost.mjs"; -import { fileRun, mayRunTests } from "../lib/test-gate.mjs"; +import { fileRun } from "../lib/test-gate.mjs"; import { newReport, reportPath, runCost } from "../lib/test-report.mjs"; import { readJsonFile, sessionStatePath, writeJsonFile, writePrivateFile } from "../lib/tmp-state.mjs"; @@ -51,16 +51,18 @@ const BOTH = `In the repository tagged repo:${REPO}, a whole run of ${FILE} coll // --- the parts ---------------------------------------------------------------- test("the head of a report gives the run's case count and its seconds", () => { - assert.deepEqual(runCost(WHOLE.slice(0, 4096)), { tests: 8000, seconds: 140, failed: 0, file: FILE }); + const whole = { tests: 8000, seconds: 140, time: 140.2, failed: 0, file: FILE }; + assert.deepEqual(runCost(WHOLE.slice(0, 4096)), whole); assert.deepEqual(runCost(report({ tests: 3, time: "0.4", failures: 2 })), { tests: 3, seconds: 0, + time: 0.4, failed: 2, file: FILE, }); // A head cut inside the first case still holds the suite's totals. const cut = WHOLE.slice(0, WHOLE.indexOf(" { - const whole = { path: FILE, dir: "", whole: true, seconds: null }; + const whole = { path: FILE, dir: "", whole: true, seconds: null, values: [] }; for (const command of [ `pytest ${FILE}`, `python -m pytest ${FILE} -q`, @@ -111,6 +114,11 @@ test("a command's one pytest run of one test file is whole or filtered with -k", ...whole, dir: "pkg", }); + // The word after a long flag is its value, or a second path where the flag takes none. + assert.deepEqual(fileRun(`pytest ${FILE} --durations 5 --no-header tests -k parse`), { + ...part, + values: ["5", "tests"], + }); // The seconds of pytest's summary, where the output holds it: the run ended inside the call. assert.equal(fileRun(`pytest ${FILE} -q`, "........\n8000 passed in 140.21s (0:02:20)").seconds, 140.21); assert.equal(fileRun(`pytest ${FILE} -k parse`, "12 passed, 7988 deselected in 2.31s").seconds, 2.31); @@ -127,6 +135,10 @@ test("a command with two pytest runs, two paths, another selection or no run of // The word after a flag that may take a value is that value. `pytest --ignore ${FILE}`, `pytest -p ${FILE}`, + // A Python file after a flag ran too, where the flag takes no value. + `pytest ${FILE} --no-header tests/test_small.py`, + `pytest ${FILE} --disable-warnings tests/test_small.py::test_one -q`, + `pytest -x -f tests/test_small.py ${FILE}`, // A selection that may run every case of the file, or is not by name. `pytest ${FILE} --lf`, `pytest ${FILE} --sw -q`, @@ -159,29 +171,6 @@ test("a command with two pytest runs, two paths, another selection or no run of } }); -test("a command that only names pytest starts no test run", () => { - for (const command of [ - "ps aux | grep pytest", - "pgrep -f pytest", - "tail -5 /tmp/pytest/out.log", - 'git commit -m "fix pytest flake"', - `echo "pytest ${FILE}"`, - `docker exec app pytest ${FILE}`, - ]) { - assert.equal(mayRunTests(command), false, command); - } - for (const command of [ - `pytest ${FILE} -k parse`, - "cd pkg && python -m pytest tests", - "make test", - "tox -e py312", - "ps aux | grep pytest; npm test", - "./runtests.py", - ]) { - assert.equal(mayRunTests(command), true, command); - } -}); - test("the stored claim and the prompt's line, byte for byte", () => { const whole = { path: FILE, tests: 8000, seconds: 140 }; assert.equal(claim(REPO, { ...whole, filtered: 2 }), BOTH); @@ -321,15 +310,30 @@ function inTmp(t, fn) { fs.writeFileSync(path.join(cwd, FILE), ""); return withTmpdir(tmp, () => fn(cwd, path.join(cwd, FILE))); } -const runs = () => readJsonFile(sessionStatePath("test-cost", SESSION), null); -const head = (xml) => (xml === null ? null : xml.slice(0, 4096)); +/** A session's cost state as `file` holds it; a pending run has the time its command returned. */ +function noted(file) { + const state = readJsonFile(file, null); + if (!state?.pending) return state; + const { at, ...pending } = state.pending; + assert.ok(Math.abs(Date.now() - at) < 60000, `the pending run was noted at ${at}`); + return { ...state, pending }; +} +const runs = () => noted(sessionStatePath("test-cost", SESSION)); +/** What `newReport` reads of a report `xml` that was written `after` ms from now. */ +const read = (xml, after = 0) => (xml === null ? null : { head: xml.slice(0, 4096), mtimeMs: Date.now() + after }); +/** Write the report `xml` to `file` as a run that ends `after` ms from now writes it. */ +function written(file, xml, after) { + fs.writeFileSync(file, xml); + const at = new Date(Date.now() + after); + fs.utimesSync(file, at, at); +} const STARTED = "Command running in background with ID: bash_1"; test("a report is the command's whose output shows the summary with the report's seconds", { skip: WINDOWS, }, (t) => { inTmp(t, (cwd, file) => { - const note = (command, output, xml) => noteCommand(SESSION, { command, output, head: head(xml), cwd }); + const note = (command, output, xml) => noteCommand(SESSION, { command, output, report: read(xml), cwd }); const whole = (seconds) => ({ tests: 8000, seconds }); note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); assert.deepEqual(runs(), { files: { [file]: { whole: whole(140) } } }); @@ -347,13 +351,16 @@ test("a report is the command's whose output shows the summary with the report's // A command that names the file from another folder, and a report of another file. note("cd tests && pytest test_big.py -q", "8000 passed in 150.00s", report({ tests: 8000, time: "150.0" })); assert.deepEqual(runs().files[file].whole, whole(150)); + // A long flag's value that names no folder. + note(`pytest ${FILE} --durations 5 -q`, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" })); + assert.deepEqual(runs().files[file].whole, whole(160)); note(WHOLE_COMMAND, "9000 passed in 900.00s", report({ tests: 9000, time: "900.0", file: "tests/test_other.py" })); - assert.deepEqual(runs().files[file].whole, whole(150)); + assert.deepEqual(runs().files[file].whole, whole(160)); // A run the option did not reach wrote no report: the one read after it is an // earlier run's, and its seconds are not the summary's. note(`PYTEST_ADDOPTS=-q pytest ${FILE} -k parse`, FILTERED_OUTPUT, report({ tests: 8000, time: "600.0" })); note(WHOLE_COMMAND, "8000 passed in 2.31s", report({ tests: 8000, time: "600.0" })); - assert.deepEqual(runs(), { files: { [file]: { whole: whole(150), filtered } } }); + assert.deepEqual(runs(), { files: { [file]: { whole: whole(160), filtered } } }); }); }); @@ -361,10 +368,13 @@ test("a command that is no file run, or names a file that is not there, leaves n skip: WINDOWS, }, (t) => { inTmp(t, (cwd) => { - const note = (command, output) => noteCommand(SESSION, { command, output, head: head(WHOLE), cwd }); + const note = (command, output) => noteCommand(SESSION, { command, output, report: read(WHOLE), cwd }); note("make test", "8000 passed in 140.21s"); note(`pytest ${FILE} -q; pytest ${FILE} -k parse`, WHOLE_OUTPUT); note(`pytest ${FILE} tests/test_small.py`, WHOLE_OUTPUT); + // The word after a long flag names a folder: pytest ran it too, where the flag takes no value. + note(`pytest ${FILE} --no-header tests`, WHOLE_OUTPUT); + note(`cd tests && pytest test_big.py --disable-warnings ../tests -q`, WHOLE_OUTPUT); note(`pytest ${FILE} --lf -q`, WHOLE_OUTPUT); note("pytest tests/test_gone.py -q", WHOLE_OUTPUT); note(`cd elsewhere && pytest ${FILE.replace("big", "gone")} -q`, WHOLE_OUTPUT); @@ -377,7 +387,7 @@ test("the files a session's state holds are the eight it ran last", { skip: WIND const note = (name) => { fs.writeFileSync(path.join(cwd, name), ""); const xml = report({ tests: 12, time: "2.3", file: name }); - noteCommand(SESSION, { command: `pytest ${name} -k parse -q`, output: FILTERED_OUTPUT, head: head(xml), cwd }); + noteCommand(SESSION, { command: `pytest ${name} -k parse -q`, output: FILTERED_OUTPUT, report: read(xml), cwd }); }; note(FILE); for (let i = 0; i < 7; i++) note(`tests/test_${i}.py`); @@ -397,7 +407,8 @@ test("the files a session's state holds are the eight it ran last", { skip: WIND test("a run that outlives its call is pending, and the report at the session's end is its", { skip: WINDOWS }, (t) => { inTmp(t, (cwd, file) => { - const note = (xml) => noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, head: head(xml), cwd }); + const note = (xml) => + noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, report: read(xml), cwd }); writePrivateFile(reportPath(SESSION), ""); writeJsonFile(sessionStatePath("test-report", SESSION), { mtimeMs: 1, size: 0 }); note(null); @@ -418,17 +429,18 @@ test("a run that outlives its call is pending, and the report at the session's e }); }); -test("a command that only names a runner keeps the pending run, and a report that came with it is that run's", { +test("a later command keeps the pending run, and a report of a run that began before it returned is its", { skip: WINDOWS, }, (t) => { inTmp(t, (cwd, file) => { - const note = (command, output, xml) => noteCommand(SESSION, { command, output, head: head(xml), cwd }); + const note = (command, output, xml) => noteCommand(SESSION, { command, output, report: read(xml), cwd }); note(`pytest ${FILE} -q`, STARTED, null); - // The session looks for its run from the shell: nothing is dropped. + // The session looks for its run from the shell, and runs another test: nothing is dropped. note("ps aux | grep pytest", "dev 4242 python -m pytest", null); note("tail -5 /tmp/pytest/out.log", "....", null); + note("make test", "ok", null); assert.deepEqual(runs(), { pending: { file, whole: true } }); - // The run has ended by the next look. + // The run has ended by the next look: its 140 s began before its command returned. note("pgrep -f pytest", "", WHOLE); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); }); @@ -436,19 +448,45 @@ test("a command that only names a runner keeps the pending run, and a report tha test("a report that could be another run's is counted for none", { skip: WINDOWS }, (t) => { inTmp(t, (cwd, file) => { - const note = (command, output, xml) => noteCommand(SESSION, { command, output, head: head(xml), cwd }); + const note = (command, output, xml, after) => + noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); const pending = () => note(`pytest ${FILE} -q`, STARTED, null); - // Another command that starts a runner: the next report could be its. + const open = { pending: { file, whole: true } }; + // A selection of the file that began after the whole run's command returned + // wrote the report 3 s from now: it is not the whole run's, whatever started + // it, and whether or not the command that came with it names the run. pending(); - note("make test", "ok", null); - assert.deepEqual(runs(), {}); - // A selection of the file started while the whole run is open. + for (const command of [ + `time pytest ${FILE} -k parse`, + `nohup python -u -m pytest ${FILE} -k parse`, + `hatch run pytest ${FILE} -k parse`, + `bash -c "pytest ${FILE} -k parse"`, + // After a script that started pytest, which no hook is run for. + "pgrep -f pytest", + "make test", + ]) { + note(command, FILTERED_OUTPUT, FILTERED, 3000); + assert.deepEqual(runs(), open, command); + } + // The whole run's own report, read with a later command, still counts. + note("pgrep -f pytest", "", WHOLE, 3000); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + + // A selection of the file started while the whole run is open: one of the + // two would be counted as the other. pending(); - note(`pytest ${FILE} -k parse`, STARTED, WHOLE); + note(`pytest ${FILE} -k parse`, STARTED, null); assert.deepEqual(runs(), {}); - // A run whose summary is in sight takes the report; the open run's is lost. + // A run whose summary is in sight takes its own report, and the open run stays. pending(); - note(FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED); + note(FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED, 3000); + assert.deepEqual(runs(), { ...open, files: { [file]: { filtered: [[12, 2]] } } }); + // The report at the session's end is a later run's too. + writePrivateFile(reportPath(SESSION), ""); + writeJsonFile(sessionStatePath("test-report", SESSION), { mtimeMs: 1, size: 0 }); + written(reportPath(SESSION), report({ tests: 30, time: "70.0" }), 71000); + settleRun(SESSION); assert.deepEqual(runs(), { files: { [file]: { filtered: [[12, 2]] } } }); }); }); @@ -471,8 +509,9 @@ const BUG = "Nested record prefixes raise an error before validation when the pa /** The repository's row as memory.get answers it. */ const row = (value = BOTH, agent = "claude-code") => ({ found: true, value, content_sha256: "abc", agent }); -/** A stub Loom server. `get` is what memory.get answers, or a status for a - * failure; `getStall` holds that answer back. A search answers after 300 ms, +/** A stub Loom server. `get` is what memory.get answers, a function of the + * request's body that gives it, or a status for a failure; `getStall` holds + * that answer back. A search answers after 300 ms, * as one that embeds its query does. Each request is kept with what * `mark()` says of the moment it came. */ async function loom(t, { get = { found: false }, getStall = 0, mark = () => ({}) } = {}) { @@ -490,8 +529,9 @@ async function loom(t, { get = { found: false }, getStall = 0, mark = () => ({}) } requests.push({ op, body, headers: req.headers, ...mark() }); const failed = op === "memory.get" && typeof get === "number"; + const row = typeof get === "function" ? get(body) : get; const answer = - op === "code.search" ? SEARCH : op === "memory.get" ? get : op === "run.begin" ? { run_id: body.run_id } : {}; + op === "code.search" ? SEARCH : op === "memory.get" ? row : op === "run.begin" ? { run_id: body.run_id } : {}; res.writeHead(failed ? get : 200, { "content-type": "application/json" }); const wait = op === "code.search" ? 300 : op === "memory.get" ? getStall : 0; // Unreferenced: an answer still held back when the test ends does not keep the run open. @@ -507,27 +547,18 @@ async function loom(t, { get = { found: false }, getStall = 0, mark = () => ({}) return { url: `http://127.0.0.1:${server.address().port}`, requests, sent }; } -/** A checkout of ORIGIN that configures pytest and holds FILE, a home and a - * temp folder, in a session that has the test report; `server` holds the - * checkout's index. */ -function sandbox(t, server) { - const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-test-cost-hook-"))); - const box = { dir, home: path.join(dir, "home"), tmp: path.join(dir, "tmp"), cwd: path.join(dir, "work") }; - for (const d of [box.home, box.tmp, box.cwd]) fs.mkdirSync(d); - fs.writeFileSync(path.join(box.cwd, "pytest.ini"), "[pytest]\n"); - box.file = path.join(box.cwd, FILE); - fs.mkdirSync(path.dirname(box.file)); - fs.writeFileSync(box.file, ""); - const git = (...a) => execFileSync("git", a, { cwd: box.cwd, stdio: "ignore" }); +/** `box` in a checkout of `origin` at `cwd`, which configures pytest and + * holds FILE; `server` holds the checkout's index. */ +function checkout(box, cwd, origin, server) { + fs.mkdirSync(path.join(cwd, path.dirname(FILE)), { recursive: true }); + fs.writeFileSync(path.join(cwd, "pytest.ini"), "[pytest]\n"); + fs.writeFileSync(path.join(cwd, FILE), ""); + const git = (...a) => execFileSync("git", a, { cwd, stdio: "ignore" }); git("init", "-q", "-b", "main"); - git("remote", "add", "origin", ORIGIN); - box.report = reportPath(SESSION, { tmp: box.tmp }); - box.runs = sessionStatePath("test-cost", SESSION, { tmp: box.tmp }); - box.row = sessionStatePath("test-cost-row", SESSION, { tmp: box.tmp }); - writePrivateFile(box.report, ""); - writeJsonFile(sessionStatePath("test-report", SESSION, { tmp: box.tmp }), { mtimeMs: 1, size: 0 }); + git("remote", "add", "origin", origin); + const repo = new URL(origin).pathname.slice(1).replace(/\.git$/, ""); fs.writeFileSync( - cachePathFor(box.cwd, box.tmp, { serverUrl: server.url, token: "t" }), + cachePathFor(cwd, box.tmp, { serverUrl: server.url, token: "t" }), JSON.stringify({ ts: Date.now(), indexed: true, @@ -535,10 +566,26 @@ function sandbox(t, server) { matchedVia: "origin", org: "o", namespace: "code-app", - repo: "example/app", + repo, prefixes: [], }), ); + return { ...box, cwd, file: path.join(cwd, FILE) }; +} + +/** A checkout of ORIGIN that configures pytest and holds FILE, a home and a + * temp folder, in a session that has the test report; `server` holds the + * checkout's index. */ +function sandbox(t, server) { + const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-test-cost-hook-"))); + const box = { dir, home: path.join(dir, "home"), tmp: path.join(dir, "tmp") }; + for (const d of [box.home, box.tmp]) fs.mkdirSync(d); + Object.assign(box, checkout(box, path.join(dir, "work"), ORIGIN, server)); + box.report = reportPath(SESSION, { tmp: box.tmp }); + box.runs = sessionStatePath("test-cost", SESSION, { tmp: box.tmp }); + box.row = sessionStatePath("test-cost-row", SESSION, { tmp: box.tmp }); + writePrivateFile(box.report, ""); + writeJsonFile(sessionStatePath("test-report", SESSION, { tmp: box.tmp }), { mtimeMs: 1, size: 0 }); box.env = (extra = {}) => hostEnv({ PATH: process.env.PATH, @@ -668,7 +715,7 @@ test("a whole run that outlived its call is stored from the report it wrote befo const box = sandbox(t, server); await ask(box); await afterCommand(box, `python -m pytest ${FILE} -q`, STARTED); - assert.deepEqual(readJsonFile(box.runs, null), { pending: { file: box.file, whole: true } }); + assert.deepEqual(noted(box.runs), { pending: { file: box.file, whole: true } }); // The run ends after its command's hook ran, and no test command follows it. fs.writeFileSync(box.report, WHOLE); await endSession(box); @@ -677,6 +724,29 @@ test("a whole run that outlived its call is stored from the report it wrote befo assert.equal(fs.existsSync(box.report), false); }); +test("a later run's report is not stored as the whole run that was pending", { skip: WINDOWS }, async (t) => { + const server = await loom(t, { get: row() }); + const box = sandbox(t, server); + await ask(box); + await afterCommand(box, `python -m pytest ${FILE} -q`, STARTED); + const open = { pending: { file: box.file, whole: true } }; + // A selection of the file, started in a way the hook does not read as a run of + // the file, ends 3 s from now: its report began after the whole run's command returned. + written(box.report, FILTERED, 3000); + await afterCommand(box, `time pytest ${FILE} -k parse`, FILTERED_OUTPUT); + assert.deepEqual(noted(box.runs), open); + // A script that starts pytest names no runner, so no hook reads its report + // before the session ends. + written(box.report, report({ tests: 12, time: "2.0" }), 4000); + await afterCommand(box, "./scripts/check.sh", FILTERED_OUTPUT); + assert.deepEqual(noted(box.runs), open); + await endSession(box); + await settled(box); + // The stored 140 s is not lowered to a selection's 2 s. + assert.deepEqual(server.sent("memory.set"), []); + assert.equal(fs.existsSync(box.runs), false); +}); + test("the launcher at an agent's SessionEnd reads the pending run's report and exchanges no token", { skip: WINDOWS, }, async (t) => { @@ -827,6 +897,43 @@ test("a session lowers the row of a file that got faster, and replaces the row o assert.equal(body.if_match_sha256, "abc"); }); +test("a session whose folder moves to another checkout reads and writes that repository's row", { + skip: WINDOWS, +}, async (t) => { + const origin = "https://github.com/example/lib.git"; + const repo = repoIdentity(origin).id; + // The first repository has a row, the second has none. + const server = await loom(t, { get: (body) => (body.memory_key === KEY ? row(BOTH, "team-bot") : { found: false }) }); + const box = sandbox(t, server); + const other = checkout(box, path.join(box.dir, "lib"), origin, server); + assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + // The second checkout holds a file at the row's path: the first repository's row is not its. + assert.equal(context(await ask(other)), BLOCK); + assert.deepEqual( + server.sent("memory.get").map((r) => r.body.memory_key), + [KEY, `repo:${repo}/test-cost/pytest`], + ); + await afterCommand(other, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + await endSession(other); + await arrived(server, box, "memory.set"); + const { body } = server.sent("memory.set")[0]; + // A first row of the second repository, not a revision of the first one's. + assert.equal(body.memory_key, `repo:${repo}/test-cost/pytest`); + assert.equal(body.agent, "claude-code"); + assert.equal(body.if_match_sha256, "absent"); + assert.equal(body.value, claim(repo, { path: FILE, tests: 8000, seconds: 140 })); + + // A session that ends in a checkout whose row no prompt read stores nothing. + const none = await loom(t); + const first = sandbox(t, none); + const second = checkout(first, path.join(first.dir, "lib"), origin, none); + await ask(first); + await afterCommand(second, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + await endSession(second); + await settled(first); + assert.deepEqual(none.sent("memory.set"), []); +}); + test("a miss is kept for the session, and a row that is not the claim's text prints nothing", { skip: WINDOWS, }, async (t) => { diff --git a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs index 487bdd9c985..f6bc9ad0243 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -47,10 +47,10 @@ // runs and an earlier session stored what a whole run of a slow test file // costs in this repository (lib/test-cost.mjs): the file, its case count and // seconds, the seconds of a run filtered with -k, and to check a change with -// -k selections. The row is read by its key once a session, beside the search -// and inside the prompt's bound, and the line is sent only when that read has -// answered by the time the search has: it never holds the pointers back. A -// row whose file the checkout does not hold prints nothing. +// -k selections. The row is read by its key once a session and checkout, +// beside the search and inside the prompt's bound, and the line is sent only +// when that read has answered by the time the search has: it never holds the +// pointers back. A row whose file the checkout does not hold prints nothing. // // A search whose query reads as a bug report (twelve words or more, or a word // such as `error` or `crash`) asks the server's pick model diff --git a/integrations/codex-plugin/hooks/loom-test-report.mjs b/integrations/codex-plugin/hooks/loom-test-report.mjs index c21d7559d69..274e67a77f3 100644 --- a/integrations/codex-plugin/hooks/loom-test-report.mjs +++ b/integrations/codex-plugin/hooks/loom-test-report.mjs @@ -76,7 +76,7 @@ function answer(payload) { // Read whatever the output shows: a report left unread would be the next command's. const report = newReport(sessionId, seen); const cwd = payload.cwd || process.cwd(); - if (COST) noteCommand(sessionId, { command, output, head: report ? report.head : null, cwd }); + if (COST) noteCommand(sessionId, { command, output, report, cwd }); if (!report || shownAlready(output)) return null; return reportContext(payload, digest(report.xml, { root: gitToplevel(cwd) || cwd, cwd, redact: redactSecrets })); } diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 943e5437363..0e183f0ce06 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -9,8 +9,9 @@ // one pytest run of one test file (`noteCommand`), in the session's private // state: for each file, the costliest whole run that passed and the runs // filtered with -k. A run that outlives its shell call writes the file after -// that call's hook ran, so the launcher reads it once more before it removes -// the file at the session's end (`settleRun`). +// that call's hook ran: a report read later is its when pytest began the run +// that wrote it before that call returned, and the launcher reads the file +// once more before it removes it at the session's end (`settleRun`). // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -26,7 +27,7 @@ import fs from "node:fs"; import path from "node:path"; import { gitToplevel, hookClient, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; -import { fileRun, mayRunTests } from "./test-gate.mjs"; +import { fileRun } from "./test-gate.mjs"; import { newReport, runCost, seenReport } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; @@ -41,10 +42,12 @@ const MAX_SAMPLES = 15; // The session's runs: `{ pending, files }`, by each file's absolute path. const RUNS = "test-cost"; -// The repository's row as the session read it: `{ read, row }`. +// The repository's row as the session read it in the checkout at `root`: +// `{ read, root, row }`. const ROW = "test-cost-row"; const isFile = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isFile()); +const isFolder = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isDirectory()); /** `file`, a path in the checkout, when it may be sent, else "". */ function sendable(file) { @@ -60,21 +63,24 @@ const apart = (seen, stored) => Math.abs(seen - stored) > Math.max(stored / 4, 2 /** `run` (`fileRun`) with `file`, the absolute path of the file it names, or * null where the command names none that is there. The payload's `cwd` is * the session's folder before the command or after it, so the run's own - * `cd` is tried first and then left out. */ + * `cd` is tried first and then left out. A run is none either when a word + * after a long flag names a folder there: pytest ran it too, where the flag + * takes no value. */ function located(run, cwd) { if (!run) return null; - const file = [path.resolve(cwd, run.dir, run.path), path.resolve(cwd, run.path)].find(isFile); - return file ? { ...run, file } : null; + const from = [path.resolve(cwd, run.dir), path.resolve(cwd)].find((dir) => isFile(path.resolve(dir, run.path))); + if (!from || run.values.some((word) => isFolder(path.resolve(from, word)))) return null; + return { ...run, file: path.resolve(from, run.path) }; } -/** Add what `run` cost to `state`, from the head of the report it wrote. A - * report whose first case is in another file is another run's (pytest names - * the file from its root, a folder at or above the file's). A whole run - * counts when no case failed: one that stopped at a failure took less. The - * file is put last, so the bound drops the one least recently run. */ -function add(state, run, head) { - const cost = runCost(head); - if (!cost?.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; +/** Add what `run` cost to `state`: `cost` is `runCost` of the head of the + * report it wrote. A report whose first case is in another file is another + * run's (pytest names the file from its root, a folder at or above the + * file's). A whole run counts when no case failed: one that stopped at a + * failure took less. The file is put last, so the bound drops the one least + * recently run. */ +function add(state, run, cost) { + if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; const whole = run.whole && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); const next = { @@ -86,38 +92,49 @@ function add(state, run, head) { state.files = Object.fromEntries(Object.entries(files).slice(-MAX_FILES)); } +/** Count `report` (`newReport`) for the session's pending run when the run + * that wrote it began before the pending run's command returned: pytest + * began it at the time the file was written less the suite's seconds. A + * command that came later, whatever it is and whether or not a hook saw it, + * began its run after that. The pending run is then settled. */ +function settle(state, report) { + const cost = report ? runCost(report.head) : null; + if (!cost || !state.pending || report.mtimeMs - cost.time * 1000 > state.pending.at) return; + add(state, state.pending, cost); + state.pending = undefined; +} + /** * Note a shell command the test report was read for: its text, its visible - * `output`, the `head` of the report when a run wrote it since the session's - * last read (else null), and the payload's `cwd`. + * `output`, the `report` when a run wrote it since the session's last read + * (`newReport`, else null), and the payload's `cwd`. * * The report is the command's when the command is one pytest run of one test * file (`fileRun`) and its output shows pytest's summary with the seconds * the report holds: a run the option did not reach writes no report, and the * one read after it is an earlier run's. A run whose output shows no summary - * has not ended: it is kept as the session's pending run. A report that - * comes with a later command is the pending run's when that command starts - * the same run again, or starts no test run at all (`mayRunTests`), as a - * command that only names a runner does. Any other command drops the pending - * run: a report after it could be either's. + * may not have ended: it is kept as the session's pending run, with the time + * its command returned. Any other report is the pending run's when its run + * began by that time (`settle`), and no run's otherwise. So a run that was + * put in the background before pytest began is not counted. An open run of + * another kind than the pending one drops both: one of the two would be + * counted as the other. */ -export function noteCommand(sessionId, { command, output, head, cwd }) { +export function noteCommand(sessionId, { command, output, report, cwd }) { try { const run = located(fileRun(command, output), cwd || process.cwd()); const state = readSessionState(RUNS, sessionId); - const pending = state.pending; - if (!run && !pending) return; - if (!run && !mayRunTests(command)) { - if (!head) return; - add(state, pending, head); - state.pending = undefined; - } else { - const open = Boolean(run && run.seconds === null); - const again = Boolean(open && pending && pending.file === run.file && pending.whole === run.whole); - // The summary's seconds and the report's are two clocks on one run. - const ended = run && !open && Math.abs(run.seconds - runCost(head)?.seconds) <= Math.max(1, run.seconds / 20); - if (head && (again || ended)) add(state, run, head); - state.pending = open && (!pending || again) ? { file: run.file, whole: run.whole } : undefined; + if (!run && !state.pending) return; + const cost = report ? runCost(report.head) : null; + const open = Boolean(run && run.seconds === null); + // The summary's seconds and the report's are two clocks on one run. + const own = run && !open && cost && Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); + if (own) add(state, run, cost); + else settle(state, report); + if (open) { + const pending = state.pending; + const free = !pending || (pending.file === run.file && pending.whole === run.whole); + state.pending = free ? { file: run.file, whole: run.whole, at: Date.now() } : undefined; } writeSessionState(RUNS, sessionId, state); } catch { @@ -126,15 +143,14 @@ export function noteCommand(sessionId, { command, output, head, cwd }) { } /** At the session's end, before its report is removed: a report written - * since the session's last read is the pending run's. One bounded read of - * the session's own file, and no token is read. */ + * since the session's last read is counted for the pending run (`settle`). + * One bounded read of the session's own file, and no token is read. */ export function settleRun(sessionId) { try { const state = readSessionState(RUNS, sessionId); if (!state.pending) return; const seen = seenReport(sessionId); - const report = seen && newReport(sessionId, seen); - if (report) add(state, state.pending, report.head); + settle(state, seen && newReport(sessionId, seen)); state.pending = undefined; writeSessionState(RUNS, sessionId, state); } catch { @@ -192,26 +208,27 @@ const identity = (scope, agent) => ({ /** * The line for a prompt of a session that has the test report, in the - * checkout at `root`, or "": the repository's row, read once a session - * (`memory.get` by key, bounded by `options.timeoutMs`) and kept in the - * session's state, a miss too, with the agent that wrote it. `scopeOf()` is - * asked only for that read. An answer that does not come and an error give no - * line, and a later prompt asks again. A row gives none whose value is not - * `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose - * file the checkout does not hold. + * checkout at `root`, or "": the repository's row, read once a session and + * checkout (`memory.get` by key, bounded by `options.timeoutMs`) and kept in + * the session's state, a miss too, with the agent that wrote it and the + * checkout it was read in: a session whose folder moved to another checkout + * reads that one's row. `scopeOf()` is asked only for that read. An answer + * that does not come and an error give no line, and a later prompt asks + * again. A row gives none whose value is not `claim`'s text, whose whole run + * is under `MIN_WHOLE_SECONDS`, or whose file the checkout does not hold. */ export async function costLine(sessionId, root, scopeOf, options) { try { if (!seenReport(sessionId)) return ""; let held = readSessionState(ROW, sessionId); - if (!held.read) { + if (!held.read || held.root !== root) { const scope = scopeOf(); if (!costKey(scope)) return ""; const fields = ["value", "content_sha256", "agent"]; const res = await postBounded("memory.get", { ...identity(scope), fields }, options); if (!res) return ""; const found = { sha: String(res.content_sha256 || ""), agent: String(res.agent || "") }; - held = { read: true, row: res.found ? { ...parseClaim(scope.repo.id, res.value), ...found } : null }; + held = { read: true, root, row: res.found ? { ...parseClaim(scope.repo.id, res.value), ...found } : null }; writeSessionState(ROW, sessionId, held); } const row = held.row; @@ -286,12 +303,12 @@ function measured(state, root) { /** * The flusher's post that stores what the session measured, or null; the * session's cost state is removed either way. Only a session whose prompt - * read the row stores, a miss included: it knows what it replaces, and where - * no prompt can read the row no session writes one. One `memory.set` of the - * repository's key follows where `revised` has a claim: a revision of the - * row as read (`if_match_sha256`, under the row's agent), else a first row - * (`absent`). The value names no file to the server (`files: []`), and its - * class says a tool measured it. + * read the row in the checkout of `cwd` stores, a miss included: it knows + * what it replaces, and where no prompt can read the row no session writes + * one. One `memory.set` of the repository's key follows where `revised` has + * a claim: a revision of the row as read (`if_match_sha256`, under the row's + * agent), else a first row (`absent`). The value names no file to the server + * (`files: []`), and its class says a tool measured it. */ export function costPost(sessionId, cwd, scopeOf) { try { @@ -299,7 +316,7 @@ export function costPost(sessionId, cwd, scopeOf) { const held = readSessionState(ROW, sessionId); for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); const root = held.read && state.files ? gitToplevel(cwd) : ""; - const runs = root ? measured(state, root) : {}; + const runs = root && held.root === root ? measured(state, root) : {}; if (!Object.keys(runs).length) return null; const row = held.row?.path ? { ...held.row, gone: !isFile(path.join(root, held.row.path)) } : held.row; const next = revised(runs, row); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 26d02f4c102..3e1673c1970 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1360,15 +1360,17 @@ const CLUSTER = /^-[A-Za-z]+[km]/; // A run that names its own result file, or turns the result file off, // does not write the session's. const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; +// A Python file, or a test in one, as a word of a pytest command. +const PYTHON_FILE = /\.py(?:::|$)/; /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, dir, whole, seconds }`, else null. `path` is the file - * as the command spells it and `dir` the folder of the one `cd` before the - * run, "" for none. `whole` is false for a run filtered with `-k`. `seconds` - * is what pytest's summary line in the visible `output` shows, null where - * the output holds none: the run did not finish inside the call. + * else to run: `{ path, dir, whole, seconds, values }`, else null. `path` is + * the file as the command spells it and `dir` the folder of the one `cd` + * before the run, "" for none. `whole` is false for a run filtered with `-k`. + * `seconds` is what pytest's summary line in the visible `output` shows, null + * where the output holds none: the run did not finish inside the call. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1378,7 +1380,10 @@ const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder the shell * expands). The word after a flag that may take a value is that value and no * path (`BARE`); a short flag written with its value (`-rf`, `-kparse`, - * `-n4`) takes none after it. + * `-n4`) takes none after it. A long flag may take none (`--no-header`), and + * the word after it is then a second path: a run with such a word that names + * a Python file is none, and the others are `values`, for a reader that can + * tell a folder (`--cov src` from `--no-header tests`). */ export function fileRun(command, output = "") { const text = String(command || "").replace(/\\\n/g, ""); @@ -1392,14 +1397,21 @@ export function fileRun(command, output = "") { cd.every((m) => !/^-$|[$~`*?]/.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; - let value = false; + const values = []; + // The flag before a word, where the word may be its value. + let flag = ""; for (const word of words) { - const flag = word.startsWith("-"); - if (!flag && !value) named.push(word); - value = flag && !word.includes("=") && !BARE.test(word) && !/^-[^-]./.test(word); + if (word.startsWith("-")) { + flag = !word.includes("=") && !BARE.test(word) && !/^-[^-]./.test(word) ? word : ""; + continue; + } + if (!flag) named.push(word); + else if (flag.startsWith("--") || PYTHON_FILE.test(word)) values.push(word); + flag = ""; } const other = (word) => !BY_NAME.test(word) && (PARTIAL.test(word) || CLUSTER.test(word) || OWN_REPORT.test(word)); if (!followed || named.length !== 1 || !/^[^\s:]+\.py$/.test(named[0]) || words.some(other)) return null; + if (values.some((word) => PYTHON_FILE.test(word))) return null; const summary = String(output || "") .split(/\r?\n/) .findLast((line) => line.length < 300 && SUMMARY.test(line)); @@ -1408,22 +1420,10 @@ export function fileRun(command, output = "") { dir: cd.length ? unquoted(cd[0][1]) : "", whole: !words.some((word) => BY_NAME.test(word)), seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, + values, }; } -// The name of pytest where a command only mentions it. -const PYTEST_NAME = /(? ranHere(text.slice(0, run.index)))) return true; - return startsRunner(text.replace(PYTEST_NAME, " ")); -} - /** * The repo-relative files and directories pytest ran to its summary on the * tree as it stands, read in transcript order (Claude Code rows; sidechains diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index a73a4fc7e4f..35583b194ed 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -118,9 +118,10 @@ export function seenReport(sessionId) { } /** The session's report when a run wrote it since the session saw it as - * `seen`: `{ xml, head }`, with "" as `xml` for a report over the read - * bound and its first `HEAD_BYTES` as `head`, and the file noted as seen. - * null when no run wrote it, or the file is not this user's regular file. */ + * `seen`: `{ xml, head, mtimeMs }`, with "" as `xml` for a report over the + * read bound, its first `HEAD_BYTES` as `head` and the time it was written, + * and the file noted as seen. null when no run wrote it, or the file is not + * this user's regular file. */ export function newReport(sessionId, seen) { let fd; try { @@ -134,7 +135,7 @@ export function newReport(sessionId, seen) { const large = st.size > MAX_REPORT_BYTES; const buf = Buffer.alloc(large ? HEAD_BYTES : st.size); const text = buf.toString("utf8", 0, fs.readSync(fd, buf, 0, buf.length, 0)); - return { xml: large ? "" : text, head: text.slice(0, HEAD_BYTES) }; + return { xml: large ? "" : text, head: text.slice(0, HEAD_BYTES), mtimeMs: st.mtimeMs }; } catch { return null; } finally { @@ -290,10 +291,11 @@ function scan(xml) { } /** What the run that wrote a result file cost, from the file's `head`: the - * first testsuite's case count, its seconds to the nearest one, how many - * cases failed or ended in an error, and the file of its first testcase, - * which pytest names in the family the option sets ("" where the head holds - * none). null for a head with no whole testsuite tag, no case or no time. */ + * first testsuite's case count, its seconds to the nearest one and as + * written (`time`), how many cases failed or ended in an error, and the file + * of its first testcase, which pytest names in the family the option sets + * ("" where the head holds none). null for a head with no whole testsuite + * tag, no case or no time. */ export function runCost(head) { const first = (text, name) => { try { @@ -313,6 +315,7 @@ export function runCost(head) { return { tests, seconds: Math.round(seconds), + time: seconds, failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), file: testcase ? attributes(testcase.attrs).file || "" : "", }; diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index e169d283940..6929939e71a 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -398,7 +398,7 @@ "integrations/claude-code-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/claude-code-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/claude-code-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "02d39ad9db1f1882a115bee950e11eb0248424c0a911e56705c38fa97493b20b", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "5133b73e57ef727a6c3db72541e33476484b8dff04b81eef98a790270985c729", "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "65a0e04dba5319c703c7d267179bb1739014a16d133f6eb6c504ef5c12e596fc", "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/claude-code-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -410,11 +410,11 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "a048dd09f6e714ae0d0e7c6da268b58bb1c6fdc1e7c89cc910a34f234c77c2cb", + "integrations/claude-code-plugin/lib/test-cost.mjs": "2e3630929e3f9f0bd23a0b243228e9d046ca50f3a5f10809a541d2198662ffa8", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "02d39ad9db1f1882a115bee950e11eb0248424c0a911e56705c38fa97493b20b", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "5133b73e57ef727a6c3db72541e33476484b8dff04b81eef98a790270985c729", "integrations/codex-plugin/hooks/loom-session-start.mjs": "65a0e04dba5319c703c7d267179bb1739014a16d133f6eb6c504ef5c12e596fc", "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "a048dd09f6e714ae0d0e7c6da268b58bb1c6fdc1e7c89cc910a34f234c77c2cb", + "integrations/codex-plugin/lib/test-cost.mjs": "2e3630929e3f9f0bd23a0b243228e9d046ca50f3a5f10809a541d2198662ffa8", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 5327b785a732d1352df7a65d35baed7dbe68f291 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 18:49:01 +0530 Subject: [PATCH 04/24] A whole run that skipped its cases is no test cost, and the cost line follows the test report's switch A whole run counts for its file only when no more than a tenth of its cases were skipped: pytest counts a skipped case in `tests`, so a run on a machine where the cases skip read as the file's whole run and lowered the repository's row under the 60 s a line needs. `costLine` reads LOOM_TEST_REPORT and the `test_report` option, so a session that has the report's state and the switch off sends no `memory.get`. The switch is read in the library a bug report loads, which keeps the test gate's library out of every other prompt. The session has one result file, and no hook runs before a shell command: a pytest run that ends before a hook read the report of a run that outlived its call replaces it. The docs state it, and a test holds it. The tests that asserted only that nothing was stored assert what the session read and noted first. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 14 +- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 7 +- .../hooks/loom-prompt-pack.mjs | 21 +-- .../claude-code-plugin/lib/test-cost.mjs | 39 ++--- .../claude-code-plugin/lib/test-gate.mjs | 5 +- .../claude-code-plugin/lib/test-report.mjs | 10 +- .../tests/test-cost.test.mjs | 136 +++++++++++++++--- .../codex-plugin/hooks/loom-prompt-pack.mjs | 21 +-- integrations/codex-plugin/lib/test-cost.mjs | 39 ++--- integrations/codex-plugin/lib/test-gate.mjs | 5 +- integrations/codex-plugin/lib/test-report.mjs | 10 +- tests/unit/session_content_senders.json | 8 +- 13 files changed, 226 insertions(+), 91 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 895d8875daa..a698eec99c9 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1656,7 +1656,9 @@ checkout, that names one test file and nothing else to run, the hook reads the n cases and the seconds pytest writes at the head of the result file, and keeps them in the session's private state, by the file: -- a whole run counts when no case failed, and the costliest one of each file is kept; +- a whole run counts when no case failed and no more than a tenth of its cases were + skipped (a run on a machine where the cases skip takes less), and the costliest one of + each file is kept; - a run filtered with `-k` counts as filtered, and a file's filtered time is the middle of the session's filtered runs of it that ran fewer cases than the whole file; - a run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a @@ -1672,7 +1674,9 @@ writes the file after the hook ran: it is read after the next shell command that test runner, or when the session ends. That file is the run's when pytest began the run that wrote it before the run's own command returned (the time the file was written, less the seconds it holds): a run that any later command started began after that, and its -file counts for no run. +file counts for no run. The session has one result file, so the next pytest run that +ends replaces it: where that run ends before a hook has read the file, the run that +outlived its call is not counted. **What is stored.** When the session ends, what it measured goes to the repository's one memory row, written with the session's turns (`memory.set`, key @@ -1725,6 +1729,12 @@ What it does not do: - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not, and neither is one that was open together with a run of another kind of the same file; +- a run that outlives its shell call is not counted when the session's next test command + is a pytest run: that run writes the same result file before any hook reads it. So a + whole run that went to the background is counted where it is the session's last pytest + run, or where a command that names a test runner and starts no pytest, such as + `pgrep -f pytest`, comes before the next one, and not where a `-k` run follows it at + once; - a row whose file was removed stays, unprinted, until a session measures a slow whole run of another file; - the row is an ordinary memory row, so recall can serve its sentence, and two diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index b866b92f4f2..734ab75f92c 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed and no more than a tenth of its cases were skipped, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index f5d4f8bdfbc..6aa37eebad8 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1339,7 +1339,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that (`runCost`, read from the file's first 4,096 bytes, also for a file over the 2 MB bound). The session's private state keeps, for each of the eight files it ran last, the costliest whole run in which no case - failed and the case count and seconds of each run filtered with `-k`. + failed and no more than a tenth of the cases were skipped, and the case + count and seconds of each run filtered with `-k`. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`, which may run every case), a run that only collects or prints, and a command with two pytest runs or two paths are noted as @@ -1365,6 +1366,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that reading a token. A run of another kind left open while one is pending drops both, since one would be counted as the other. A run put in the background at once returns before pytest began, and is not counted. + The session has one result file, and no hook runs between two + commands: where the session's next pytest run ends before a hook has + read the file, that run's report replaces the pending run's, which is + then not counted. At SessionEnd `loom-session-memory` hands one `memory.set` to the flusher, with the session's turns, where a prompt of the session read the row, a miss included, and its runs say something the row does not diff --git a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index f6bc9ad0243..f2cdab2e217 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -43,14 +43,15 @@ // the line is the test gate's. // // Below those goes one test cost line, for a bug report (as the next paragraph -// reads one) in a session that has the test report, where the memory plane -// runs and an earlier session stored what a whole run of a slow test file -// costs in this repository (lib/test-cost.mjs): the file, its case count and -// seconds, the seconds of a run filtered with -k, and to check a change with -// -k selections. The row is read by its key once a session and checkout, -// beside the search and inside the prompt's bound, and the line is sent only -// when that read has answered by the time the search has: it never holds the -// pointers back. A row whose file the checkout does not hold prints nothing. +// reads one) in a session that has the test report (LOOM_TEST_REPORT=off +// stops the line), where the memory plane runs and an earlier session stored +// what a whole run of a slow test file costs in this repository +// (lib/test-cost.mjs): the file, its case count and seconds, the seconds of a +// run filtered with -k, and to check a change with -k selections. The row is +// read by its key once a session and checkout, beside the search and inside +// the prompt's bound, and the line is sent only when that read has answered +// by the time the search has: it never holds the pointers back. A row whose +// file the checkout does not hold prints nothing. // // A search whose query reads as a bug report (twelve words or more, or a word // such as `error` or `crash`) asks the server's pick model @@ -133,7 +134,9 @@ const TOP_K = Math.round(envNumber("LOOM_PROMPT_PACK_TOP_K", 3, { min: 1, max: 5 const PICK_TIMEOUT_MS = Math.round(envNumber("LOOM_PROMPT_PACK_PICK_TIMEOUT_MS", 6000, { min: 200 })); // The test line is the test gate's: sent in the modes that name a test at edit time. const TEST_LINE = gateAdvises(); -// The test cost line is read from memory: only where that plane runs too. +// The test cost line is read from memory: only where that plane runs too. The +// test report's switch is read with the line (`costLine`), in the library a +// bug report loads. const COST_LINE = planeEnabled("memory"); const CONSUMER = "claude-code-prompt-pack"; diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 0e183f0ce06..07edc6b4b98 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -11,7 +11,9 @@ // filtered with -k. A run that outlives its shell call writes the file after // that call's hook ran: a report read later is its when pytest began the run // that wrote it before that call returned, and the launcher reads the file -// once more before it removes it at the session's end (`settleRun`). +// once more before it removes it at the session's end (`settleRun`). The +// file is one a session: a pytest run that ends before a hook read it +// replaces it, and the run that outlived its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -28,13 +30,15 @@ import fs from "node:fs"; import path from "node:path"; import { gitToplevel, hookClient, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; import { fileRun } from "./test-gate.mjs"; -import { newReport, runCost, seenReport } from "./test-report.mjs"; +import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; // A whole run shorter than this is not worth a line in a prompt. const MIN_WHOLE_SECONDS = 60; // The default timeout of one shell call under Claude Code. const CALL_TIMEOUT_SECONDS = 120; +// A whole run that skipped a larger share of its cases did not run the file. +const MAX_SKIPPED_SHARE = 0.1; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. const MAX_FILES = 8; @@ -76,13 +80,15 @@ function located(run, cwd) { /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another * run's (pytest names the file from its root, a folder at or above the - * file's). A whole run counts when no case failed: one that stopped at a - * failure took less. The file is put last, so the bound drops the one least - * recently run. */ + * file's). A whole run counts when no case failed and no more than + * `MAX_SKIPPED_SHARE` of them were skipped: one that stopped at a failure, + * or ran where its cases skip, took less. The file is put last, so the + * bound drops the one least recently run. */ function add(state, run, cost) { if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; - const whole = run.whole && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); + const ran = !cost.failed && cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; + const whole = run.whole && ran && cost.seconds > (seen.whole?.seconds ?? -1); const next = { ...seen, ...(whole ? { whole: { tests: cost.tests, seconds: cost.seconds } } : {}), @@ -207,19 +213,20 @@ const identity = (scope, agent) => ({ }); /** - * The line for a prompt of a session that has the test report, in the - * checkout at `root`, or "": the repository's row, read once a session and - * checkout (`memory.get` by key, bounded by `options.timeoutMs`) and kept in - * the session's state, a miss too, with the agent that wrote it and the - * checkout it was read in: a session whose folder moved to another checkout - * reads that one's row. `scopeOf()` is asked only for that read. An answer - * that does not come and an error give no line, and a later prompt asks - * again. A row gives none whose value is not `claim`'s text, whose whole run - * is under `MIN_WHOLE_SECONDS`, or whose file the checkout does not hold. + * The line for a prompt of a session that has the test report and has not + * switched it off, in the checkout at `root`, or "": the repository's row, + * read once a session and checkout (`memory.get` by key, bounded by + * `options.timeoutMs`) and kept in the session's state, a miss too, with the + * agent that wrote it and the checkout it was read in: a session whose + * folder moved to another checkout reads that one's row. `scopeOf()` is + * asked only for that read. An answer that does not come and an error give + * no line, and a later prompt asks again. A row gives none whose value is + * not `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose + * file the checkout does not hold. */ export async function costLine(sessionId, root, scopeOf, options) { try { - if (!seenReport(sessionId)) return ""; + if (!testReportOn() || !seenReport(sessionId)) return ""; let held = readSessionState(ROW, sessionId); if (!held.read || held.root !== root) { const scope = scopeOf(); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 3e1673c1970..19fbda8de3b 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1382,8 +1382,9 @@ const PYTHON_FILE = /\.py(?:::|$)/; * path (`BARE`); a short flag written with its value (`-rf`, `-kparse`, * `-n4`) takes none after it. A long flag may take none (`--no-header`), and * the word after it is then a second path: a run with such a word that names - * a Python file is none, and the others are `values`, for a reader that can - * tell a folder (`--cov src` from `--no-header tests`). + * a Python file is none, and the others are `values`. The caller drops a run + * where one of them names a folder (`--no-header tests`, and `--cov src` + * too): the flag may take no value. */ export function fileRun(command, output = "") { const text = String(command || "").replace(/\\\n/g, ""); diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index 35583b194ed..d451030c54c 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -292,10 +292,11 @@ function scan(xml) { /** What the run that wrote a result file cost, from the file's `head`: the * first testsuite's case count, its seconds to the nearest one and as - * written (`time`), how many cases failed or ended in an error, and the file - * of its first testcase, which pytest names in the family the option sets - * ("" where the head holds none). null for a head with no whole testsuite - * tag, no case or no time. */ + * written (`time`), how many cases failed or ended in an error, how many + * were skipped (pytest counts them as cases), and the file of its first + * testcase, which pytest names in the family the option sets ("" where the + * head holds none). null for a head with no whole testsuite tag, no case or + * no time. */ export function runCost(head) { const first = (text, name) => { try { @@ -317,6 +318,7 @@ export function runCost(head) { seconds: Math.round(seconds), time: seconds, failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), + skipped: Number(has.skipped) || 0, file: testcase ? attributes(testcase.attrs).file || "" : "", }; } diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index e662b3ed9ab..aeecd3fb9d7 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -31,10 +31,10 @@ const KEY = `repo:${REPO}/test-cost/pytest`; /** A result file as pytest writes it in the family the option sets, which * names each case's file: one suite of `tests` cases that took `time`. */ -function report({ tests, time, file = FILE, failures = 0 }) { +function report({ tests, time, file = FILE, failures = 0, skipped = 0 }) { return ( `` + + `failures="${failures}" skipped="${skipped}" tests="${tests}" time="${time}" timestamp="2000-01-01T00:00:00" hostname="h">` + `` + `` ); @@ -51,13 +51,14 @@ const BOTH = `In the repository tagged repo:${REPO}, a whole run of ${FILE} coll // --- the parts ---------------------------------------------------------------- test("the head of a report gives the run's case count and its seconds", () => { - const whole = { tests: 8000, seconds: 140, time: 140.2, failed: 0, file: FILE }; + const whole = { tests: 8000, seconds: 140, time: 140.2, failed: 0, skipped: 0, file: FILE }; assert.deepEqual(runCost(WHOLE.slice(0, 4096)), whole); - assert.deepEqual(runCost(report({ tests: 3, time: "0.4", failures: 2 })), { + assert.deepEqual(runCost(report({ tests: 3, time: "0.4", failures: 2, skipped: 1 })), { tests: 3, seconds: 0, time: 0.4, failed: 2, + skipped: 1, file: FILE, }); // A head cut inside the first case still holds the suite's totals. @@ -85,7 +86,14 @@ test("a report over the read bound is read for its head", { skip: WINDOWS }, (t) assert.equal(read.xml, ""); assert.equal(read.head.length, 4096); assert.equal(read.mtimeMs, fs.statSync(reportPath(SESSION)).mtimeMs); - assert.deepEqual(runCost(read.head), { tests: 8000, seconds: 140, time: 140.2, failed: 0, file: FILE }); + assert.deepEqual(runCost(read.head), { + tests: 8000, + seconds: 140, + time: 140.2, + failed: 0, + skipped: 0, + file: FILE, + }); }); }); @@ -356,11 +364,16 @@ test("a report is the command's whose output shows the summary with the report's assert.deepEqual(runs().files[file].whole, whole(160)); note(WHOLE_COMMAND, "9000 passed in 900.00s", report({ tests: 9000, time: "900.0", file: "tests/test_other.py" })); assert.deepEqual(runs().files[file].whole, whole(160)); + // A run that skipped more than a tenth of its cases did not run the file; a tenth still counts. + note(WHOLE_COMMAND, "7199 passed, 801 skipped in 400.00s", report({ tests: 8000, time: "400.0", skipped: 801 })); + assert.deepEqual(runs().files[file].whole, whole(160)); + note(WHOLE_COMMAND, "7200 passed, 800 skipped in 170.00s", report({ tests: 8000, time: "170.0", skipped: 800 })); + assert.deepEqual(runs().files[file].whole, whole(170)); // A run the option did not reach wrote no report: the one read after it is an // earlier run's, and its seconds are not the summary's. note(`PYTEST_ADDOPTS=-q pytest ${FILE} -k parse`, FILTERED_OUTPUT, report({ tests: 8000, time: "600.0" })); note(WHOLE_COMMAND, "8000 passed in 2.31s", report({ tests: 8000, time: "600.0" })); - assert.deepEqual(runs(), { files: { [file]: { whole: whole(160), filtered } } }); + assert.deepEqual(runs(), { files: { [file]: { whole: whole(170), filtered } } }); }); }); @@ -699,6 +712,8 @@ test("a session whose prompts read no row stores nothing", { skip: WINDOWS }, as const server = await loom(t); const box = sandbox(t, server); await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + // The session measured a run that makes a first row. + assert.deepEqual(readJsonFile(box.runs, null), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); // A question is no bug report: it reads no row. assert.equal(context(await ask(box, { prompt: "How are nested record prefixes combined?" })), BLOCK); await endSession(box); @@ -771,41 +786,110 @@ test("the launcher at an agent's SessionEnd reads the pending run's report and e ); }); -test("nothing is stored for a whole run under 60 s, a command of two runs or two paths, or with a switch off", { +test("nothing is stored for a whole run under 60 s, a command of two runs or two paths, or with session memory off", { skip: WINDOWS, }, async (t) => { const server = await loom(t); + const whole = (seconds) => ({ whole: { tests: 8000, seconds } }); const cases = [ - // Under 60 s. - [`python -m pytest ${FILE} -q`, "8000 passed in 59.40s", report({ tests: 8000, time: "59.4" }), {}], + // Under 60 s: noted, and no first row. + [`python -m pytest ${FILE} -q`, "8000 passed in 59.40s", report({ tests: 8000, time: "59.4" }), {}, whole(59)], // Two runs, two paths, and a selection that is not by name: nothing is noted. - [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}], - [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}], - [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}], - // The session hands nothing to memory, or has no test report. - [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }], - [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_TEST_REPORT: "off" }], + [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}, null], + [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}, null], + [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}, null], + // The session hands nothing to memory. + [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }, whole(140)], ]; - for (const [command, output, xml, extra] of cases) { + for (const [at, [command, output, xml, extra, seen]] of cases.entries()) { const box = sandbox(t, server); await ask(box, { extra }); + // The session's prompt read the row, a miss: its end may store a first one. + assert.equal(server.sent("memory.get").length, at + 1, command); await afterCommand(box, command, output, xml, extra); + assert.deepEqual(readJsonFile(box.runs, null), seen && { files: { [box.file]: seen } }, command); await endSession(box, extra); await settled(box); } assert.deepEqual(server.sent("memory.set"), []); }); +test("a session's end with the test report switched off reads no report and stores nothing", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await ask(box); + assert.equal(server.sent("memory.get").length, 1); + // A whole run that makes a first row, and one that outlived its call and wrote its report since. + await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + await afterCommand(box, `python -m pytest ${FILE} -q`, STARTED); + fs.writeFileSync(box.report, report({ tests: 8000, time: "200.0" })); + const held = noted(box.runs); + assert.deepEqual(held, { + pending: { file: box.file, whole: true }, + files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } }, + }); + await endSession(box, { LOOM_TEST_REPORT: "off" }); + await settled(box); + // The launcher did not read the pending run's report, and nothing was handed to memory. + assert.deepEqual(noted(box.runs), held); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a pytest run that ends before a hook read the pending run's report replaces it", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await ask(box); + await afterCommand(box, `python -m pytest ${FILE} -q`, STARTED); + // The whole run ends and writes the session's result file. No hook runs before + // the session's next pytest run, which writes the same file. + fs.writeFileSync(box.report, WHOLE); + await afterCommand(box, FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED); + assert.deepEqual(noted(box.runs), { + pending: { file: box.file, whole: true }, + files: { [box.file]: { filtered: [[12, 2]] } }, + }); + await endSession(box); + await settled(box); + // The whole run is not counted, and a filtered time alone makes no row. + assert.equal(server.sent("memory.get").length, 1); + assert.deepEqual(server.sent("memory.set"), []); + assert.equal(fs.existsSync(box.runs), false); +}); + +test("a whole run that skipped most of its cases does not lower the row", { skip: WINDOWS }, async (t) => { + const server = await loom(t, { get: row() }); + const box = sandbox(t, server); + assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + // The cases need a service this machine does not run. + const xml = report({ tests: 8000, time: "2.3", skipped: 7988 }); + await afterCommand(box, WHOLE_COMMAND, "12 passed, 7988 skipped in 2.31s", xml); + // The report was the command's, and counted for nothing. + assert.deepEqual(readJsonFile(box.runs, null), { files: {} }); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + test("code-only mode notes nothing, stores nothing and prints no line", { skip: WINDOWS }, async (t) => { const server = await loom(t, { get: row() }); const box = sandbox(t, server); const code = { LOOM_MODE: "code" }; - await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, code); - assert.equal(fs.existsSync(box.runs), false); + // In the default mode the session has the line, and a whole run that revises the row. + assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + await afterCommand(box, WHOLE_COMMAND, "8000 passed in 200.00s", report({ tests: 8000, time: "200.0" })); + const held = { files: { [box.file]: { whole: { tests: 8000, seconds: 200 } } } }; + assert.deepEqual(readJsonFile(box.runs, null), held); + // In code-only mode a costlier run is not noted, the prompt has no line, and the end stores nothing. + await afterCommand(box, WHOLE_COMMAND, "8000 passed in 300.00s", report({ tests: 8000, time: "300.0" }), code); + assert.deepEqual(readJsonFile(box.runs, null), held); assert.equal(context(await ask(box, { extra: code })), BLOCK); await endSession(box, code); await settled(box); - assert.deepEqual(server.sent("memory.get"), []); + assert.equal(server.sent("memory.get").length, 1); assert.deepEqual(server.sent("memory.set"), []); }); @@ -953,12 +1037,22 @@ test("a miss is kept for the session, and a row that is not the claim's text pri assert.deepEqual(other.sent("memory.set"), []); }); -test("a session without the test report reads no row", { skip: WINDOWS }, async (t) => { +test("a session without the test report, or with it switched off, reads no row", { + skip: WINDOWS, +}, async (t) => { const server = await loom(t, { get: row() }); const box = sandbox(t, server); - fs.rmSync(sessionStatePath("test-report", SESSION, { tmp: box.tmp })); + const seen = sessionStatePath("test-report", SESSION, { tmp: box.tmp }); + // Switched off in a session that was set up for the report. + assert.equal(context(await ask(box, { extra: { LOOM_TEST_REPORT: "off" } })), BLOCK); + // Not set up for the report. + fs.rmSync(seen); assert.equal(context(await ask(box)), BLOCK); assert.deepEqual(server.sent("memory.get"), []); + // Set up and on, the same prompt reads the row. + writeJsonFile(seen, { mtimeMs: 1, size: 0 }); + assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + assert.equal(server.sent("memory.get").length, 1); }); test("a read that fails or is slow leaves the pointer block as it is, and does not hold it back", { diff --git a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs index f6bc9ad0243..f2cdab2e217 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -43,14 +43,15 @@ // the line is the test gate's. // // Below those goes one test cost line, for a bug report (as the next paragraph -// reads one) in a session that has the test report, where the memory plane -// runs and an earlier session stored what a whole run of a slow test file -// costs in this repository (lib/test-cost.mjs): the file, its case count and -// seconds, the seconds of a run filtered with -k, and to check a change with -// -k selections. The row is read by its key once a session and checkout, -// beside the search and inside the prompt's bound, and the line is sent only -// when that read has answered by the time the search has: it never holds the -// pointers back. A row whose file the checkout does not hold prints nothing. +// reads one) in a session that has the test report (LOOM_TEST_REPORT=off +// stops the line), where the memory plane runs and an earlier session stored +// what a whole run of a slow test file costs in this repository +// (lib/test-cost.mjs): the file, its case count and seconds, the seconds of a +// run filtered with -k, and to check a change with -k selections. The row is +// read by its key once a session and checkout, beside the search and inside +// the prompt's bound, and the line is sent only when that read has answered +// by the time the search has: it never holds the pointers back. A row whose +// file the checkout does not hold prints nothing. // // A search whose query reads as a bug report (twelve words or more, or a word // such as `error` or `crash`) asks the server's pick model @@ -133,7 +134,9 @@ const TOP_K = Math.round(envNumber("LOOM_PROMPT_PACK_TOP_K", 3, { min: 1, max: 5 const PICK_TIMEOUT_MS = Math.round(envNumber("LOOM_PROMPT_PACK_PICK_TIMEOUT_MS", 6000, { min: 200 })); // The test line is the test gate's: sent in the modes that name a test at edit time. const TEST_LINE = gateAdvises(); -// The test cost line is read from memory: only where that plane runs too. +// The test cost line is read from memory: only where that plane runs too. The +// test report's switch is read with the line (`costLine`), in the library a +// bug report loads. const COST_LINE = planeEnabled("memory"); const CONSUMER = "claude-code-prompt-pack"; diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 0e183f0ce06..07edc6b4b98 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -11,7 +11,9 @@ // filtered with -k. A run that outlives its shell call writes the file after // that call's hook ran: a report read later is its when pytest began the run // that wrote it before that call returned, and the launcher reads the file -// once more before it removes it at the session's end (`settleRun`). +// once more before it removes it at the session's end (`settleRun`). The +// file is one a session: a pytest run that ends before a hook read it +// replaces it, and the run that outlived its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -28,13 +30,15 @@ import fs from "node:fs"; import path from "node:path"; import { gitToplevel, hookClient, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; import { fileRun } from "./test-gate.mjs"; -import { newReport, runCost, seenReport } from "./test-report.mjs"; +import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; // A whole run shorter than this is not worth a line in a prompt. const MIN_WHOLE_SECONDS = 60; // The default timeout of one shell call under Claude Code. const CALL_TIMEOUT_SECONDS = 120; +// A whole run that skipped a larger share of its cases did not run the file. +const MAX_SKIPPED_SHARE = 0.1; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. const MAX_FILES = 8; @@ -76,13 +80,15 @@ function located(run, cwd) { /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another * run's (pytest names the file from its root, a folder at or above the - * file's). A whole run counts when no case failed: one that stopped at a - * failure took less. The file is put last, so the bound drops the one least - * recently run. */ + * file's). A whole run counts when no case failed and no more than + * `MAX_SKIPPED_SHARE` of them were skipped: one that stopped at a failure, + * or ran where its cases skip, took less. The file is put last, so the + * bound drops the one least recently run. */ function add(state, run, cost) { if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; - const whole = run.whole && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); + const ran = !cost.failed && cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; + const whole = run.whole && ran && cost.seconds > (seen.whole?.seconds ?? -1); const next = { ...seen, ...(whole ? { whole: { tests: cost.tests, seconds: cost.seconds } } : {}), @@ -207,19 +213,20 @@ const identity = (scope, agent) => ({ }); /** - * The line for a prompt of a session that has the test report, in the - * checkout at `root`, or "": the repository's row, read once a session and - * checkout (`memory.get` by key, bounded by `options.timeoutMs`) and kept in - * the session's state, a miss too, with the agent that wrote it and the - * checkout it was read in: a session whose folder moved to another checkout - * reads that one's row. `scopeOf()` is asked only for that read. An answer - * that does not come and an error give no line, and a later prompt asks - * again. A row gives none whose value is not `claim`'s text, whose whole run - * is under `MIN_WHOLE_SECONDS`, or whose file the checkout does not hold. + * The line for a prompt of a session that has the test report and has not + * switched it off, in the checkout at `root`, or "": the repository's row, + * read once a session and checkout (`memory.get` by key, bounded by + * `options.timeoutMs`) and kept in the session's state, a miss too, with the + * agent that wrote it and the checkout it was read in: a session whose + * folder moved to another checkout reads that one's row. `scopeOf()` is + * asked only for that read. An answer that does not come and an error give + * no line, and a later prompt asks again. A row gives none whose value is + * not `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose + * file the checkout does not hold. */ export async function costLine(sessionId, root, scopeOf, options) { try { - if (!seenReport(sessionId)) return ""; + if (!testReportOn() || !seenReport(sessionId)) return ""; let held = readSessionState(ROW, sessionId); if (!held.read || held.root !== root) { const scope = scopeOf(); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 3e1673c1970..19fbda8de3b 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1382,8 +1382,9 @@ const PYTHON_FILE = /\.py(?:::|$)/; * path (`BARE`); a short flag written with its value (`-rf`, `-kparse`, * `-n4`) takes none after it. A long flag may take none (`--no-header`), and * the word after it is then a second path: a run with such a word that names - * a Python file is none, and the others are `values`, for a reader that can - * tell a folder (`--cov src` from `--no-header tests`). + * a Python file is none, and the others are `values`. The caller drops a run + * where one of them names a folder (`--no-header tests`, and `--cov src` + * too): the flag may take no value. */ export function fileRun(command, output = "") { const text = String(command || "").replace(/\\\n/g, ""); diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index 35583b194ed..d451030c54c 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -292,10 +292,11 @@ function scan(xml) { /** What the run that wrote a result file cost, from the file's `head`: the * first testsuite's case count, its seconds to the nearest one and as - * written (`time`), how many cases failed or ended in an error, and the file - * of its first testcase, which pytest names in the family the option sets - * ("" where the head holds none). null for a head with no whole testsuite - * tag, no case or no time. */ + * written (`time`), how many cases failed or ended in an error, how many + * were skipped (pytest counts them as cases), and the file of its first + * testcase, which pytest names in the family the option sets ("" where the + * head holds none). null for a head with no whole testsuite tag, no case or + * no time. */ export function runCost(head) { const first = (text, name) => { try { @@ -317,6 +318,7 @@ export function runCost(head) { seconds: Math.round(seconds), time: seconds, failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), + skipped: Number(has.skipped) || 0, file: testcase ? attributes(testcase.attrs).file || "" : "", }; } diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 6929939e71a..222f1983511 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -398,7 +398,7 @@ "integrations/claude-code-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/claude-code-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/claude-code-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "5133b73e57ef727a6c3db72541e33476484b8dff04b81eef98a790270985c729", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "f30dba22ec793ab2f95bca8b401d034c92c0c70e3433e17e16f2871aa98f4a9e", "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "65a0e04dba5319c703c7d267179bb1739014a16d133f6eb6c504ef5c12e596fc", "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/claude-code-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -410,11 +410,11 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "2e3630929e3f9f0bd23a0b243228e9d046ca50f3a5f10809a541d2198662ffa8", + "integrations/claude-code-plugin/lib/test-cost.mjs": "0ef6e965d8a76b3d9387e99519227dc788322649a32eacfe3464b0b6a183fcd4", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "5133b73e57ef727a6c3db72541e33476484b8dff04b81eef98a790270985c729", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "f30dba22ec793ab2f95bca8b401d034c92c0c70e3433e17e16f2871aa98f4a9e", "integrations/codex-plugin/hooks/loom-session-start.mjs": "65a0e04dba5319c703c7d267179bb1739014a16d133f6eb6c504ef5c12e596fc", "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "2e3630929e3f9f0bd23a0b243228e9d046ca50f3a5f10809a541d2198662ffa8", + "integrations/codex-plugin/lib/test-cost.mjs": "0ef6e965d8a76b3d9387e99519227dc788322649a32eacfe3464b0b6a183fcd4", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 6cf172cc79f07d9bb87d1cdcd8da5477229fdf26 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 19:29:36 +0530 Subject: [PATCH 05/24] A test run's end is read from pytest's last line, and its summary says how many cases were skipped A run that ended with no case passed or failed (every case deselected, skipped or an expected failure) was read as a run that had not ended, and dropped a pending whole run of the same file. The suite's skipped count holds the expected failures too, so a whole run of a file with many of them was never counted: a run whose summary is in sight now takes the skipped cases from that line. A run that skipped more than a tenth of its cases is no filtered time either. The docs name the bound of 15 filtered runs a file, the report of an overlapping run that is taken for a pending run's, and that the test cost write does not depend on the session's turns. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 51 +++++++++++-------- integrations/claude-code-plugin/README.md | 4 +- .../claude-code-plugin/hooks/HOOKS.md | 44 ++++++++++------ .../hooks/loom-session-memory.mjs | 8 +-- .../claude-code-plugin/lib/loom-client.mjs | 2 +- .../claude-code-plugin/lib/test-cost.mjs | 48 +++++++++-------- .../claude-code-plugin/lib/test-gate.mjs | 22 +++++--- .../claude-code-plugin/lib/test-report.mjs | 3 +- .../tests/test-cost.test.mjs | 45 ++++++++++++++-- .../hooks/loom-session-memory.mjs | 8 +-- integrations/codex-plugin/lib/loom-client.mjs | 2 +- integrations/codex-plugin/lib/test-cost.mjs | 48 +++++++++-------- integrations/codex-plugin/lib/test-gate.mjs | 22 +++++--- integrations/codex-plugin/lib/test-report.mjs | 3 +- tests/unit/session_content_senders.json | 8 +-- 15 files changed, 199 insertions(+), 119 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index a698eec99c9..af29eb54458 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1089,7 +1089,7 @@ The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. | Stop, PreCompact, SessionEnd | `loom-capture.mjs` | crystallises the session (`observe.crystallize`) | none | | PreCompact, SessionEnd | `loom-session-brief.mjs` | revises the branch's session brief (`session.brief_save`, key `auto//`) | `LOOM_SESSION_BRIEF=off` | | SessionEnd | `loom-run.mjs` | closes the run (`run.complete`, `outcome: none`, the last reply as the final response) | `LOOM_RUN_LEDGER=off` | -| SessionEnd | `loom-session-memory.mjs` | hands the session's turns to `memory.set_from_messages(defer=true)`, which extracts facts and writes the session summary, and with them one `memory.set` of what a slow whole run of one test file cost ([what a whole run costs](#what-a-whole-run-costs)); a session with under 40 bytes (UTF-8) of user and assistant text is not sent and gets neither | `LOOM_SESSION_MEMORY=off` | +| SessionEnd | `loom-session-memory.mjs` | hands the session's turns to `memory.set_from_messages(defer=true)`, which extracts facts and writes the session summary; a session with under 40 bytes (UTF-8) of user and assistant text is not sent and gets neither. The same hand-off carries one `memory.set` of what a slow whole run of one test file cost, whether or not the turns are sent ([what a whole run costs](#what-a-whole-run-costs)) | `LOOM_SESSION_MEMORY=off` | The plugin's hooks and its MCP header helper (the script that adds the token to Loom's MCP requests) run `node`, `git` and `grep` on your machine: `git` reads the checkout's @@ -1656,30 +1656,31 @@ checkout, that names one test file and nothing else to run, the hook reads the n cases and the seconds pytest writes at the head of the result file, and keeps them in the session's private state, by the file: -- a whole run counts when no case failed and no more than a tenth of its cases were - skipped (a run on a machine where the cases skip takes less), and the costliest one of - each file is kept; +- a whole run counts when no case failed, and the costliest one of each file is kept; - a run filtered with `-k` counts as filtered, and a file's filtered time is the middle - of the session's filtered runs of it that ran fewer cases than the whole file; + of the session's last 15 filtered runs of it that ran fewer cases than the whole file; +- a run that skipped more than a tenth of its cases counts as neither: a run on a machine + where the cases skip takes less. The skipped cases are the ones pytest's summary line + counts, apart from the expected failures (`xfail`); - a run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, and a run that only collects or prints (`--collect-only`, `--fixtures`) count as neither. The word after a long flag is a second path where the flag takes no value (`--no-header tests`): a run with such a word that names a Python file or a folder counts as neither too. -The result file is the command's when the command's output shows pytest's summary line -with the seconds the file holds (within a second, or a twentieth of them), and the file's -first case is in the test file the command names. A run that outlives its shell call -writes the file after the hook ran: it is read after the next shell command that names a -test runner, or when the session ends. That file is the run's when pytest began the run -that wrote it before the run's own command returned (the time the file was written, less -the seconds it holds): a run that any later command started began after that, and its -file counts for no run. The session has one result file, so the next pytest run that -ends replaces it: where that run ends before a hook has read the file, the run that -outlived its call is not counted. +The result file is the command's when the command's output shows pytest's summary line, +whatever it counts, with the seconds the file holds (within a second, or a twentieth of +them), and the file's first case is in the test file the command names. A run that +outlives its shell call writes the file after the hook ran: it is read after the next +shell command that names a test runner, or when the session ends. That file is the run's +when pytest began the run that wrote it before the run's own command returned (the time +the file was written, less the seconds it holds): a run that any later command started +began after that, and its file counts for no run. The session has one result file, so +the next pytest run that ends replaces it: where that run ends before a hook has read +the file, the run that outlived its call is not counted. **What is stored.** When the session ends, what it measured goes to the repository's one -memory row, written with the session's turns (`memory.set`, key +memory row, in the hand-off that carries the session's turns (`memory.set`, key `repo:/test-cost/pytest`, in the session's namespace): ```text @@ -1729,12 +1730,18 @@ What it does not do: - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not, and neither is one that was open together with a run of another kind of the same file; -- a run that outlives its shell call is not counted when the session's next test command - is a pytest run: that run writes the same result file before any hook reads it. So a - whole run that went to the background is counted where it is the session's last pytest - run, or where a command that names a test runner and starts no pytest, such as - `pgrep -f pytest`, comes before the next one, and not where a `-k` run follows it at - once; +- a run that outlives its shell call is not counted when the session's next pytest run + ends before a hook has read the result file: that run writes the same file over it. So + a whole run that went to the background is counted where it is the session's last + pytest run, or where a command that names a test runner and starts no pytest, such as + `pgrep -f pytest`, comes after it ended and before the next pytest run ends, and not + where a `-k` run follows its end at once; +- a run that outlives its shell call has no summary line, and the result file counts an + expected failure (`xfail`) as skipped: such a run of a file where more than a tenth of + the cases are expected failures is not counted; +- the result file of a run of the same file that something else started while a run that + outlived its shell call was in that call, such as a script in the background, is + counted as that run's when a command that is not the other run reads it; - a row whose file was removed stays, unprinted, until a session measures a slow whole run of another file; - the row is an ordinary memory row, so recall can serve its sentence, and two diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 734ab75f92c..9f4faea1a86 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -301,7 +301,7 @@ the duplicate, run `claude mcp remove -s user`. | `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. A new or cleared conversation whose checkout is on another branch than the note names gets its primer without the note. 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. The body also names the files the session changed in its checkout (each path and the time it was last written, never its content), which decide the session's fix record whatever tool wrote them, and `HEAD` as the commit that holds them, when its history has a commit of the session's that touches every file its edit tool wrote (the tag `change:`). 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. With the turns goes one `memory.set` of what a slow whole run of one test file cost, where the session measured one and its bug report read the repository's row (**The test report**, above). `LOOM_SESSION_MEMORY=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. The body also names the files the session changed in its checkout (each path and the time it was last written, never its content), which decide the session's fix record whatever tool wrote them, and `HEAD` as the commit that holds them, when its history has a commit of the session's that touches every file its edit tool wrote (the tag `change:`). 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. The same hand-off carries one `memory.set` of what a slow whole run of one test file cost, where the session measured one and its bug report read the repository's row, whether or not its turns are sent (**The test report**, below). `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 names 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. On a server whose default scope is `all_mine`, the request of a checkout with a remote is also answered with the rows you wrote in your other namespaces; such a row reads ` (namespace ""): …`. 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. @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed and no more than a tenth of its cases were skipped, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 6aa37eebad8..f7525d2d623 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1339,8 +1339,14 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that (`runCost`, read from the file's first 4,096 bytes, also for a file over the 2 MB bound). The session's private state keeps, for each of the eight files it ran last, the costliest whole run in which no case - failed and no more than a tenth of the cases were skipped, and the case - count and seconds of each run filtered with `-k`. + failed, and the case count and seconds of its last 15 runs filtered + with `-k`. A run that skipped more than a tenth of its cases is not + kept: it ran where the cases skip, and took less. The skipped cases are + the ones pytest's last line counts, where the command's output shows + it. The report counts an expected failure (`xfail`) as skipped too, and + a run that outlived its shell call has the report alone: such a run of + a file where more than a tenth of the cases are expected failures is + not kept. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`, which may run every case), a run that only collects or prints, and a command with two pytest runs or two paths are noted as @@ -1353,25 +1359,31 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that pytest's summary line with the seconds the report holds, within a second or a twentieth of them, and the report's first case is in the file the command names: a run the option did not reach writes no - report, and the one read after it is an earlier run's. A run whose - output shows no summary may not have ended: one that outlives its - shell call writes the file after the hook ran. It is kept as the - session's pending run, with the time its command returned. Any other - report the hook reads is the pending run's when the run that wrote it - began by that time, and no run's otherwise: pytest began it at the - time the file was written less the seconds of its `testsuite`, and a - run that a later command started, by any launcher and whether or not - a hook ran for that command, began after it. The launcher reads the - report once more at SessionEnd, before it removes the file, without - reading a token. A run of another kind left open while one is pending - drops both, since one would be counted as the other. A run put in the - background at once returns before pytest began, and is not counted. + report, and the one read after it is an earlier run's. The summary is + pytest's last line, whatever it counts (`8000 deselected in 1.20s` and + `no tests ran in 0.01s` too). A run whose output shows no such line may + not have ended: one that outlives its shell call writes the file after + the hook ran. It is kept as the session's pending run, with the time its + command returned. Any other report the hook reads is the pending run's + when the run that wrote it began by that time, and no run's otherwise: + pytest began it at the time the file was written less the seconds of + its `testsuite`, and a run that a later command started, by any + launcher and whether or not a hook ran for that command, began after + it. A run of the file that something else started while the pending run + was in its call, such as a script in the background, began before that + time too: its report, read with a command that is not that run, is + counted as the pending run's. The launcher reads the report once more + at SessionEnd, before it removes the file, without reading a token. A + run of another kind left open while one is pending drops both, since + one would be counted as the other. A run put in the background at once + returns before pytest began, and is not counted. The session has one result file, and no hook runs between two commands: where the session's next pytest run ends before a hook has read the file, that run's report replaces the pending run's, which is then not counted. At SessionEnd `loom-session-memory` hands one `memory.set` to the - flusher, with the session's turns, where a prompt of the session read + flusher, beside the session's turns or alone where they are not sent, + where a prompt of the session read the row, a miss included, and its runs say something the row does not (`revised`). With no row, the costliest whole run is stored when it took 60 s or more. The row's own file is revised by the session's diff --git a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs index 0107f4563d2..980c910a7a3 100644 --- a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs @@ -5,10 +5,10 @@ // the turns as the facts' source evidence; the hook itself runs no model (see // lib/session-memory.mjs). // -// With the turns goes what the session's test runs cost: one memory.set of -// the repository's test cost row, where the session's runs of a test file say -// something the row one of its prompts read does not (lib/test-cost.mjs; -// LOOM_TEST_REPORT=off stops it). +// The same hand-off carries what the session's test runs cost, whether or +// not its turns are sent: one memory.set of the repository's test cost row, +// where the session's runs of a test file say something the row one of its +// prompts read does not (lib/test-cost.mjs; LOOM_TEST_REPORT=off stops it). // // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget // through the detached flusher so the agent never waits on the request. diff --git a/integrations/claude-code-plugin/lib/loom-client.mjs b/integrations/claude-code-plugin/lib/loom-client.mjs index ff4ced71cb1..85e670c0200 100644 --- a/integrations/claude-code-plugin/lib/loom-client.mjs +++ b/integrations/claude-code-plugin/lib/loom-client.mjs @@ -596,7 +596,7 @@ export function realPath(p) { } } -function isDirectory(p) { +export function isDirectory(p) { try { return statSync(p).isDirectory(); } catch { diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 07edc6b4b98..68ea98e60ce 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -7,11 +7,11 @@ // (lib/test-report.mjs): its first testsuite holds the case count and the // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private -// state: for each file, the costliest whole run that passed and the runs -// filtered with -k. A run that outlives its shell call writes the file after -// that call's hook ran: a report read later is its when pytest began the run -// that wrote it before that call returned, and the launcher reads the file -// once more before it removes it at the session's end (`settleRun`). The +// state: for each file, the costliest whole run that passed and its latest +// runs filtered with -k. A run that outlives its shell call writes the file +// after that call's hook ran: a report read later is its when pytest began +// the run that wrote it before that call returned, and the launcher reads the +// file once more before it removes it at the session's end (`settleRun`). The // file is one a session: a pytest run that ends before a hook read it // replaces it, and the run that outlived its call is then not counted. // @@ -26,10 +26,9 @@ // outside letters, digits and `._/-`, is over 160 characters or is changed by // the secret redaction is not sent. -import fs from "node:fs"; import path from "node:path"; -import { gitToplevel, hookClient, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; -import { fileRun } from "./test-gate.mjs"; +import { gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; +import { fileRun, isFile } from "./test-gate.mjs"; import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; @@ -37,7 +36,9 @@ import { readSessionState, removeFile, sessionStatePath, writeSessionState } fro const MIN_WHOLE_SECONDS = 60; // The default timeout of one shell call under Claude Code. const CALL_TIMEOUT_SECONDS = 120; -// A whole run that skipped a larger share of its cases did not run the file. +// A run that skipped a larger share of its cases did not run them. +// The report counts an expected failure (xfail) as skipped, the summary line +// does not: a run that outlived its call has the report's count only. const MAX_SKIPPED_SHARE = 0.1; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. @@ -50,9 +51,6 @@ const RUNS = "test-cost"; // `{ read, root, row }`. const ROW = "test-cost-row"; -const isFile = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isFile()); -const isFolder = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isDirectory()); - /** `file`, a path in the checkout, when it may be sent, else "". */ function sendable(file) { const p = String(file || ""); @@ -73,26 +71,28 @@ const apart = (seen, stored) => Math.abs(seen - stored) > Math.max(stored / 4, 2 function located(run, cwd) { if (!run) return null; const from = [path.resolve(cwd, run.dir), path.resolve(cwd)].find((dir) => isFile(path.resolve(dir, run.path))); - if (!from || run.values.some((word) => isFolder(path.resolve(from, word)))) return null; + if (!from || run.values.some((word) => isDirectory(path.resolve(from, word)))) return null; return { ...run, file: path.resolve(from, run.path) }; } /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another * run's (pytest names the file from its root, a folder at or above the - * file's). A whole run counts when no case failed and no more than - * `MAX_SKIPPED_SHARE` of them were skipped: one that stopped at a failure, - * or ran where its cases skip, took less. The file is put last, so the - * bound drops the one least recently run. */ + * file's). A run counts when no more than `MAX_SKIPPED_SHARE` of its cases + * were skipped, and a whole run when no case failed either: one that ran + * where its cases skip, or stopped at a failure, took less. The file is put + * last, so the bound drops the one least recently run. */ function add(state, run, cost) { if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; - const ran = !cost.failed && cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; - const whole = run.whole && ran && cost.seconds > (seen.whole?.seconds ?? -1); + const ran = cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; + const whole = run.whole && ran && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); const next = { ...seen, ...(whole ? { whole: { tests: cost.tests, seconds: cost.seconds } } : {}), - ...(run.whole ? {} : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), + ...(run.whole || !ran + ? {} + : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), }; if (next.whole || next.filtered) files[run.file] = next; state.files = Object.fromEntries(Object.entries(files).slice(-MAX_FILES)); @@ -102,7 +102,10 @@ function add(state, run, cost) { * that wrote it began before the pending run's command returned: pytest * began it at the time the file was written less the suite's seconds. A * command that came later, whatever it is and whether or not a hook saw it, - * began its run after that. The pending run is then settled. */ + * began its run after that. A run of the file that something else started + * while the pending run was in its call began before it too: its report, + * read with a command that is not that run, is taken for the pending run's. + * The pending run is then settled. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; if (!cost || !state.pending || report.mtimeMs - cost.time * 1000 > state.pending.at) return; @@ -135,7 +138,8 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { const open = Boolean(run && run.seconds === null); // The summary's seconds and the report's are two clocks on one run. const own = run && !open && cost && Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); - if (own) add(state, run, cost); + // The summary counts the skipped cases apart from the expected failures. + if (own) add(state, run, { ...cost, skipped: run.skipped }); else settle(state, report); if (open) { const pending = state.pending; diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 19fbda8de3b..d62233419a9 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -747,7 +747,7 @@ export function pytestOptions(root, testPath, python, { sessionId, env } = {}) { return { quiet, ...known }; } -function isFile(p) { +export function isFile(p) { try { return fs.statSync(p).isFile(); } catch { @@ -1362,15 +1362,22 @@ const CLUSTER = /^-[A-Za-z]+[km]/; const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; // A Python file, or a test in one, as a word of a pytest command. const PYTHON_FILE = /\.py(?:::|$)/; +// pytest's last line of a run that ended, whatever it counts: a run that +// selected or ran nothing prints `8000 deselected in 1.20s`, `12 skipped in +// 0.31s` or `no tests ran in 0.01s`. +const LAST_LINE = + /\b(?:\d+ (?:passed|failed|errors?|skipped|deselected|xfailed|xpassed|warnings?)|no tests ran)\b.* in [\d.]+s\b/; /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, dir, whole, seconds, values }`, else null. `path` is - * the file as the command spells it and `dir` the folder of the one `cd` - * before the run, "" for none. `whole` is false for a run filtered with `-k`. - * `seconds` is what pytest's summary line in the visible `output` shows, null - * where the output holds none: the run did not finish inside the call. + * else to run: `{ path, dir, whole, seconds, skipped, values }`, else null. + * `path` is the file as the command spells it and `dir` the folder of the one + * `cd` before the run, "" for none. `whole` is false for a run filtered with + * `-k`. `seconds` is what pytest's last line in the visible `output` shows + * (`LAST_LINE`) and `skipped` the skipped cases that line counts, apart from + * the expected failures; both are null where the output holds no such line: + * the run did not finish inside the call. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1415,12 +1422,13 @@ export function fileRun(command, output = "") { if (values.some((word) => PYTHON_FILE.test(word))) return null; const summary = String(output || "") .split(/\r?\n/) - .findLast((line) => line.length < 300 && SUMMARY.test(line)); + .findLast((line) => line.length < 300 && LAST_LINE.test(line)); return { path: named[0], dir: cd.length ? unquoted(cd[0][1]) : "", whole: !words.some((word) => BY_NAME.test(word)), seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, + skipped: summary ? Number(/\b(\d+) skipped\b/.exec(summary)?.[1] ?? 0) : null, values, }; } diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index d451030c54c..4cb7c63612c 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -293,7 +293,8 @@ function scan(xml) { /** What the run that wrote a result file cost, from the file's `head`: the * first testsuite's case count, its seconds to the nearest one and as * written (`time`), how many cases failed or ended in an error, how many - * were skipped (pytest counts them as cases), and the file of its first + * were skipped (pytest counts them as cases, and an expected failure among + * the skipped), and the file of its first * testcase, which pytest names in the family the option sets ("" where the * head holds none). null for a head with no whole testsuite tag, no case or * no time. */ diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index aeecd3fb9d7..e0a7fa70499 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -98,7 +98,7 @@ test("a report over the read bound is read for its head", { skip: WINDOWS }, (t) }); test("a command's one pytest run of one test file is whole or filtered with -k", () => { - const whole = { path: FILE, dir: "", whole: true, seconds: null, values: [] }; + const whole = { path: FILE, dir: "", whole: true, seconds: null, skipped: null, values: [] }; for (const command of [ `pytest ${FILE}`, `python -m pytest ${FILE} -q`, @@ -131,6 +131,21 @@ test("a command's one pytest run of one test file is whole or filtered with -k", assert.equal(fileRun(`pytest ${FILE} -q`, "........\n8000 passed in 140.21s (0:02:20)").seconds, 140.21); assert.equal(fileRun(`pytest ${FILE} -k parse`, "12 passed, 7988 deselected in 2.31s").seconds, 2.31); assert.equal(fileRun(`pytest ${FILE} -q`, "Command running in background with ID: bash_1").seconds, null); + // The last line of a run that ended, whatever it counts, with its skipped + // cases apart from the expected failures. + for (const [line, seconds, skipped] of [ + ["8000 passed in 140.21s (0:02:20)", 140.21, 0], + ["=== 7000 passed, 100 skipped, 900 xfailed in 170.00s (0:02:50) ===", 170, 100], + ["1 failed, 7999 passed in 300.00s", 300, 0], + ["8000 deselected in 1.20s", 1.2, 0], + ["12 skipped in 0.31s", 0.31, 12], + ["3 xfailed in 0.50s", 0.5, 0], + ["no tests ran in 0.01s", 0.01, 0], + ["1 warning in 0.02s", 0.02, 0], + ]) { + const run = fileRun(`pytest ${FILE} -q`, `collected 8000 items\n${line}`); + assert.deepEqual([run.seconds, run.skipped], [seconds, skipped], line); + } }); test("a command with two pytest runs, two paths, another selection or no run of its own is no file run", () => { @@ -369,11 +384,17 @@ test("a report is the command's whose output shows the summary with the report's assert.deepEqual(runs().files[file].whole, whole(160)); note(WHOLE_COMMAND, "7200 passed, 800 skipped in 170.00s", report({ tests: 8000, time: "170.0", skipped: 800 })); assert.deepEqual(runs().files[file].whole, whole(170)); + // The report counts an expected failure as skipped and the summary does not: the cases ran. + const xfailed = report({ tests: 8000, time: "180.0", skipped: 1000 }); + note(WHOLE_COMMAND, "7000 passed, 100 skipped, 900 xfailed in 180.00s", xfailed); + assert.deepEqual(runs().files[file].whole, whole(180)); + // A -k run whose cases skipped is no filtered time. + note(FILTERED_COMMAND, "12 skipped, 7988 deselected in 0.31s", report({ tests: 12, time: "0.3", skipped: 12 })); // A run the option did not reach wrote no report: the one read after it is an // earlier run's, and its seconds are not the summary's. note(`PYTEST_ADDOPTS=-q pytest ${FILE} -k parse`, FILTERED_OUTPUT, report({ tests: 8000, time: "600.0" })); note(WHOLE_COMMAND, "8000 passed in 2.31s", report({ tests: 8000, time: "600.0" })); - assert.deepEqual(runs(), { files: { [file]: { whole: whole(170), filtered } } }); + assert.deepEqual(runs(), { files: { [file]: { whole: whole(180), filtered } } }); }); }); @@ -395,11 +416,13 @@ test("a command that is no file run, or names a file that is not there, leaves n }); }); -test("the files a session's state holds are the eight it ran last", { skip: WINDOWS }, (t) => { +test("a session's state holds the eight files it ran last, and the last 15 filtered runs of each", { + skip: WINDOWS, +}, (t) => { inTmp(t, (cwd, file) => { - const note = (name) => { + const note = (name, tests = 12) => { fs.writeFileSync(path.join(cwd, name), ""); - const xml = report({ tests: 12, time: "2.3", file: name }); + const xml = report({ tests, time: "2.3", file: name }); noteCommand(SESSION, { command: `pytest ${name} -k parse -q`, output: FILTERED_OUTPUT, report: read(xml), cwd }); }; note(FILE); @@ -415,6 +438,12 @@ test("the files a session's state holds are the eight it ran last", { skip: WIND [12, 2], [12, 2], ]); + // Sixteen more filtered runs of the file: the first three of its eighteen are dropped. + for (let tests = 1; tests <= 16; tests++) note(FILE, tests); + assert.deepEqual( + runs().files[file].filtered, + Array.from({ length: 15 }, (_, i) => [i + 2, 2]), + ); }); }); @@ -453,6 +482,12 @@ test("a later command keeps the pending run, and a report of a run that began be note("tail -5 /tmp/pytest/out.log", "....", null); note("make test", "ok", null); assert.deepEqual(runs(), { pending: { file, whole: true } }); + // A run of the file that ended with no case passed or failed has ended: it + // is no open run of another kind, and the pending run stays. + note(`pytest ${FILE} -k typo`, "8000 deselected in 1.20s", report({ tests: 0, time: "1.2" })); + note(`pytest ${FILE} -k typo -q`, "no tests ran in 0.01s", null); + note(`pytest ${FILE} -k windows`, "12 skipped, 7988 deselected in 0.31s", null); + assert.deepEqual(runs(), { pending: { file, whole: true } }); // The run has ended by the next look: its 140 s began before its command returned. note("pgrep -f pytest", "", WHOLE); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); diff --git a/integrations/codex-plugin/hooks/loom-session-memory.mjs b/integrations/codex-plugin/hooks/loom-session-memory.mjs index 0107f4563d2..980c910a7a3 100644 --- a/integrations/codex-plugin/hooks/loom-session-memory.mjs +++ b/integrations/codex-plugin/hooks/loom-session-memory.mjs @@ -5,10 +5,10 @@ // the turns as the facts' source evidence; the hook itself runs no model (see // lib/session-memory.mjs). // -// With the turns goes what the session's test runs cost: one memory.set of -// the repository's test cost row, where the session's runs of a test file say -// something the row one of its prompts read does not (lib/test-cost.mjs; -// LOOM_TEST_REPORT=off stops it). +// The same hand-off carries what the session's test runs cost, whether or +// not its turns are sent: one memory.set of the repository's test cost row, +// where the session's runs of a test file say something the row one of its +// prompts read does not (lib/test-cost.mjs; LOOM_TEST_REPORT=off stops it). // // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget // through the detached flusher so the agent never waits on the request. diff --git a/integrations/codex-plugin/lib/loom-client.mjs b/integrations/codex-plugin/lib/loom-client.mjs index ff4ced71cb1..85e670c0200 100644 --- a/integrations/codex-plugin/lib/loom-client.mjs +++ b/integrations/codex-plugin/lib/loom-client.mjs @@ -596,7 +596,7 @@ export function realPath(p) { } } -function isDirectory(p) { +export function isDirectory(p) { try { return statSync(p).isDirectory(); } catch { diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 07edc6b4b98..68ea98e60ce 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -7,11 +7,11 @@ // (lib/test-report.mjs): its first testsuite holds the case count and the // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private -// state: for each file, the costliest whole run that passed and the runs -// filtered with -k. A run that outlives its shell call writes the file after -// that call's hook ran: a report read later is its when pytest began the run -// that wrote it before that call returned, and the launcher reads the file -// once more before it removes it at the session's end (`settleRun`). The +// state: for each file, the costliest whole run that passed and its latest +// runs filtered with -k. A run that outlives its shell call writes the file +// after that call's hook ran: a report read later is its when pytest began +// the run that wrote it before that call returned, and the launcher reads the +// file once more before it removes it at the session's end (`settleRun`). The // file is one a session: a pytest run that ends before a hook read it // replaces it, and the run that outlived its call is then not counted. // @@ -26,10 +26,9 @@ // outside letters, digits and `._/-`, is over 160 characters or is changed by // the secret redaction is not sent. -import fs from "node:fs"; import path from "node:path"; -import { gitToplevel, hookClient, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; -import { fileRun } from "./test-gate.mjs"; +import { gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; +import { fileRun, isFile } from "./test-gate.mjs"; import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; @@ -37,7 +36,9 @@ import { readSessionState, removeFile, sessionStatePath, writeSessionState } fro const MIN_WHOLE_SECONDS = 60; // The default timeout of one shell call under Claude Code. const CALL_TIMEOUT_SECONDS = 120; -// A whole run that skipped a larger share of its cases did not run the file. +// A run that skipped a larger share of its cases did not run them. +// The report counts an expected failure (xfail) as skipped, the summary line +// does not: a run that outlived its call has the report's count only. const MAX_SKIPPED_SHARE = 0.1; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. @@ -50,9 +51,6 @@ const RUNS = "test-cost"; // `{ read, root, row }`. const ROW = "test-cost-row"; -const isFile = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isFile()); -const isFolder = (file) => Boolean(fs.statSync(file, { throwIfNoEntry: false })?.isDirectory()); - /** `file`, a path in the checkout, when it may be sent, else "". */ function sendable(file) { const p = String(file || ""); @@ -73,26 +71,28 @@ const apart = (seen, stored) => Math.abs(seen - stored) > Math.max(stored / 4, 2 function located(run, cwd) { if (!run) return null; const from = [path.resolve(cwd, run.dir), path.resolve(cwd)].find((dir) => isFile(path.resolve(dir, run.path))); - if (!from || run.values.some((word) => isFolder(path.resolve(from, word)))) return null; + if (!from || run.values.some((word) => isDirectory(path.resolve(from, word)))) return null; return { ...run, file: path.resolve(from, run.path) }; } /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another * run's (pytest names the file from its root, a folder at or above the - * file's). A whole run counts when no case failed and no more than - * `MAX_SKIPPED_SHARE` of them were skipped: one that stopped at a failure, - * or ran where its cases skip, took less. The file is put last, so the - * bound drops the one least recently run. */ + * file's). A run counts when no more than `MAX_SKIPPED_SHARE` of its cases + * were skipped, and a whole run when no case failed either: one that ran + * where its cases skip, or stopped at a failure, took less. The file is put + * last, so the bound drops the one least recently run. */ function add(state, run, cost) { if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; - const ran = !cost.failed && cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; - const whole = run.whole && ran && cost.seconds > (seen.whole?.seconds ?? -1); + const ran = cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; + const whole = run.whole && ran && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); const next = { ...seen, ...(whole ? { whole: { tests: cost.tests, seconds: cost.seconds } } : {}), - ...(run.whole ? {} : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), + ...(run.whole || !ran + ? {} + : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), }; if (next.whole || next.filtered) files[run.file] = next; state.files = Object.fromEntries(Object.entries(files).slice(-MAX_FILES)); @@ -102,7 +102,10 @@ function add(state, run, cost) { * that wrote it began before the pending run's command returned: pytest * began it at the time the file was written less the suite's seconds. A * command that came later, whatever it is and whether or not a hook saw it, - * began its run after that. The pending run is then settled. */ + * began its run after that. A run of the file that something else started + * while the pending run was in its call began before it too: its report, + * read with a command that is not that run, is taken for the pending run's. + * The pending run is then settled. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; if (!cost || !state.pending || report.mtimeMs - cost.time * 1000 > state.pending.at) return; @@ -135,7 +138,8 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { const open = Boolean(run && run.seconds === null); // The summary's seconds and the report's are two clocks on one run. const own = run && !open && cost && Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); - if (own) add(state, run, cost); + // The summary counts the skipped cases apart from the expected failures. + if (own) add(state, run, { ...cost, skipped: run.skipped }); else settle(state, report); if (open) { const pending = state.pending; diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 19fbda8de3b..d62233419a9 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -747,7 +747,7 @@ export function pytestOptions(root, testPath, python, { sessionId, env } = {}) { return { quiet, ...known }; } -function isFile(p) { +export function isFile(p) { try { return fs.statSync(p).isFile(); } catch { @@ -1362,15 +1362,22 @@ const CLUSTER = /^-[A-Za-z]+[km]/; const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; // A Python file, or a test in one, as a word of a pytest command. const PYTHON_FILE = /\.py(?:::|$)/; +// pytest's last line of a run that ended, whatever it counts: a run that +// selected or ran nothing prints `8000 deselected in 1.20s`, `12 skipped in +// 0.31s` or `no tests ran in 0.01s`. +const LAST_LINE = + /\b(?:\d+ (?:passed|failed|errors?|skipped|deselected|xfailed|xpassed|warnings?)|no tests ran)\b.* in [\d.]+s\b/; /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, dir, whole, seconds, values }`, else null. `path` is - * the file as the command spells it and `dir` the folder of the one `cd` - * before the run, "" for none. `whole` is false for a run filtered with `-k`. - * `seconds` is what pytest's summary line in the visible `output` shows, null - * where the output holds none: the run did not finish inside the call. + * else to run: `{ path, dir, whole, seconds, skipped, values }`, else null. + * `path` is the file as the command spells it and `dir` the folder of the one + * `cd` before the run, "" for none. `whole` is false for a run filtered with + * `-k`. `seconds` is what pytest's last line in the visible `output` shows + * (`LAST_LINE`) and `skipped` the skipped cases that line counts, apart from + * the expected failures; both are null where the output holds no such line: + * the run did not finish inside the call. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1415,12 +1422,13 @@ export function fileRun(command, output = "") { if (values.some((word) => PYTHON_FILE.test(word))) return null; const summary = String(output || "") .split(/\r?\n/) - .findLast((line) => line.length < 300 && SUMMARY.test(line)); + .findLast((line) => line.length < 300 && LAST_LINE.test(line)); return { path: named[0], dir: cd.length ? unquoted(cd[0][1]) : "", whole: !words.some((word) => BY_NAME.test(word)), seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, + skipped: summary ? Number(/\b(\d+) skipped\b/.exec(summary)?.[1] ?? 0) : null, values, }; } diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index d451030c54c..4cb7c63612c 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -293,7 +293,8 @@ function scan(xml) { /** What the run that wrote a result file cost, from the file's `head`: the * first testsuite's case count, its seconds to the nearest one and as * written (`time`), how many cases failed or ended in an error, how many - * were skipped (pytest counts them as cases), and the file of its first + * were skipped (pytest counts them as cases, and an expected failure among + * the skipped), and the file of its first * testcase, which pytest names in the family the option sets ("" where the * head holds none). null for a head with no whole testsuite tag, no case or * no time. */ diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 222f1983511..22f2829ba78 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -403,14 +403,14 @@ "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/claude-code-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", "integrations/claude-code-plugin/lib/flush-job.mjs": "e6c4ae5e42a54cba0e171b727688be621a81245023bf85a8ac093d334bc9bfd5", - "integrations/claude-code-plugin/lib/loom-client.mjs": "33b83b0977c4a39d11bf0e9de44bc6bccd6c2bfef56f1639a26b54e14a6b7f4c", + "integrations/claude-code-plugin/lib/loom-client.mjs": "e83ba2d3b506cfdf990098e6ca9c4de397aaff114688f4b2bd5dc53293fb4dd5", "integrations/claude-code-plugin/lib/namespace-health.mjs": "c8a9aab01f1e996c97643aee7b8f367bf6447f7a6c74dec01a70dc50a0caa182", "integrations/claude-code-plugin/lib/prompt-pack.mjs": "d81782c64350dfd2f60c428d304db40838d9bd1dd60456fca8ab14abe7ea7def", "integrations/claude-code-plugin/lib/repo-scope.mjs": "fda581229e84dbc702d651e07da3f7dd4c68f9621fdbc86521ac3f97886df5a5", "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "0ef6e965d8a76b3d9387e99519227dc788322649a32eacfe3464b0b6a183fcd4", + "integrations/claude-code-plugin/lib/test-cost.mjs": "b7a886ec488c6af822e9ad74a5239bb9c61058b782a4e06d0ceab5537d264191", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -419,14 +419,14 @@ "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", "integrations/codex-plugin/lib/flush-job.mjs": "e6c4ae5e42a54cba0e171b727688be621a81245023bf85a8ac093d334bc9bfd5", - "integrations/codex-plugin/lib/loom-client.mjs": "33b83b0977c4a39d11bf0e9de44bc6bccd6c2bfef56f1639a26b54e14a6b7f4c", + "integrations/codex-plugin/lib/loom-client.mjs": "e83ba2d3b506cfdf990098e6ca9c4de397aaff114688f4b2bd5dc53293fb4dd5", "integrations/codex-plugin/lib/namespace-health.mjs": "c8a9aab01f1e996c97643aee7b8f367bf6447f7a6c74dec01a70dc50a0caa182", "integrations/codex-plugin/lib/prompt-pack.mjs": "d81782c64350dfd2f60c428d304db40838d9bd1dd60456fca8ab14abe7ea7def", "integrations/codex-plugin/lib/repo-scope.mjs": "fda581229e84dbc702d651e07da3f7dd4c68f9621fdbc86521ac3f97886df5a5", "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "0ef6e965d8a76b3d9387e99519227dc788322649a32eacfe3464b0b6a183fcd4", + "integrations/codex-plugin/lib/test-cost.mjs": "b7a886ec488c6af822e9ad74a5239bb9c61058b782a4e06d0ceab5537d264191", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 8d3e46246f02f3b993f3fb282749d44cf657218b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 20:17:03 +0530 Subject: [PATCH 06/24] A run that left cases out with no -k in its words is no whole run, and the costliest whole run stays in the session's state A pytest run's words end at the first `&`, so a `-k` written after `2>&1` was not among them, and a selection in `PYTEST_ADDOPTS` is in no command: such a run was read as a whole run and its few seconds replaced the stored time. A run with no `-k` whose last line counts deselected cases is now neither whole nor filtered. The session's state dropped the file least recently run, which could be the one with the slow whole run the session's end stores. The file with the costliest whole run is now never the one dropped. A hook-level test covers the paths that are not sent: one with another character, one over 160 characters and one the secret redaction changes. The docs name the eight-file bound, a run that outlived its call with a selection its command does not show, and a whole run under xdist workers. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 14 ++++- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 17 ++++-- .../claude-code-plugin/lib/test-cost.mjs | 11 +++- .../claude-code-plugin/lib/test-gate.mjs | 9 ++- .../tests/test-cost.test.mjs | 58 ++++++++++++++++++- integrations/codex-plugin/lib/test-cost.mjs | 11 +++- integrations/codex-plugin/lib/test-gate.mjs | 9 ++- tests/unit/session_content_senders.json | 4 +- 9 files changed, 116 insertions(+), 19 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index a1c8d6c1487..73f32e0e4d1 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1681,6 +1681,9 @@ session's private state, by the file: - a run that skipped more than a tenth of its cases counts as neither: a run on a machine where the cases skip takes less. The skipped cases are the ones pytest's summary line counts, apart from the expected failures (`xfail`); +- a run with no `-k` in its command whose summary line counts deselected cases counts as + neither: a selection the command does not show left cases out (one in `PYTEST_ADDOPTS` + or the repository's pytest settings, or one written after `2>&1`); - a run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, and a run that only collects or prints (`--collect-only`, `--fixtures`) count as neither. The word after a long flag is a @@ -1743,6 +1746,13 @@ What it does not do: - it is one row a repository and names one test file, the costliest one a session ran whole; +- the session's state holds eight test files, the one with the costliest whole run and + the ones run last: the runs of any other file are dropped once the session has run + eight files after it; +- a whole run started with xdist workers (`-n`) counts with the seconds it took, and the + row does not say how its run was started: a session that runs the file only in + parallel lowers a row that a serial run made, a row under 60 s prints nothing, and the + next serial run raises it again; - a session none of whose prompts read the row stores nothing: one with no bug report, and every session in `memory` mode, with the prompt pointers off or in a repository this Loom does not index; @@ -1757,7 +1767,9 @@ What it does not do: where a `-k` run follows its end at once; - a run that outlives its shell call has no summary line, and the result file counts an expected failure (`xfail`) as skipped: such a run of a file where more than a tenth of - the cases are expected failures is not counted; + the cases are expected failures is not counted. Nor does the result file count the + deselected cases: such a run with a selection its command does not show is counted as + a whole run, with the cases it ran; - the result file of a run of the same file that something else started while a run that outlived its shell call was in that call, such as a script in the background, is counted as that run's when a command that is not the other run reads it; diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index f3b765bd007..389d96d05da 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 3de3c7efdd7..3b105e0b943 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1360,9 +1360,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that case count and the seconds of the report's first `testsuite` (`runCost`, read from the file's first 4,096 bytes, also for a file over the 2 MB bound). The session's private state keeps, for each of - the eight files it ran last, the costliest whole run in which no case - failed, and the case count and seconds of its last 15 runs filtered - with `-k`. A run that skipped more than a tenth of its cases is not + eight files, the costliest whole run in which no case failed, and the + case count and seconds of its last 15 runs filtered with `-k`. The + eight are the file with the costliest whole run, which is what the + session's end stores, and the ones run last. A run that skipped more than a tenth of its cases is not kept: it ran where the cases skip, and took less. The skipped cases are the ones pytest's last line counts, where the command's output shows it. The report counts an expected failure (`xfail`) as skipped too, and @@ -1372,7 +1373,15 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`, which may run every case), a run that only collects or prints, and a command with two pytest runs or two paths are noted as - nothing (lib/test-cost.mjs). The word after a long flag is a second + nothing (lib/test-cost.mjs). So is a run with no `-k` among its words + whose last line counts deselected cases: a selection the words do not + show left cases out, one in `PYTEST_ADDOPTS` or the settings file, or + one written after `2>&1`, where the words end. A run that outlived its + shell call shows no last line, and such a run is counted as a whole + run with the cases it ran. A whole run started with xdist workers + (`-n`) counts with the seconds it took: the row does not say how its + run was started, so a session that runs the file only in parallel + lowers a row that a serial run made. The word after a long flag is a second path where the flag takes no value (`--no-header tests`), so a run with such a word that names a Python file or a folder is noted as nothing too. The file is the one the command names, from the payload's diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 68ea98e60ce..745ea2c8602 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -81,7 +81,8 @@ function located(run, cwd) { * file's). A run counts when no more than `MAX_SKIPPED_SHARE` of its cases * were skipped, and a whole run when no case failed either: one that ran * where its cases skip, or stopped at a failure, took less. The file is put - * last, so the bound drops the one least recently run. */ + * last, and the bound drops the one least recently run that is not the one + * with the costliest whole run: that run is what the session's end stores. */ function add(state, run, cost) { if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; @@ -95,7 +96,13 @@ function add(state, run, cost) { : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), }; if (next.whole || next.filtered) files[run.file] = next; - state.files = Object.fromEntries(Object.entries(files).slice(-MAX_FILES)); + const held = Object.entries(files); + const slowest = held.reduce( + (top, entry) => ((entry[1].whole?.seconds ?? -1) > (top?.[1].whole.seconds ?? -1) ? entry : top), + null, + ); + const dropped = held.length > MAX_FILES ? held.find((entry) => entry !== slowest) : null; + state.files = Object.fromEntries(held.filter((entry) => entry !== dropped)); } /** Count `report` (`newReport`) for the session's pending run when the run diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index d62233419a9..7404a3aeb87 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1377,7 +1377,10 @@ const LAST_LINE = * `-k`. `seconds` is what pytest's last line in the visible `output` shows * (`LAST_LINE`) and `skipped` the skipped cases that line counts, apart from * the expected failures; both are null where the output holds no such line: - * the run did not finish inside the call. + * the run did not finish inside the call. A run with no `-k` whose last line + * counts deselected cases is none: a selection its words do not show left + * cases out (one in `PYTEST_ADDOPTS` or the settings file, or written after + * `2>&1`, where the words end). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1423,10 +1426,12 @@ export function fileRun(command, output = "") { const summary = String(output || "") .split(/\r?\n/) .findLast((line) => line.length < 300 && LAST_LINE.test(line)); + const whole = !words.some((word) => BY_NAME.test(word)); + if (whole && summary && /\b\d+ deselected\b/.test(summary)) return null; return { path: named[0], dir: cd.length ? unquoted(cd[0][1]) : "", - whole: !words.some((word) => BY_NAME.test(word)), + whole, seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, skipped: summary ? Number(/\b(\d+) skipped\b/.exec(summary)?.[1] ?? 0) : null, values, diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index e0a7fa70499..c1d5af2b04b 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -143,7 +143,7 @@ test("a command's one pytest run of one test file is whole or filtered with -k", ["no tests ran in 0.01s", 0.01, 0], ["1 warning in 0.02s", 0.02, 0], ]) { - const run = fileRun(`pytest ${FILE} -q`, `collected 8000 items\n${line}`); + const run = fileRun(`pytest ${FILE} -k parse -q`, `collected 8000 items\n${line}`); assert.deepEqual([run.seconds, run.skipped], [seconds, skipped], line); } }); @@ -192,6 +192,16 @@ test("a command with two pytest runs, two paths, another selection or no run of ]) { assert.equal(fileRun(command), null, command); } + // A selection the run's words do not show: the last line counts deselected cases. + for (const command of [ + `pytest ${FILE} -q`, + `pytest ${FILE} 2>&1 -k parse | tail -3`, + `export PYTEST_ADDOPTS="$PYTEST_ADDOPTS -k parse"; pytest ${FILE}`, + ]) { + assert.equal(fileRun(command, WHOLE_OUTPUT).whole, true, command); + assert.equal(fileRun(command, FILTERED_OUTPUT), null, command); + assert.equal(fileRun(command, "8000 deselected in 1.20s"), null, command); + } }); test("the stored claim and the prompt's line, byte for byte", () => { @@ -416,7 +426,7 @@ test("a command that is no file run, or names a file that is not there, leaves n }); }); -test("a session's state holds the eight files it ran last, and the last 15 filtered runs of each", { +test("a session's state holds eight files, the costliest whole run among them, and 15 filtered runs of each", { skip: WINDOWS, }, (t) => { inTmp(t, (cwd, file) => { @@ -444,6 +454,16 @@ test("a session's state holds the eight files it ran last, and the last 15 filte runs().files[file].filtered, Array.from({ length: 15 }, (_, i) => [i + 2, 2]), ); + // The file with the costliest whole run stays, however long ago it ran: + // eight files run after it drop the seven before it and the first of their own. + noteCommand(SESSION, { command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(WHOLE), cwd }); + for (let i = 8; i < 16; i++) note(`tests/test_${i}.py`); + const last = runs().files; + assert.deepEqual(Object.keys(last), [ + file, + ...Array.from({ length: 7 }, (_, i) => path.join(cwd, `tests/test_${i + 9}.py`)), + ]); + assert.deepEqual(last[file].whole, { tests: 8000, seconds: 140 }); }); }); @@ -849,6 +869,33 @@ test("nothing is stored for a whole run under 60 s, a command of two runs or two assert.deepEqual(server.sent("memory.set"), []); }); +test("a slow whole run of a file whose path is not sent stores nothing", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const names = [ + // A character outside letters, digits and `._/-`. + "tests/test_big+v2.py", + // Over 160 characters. + `tests/test_${"x".repeat(160)}.py`, + // The secret redaction changes it. + `tests/ghp_${"a".repeat(36)}.py`, + ]; + for (const [at, name] of names.entries()) { + const box = sandbox(t, server); + fs.writeFileSync(path.join(box.cwd, name), ""); + // The session's prompt read the row, a miss: its end may store a first one. + await ask(box); + assert.equal(server.sent("memory.get").length, at + 1, name); + const xml = report({ tests: 8000, time: "140.2", file: name }); + await afterCommand(box, `python -m pytest ${name} -q`, WHOLE_OUTPUT, xml); + const seen = { [path.join(box.cwd, name)]: { whole: { tests: 8000, seconds: 140 } } }; + assert.deepEqual(readJsonFile(box.runs, null), { files: seen }, name); + await endSession(box); + await settled(box); + assert.equal(fs.existsSync(box.runs), false, name); + } + assert.deepEqual(server.sent("memory.set"), []); +}); + test("a session's end with the test report switched off reads no report and stores nothing", { skip: WINDOWS, }, async (t) => { @@ -895,10 +942,15 @@ test("a pytest run that ends before a hook read the pending run's report replace assert.equal(fs.existsSync(box.runs), false); }); -test("a whole run that skipped most of its cases does not lower the row", { skip: WINDOWS }, async (t) => { +test("a run that skipped most of its cases, or left cases out by a selection its command does not show, does not lower the row", { + skip: WINDOWS, +}, async (t) => { const server = await loom(t, { get: row() }); const box = sandbox(t, server); assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + // The command's words end at `2>&1`: its last line says cases were left out. + await afterCommand(box, `python -m pytest ${FILE} 2>&1 -k parse | tail -3`, FILTERED_OUTPUT, FILTERED); + assert.equal(readJsonFile(box.runs, null), null); // The cases need a service this machine does not run. const xml = report({ tests: 8000, time: "2.3", skipped: 7988 }); await afterCommand(box, WHOLE_COMMAND, "12 passed, 7988 skipped in 2.31s", xml); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 68ea98e60ce..745ea2c8602 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -81,7 +81,8 @@ function located(run, cwd) { * file's). A run counts when no more than `MAX_SKIPPED_SHARE` of its cases * were skipped, and a whole run when no case failed either: one that ran * where its cases skip, or stopped at a failure, took less. The file is put - * last, so the bound drops the one least recently run. */ + * last, and the bound drops the one least recently run that is not the one + * with the costliest whole run: that run is what the session's end stores. */ function add(state, run, cost) { if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; @@ -95,7 +96,13 @@ function add(state, run, cost) { : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), }; if (next.whole || next.filtered) files[run.file] = next; - state.files = Object.fromEntries(Object.entries(files).slice(-MAX_FILES)); + const held = Object.entries(files); + const slowest = held.reduce( + (top, entry) => ((entry[1].whole?.seconds ?? -1) > (top?.[1].whole.seconds ?? -1) ? entry : top), + null, + ); + const dropped = held.length > MAX_FILES ? held.find((entry) => entry !== slowest) : null; + state.files = Object.fromEntries(held.filter((entry) => entry !== dropped)); } /** Count `report` (`newReport`) for the session's pending run when the run diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index d62233419a9..7404a3aeb87 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1377,7 +1377,10 @@ const LAST_LINE = * `-k`. `seconds` is what pytest's last line in the visible `output` shows * (`LAST_LINE`) and `skipped` the skipped cases that line counts, apart from * the expected failures; both are null where the output holds no such line: - * the run did not finish inside the call. + * the run did not finish inside the call. A run with no `-k` whose last line + * counts deselected cases is none: a selection its words do not show left + * cases out (one in `PYTEST_ADDOPTS` or the settings file, or written after + * `2>&1`, where the words end). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1423,10 +1426,12 @@ export function fileRun(command, output = "") { const summary = String(output || "") .split(/\r?\n/) .findLast((line) => line.length < 300 && LAST_LINE.test(line)); + const whole = !words.some((word) => BY_NAME.test(word)); + if (whole && summary && /\b\d+ deselected\b/.test(summary)) return null; return { path: named[0], dir: cd.length ? unquoted(cd[0][1]) : "", - whole: !words.some((word) => BY_NAME.test(word)), + whole, seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, skipped: summary ? Number(/\b(\d+) skipped\b/.exec(summary)?.[1] ?? 0) : null, values, diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 6917e3f8f48..6f832fac77a 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "b7a886ec488c6af822e9ad74a5239bb9c61058b782a4e06d0ceab5537d264191", + "integrations/claude-code-plugin/lib/test-cost.mjs": "0a51a192dfa8799f1366266a135f7aa1f9d7ce4151ad2f48a9548c0a59b3014c", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "b7a886ec488c6af822e9ad74a5239bb9c61058b782a4e06d0ceab5537d264191", + "integrations/codex-plugin/lib/test-cost.mjs": "0a51a192dfa8799f1366266a135f7aa1f9d7ce4151ad2f48a9548c0a59b3014c", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From a26b691789c9ee8211f40c56e89cb91e7c69b6c8 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 20:56:34 +0530 Subject: [PATCH 07/24] A test report is a command's only when pytest's last line counts its cases and failures The seconds alone do not tell two short runs apart: the report an unread -k run left was counted for a later whole run that wrote none and ended within a second of it, and the session's end lowered the repository's row to that run. The command's last line now has to count the cases and the failures the report holds as well. The page and the README say that a pinned row of another repository in the namespace refuses the write, and the test_report option's title names the test cost. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 28 ++++--- .../.claude-plugin/plugin.json | 2 +- integrations/claude-code-plugin/README.md | 4 +- .../claude-code-plugin/hooks/HOOKS.md | 20 ++--- .../claude-code-plugin/lib/test-cost.mjs | 27 ++++--- .../claude-code-plugin/lib/test-gate.mjs | 31 ++++--- .../tests/test-cost.test.mjs | 81 +++++++++++++++---- integrations/codex-plugin/lib/test-cost.mjs | 27 ++++--- integrations/codex-plugin/lib/test-gate.mjs | 31 ++++--- tests/unit/session_content_senders.json | 4 +- 10 files changed, 175 insertions(+), 80 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 795caacc435..098b66fdfb8 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1715,15 +1715,19 @@ session's private state, by the file: that names a Python file or a folder counts as neither too. The result file is the command's when the command's output shows pytest's summary line, -whatever it counts, with the seconds the file holds (within a second, or a twentieth of -them), and the file's first case is in the test file the command names. A run that -outlives its shell call writes the file after the hook ran: it is read after the next -shell command that names a test runner, or when the session ends. That file is the run's -when pytest began the run that wrote it before the run's own command returned (the time -the file was written, less the seconds it holds): a run that any later command started -began after that, and its file counts for no run. The session has one result file, so -the next pytest run that ends replaces it: where that run ends before a hook has read -the file, the run that outlived its call is not counted. +whatever it counts, with the cases, the failures and the seconds the file holds (the +seconds within a second, or a twentieth of them), and the file's first case is in the +test file the command names. The seconds alone do not tell two short runs apart: a run +that wrote no file, such as one that sets its own `PYTEST_ADDOPTS`, is read with the +file an earlier run left. + +A run that outlives its shell call writes the file after the hook ran: it is read after +the next shell command that names a test runner, or when the session ends. That file is +the run's when pytest began the run that wrote it before the run's own command returned +(the time the file was written, less the seconds it holds): a run that any later command +started began after that, and its file counts for no run. The session has one result +file, so the next pytest run that ends replaces it: where that run ends before a hook +has read the file, the run that outlived its call is not counted. **What is stored.** When the session ends, what it measured goes to the repository's one memory row, in the hand-off that carries the session's turns (`memory.set`, key @@ -1794,6 +1798,8 @@ What it does not do: the cases are expected failures is not counted. Nor does the result file count the deselected cases: such a run with a selection its command does not show is counted as a whole run, with the cases it ran; +- a run in which a case's teardown raised an error after the case passed or failed is not + counted: pytest's summary line counts that case twice and the result file once; - the result file of a run of the same file that something else started while a run that outlived its shell call was in that call, such as a script in the background, is counted as that run's when a command that is not the other run reads it; @@ -1801,7 +1807,9 @@ What it does not do: run of another file; - the row is an ordinary memory row, so recall can serve its sentence, and two repositories' rows in one namespace read alike, so the server's conflict check can - mark one `conflicted`; both are still read by key; + mark one `conflicted`; both are still read by key. Where the other repository's row is + pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no + row and no line until that row is unpinned; - it is pytest under Claude Code only: Codex names no file for the result-file option. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index f3ff54f72fc..47b584174bb 100644 --- a/integrations/claude-code-plugin/.claude-plugin/plugin.json +++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json @@ -70,7 +70,7 @@ }, "test_report": { "type": "boolean", - "title": "Failure reasons after a cut pytest run", + "title": "pytest failure reasons and test cost", "description": "On by default. In a checkout that configures pytest, the plugin adds its result-file option to PYTEST_ADDOPTS for the session's shell commands (--junitxml, to a private file in the temp directory, with -o junit_family=xunit1), and after a test command whose visible output names no failure's reason it adds a digest of that file to the tool result, at most 700 characters. pytest names the file in one line of its summary on a run that is not quiet (-q). No request is sent for the digest and nothing of it is stored. With the memory plane on, what a whole pytest run of one test file cost (its path, the number of cases and the seconds) is kept as one memory row a repository when it took a minute or more, and a later bug report in that repository carries it as one line under its code pointers. Off: no option, no digest and no test cost, from the session's next start (LOOM_TEST_REPORT=off does the same).", "default": true }, diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 5440c3ab44d..ff8514a6d3a 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. @@ -336,7 +336,7 @@ Only a session whose bug report read the row writes, a miss included. With no ro Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session and checkout, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, and `code` mode all three; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session and checkout, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, and `code` mode all three; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 6ef0090cbae..995c7e0cc53 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1431,15 +1431,17 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that nothing too. The file is the one the command names, from the payload's folder and the command's one `cd`, where it is there. The report is the command's when the command's visible output shows - pytest's summary line with the seconds the report holds, within a - second or a twentieth of them, and the report's first case is in the - file the command names: a run the option did not reach writes no - report, and the one read after it is an earlier run's. The summary is - pytest's last line, whatever it counts (`8000 deselected in 1.20s` and - `no tests ran in 0.01s` too). A run whose output shows no such line may - not have ended: one that outlives its shell call writes the file after - the hook ran. It is kept as the session's pending run, with the time its - command returned. Any other report the hook reads is the pending run's + pytest's summary line with the cases, the failures and the seconds + the report holds, the seconds within a second or a twentieth of them, + and the report's first case is in the file the command names: a run + the option did not reach writes no report, and the one read after it + is an earlier run's, which the seconds of two short runs do not tell + apart. The summary is pytest's last line, whatever it counts + (`8000 deselected in 1.20s` and `no tests ran in 0.01s` too). A run + whose output shows no such line may not have ended: one that outlives + its shell call writes the file after the hook ran. It is kept as the + session's pending run, with the time its command returned. Any other + report the hook reads is the pending run's when the run that wrote it began by that time, and no run's otherwise: pytest began it at the time the file was written less the seconds of its `testsuite`, and a run that a later command started, by any diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 745ea2c8602..556836e1272 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -126,15 +126,16 @@ function settle(state, report) { * (`newReport`, else null), and the payload's `cwd`. * * The report is the command's when the command is one pytest run of one test - * file (`fileRun`) and its output shows pytest's summary with the seconds - * the report holds: a run the option did not reach writes no report, and the - * one read after it is an earlier run's. A run whose output shows no summary - * may not have ended: it is kept as the session's pending run, with the time - * its command returned. Any other report is the pending run's when its run - * began by that time (`settle`), and no run's otherwise. So a run that was - * put in the background before pytest began is not counted. An open run of - * another kind than the pending one drops both: one of the two would be - * counted as the other. + * file (`fileRun`) and its output shows pytest's summary with the cases, the + * failures and the seconds the report holds: a run the option did not reach + * writes no report, and the one read after it is an earlier run's. The + * seconds alone do not tell two short runs apart. A run whose output shows + * no summary may not have ended: it is kept as the session's pending run, + * with the time its command returned. Any other report is the pending run's + * when its run began by that time (`settle`), and no run's otherwise. So a + * run that was put in the background before pytest began is not counted. An + * open run of another kind than the pending one drops both: one of the two + * would be counted as the other. */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { @@ -144,7 +145,13 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { const cost = report ? runCost(report.head) : null; const open = Boolean(run && run.seconds === null); // The summary's seconds and the report's are two clocks on one run. - const own = run && !open && cost && Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); + const own = + run && + !open && + cost && + run.cases === cost.tests && + run.failed === cost.failed && + Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); // The summary counts the skipped cases apart from the expected failures. if (own) add(state, run, { ...cost, skipped: run.skipped }); else settle(state, report); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 7404a3aeb87..77cf93fbaba 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1367,20 +1367,27 @@ const PYTHON_FILE = /\.py(?:::|$)/; // 0.31s` or `no tests ran in 0.01s`. const LAST_LINE = /\b(?:\d+ (?:passed|failed|errors?|skipped|deselected|xfailed|xpassed|warnings?)|no tests ran)\b.* in [\d.]+s\b/; +/** The sum of the counts `line` gives for `kinds`, an alternation of the + * words of pytest's last line. */ +const counted = (line, kinds) => + [...line.matchAll(new RegExp(`\\b(\\d+) (?:${kinds})\\b`, "g"))].reduce((sum, found) => sum + Number(found[1]), 0); /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, dir, whole, seconds, skipped, values }`, else null. - * `path` is the file as the command spells it and `dir` the folder of the one - * `cd` before the run, "" for none. `whole` is false for a run filtered with - * `-k`. `seconds` is what pytest's last line in the visible `output` shows - * (`LAST_LINE`) and `skipped` the skipped cases that line counts, apart from - * the expected failures; both are null where the output holds no such line: - * the run did not finish inside the call. A run with no `-k` whose last line - * counts deselected cases is none: a selection its words do not show left - * cases out (one in `PYTEST_ADDOPTS` or the settings file, or written after - * `2>&1`, where the words end). + * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values }`, + * else null. `path` is the file as the command spells it and `dir` the folder + * of the one `cd` before the run, "" for none. `whole` is false for a run + * filtered with `-k`. `seconds` is what pytest's last line in the visible + * `output` shows (`LAST_LINE`). `cases` is the cases that line counts, all + * but the deselected: the result file's `tests`, but for a case whose + * teardown raised an error, which the line counts twice and the file once. + * `failed` is the failures and errors among them and `skipped` the skipped + * ones, apart from the expected failures. All four are null where the output + * holds no such line: the run did not finish inside the call. A run with no + * `-k` whose last line counts deselected cases is none: a selection its words + * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings file, + * or written after `2>&1`, where the words end). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1433,7 +1440,9 @@ export function fileRun(command, output = "") { dir: cd.length ? unquoted(cd[0][1]) : "", whole, seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, - skipped: summary ? Number(/\b(\d+) skipped\b/.exec(summary)?.[1] ?? 0) : null, + cases: summary ? counted(summary, "passed|failed|errors?|skipped|xfailed|xpassed") : null, + failed: summary ? counted(summary, "failed|errors?") : null, + skipped: summary ? counted(summary, "skipped") : null, values, }; } diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index c1d5af2b04b..301ed512ec0 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -98,7 +98,16 @@ test("a report over the read bound is read for its head", { skip: WINDOWS }, (t) }); test("a command's one pytest run of one test file is whole or filtered with -k", () => { - const whole = { path: FILE, dir: "", whole: true, seconds: null, skipped: null, values: [] }; + const whole = { + path: FILE, + dir: "", + whole: true, + seconds: null, + cases: null, + failed: null, + skipped: null, + values: [], + }; for (const command of [ `pytest ${FILE}`, `python -m pytest ${FILE} -q`, @@ -131,20 +140,24 @@ test("a command's one pytest run of one test file is whole or filtered with -k", assert.equal(fileRun(`pytest ${FILE} -q`, "........\n8000 passed in 140.21s (0:02:20)").seconds, 140.21); assert.equal(fileRun(`pytest ${FILE} -k parse`, "12 passed, 7988 deselected in 2.31s").seconds, 2.31); assert.equal(fileRun(`pytest ${FILE} -q`, "Command running in background with ID: bash_1").seconds, null); - // The last line of a run that ended, whatever it counts, with its skipped - // cases apart from the expected failures. - for (const [line, seconds, skipped] of [ - ["8000 passed in 140.21s (0:02:20)", 140.21, 0], - ["=== 7000 passed, 100 skipped, 900 xfailed in 170.00s (0:02:50) ===", 170, 100], - ["1 failed, 7999 passed in 300.00s", 300, 0], - ["8000 deselected in 1.20s", 1.2, 0], - ["12 skipped in 0.31s", 0.31, 12], - ["3 xfailed in 0.50s", 0.5, 0], - ["no tests ran in 0.01s", 0.01, 0], - ["1 warning in 0.02s", 0.02, 0], + // The last line of a run that ended, whatever it counts: its seconds, the + // cases the result file counts too (all but the deselected), the failures + // and errors among them, and the skipped ones apart from the expected failures. + for (const [line, seconds, cases, failed, skipped] of [ + ["8000 passed in 140.21s (0:02:20)", 140.21, 8000, 0, 0], + ["=== 7000 passed, 100 skipped, 900 xfailed in 170.00s (0:02:50) ===", 170, 8000, 0, 100], + ["1 failed, 7999 passed in 300.00s", 300, 8000, 1, 0], + ["2 failed, 9 passed, 1 xpassed, 3 warnings, 1 error in 4.00s", 4, 13, 3, 0], + ["12 passed, 7988 deselected in 2.31s", 2.31, 12, 0, 0], + ["8000 deselected in 1.20s", 1.2, 0, 0, 0], + ["12 skipped in 0.31s", 0.31, 12, 0, 12], + ["3 xfailed in 0.50s", 0.5, 3, 0, 0], + ["2 errors in 0.52s", 0.52, 2, 2, 0], + ["no tests ran in 0.01s", 0.01, 0, 0, 0], + ["1 warning in 0.02s", 0.02, 0, 0, 0], ]) { const run = fileRun(`pytest ${FILE} -k parse -q`, `collected 8000 items\n${line}`); - assert.deepEqual([run.seconds, run.skipped], [seconds, skipped], line); + assert.deepEqual([run.seconds, run.cases, run.failed, run.skipped], [seconds, cases, failed, skipped], line); } }); @@ -400,6 +413,9 @@ test("a report is the command's whose output shows the summary with the report's assert.deepEqual(runs().files[file].whole, whole(180)); // A -k run whose cases skipped is no filtered time. note(FILTERED_COMMAND, "12 skipped, 7988 deselected in 0.31s", report({ tests: 12, time: "0.3", skipped: 12 })); + // A case whose teardown raised is twice on the summary and once in the report. + const raised = report({ tests: 12, time: "2.3", failures: 1 }); + note(FILTERED_COMMAND, "12 passed, 7988 deselected, 1 error in 2.31s", raised); // A run the option did not reach wrote no report: the one read after it is an // earlier run's, and its seconds are not the summary's. note(`PYTEST_ADDOPTS=-q pytest ${FILE} -k parse`, FILTERED_OUTPUT, report({ tests: 8000, time: "600.0" })); @@ -408,6 +424,26 @@ test("a report is the command's whose output shows the summary with the report's }); }); +test("an earlier short run's report is not that of a later short run that wrote none", { skip: WINDOWS }, (t) => { + inTmp(t, (cwd, file) => { + const note = (output, xml) => + noteCommand(SESSION, { command: `PYTEST_ADDOPTS=-q pytest -x ${FILE}`, output, report: read(xml), cwd }); + // A -k run that no hook read left its report: 12 cases in 1.4 s. The run + // after it set its own options and wrote none, and its summary's seconds + // are within a second of the report's: it does not count the report's cases. + const earlier = report({ tests: 12, time: "1.4" }); + note("1 error in 0.52s", earlier); + note("1 failed in 0.80s", earlier); + // The report's cases, and a failure the report does not hold. + note("1 error in 0.52s", report({ tests: 1, time: "0.6" })); + note("1 failed, 11 passed in 1.10s", earlier); + assert.deepEqual(runs(), {}); + // The summary of the run that wrote the report counts its cases and failures. + note("12 passed in 1.38s", earlier); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 12, seconds: 1 } } } }); + }); +}); + test("a command that is no file run, or names a file that is not there, leaves no state", { skip: WINDOWS, }, (t) => { @@ -433,7 +469,8 @@ test("a session's state holds eight files, the costliest whole run among them, a const note = (name, tests = 12) => { fs.writeFileSync(path.join(cwd, name), ""); const xml = report({ tests, time: "2.3", file: name }); - noteCommand(SESSION, { command: `pytest ${name} -k parse -q`, output: FILTERED_OUTPUT, report: read(xml), cwd }); + const output = `${tests} passed, ${8000 - tests} deselected in 2.31s`; + noteCommand(SESSION, { command: `pytest ${name} -k parse -q`, output, report: read(xml), cwd }); }; note(FILE); for (let i = 0; i < 7; i++) note(`tests/test_${i}.py`); @@ -961,6 +998,22 @@ test("a run that skipped most of its cases, or left cases out by a selection its assert.deepEqual(server.sent("memory.set"), []); }); +test("an earlier short run's report, read after a short run that wrote none, does not lower the row", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t, { get: row() }); + const box = sandbox(t, server); + assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + // A -k run that no hook read wrote the report. The run of this command set + // its own options, wrote none and stopped at an error half a second in. + const earlier = report({ tests: 12, time: "1.4" }); + await afterCommand(box, `PYTEST_ADDOPTS=-q pytest -x ${FILE}`, "1 error in 0.52s", earlier); + assert.deepEqual(readJsonFile(box.runs, null), {}); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + test("code-only mode notes nothing, stores nothing and prints no line", { skip: WINDOWS }, async (t) => { const server = await loom(t, { get: row() }); const box = sandbox(t, server); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 745ea2c8602..556836e1272 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -126,15 +126,16 @@ function settle(state, report) { * (`newReport`, else null), and the payload's `cwd`. * * The report is the command's when the command is one pytest run of one test - * file (`fileRun`) and its output shows pytest's summary with the seconds - * the report holds: a run the option did not reach writes no report, and the - * one read after it is an earlier run's. A run whose output shows no summary - * may not have ended: it is kept as the session's pending run, with the time - * its command returned. Any other report is the pending run's when its run - * began by that time (`settle`), and no run's otherwise. So a run that was - * put in the background before pytest began is not counted. An open run of - * another kind than the pending one drops both: one of the two would be - * counted as the other. + * file (`fileRun`) and its output shows pytest's summary with the cases, the + * failures and the seconds the report holds: a run the option did not reach + * writes no report, and the one read after it is an earlier run's. The + * seconds alone do not tell two short runs apart. A run whose output shows + * no summary may not have ended: it is kept as the session's pending run, + * with the time its command returned. Any other report is the pending run's + * when its run began by that time (`settle`), and no run's otherwise. So a + * run that was put in the background before pytest began is not counted. An + * open run of another kind than the pending one drops both: one of the two + * would be counted as the other. */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { @@ -144,7 +145,13 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { const cost = report ? runCost(report.head) : null; const open = Boolean(run && run.seconds === null); // The summary's seconds and the report's are two clocks on one run. - const own = run && !open && cost && Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); + const own = + run && + !open && + cost && + run.cases === cost.tests && + run.failed === cost.failed && + Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); // The summary counts the skipped cases apart from the expected failures. if (own) add(state, run, { ...cost, skipped: run.skipped }); else settle(state, report); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 7404a3aeb87..77cf93fbaba 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1367,20 +1367,27 @@ const PYTHON_FILE = /\.py(?:::|$)/; // 0.31s` or `no tests ran in 0.01s`. const LAST_LINE = /\b(?:\d+ (?:passed|failed|errors?|skipped|deselected|xfailed|xpassed|warnings?)|no tests ran)\b.* in [\d.]+s\b/; +/** The sum of the counts `line` gives for `kinds`, an alternation of the + * words of pytest's last line. */ +const counted = (line, kinds) => + [...line.matchAll(new RegExp(`\\b(\\d+) (?:${kinds})\\b`, "g"))].reduce((sum, found) => sum + Number(found[1]), 0); /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, dir, whole, seconds, skipped, values }`, else null. - * `path` is the file as the command spells it and `dir` the folder of the one - * `cd` before the run, "" for none. `whole` is false for a run filtered with - * `-k`. `seconds` is what pytest's last line in the visible `output` shows - * (`LAST_LINE`) and `skipped` the skipped cases that line counts, apart from - * the expected failures; both are null where the output holds no such line: - * the run did not finish inside the call. A run with no `-k` whose last line - * counts deselected cases is none: a selection its words do not show left - * cases out (one in `PYTEST_ADDOPTS` or the settings file, or written after - * `2>&1`, where the words end). + * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values }`, + * else null. `path` is the file as the command spells it and `dir` the folder + * of the one `cd` before the run, "" for none. `whole` is false for a run + * filtered with `-k`. `seconds` is what pytest's last line in the visible + * `output` shows (`LAST_LINE`). `cases` is the cases that line counts, all + * but the deselected: the result file's `tests`, but for a case whose + * teardown raised an error, which the line counts twice and the file once. + * `failed` is the failures and errors among them and `skipped` the skipped + * ones, apart from the expected failures. All four are null where the output + * holds no such line: the run did not finish inside the call. A run with no + * `-k` whose last line counts deselected cases is none: a selection its words + * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings file, + * or written after `2>&1`, where the words end). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1433,7 +1440,9 @@ export function fileRun(command, output = "") { dir: cd.length ? unquoted(cd[0][1]) : "", whole, seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, - skipped: summary ? Number(/\b(\d+) skipped\b/.exec(summary)?.[1] ?? 0) : null, + cases: summary ? counted(summary, "passed|failed|errors?|skipped|xfailed|xpassed") : null, + failed: summary ? counted(summary, "failed|errors?") : null, + skipped: summary ? counted(summary, "skipped") : null, values, }; } diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 7ad5d794433..a4948f9e1f9 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "0a51a192dfa8799f1366266a135f7aa1f9d7ce4151ad2f48a9548c0a59b3014c", + "integrations/claude-code-plugin/lib/test-cost.mjs": "80fa24453eb6b812402f055f12c946522b1d6ddecc17cb5d50cae28fa4b3eb8b", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "0a51a192dfa8799f1366266a135f7aa1f9d7ce4151ad2f48a9548c0a59b3014c", + "integrations/codex-plugin/lib/test-cost.mjs": "80fa24453eb6b812402f055f12c946522b1d6ddecc17cb5d50cae28fa4b3eb8b", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 02eb1fcaf18b1ff2a9a342b890472c480009e817 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 21:45:46 +0530 Subject: [PATCH 08/24] A run pytest ended early is no measure of a test file's cost pytest prints an ordinary last line and writes its result file for a run it ended before the last case: at a failure limit, an error during collection, an interrupt or pytest.exit. Such a whole run was kept as the file's whole run and lowered the stored seconds, and such a -k run was kept as a filtered sample. fileRun now reads the line pytest prints above the last one, the reason between runs of `!`, and such a run is neither. The launcher loads lib/test-cost.mjs at SessionEnd only, so the prompt hook's own load of it is the only one at a prompt. noteCommand takes the caller's cwd as it is. The prompt hook's comments, the hooks reference and the Claude Code page say what the cost line's read can hold back: the git calls that resolve the checkout's scope before the read is sent, and, for a script started on its own, the read until it settles or the exit grace passes. The two requests of the cost hooks and the reply the prompt hook reads are a fixture: the plugin's tests hold the hooks to it, and tests/unit/test_plugin_memory_contract.py holds it to MemoryGetInput, MemoryGetOutput and MemorySetInput. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 13 +++- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 17 ++++- .../hooks/loom-prompt-pack.mjs | 14 +++- .../claude-code-plugin/hooks/loom-record.mjs | 6 +- .../claude-code-plugin/lib/test-cost.mjs | 6 +- .../claude-code-plugin/lib/test-gate.mjs | 15 +++- .../tests/fixtures/test-cost-wire.json | 30 ++++++++ .../tests/test-cost.test.mjs | 74 +++++++++++++------ .../codex-plugin/hooks/loom-prompt-pack.mjs | 14 +++- .../codex-plugin/hooks/loom-record.mjs | 6 +- integrations/codex-plugin/lib/test-cost.mjs | 6 +- integrations/codex-plugin/lib/test-gate.mjs | 15 +++- tests/unit/session_content_senders.json | 8 +- tests/unit/test_plugin_memory_contract.py | 38 ++++++++++ 15 files changed, 212 insertions(+), 52 deletions(-) create mode 100644 integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json create mode 100644 tests/unit/test_plugin_memory_contract.py diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 098b66fdfb8..4a6cdfefb6c 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1708,6 +1708,11 @@ session's private state, by the file: - a run with no `-k` in its command whose summary line counts deselected cases counts as neither: a selection the command does not show left cases out (one in `PYTEST_ADDOPTS` or the repository's pytest settings, or one written after `2>&1`); +- a run pytest ended before its last case counts as neither: at a failure limit (`-x`, + `--maxfail`), at an error during collection, at an interrupt or at `pytest.exit`. The + line pytest prints above its summary line says so (`stopping after 1 failures` between + two runs of `!`), and the summary line and the result file count the cases the run got + to; - a run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, and a run that only collects or prints (`--collect-only`, `--fixtures`) count as neither. The word after a long flag is a @@ -1766,7 +1771,10 @@ The clause about the timeout is printed for a run over 120 s, the default of a s under Claude Code, and the middle sentence where a filtered run was measured. The row is read with one `memory.get` a session and checkout, sent beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the -pointers are printed as they are. The line is made of the row's path and numbers, so a +pointers are printed as they are. Before the read is sent the hook names the repository +from the checkout's git remote. Where no other hook of the prompt has done so, that is +one `git config` call as a rule, bounded at 1,500 ms, and the search's answer is taken +after it. The line is made of the row's path and numbers, so a value someone rewrote is neither printed nor overwritten. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. @@ -1798,6 +1806,9 @@ What it does not do: the cases are expected failures is not counted. Nor does the result file count the deselected cases: such a run with a selection its command does not show is counted as a whole run, with the cases it ran; +- a run pytest ended early is counted with the cases it got to where the command cut + pytest's line about it from its output (`| tail -1`), or where the run outlived its + shell call; - a run in which a case's teardown raised an error after the case passed or failed is not counted: pytest's summary line counts that case twice and the result file once; - the result file of a run of the same file that something else started while a run that diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index ff8514a6d3a..7be15a95d60 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 995c7e0cc53..f4fdedc573f 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -972,7 +972,14 @@ default 120 s timeout of a shell call. A run filtered with -k takes about row by its key with one `memory.get`, sent beside the search and inside its bound, and never waits for it past the search's answer: an answer that has not come by then, an error and a miss print nothing, and the - pointers are the same bytes with or without the line. The row as it was + pointers are the same bytes with or without the line. Before the read is + sent the hook resolves the checkout's scope in its own thread: where no + script of the prompt has done so in the process, that is git calls of + 1,500 ms at most each (one `git config` where the index's match is + cached), and the search's answer is taken after them. The launcher + exits with the prompt's answer; a script started on its own prints the + pointers and stays until the read has settled or its exit grace has + passed. The row as it was read, a miss too, is kept in the session's state with its hash, the agent that wrote it and the checkout it was read in, so a session asks once in a checkout; a read that failed or came late is asked again at @@ -1414,6 +1421,14 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that a run that outlived its shell call has the report alone: such a run of a file where more than a tenth of the cases are expected failures is not kept. + A run pytest ended before its last case is noted as nothing: at a + failure limit (`-x`, `--maxfail`), at an error during collection, at an + interrupt or at `pytest.exit`. Its last line and its report count the + cases it got to, and the line pytest prints above the last one says so + (`!!!! stopping after 1 failures !!!!`, `!!!! KeyboardInterrupt !!!!`). + Where the command cut that line from its output (`| tail -1`), or the + run outlived its shell call, the run is counted with the cases it got + to. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`, which may run every case), a run that only collects or prints, and a command with two pytest runs or two paths are noted as diff --git a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index 4539d501702..c663619a7eb 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -50,7 +50,13 @@ // run filtered with -k, and to check a change with -k selections. The row is // read by its key once a session and checkout, beside the search and inside // the prompt's bound, and the line is sent only when that read has answered -// by the time the search has: it never holds the pointers back. A row whose +// by the time the search has: under the launcher the read never holds the +// pointers back. The git calls that resolve the checkout's scope for it can. +// Where no script of the prompt has resolved the scope in the process, they +// run in this thread before the read is sent, each bounded at 1,500 ms (one +// `git config` where the index's match is cached), and the search's answer is +// taken after them. A script started on its own prints the pointers and then +// stays until the read has settled or the exit grace has passed. A row whose // file the checkout does not hold prints nothing. // // A search whose query reads as a bug report (twelve words or more, or a word @@ -227,8 +233,10 @@ async function testLine(pointers, prompt, root, payload, until) { } /** The test cost line of the session's repository, or "" (`costLine` in - * lib/test-cost.mjs, loaded only for a bug report). Never rejects: nothing - * waits for it when the search answers first. */ + * lib/test-cost.mjs, loaded only for a bug report). Never rejects. `main` + * does not wait for it when the search answers first, and neither does the + * launcher, which exits with the answer; a script started on its own stays + * until the read has settled or the exit grace has passed (`scheduleExit`). */ function costNote(payload, root, cwd, options) { return import("../lib/test-cost.mjs") .then(({ costLine }) => costLine(payload.session_id, root, () => resolveScope(cwd), options)) diff --git a/integrations/claude-code-plugin/hooks/loom-record.mjs b/integrations/claude-code-plugin/hooks/loom-record.mjs index 86e4dd01ebb..1cb9c638e6e 100644 --- a/integrations/claude-code-plugin/hooks/loom-record.mjs +++ b/integrations/claude-code-plugin/hooks/loom-record.mjs @@ -80,7 +80,6 @@ import { import { keepRunBegin, runLedgerEnabled } from "../lib/run-hook.mjs"; import { readsOnly } from "../lib/shell-command.mjs"; import { useHooksServer } from "../lib/plugin-options.mjs"; -import { settleRun } from "../lib/test-cost.mjs"; import { startsRunner } from "../lib/test-gate.mjs"; import { endReport, reportPath, showsRefusal, testReportOn, visibleOutput } from "../lib/test-report.mjs"; import { readPrivateFile, removeFile } from "../lib/tmp-state.mjs"; @@ -233,10 +232,11 @@ async function hook(script, event, client) { const raw = await readStdinText(); // The session's test report goes with the session, whatever else is recorded. A // run that had not ended when its command returned wrote the report since: what - // it cost is read first, for the session's hand-off to memory. + // it cost is read first, for the session's hand-off to memory. The library + // that reads it is loaded for this event only. if (event === "SessionEnd") { const sessionId = parsePayload(raw).session_id; - if (planeEnabled("memory") && testReportOn()) settleRun(sessionId); + if (planeEnabled("memory") && testReportOn()) (await import("../lib/test-cost.mjs")).settleRun(sessionId); endReport(sessionId); } if (recordedInHook(event)) { diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 556836e1272..bba7998c991 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -139,7 +139,7 @@ function settle(state, report) { */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { - const run = located(fileRun(command, output), cwd || process.cwd()); + const run = located(fileRun(command, output), cwd); const state = readSessionState(RUNS, sessionId); if (!run && !state.pending) return; const cost = report ? runCost(report.head) : null; @@ -237,7 +237,9 @@ const identity = (scope, agent) => ({ * `options.timeoutMs`) and kept in the session's state, a miss too, with the * agent that wrote it and the checkout it was read in: a session whose * folder moved to another checkout reads that one's row. `scopeOf()` is - * asked only for that read. An answer that does not come and an error give + * asked only for that read, before it is sent: where the process has not + * resolved the checkout's scope yet, its git calls run then, in the caller's + * thread. An answer that does not come and an error give * no line, and a later prompt asks again. A row gives none whose value is * not `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose * file the checkout does not hold. diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 77cf93fbaba..56a7636badf 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1367,6 +1367,11 @@ const PYTHON_FILE = /\.py(?:::|$)/; // 0.31s` or `no tests ran in 0.01s`. const LAST_LINE = /\b(?:\d+ (?:passed|failed|errors?|skipped|deselected|xfailed|xpassed|warnings?)|no tests ran)\b.* in [\d.]+s\b/; +// The line pytest prints above the last line of a run it ended before its +// last case, whatever ended it: a failure limit, an error at collection, an +// interrupt, `pytest.exit`. The message stands between two runs of `!`, of +// one each where the message is as wide as the terminal. +const CUT_SHORT = /^!+ .+ !+$/; /** The sum of the counts `line` gives for `kinds`, an alternation of the * words of pytest's last line. */ const counted = (line, kinds) => @@ -1387,7 +1392,9 @@ const counted = (line, kinds) => * holds no such line: the run did not finish inside the call. A run with no * `-k` whose last line counts deselected cases is none: a selection its words * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings file, - * or written after `2>&1`, where the words end). + * or written after `2>&1`, where the words end). Nor is a run pytest ended + * before its last case, which the line above its last one says (`CUT_SHORT`): + * its last line and its result file count the cases it got to. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1430,9 +1437,9 @@ export function fileRun(command, output = "") { const other = (word) => !BY_NAME.test(word) && (PARTIAL.test(word) || CLUSTER.test(word) || OWN_REPORT.test(word)); if (!followed || named.length !== 1 || !/^[^\s:]+\.py$/.test(named[0]) || words.some(other)) return null; if (values.some((word) => PYTHON_FILE.test(word))) return null; - const summary = String(output || "") - .split(/\r?\n/) - .findLast((line) => line.length < 300 && LAST_LINE.test(line)); + const lines = String(output || "").split(/\r?\n/); + if (lines.some((line) => CUT_SHORT.test(line.trim()))) return null; + const summary = lines.findLast((line) => line.length < 300 && LAST_LINE.test(line)); const whole = !words.some((word) => BY_NAME.test(word)); if (whole && summary && /\b\d+ deselected\b/.test(summary)) return null; return { diff --git a/integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json b/integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json new file mode 100644 index 00000000000..055f31494a3 --- /dev/null +++ b/integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json @@ -0,0 +1,30 @@ +{ + "requests": { + "memory.get": { + "org": "default", + "namespace": "coding", + "agent": "claude-code", + "memory_key": "repo:315f533aed/test-cost/pytest", + "fields": ["value", "content_sha256", "agent"] + }, + "memory.set": { + "org": "default", + "namespace": "coding", + "agent": "claude-code", + "memory_key": "repo:315f533aed/test-cost/pytest", + "value": "In the repository tagged repo:315f533aed, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s.", + "tags": ["repo:315f533aed", "source:claude-code", "test-cost"], + "files": [], + "source_class": "external", + "if_match_sha256": "absent" + } + }, + "responses": { + "memory.get": { + "found": true, + "value": "In the repository tagged repo:315f533aed, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s.", + "content_sha256": "abc", + "agent": "claude-code" + } + } +} diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 301ed512ec0..6a489749775 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -215,6 +215,22 @@ test("a command with two pytest runs, two paths, another selection or no run of assert.equal(fileRun(command, FILTERED_OUTPUT), null, command); assert.equal(fileRun(command, "8000 deselected in 1.20s"), null, command); } + // A run pytest ended before its last case: the line above its last one says + // so, between runs of `!` that are one long where the message is wide. + for (const [command, banner, line] of [ + [`pytest ${FILE} -q`, `${"!".repeat(30)} KeyboardInterrupt ${"!".repeat(31)}`, "120 passed in 30.00s"], + [`pytest ${FILE}`, "!!!!!!!! _pytest.outcomes.Exit: enough !!!!!!!!", "120 passed in 30.00s"], + [`pytest ${FILE}`, `! _pytest.outcomes.Exit: ${"x".repeat(120)} !`, "120 passed in 30.00s"], + [ + `pytest ${FILE} -k parse -x`, + "!!!!!! stopping after 1 failures !!!!!!", + "1 failed, 3 passed, 7988 deselected in 0.52s", + ], + [`pytest ${FILE} -k parse`, "!!!!! Interrupted: 1 error during collection !!!!!", "1 error in 0.52s"], + ]) { + assert.equal(fileRun(command, line).seconds > 0, true, command); + assert.equal(fileRun(command, `collected 8000 items\n${banner}\n${line}`), null, banner); + } }); test("the stored claim and the prompt's line, byte for byte", () => { @@ -416,6 +432,22 @@ test("a report is the command's whose output shows the summary with the report's // A case whose teardown raised is twice on the summary and once in the report. const raised = report({ tests: 12, time: "2.3", failures: 1 }); note(FILTERED_COMMAND, "12 passed, 7988 deselected, 1 error in 2.31s", raised); + // A run pytest ended early is neither: its last line and its report count the cases it got to. + const early = "!!!!!!!! KeyboardInterrupt !!!!!!!!\n"; + note(WHOLE_COMMAND, `${early}8000 passed in 500.00s`, report({ tests: 8000, time: "500.0" })); + const stopped = report({ tests: 4, time: "0.5", failures: 1 }); + note( + `${FILTERED_COMMAND} -x`, + "!!!!! stopping after 1 failures !!!!!\n1 failed, 3 passed, 7996 deselected in 0.52s", + stopped, + ); + // A -k run that failed and ran its whole selection is a filtered run. + note( + FILTERED_COMMAND, + "1 failed, 29 passed, 7970 deselected in 3.61s", + report({ tests: 30, time: "3.6", failures: 1 }), + ); + filtered.push([30, 4]); // A run the option did not reach wrote no report: the one read after it is an // earlier run's, and its seconds are not the summary's. note(`PYTEST_ADDOPTS=-q pytest ${FILE} -k parse`, FILTERED_OUTPUT, report({ tests: 8000, time: "600.0" })); @@ -611,8 +643,13 @@ const LINE = renderCost({ path: FILE, tests: 8000, seconds: 140, filtered: 2 }); // Reads as a bug report: the prompt hook asks for the pick, and for the cost line. const BUG = "Nested record prefixes raise an error before validation when the parser is given an empty prefix."; +// The two requests of the hooks and the reply the prompt hook reads, as a +// checkout of ORIGIN sends and gets them: tests/unit/test_plugin_memory_contract.py +// holds them to the server's wire models. +const WIRE = JSON.parse(fs.readFileSync(new URL("./fixtures/test-cost-wire.json", import.meta.url), "utf8")); + /** The repository's row as memory.get answers it. */ -const row = (value = BOTH, agent = "claude-code") => ({ found: true, value, content_sha256: "abc", agent }); +const row = (value = BOTH, agent = "claude-code") => ({ ...WIRE.responses["memory.get"], value, agent }); /** A stub Loom server. `get` is what memory.get answers, a function of the * request's body that gives it, or a status for a failure; `getStall` holds @@ -782,18 +819,12 @@ test("a slow whole run and a filtered one are noted, and the session's end store await arrived(server, box, "memory.set"); const [stored] = server.sent("memory.set"); assert.equal(server.sent("memory.set").length, 1); - assert.deepEqual(stored.body, { - org: "default", - namespace: "coding", - agent: "claude-code", - memory_key: KEY, - value: BOTH, - tags: [`repo:${REPO}`, "source:claude-code", "test-cost"], - files: [], - source_class: "external", - // The session's read was a miss: the server writes only where there is no row. - if_match_sha256: "absent", - }); + // The session's read was a miss: the server writes only where there is no row. + assert.deepEqual(stored.body, WIRE.requests["memory.set"]); + assert.deepEqual( + [stored.body.memory_key, stored.body.value, stored.body.if_match_sha256, stored.body.files], + [KEY, BOTH, "absent", []], + ); assert.equal(stored.headers["x-loom-session-protection"], undefined); // The session's cost state went with the hand-off, and nothing was read again. assert.equal(fs.existsSync(box.runs), false); @@ -979,12 +1010,16 @@ test("a pytest run that ends before a hook read the pending run's report replace assert.equal(fs.existsSync(box.runs), false); }); -test("a run that skipped most of its cases, or left cases out by a selection its command does not show, does not lower the row", { +test("a run that pytest ended early, that skipped most of its cases, or that left cases out by a selection its command does not show, does not lower the row", { skip: WINDOWS, }, async (t) => { const server = await loom(t, { get: row() }); const box = sandbox(t, server); assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); + // An interrupt ended the run 120 cases in: the line above its last one says so. + const early = `!!!!!!!! KeyboardInterrupt !!!!!!!!\n${FILE}:4: KeyboardInterrupt\n120 passed in 30.00s`; + await afterCommand(box, `python -m pytest ${FILE} -q`, early, report({ tests: 120, time: "30.0" })); + assert.equal(readJsonFile(box.runs, null), null); // The command's words end at `2>&1`: its last line says cases were left out. await afterCommand(box, `python -m pytest ${FILE} 2>&1 -k parse | tail -3`, FILTERED_OUTPUT, FILTERED); assert.equal(readJsonFile(box.runs, null), null); @@ -1042,13 +1077,10 @@ test("a bug report carries the repository's cost line under its pointers, from o assert.deepEqual({ code: first.code, stderr: first.stderr }, { code: 0, stderr: "" }); assert.equal(context(first), `${BLOCK}\n${LINE}`); const [read] = server.sent("memory.get"); - assert.deepEqual(read.body, { - org: "default", - namespace: "coding", - agent: "claude-code", - memory_key: KEY, - fields: ["value", "content_sha256", "agent"], - }); + assert.deepEqual(read.body, WIRE.requests["memory.get"]); + assert.equal(read.body.memory_key, KEY); + // The reply the fixture holds is the row this line was made of. + assert.deepEqual(row(), WIRE.responses["memory.get"]); assert.equal(read.headers["x-loom-session-protection"], undefined); // The next bug report has the line from the session's state. assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); diff --git a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs index 4539d501702..c663619a7eb 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -50,7 +50,13 @@ // run filtered with -k, and to check a change with -k selections. The row is // read by its key once a session and checkout, beside the search and inside // the prompt's bound, and the line is sent only when that read has answered -// by the time the search has: it never holds the pointers back. A row whose +// by the time the search has: under the launcher the read never holds the +// pointers back. The git calls that resolve the checkout's scope for it can. +// Where no script of the prompt has resolved the scope in the process, they +// run in this thread before the read is sent, each bounded at 1,500 ms (one +// `git config` where the index's match is cached), and the search's answer is +// taken after them. A script started on its own prints the pointers and then +// stays until the read has settled or the exit grace has passed. A row whose // file the checkout does not hold prints nothing. // // A search whose query reads as a bug report (twelve words or more, or a word @@ -227,8 +233,10 @@ async function testLine(pointers, prompt, root, payload, until) { } /** The test cost line of the session's repository, or "" (`costLine` in - * lib/test-cost.mjs, loaded only for a bug report). Never rejects: nothing - * waits for it when the search answers first. */ + * lib/test-cost.mjs, loaded only for a bug report). Never rejects. `main` + * does not wait for it when the search answers first, and neither does the + * launcher, which exits with the answer; a script started on its own stays + * until the read has settled or the exit grace has passed (`scheduleExit`). */ function costNote(payload, root, cwd, options) { return import("../lib/test-cost.mjs") .then(({ costLine }) => costLine(payload.session_id, root, () => resolveScope(cwd), options)) diff --git a/integrations/codex-plugin/hooks/loom-record.mjs b/integrations/codex-plugin/hooks/loom-record.mjs index 86e4dd01ebb..1cb9c638e6e 100644 --- a/integrations/codex-plugin/hooks/loom-record.mjs +++ b/integrations/codex-plugin/hooks/loom-record.mjs @@ -80,7 +80,6 @@ import { import { keepRunBegin, runLedgerEnabled } from "../lib/run-hook.mjs"; import { readsOnly } from "../lib/shell-command.mjs"; import { useHooksServer } from "../lib/plugin-options.mjs"; -import { settleRun } from "../lib/test-cost.mjs"; import { startsRunner } from "../lib/test-gate.mjs"; import { endReport, reportPath, showsRefusal, testReportOn, visibleOutput } from "../lib/test-report.mjs"; import { readPrivateFile, removeFile } from "../lib/tmp-state.mjs"; @@ -233,10 +232,11 @@ async function hook(script, event, client) { const raw = await readStdinText(); // The session's test report goes with the session, whatever else is recorded. A // run that had not ended when its command returned wrote the report since: what - // it cost is read first, for the session's hand-off to memory. + // it cost is read first, for the session's hand-off to memory. The library + // that reads it is loaded for this event only. if (event === "SessionEnd") { const sessionId = parsePayload(raw).session_id; - if (planeEnabled("memory") && testReportOn()) settleRun(sessionId); + if (planeEnabled("memory") && testReportOn()) (await import("../lib/test-cost.mjs")).settleRun(sessionId); endReport(sessionId); } if (recordedInHook(event)) { diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 556836e1272..bba7998c991 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -139,7 +139,7 @@ function settle(state, report) { */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { - const run = located(fileRun(command, output), cwd || process.cwd()); + const run = located(fileRun(command, output), cwd); const state = readSessionState(RUNS, sessionId); if (!run && !state.pending) return; const cost = report ? runCost(report.head) : null; @@ -237,7 +237,9 @@ const identity = (scope, agent) => ({ * `options.timeoutMs`) and kept in the session's state, a miss too, with the * agent that wrote it and the checkout it was read in: a session whose * folder moved to another checkout reads that one's row. `scopeOf()` is - * asked only for that read. An answer that does not come and an error give + * asked only for that read, before it is sent: where the process has not + * resolved the checkout's scope yet, its git calls run then, in the caller's + * thread. An answer that does not come and an error give * no line, and a later prompt asks again. A row gives none whose value is * not `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose * file the checkout does not hold. diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 77cf93fbaba..56a7636badf 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1367,6 +1367,11 @@ const PYTHON_FILE = /\.py(?:::|$)/; // 0.31s` or `no tests ran in 0.01s`. const LAST_LINE = /\b(?:\d+ (?:passed|failed|errors?|skipped|deselected|xfailed|xpassed|warnings?)|no tests ran)\b.* in [\d.]+s\b/; +// The line pytest prints above the last line of a run it ended before its +// last case, whatever ended it: a failure limit, an error at collection, an +// interrupt, `pytest.exit`. The message stands between two runs of `!`, of +// one each where the message is as wide as the terminal. +const CUT_SHORT = /^!+ .+ !+$/; /** The sum of the counts `line` gives for `kinds`, an alternation of the * words of pytest's last line. */ const counted = (line, kinds) => @@ -1387,7 +1392,9 @@ const counted = (line, kinds) => * holds no such line: the run did not finish inside the call. A run with no * `-k` whose last line counts deselected cases is none: a selection its words * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings file, - * or written after `2>&1`, where the words end). + * or written after `2>&1`, where the words end). Nor is a run pytest ended + * before its last case, which the line above its last one says (`CUT_SHORT`): + * its last line and its result file count the cases it got to. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1430,9 +1437,9 @@ export function fileRun(command, output = "") { const other = (word) => !BY_NAME.test(word) && (PARTIAL.test(word) || CLUSTER.test(word) || OWN_REPORT.test(word)); if (!followed || named.length !== 1 || !/^[^\s:]+\.py$/.test(named[0]) || words.some(other)) return null; if (values.some((word) => PYTHON_FILE.test(word))) return null; - const summary = String(output || "") - .split(/\r?\n/) - .findLast((line) => line.length < 300 && LAST_LINE.test(line)); + const lines = String(output || "").split(/\r?\n/); + if (lines.some((line) => CUT_SHORT.test(line.trim()))) return null; + const summary = lines.findLast((line) => line.length < 300 && LAST_LINE.test(line)); const whole = !words.some((word) => BY_NAME.test(word)); if (whole && summary && /\b\d+ deselected\b/.test(summary)) return null; return { diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index a4948f9e1f9..718b2d8a878 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -398,7 +398,7 @@ "integrations/claude-code-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/claude-code-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/claude-code-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "4bd9d905379c5d33d88ae2d8da1009892e048c8dc130dd2d47edd6846a6cbb94", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "8d594f4b2bdfc40ca02b6b0fc10d366d2563b98149f86a1a8499c7f16b8e5189", "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "31ba0130495c6cbd40a3e4e673d9709deafb0cefb0b655b117d22a2437502b78", "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/claude-code-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -410,11 +410,11 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "80fa24453eb6b812402f055f12c946522b1d6ddecc17cb5d50cae28fa4b3eb8b", + "integrations/claude-code-plugin/lib/test-cost.mjs": "444fcf1ec3d13a041363c52b6a4ff9241571925cde72be8a23da8a774ef83a82", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "4bd9d905379c5d33d88ae2d8da1009892e048c8dc130dd2d47edd6846a6cbb94", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "8d594f4b2bdfc40ca02b6b0fc10d366d2563b98149f86a1a8499c7f16b8e5189", "integrations/codex-plugin/hooks/loom-session-start.mjs": "31ba0130495c6cbd40a3e4e673d9709deafb0cefb0b655b117d22a2437502b78", "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "80fa24453eb6b812402f055f12c946522b1d6ddecc17cb5d50cae28fa4b3eb8b", + "integrations/codex-plugin/lib/test-cost.mjs": "444fcf1ec3d13a041363c52b6a4ff9241571925cde72be8a23da8a774ef83a82", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", diff --git a/tests/unit/test_plugin_memory_contract.py b/tests/unit/test_plugin_memory_contract.py new file mode 100644 index 00000000000..bcc47d88ea5 --- /dev/null +++ b/tests/unit/test_plugin_memory_contract.py @@ -0,0 +1,38 @@ +"""The test cost hooks send requests, and read a reply, that the memory wire models serve.""" + +import json +from pathlib import Path + +from server.memory.api.models_crud import MemoryGetInput, MemoryGetOutput, MemorySetInput +from server.memory.domain.provenance import source_class_for +from server.operations import read_projection + +_WIRE = ( + Path(__file__).resolve().parents[2] + / "integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json" +) + + +def test_test_cost_requests_and_reply_match_the_memory_wire_models(): + """The plugin's tests hold the hooks to the fixture. A field the server renames fails + here: the hook would get a refusal or an empty field, print no line and store nothing.""" + wire = json.loads(_WIRE.read_text()) + get, put = wire["requests"]["memory.get"], wire["requests"]["memory.set"] + reply = wire["responses"]["memory.get"] + + assert get.keys() <= MemoryGetInput.model_fields.keys() + asked = MemoryGetInput.model_validate(get) + # The projection the handler resolves: a field name the reply does not have is refused. + served = read_projection.resolve( + MemoryGetOutput, asked.fields, always=read_projection.GET_ALWAYS + ) + assert served is not None and reply.keys() <= served + row = MemoryGetOutput.model_validate(reply) + assert row.found and row.value == put["value"] + + assert put.keys() <= MemorySetInput.model_fields.keys() + stored = MemorySetInput.model_validate(put) + # The row names no file to the server: an empty list, where an unset one is detected. + assert stored.files == [] + # A class a request body may declare. + assert source_class_for(default="asserted", requested=stored.source_class) == "external" From 61c36991c809b5e23ff91d05bac4ff2881a98387 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 22:26:25 +0530 Subject: [PATCH 09/24] A run with a runner started after it is no file run, and a session's cost state ends with the session fileRun read the command only up to its one pytest run. A runner started after the run (`pytest -q && make test`, `; tox`, a script) writes the session's result file and prints the last line, so the two agreed and the wrapper's cases and seconds could be stored as the named file's whole run. Only what the gate's onlyRuns allows may follow the run now: tail, head, grep and echo, with a redirect of the run to a file read past. The session's cost state was removed only by costPost, behind the switches of the write. loom-session-memory now removes it for every session (endCost), and the test report hook notes a run only where the session's end may store it: with LOOM_SESSION_MEMORY=off nothing is noted. The comments and the paragraphs of the hooks reference that held a line broken mid-sentence are rewrapped. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 16 +- integrations/claude-code-plugin/README.md | 4 +- .../claude-code-plugin/hooks/HOOKS.md | 148 +++++++++--------- .../hooks/loom-session-memory.mjs | 14 +- .../hooks/loom-test-report.mjs | 14 +- .../claude-code-plugin/lib/test-cost.mjs | 49 +++--- .../claude-code-plugin/lib/test-gate.mjs | 9 +- .../claude-code-plugin/lib/test-report.mjs | 7 +- .../tests/test-cost.test.mjs | 34 ++-- .../hooks/loom-session-memory.mjs | 14 +- .../codex-plugin/hooks/loom-test-report.mjs | 14 +- integrations/codex-plugin/lib/test-cost.mjs | 49 +++--- integrations/codex-plugin/lib/test-gate.mjs | 9 +- integrations/codex-plugin/lib/test-report.mjs | 7 +- tests/unit/session_content_senders.json | 4 +- 15 files changed, 227 insertions(+), 165 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 4a6cdfefb6c..0a62a2bfeb9 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1691,8 +1691,8 @@ no option and no digest after that. A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory -plane on, the test report also notes what a pytest run cost, and a later session in the -repository is told before it chooses. +plane on and session memory not switched off, the test report also notes what a pytest +run cost, and a later session in the repository is told before it chooses. **What is noted.** After a shell command that holds one pytest run, started in the checkout, that names one test file and nothing else to run, the hook reads the number of @@ -1717,7 +1717,11 @@ session's private state, by the file: command with two pytest runs or two paths, and a run that only collects or prints (`--collect-only`, `--fixtures`) count as neither. The word after a long flag is a second path where the flag takes no value (`--no-header tests`): a run with such a word - that names a Python file or a folder counts as neither too. + that names a Python file or a folder counts as neither too; +- a run that anything follows in its command but `tail`, `head`, `grep` and `echo` counts + as neither (`pytest tests/test_big.py -q && make test`): a runner started after it + writes the result file and prints the summary line. A redirect of the run to a file + may stand before them. The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the @@ -1823,8 +1827,10 @@ What it does not do: row and no line until that row is unpinned; - it is pytest under Claude Code only: Codex names no file for the result-file option. -`LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, -and [`code` mode](#modes) all three. `memory.delete` on the row's key removes it. +`LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note +and the write, and [`code` mode](#modes) all three. What a session noted and the row it +read are removed from its private state when it ends, whatever it stores. +`memory.delete` on the row's key removes the row. ## The code shunt diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 7be15a95d60..a2e184da9a3 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. @@ -336,7 +336,7 @@ Only a session whose bug report read the row writes, a miss included. With no ro Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session and checkout, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the write, and `code` mode all three; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session and checkout, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index f4fdedc573f..1377628c803 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -979,12 +979,11 @@ default 120 s timeout of a shell call. A run filtered with -k takes about cached), and the search's answer is taken after them. The launcher exits with the prompt's answer; a script started on its own prints the pointers and stays until the read has settled or its exit grace has - passed. The row as it was - read, a miss too, is kept in the session's state with its hash, the - agent that wrote it and the checkout it was read in, so a session asks - once in a checkout; a read that failed or came late is asked again at - the next bug report. The line is made of the row's - path and numbers and never of its text: a value that is not the stored + passed. The row as it was read, a miss too, is kept in the session's + state with its hash, the agent that wrote it and the checkout it was read + in, so a session asks once in a checkout; a read that failed or came late + is asked again at the next bug report. The line is made of the row's path + and numbers and never of its text: a value that is not the stored sentence prints nothing. Nor does a row whose whole run is under 60 s, or whose file the checkout does not hold. It needs the memory plane and a session that has the test report. @@ -1405,22 +1404,22 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that - **The cost of a run.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a selection of its cases answers in seconds. Where the memory plane is - on, the hook notes what a shell command's pytest run cost when the - command holds one pytest run, started in the checkout, that names one - test file and nothing else to run (`fileRun` in lib/test-gate.mjs): the - case count and the seconds of the report's first `testsuite` - (`runCost`, read from the file's first 4,096 bytes, also for a file - over the 2 MB bound). The session's private state keeps, for each of - eight files, the costliest whole run in which no case failed, and the - case count and seconds of its last 15 runs filtered with `-k`. The - eight are the file with the costliest whole run, which is what the - session's end stores, and the ones run last. A run that skipped more than a tenth of its cases is not - kept: it ran where the cases skip, and took less. The skipped cases are - the ones pytest's last line counts, where the command's output shows - it. The report counts an expected failure (`xfail`) as skipped too, and - a run that outlived its shell call has the report alone: such a run of - a file where more than a tenth of the cases are expected failures is - not kept. + on and session memory is not switched off, the hook notes what a shell + command's pytest run cost when the command holds one pytest run, + started in the checkout, that names one test file and nothing else to + run (`fileRun` in lib/test-gate.mjs): the case count and the seconds of + the report's first `testsuite` (`runCost`, read from the file's first + 4,096 bytes, also for a file over the 2 MB bound). The session's + private state keeps, for each of eight files, the costliest whole run + in which no case failed, and the case count and seconds of its last 15 + runs filtered with `-k`. The eight are the file with the costliest + whole run, which is what the session's end stores, and the ones run + last. A run that skipped more than a tenth of its cases is not kept: it + ran where the cases skip, and took less. The skipped cases are the ones + pytest's last line counts, where the command's output shows it. The + report counts an expected failure (`xfail`) as skipped too, and a run + that outlived its shell call has the report alone: such a run of a file + where more than a tenth of the cases are expected failures is not kept. A run pytest ended before its last case is noted as nothing: at a failure limit (`-x`, `--maxfail`), at an error during collection, at an interrupt or at `pytest.exit`. Its last line and its report count the @@ -1432,19 +1431,23 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`, which may run every case), a run that only collects or prints, and a command with two pytest runs or two paths are noted as - nothing (lib/test-cost.mjs). So is a run with no `-k` among its words - whose last line counts deselected cases: a selection the words do not - show left cases out, one in `PYTEST_ADDOPTS` or the settings file, or - one written after `2>&1`, where the words end. A run that outlived its - shell call shows no last line, and such a run is counted as a whole - run with the cases it ran. A whole run started with xdist workers - (`-n`) counts with the seconds it took: the row does not say how its - run was started, so a session that runs the file only in parallel - lowers a row that a serial run made. The word after a long flag is a second - path where the flag takes no value (`--no-header tests`), so a run - with such a word that names a Python file or a folder is noted as - nothing too. The file is the one the command names, from the payload's - folder and the command's one `cd`, where it is there. + nothing (lib/test-cost.mjs). So is a run that anything follows in its + command but `tail`, `head`, `grep` and `echo`, a redirect of the run to + a file aside (`onlyRuns` in lib/test-gate.mjs): a runner started after + it (`&& make test`, `; tox`) writes the result file and prints the last + line. So is a run with no `-k` among its words whose last line counts + deselected cases: a selection the words do not show left cases out, one + in `PYTEST_ADDOPTS` or the settings file, or one written after `2>&1`, + where the words end. A run that outlived its shell call shows no last + line, and such a run is counted as a whole run with the cases it ran. A + whole run started with xdist workers (`-n`) counts with the seconds it + took: the row does not say how its run was started, so a session that + runs the file only in parallel lowers a row that a serial run made. The + word after a long flag is a second path where the flag takes no value + (`--no-header tests`), so a run with such a word that names a Python + file or a folder is noted as nothing too. The file is the one the + command names, from the payload's folder and the command's one `cd`, + where it is there. The report is the command's when the command's visible output shows pytest's summary line with the cases, the failures and the seconds the report holds, the seconds within a second or a twentieth of them, @@ -1456,56 +1459,59 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that whose output shows no such line may not have ended: one that outlives its shell call writes the file after the hook ran. It is kept as the session's pending run, with the time its command returned. Any other - report the hook reads is the pending run's - when the run that wrote it began by that time, and no run's otherwise: - pytest began it at the time the file was written less the seconds of - its `testsuite`, and a run that a later command started, by any - launcher and whether or not a hook ran for that command, began after - it. A run of the file that something else started while the pending run - was in its call, such as a script in the background, began before that - time too: its report, read with a command that is not that run, is - counted as the pending run's. The launcher reads the report once more - at SessionEnd, before it removes the file, without reading a token. A - run of another kind left open while one is pending drops both, since - one would be counted as the other. A run put in the background at once - returns before pytest began, and is not counted. + report the hook reads is the pending run's when the run that wrote it + began by that time, and no run's otherwise: pytest began it at the time + the file was written less the seconds of its `testsuite`, and a run that + a later command started, by any launcher and whether or not a hook ran + for that command, began after it. A run of the file that something else + started while the pending run was in its call, such as a script in the + background, began before that time too: its report, read with a command + that is not that run, is counted as the pending run's. The launcher + reads the report once more at SessionEnd, before it removes the file, + without reading a token. A run of another kind left open while one is + pending drops both, since one would be counted as the other. A run put + in the background at once returns before pytest began, and is not + counted. The session has one result file, and no hook runs between two commands: where the session's next pytest run ends before a hook has read the file, that run's report replaces the pending run's, which is then not counted. At SessionEnd `loom-session-memory` hands one `memory.set` to the flusher, beside the session's turns or alone where they are not sent, - where a prompt of the session read - the row, a miss included, and its runs say something the row does not - (`revised`). With no row, the costliest whole run is stored when it - took 60 s or more. The row's own file is revised by the session's - whole run of it when that is more than a quarter away from the stored - seconds, down as well as up, and by the middle of its filtered runs - that ran fewer cases than the whole file, when the row has no such time - or one more than a quarter and two seconds away. Another file takes the - row with a whole run of 60 s or more that is over a quarter longer than - the row's file takes, and any such run takes a row whose file the - checkout no longer holds. The key is `repo:/test-cost/pytest`, one - row a repository in the session's namespace, tagged `repo:`, - `source:` and `test-cost`, with `files: []`, so that no file's - memory serves it, and `source_class: "external"`. The value is one - sentence, which names the repository by its tag because recall can - serve the row in another repository of the namespace: + where a prompt of the session read the row, a miss included, and its + runs say something the row does not (`revised`). With no row, the + costliest whole run is stored when it took 60 s or more. The row's own + file is revised by the session's whole run of it when that is more than + a quarter away from the stored seconds, down as well as up, and by the + middle of its filtered runs that ran fewer cases than the whole file, + when the row has no such time or one more than a quarter and two seconds + away. Another file takes the row with a whole run of 60 s or more that + is over a quarter longer than the row's file takes, and any such run + takes a row whose file the checkout no longer holds. The key is + `repo:/test-cost/pytest`, one row a repository in the session's + namespace, tagged `repo:`, `source:` and `test-cost`, with + `files: []`, so that no file's memory serves it, and + `source_class: "external"`. The value is one sentence, which names the + repository by its tag because recall can serve the row in another + repository of the namespace: `In the repository tagged repo:, a whole run of collects about cases and takes about s; a run of it filtered with -k takes -about s.` The write revises the row the session read - (`if_match_sha256`), under the agent that wrote it, and is create-only - (`absent`) after a miss, so it replaces no row the session did not - see; a value that is not that sentence is left as it is. A session - none of whose prompts read the row stores nothing. +about s.` The write revises the row the session read (`if_match_sha256`), + under the agent that wrote it, and is create-only (`absent`) after a + miss, so it replaces no row the session did not see; a value that is + not that sentence is left as it is. A session none of whose prompts + read the row stores nothing. What leaves the machine is the file's path in the checkout, the case count and the seconds. A path that holds a character outside letters, digits and `._/-`, is over 160 characters or is changed by the secret redaction is not sent, and neither is a file that is gone by the session's end. `loom-prompt-pack` prints the row under a bug report's pointers (**The - test cost line**, above). `LOOM_SESSION_MEMORY=off` stops the write, and - a session in code-only mode notes, stores and prints nothing. + test cost line**, above). `LOOM_SESSION_MEMORY=off` stops the note and + the write, and a session in code-only mode notes, stores and prints + nothing. At SessionEnd `loom-session-memory` removes what the session + noted and the row it read from the session's state, whatever it + stores. - LOOM_TEST_REPORT=off, or the `test_report` option set to false, stops all of it from the session's next start. - **loom-usage.** Reads the transcript's last MiB, dedupes assistant turns diff --git a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs index 980c910a7a3..5a4544fbc0d 100644 --- a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs @@ -9,6 +9,7 @@ // not its turns are sent: one memory.set of the repository's test cost row, // where the session's runs of a test file say something the row one of its // prompts read does not (lib/test-cost.mjs; LOOM_TEST_REPORT=off stops it). +// The session's cost state is removed here, whatever is handed off. // // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget // through the detached flusher so the agent never waits on the request. @@ -30,7 +31,7 @@ import { sessionToolEchoes, transcriptTurns, } from "../lib/session-memory.mjs"; -import { costPost } from "../lib/test-cost.mjs"; +import { costPost, endCost } from "../lib/test-cost.mjs"; import { sessionStart } from "../lib/test-gate.mjs"; import { testReportOn } from "../lib/test-report.mjs"; import { editedFiles } from "../lib/working-memory.mjs"; @@ -52,11 +53,12 @@ async function main() { const recalledKeys = readRecalledStash(sid); const journal = readJournal(sid); removeFile(recalledStashPath(sid)); - if (planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken()) { - const posts = [ - await handOff(payload, journal, recalledKeys), - testReportOn() ? costPost(sid, payload.cwd, () => resolveScope(payload.cwd)) : null, - ].filter(Boolean); + const stores = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken(); + // Read for a session that stores, and removed for every session. + const cost = stores && testReportOn() ? costPost(sid, payload.cwd, () => resolveScope(payload.cwd)) : null; + endCost(sid); + if (stores) { + const posts = [await handOff(payload, journal, recalledKeys), cost].filter(Boolean); // Spawn failure: nothing is lost that the next session cannot say again. if (posts.length) dispatchFlush({ posts }); } diff --git a/integrations/claude-code-plugin/hooks/loom-test-report.mjs b/integrations/claude-code-plugin/hooks/loom-test-report.mjs index 274e67a77f3..cef2dddd018 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-report.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-report.mjs @@ -21,10 +21,11 @@ // notes the refusal, so no later command and no later start of the session // gets the option. // -// Where the memory plane runs, the hook also notes what a pytest run of one -// test file cost, from the report's head, in the session's private state -// (lib/test-cost.mjs): the session's end hands the cost of a slow whole run -// to memory, and a later session's prompt carries it. +// Where the memory plane runs and session memory is not switched off, the +// hook also notes what a pytest run of one test file cost, from the report's +// head, in the session's private state (lib/test-cost.mjs): the session's end +// hands the cost of a slow whole run to memory, and a later session's prompt +// carries it. // // No request, a bounded read of one private file, and silence on every // error. It reads the session's own record of its test runs and sends @@ -34,6 +35,7 @@ import { commandText, + envSwitch, gitToplevel, planeEnabled, readStdinJson, @@ -56,8 +58,8 @@ import { } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); -// What a run cost is memory's: noted only where that plane runs. -const COST = planeEnabled("memory"); +// What a run cost is memory's: noted only where the session's end may store it. +const COST = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true); // True of a command the option did not reach too (one run in the sandbox). const REFUSED = "Loom: this command's pytest does not accept the report option Loom added (`--junitxml`), and a run that got it ended with `unrecognized arguments`. The option is removed for the rest of this session: run the command again if it ended that way."; diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index bba7998c991..f19db3a4a07 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -7,19 +7,21 @@ // (lib/test-report.mjs): its first testsuite holds the case count and the // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private -// state: for each file, the costliest whole run that passed and its latest -// runs filtered with -k. A run that outlives its shell call writes the file -// after that call's hook ran: a report read later is its when pytest began -// the run that wrote it before that call returned, and the launcher reads the -// file once more before it removes it at the session's end (`settleRun`). The -// file is one a session: a pytest run that ends before a hook read it -// replaces it, and the run that outlived its call is then not counted. +// state, for a session whose end may store them: for each file, the costliest +// whole run that passed and its latest runs filtered with -k. A run that +// outlives its shell call writes the file after that call's hook ran: a +// report read later is its when pytest began the run that wrote it before +// that call returned, and the launcher reads the file once more before it +// removes it at the session's end (`settleRun`). The file is one a session: a +// pytest run that ends before a hook read it replaces it, and the run that +// outlived its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers // (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the // row to the flusher (`costPost`), where the session's runs say something -// the row it read does not (`revised`). +// the row it read does not (`revised`), and removes the session's cost state +// whatever it stores (`endCost`). // // What leaves the machine is the file's path in the checkout, a case count // and seconds, under the repository's id. A path that holds a character @@ -239,10 +241,10 @@ const identity = (scope, agent) => ({ * folder moved to another checkout reads that one's row. `scopeOf()` is * asked only for that read, before it is sent: where the process has not * resolved the checkout's scope yet, its git calls run then, in the caller's - * thread. An answer that does not come and an error give - * no line, and a later prompt asks again. A row gives none whose value is - * not `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose - * file the checkout does not hold. + * thread. An answer that does not come and an error give no line, and a + * later prompt asks again. A row gives none whose value is not `claim`'s + * text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose file the + * checkout does not hold. */ export async function costLine(sessionId, root, scopeOf, options) { try { @@ -328,20 +330,19 @@ function measured(state, root) { } /** - * The flusher's post that stores what the session measured, or null; the - * session's cost state is removed either way. Only a session whose prompt - * read the row in the checkout of `cwd` stores, a miss included: it knows - * what it replaces, and where no prompt can read the row no session writes - * one. One `memory.set` of the repository's key follows where `revised` has - * a claim: a revision of the row as read (`if_match_sha256`, under the row's - * agent), else a first row (`absent`). The value names no file to the server - * (`files: []`), and its class says a tool measured it. + * The flusher's post that stores what the session measured, or null. Only a + * session whose prompt read the row in the checkout of `cwd` stores, a miss + * included: it knows what it replaces, and where no prompt can read the row + * no session writes one. One `memory.set` of the repository's key follows + * where `revised` has a claim: a revision of the row as read + * (`if_match_sha256`, under the row's agent), else a first row (`absent`). + * The value names no file to the server (`files: []`), and its class says a + * tool measured it. */ export function costPost(sessionId, cwd, scopeOf) { try { const state = readSessionState(RUNS, sessionId); const held = readSessionState(ROW, sessionId); - for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); const root = held.read && state.files ? gitToplevel(cwd) : ""; const runs = root && held.root === root ? measured(state, root) : {}; if (!Object.keys(runs).length) return null; @@ -362,3 +363,9 @@ export function costPost(sessionId, cwd, scopeOf) { return null; } } + +/** Remove the session's cost state. It goes with the session, as its report + * does, whatever the session stores: a resumed session reads the row again. */ +export function endCost(sessionId) { + for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); +} diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 56a7636badf..e461e922dff 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1394,7 +1394,11 @@ const counted = (line, kinds) => * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings file, * or written after `2>&1`, where the words end). Nor is a run pytest ended * before its last case, which the line above its last one says (`CUT_SHORT`): - * its last line and its result file count the cases it got to. + * its last line and its result file count the cases it got to. Nor is a run + * that anything follows in the command but `tail`, `head`, `grep` and `echo` + * (`onlyRuns`), a redirect to a file aside: a runner started after it + * (`&& make test`, `; tox`) writes the session's result file and prints the + * last line. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1415,6 +1419,9 @@ export function fileRun(command, output = "") { const runs = [...text.matchAll(PYTEST)]; const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; if (runs.length !== 1 || !ranHere(head)) return null; + // Only what reads the run's output may follow it. A redirect to a file is + // the run's own, and is left out of that reading. + if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "))) return null; const cd = [...head.matchAll(CD)]; const followed = cd.length < 2 && diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index 4cb7c63612c..bf6b17197f6 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -294,10 +294,9 @@ function scan(xml) { * first testsuite's case count, its seconds to the nearest one and as * written (`time`), how many cases failed or ended in an error, how many * were skipped (pytest counts them as cases, and an expected failure among - * the skipped), and the file of its first - * testcase, which pytest names in the family the option sets ("" where the - * head holds none). null for a head with no whole testsuite tag, no case or - * no time. */ + * the skipped), and the file of its first testcase, which pytest names in + * the family the option sets ("" where the head holds none). null for a head + * with no whole testsuite tag, no case or no time. */ export function runCost(head) { const first = (text, name) => { try { diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 6a489749775..fa798397286 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -115,6 +115,8 @@ test("a command's one pytest run of one test file is whole or filtered with -k", `timeout 600 pytest ${FILE} -p no:cacheprovider`, // A short flag written with its value takes none after it. `pytest -rf -n4 ${FILE}`, + // What reads the run's output may follow it. + `make build && pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt; echo exit=$?`, ]) { assert.deepEqual(fileRun(command), whole, command); } @@ -196,6 +198,12 @@ test("a command with two pytest runs, two paths, another selection or no run of `pushd pkg && pytest ${FILE}`, `(cd pkg && make build); pytest ${FILE}`, `cd "$PKG" && pytest ${FILE}`, + // A runner started after the run writes the result file and prints the last line. + `pytest ${FILE} -q && make test`, + `pytest ${FILE} -q 2>&1 | tail -3; tox`, + `pytest ${FILE} > /tmp/out.txt; ./run_tests.sh`, + `pytest ${FILE} -q >/dev/null;make test`, + `pytest ${FILE} -q | tee "$(make test)"`, // Run elsewhere, or not run. `docker exec app pytest ${FILE}`, `echo "pytest ${FILE}"`, @@ -888,17 +896,17 @@ test("a later run's report is not stored as the whole run that was pending", { s test("the launcher at an agent's SessionEnd reads the pending run's report and exchanges no token", { skip: WINDOWS, }, async (t) => { - const probe = { report: "" }; - const server = await loom(t, { mark: () => ({ report: fs.existsSync(probe.report) }) }); + const probe = { report: "", runs: "" }; + const mark = () => ({ report: fs.existsSync(probe.report), runs: readJsonFile(probe.runs, null) }); + const server = await loom(t, { mark }); const box = sandbox(t, server); - probe.report = box.report; + Object.assign(probe, { report: box.report, runs: box.runs }); await afterCommand(box, `python -m pytest ${FILE} -q`, STARTED); await settled(box); fs.writeFileSync(box.report, WHOLE); // An agent whose token is due: the exchange is a child process the caller waits for. await endSession(box, { LOOM_API_KEY: "", LOOM_CLIENT_ID: "ci", LOOM_WORKLOAD_TOKEN: "workload-proof" }); await settled(box); - assert.deepEqual(readJsonFile(box.runs, null), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); // The launcher removes the report before it starts the copy: an exchange that // found the report there was the launcher's own. const exchanges = server.sent("/oauth/token"); @@ -907,6 +915,10 @@ test("the launcher at an agent's SessionEnd reads the pending run's report and e exchanges.map((r) => r.report), exchanges.map(() => false), ); + // The copy's first exchange found the run the launcher had read from the report, + // and the state went with the session, which had no token to store with. + assert.deepEqual(exchanges[0].runs, { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); + assert.equal(fs.existsSync(box.runs), false); }); test("nothing is stored for a whole run under 60 s, a command of two runs or two paths, or with session memory off", { @@ -921,8 +933,8 @@ test("nothing is stored for a whole run under 60 s, a command of two runs or two [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}, null], [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}, null], [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}, null], - // The session hands nothing to memory. - [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }, whole(140)], + // The session hands nothing to memory: nothing is noted for it. + [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }, null], ]; for (const [at, [command, output, xml, extra, seen]] of cases.entries()) { const box = sandbox(t, server); @@ -931,8 +943,11 @@ test("nothing is stored for a whole run under 60 s, a command of two runs or two assert.equal(server.sent("memory.get").length, at + 1, command); await afterCommand(box, command, output, xml, extra); assert.deepEqual(readJsonFile(box.runs, null), seen && { files: { [box.file]: seen } }, command); + assert.equal(readJsonFile(box.row, {}).row, null, command); await endSession(box, extra); await settled(box); + // The session's cost state goes with the session, whatever it stores. + assert.deepEqual([box.runs, box.row].filter(fs.existsSync), [], command); } assert.deepEqual(server.sent("memory.set"), []); }); @@ -964,7 +979,7 @@ test("a slow whole run of a file whose path is not sent stores nothing", { skip: assert.deepEqual(server.sent("memory.set"), []); }); -test("a session's end with the test report switched off reads no report and stores nothing", { +test("a session's end with the test report switched off stores nothing and removes the session's cost state", { skip: WINDOWS, }, async (t) => { const server = await loom(t); @@ -982,9 +997,9 @@ test("a session's end with the test report switched off reads no report and stor }); await endSession(box, { LOOM_TEST_REPORT: "off" }); await settled(box); - // The launcher did not read the pending run's report, and nothing was handed to memory. - assert.deepEqual(noted(box.runs), held); + // Nothing was handed to memory, and the state went with the session. assert.deepEqual(server.sent("memory.set"), []); + assert.deepEqual([box.runs, box.row].filter(fs.existsSync), []); }); test("a pytest run that ends before a hook read the pending run's report replaces it", { @@ -1066,6 +1081,7 @@ test("code-only mode notes nothing, stores nothing and prints no line", { skip: await settled(box); assert.equal(server.sent("memory.get").length, 1); assert.deepEqual(server.sent("memory.set"), []); + assert.deepEqual([box.runs, box.row].filter(fs.existsSync), []); }); test("a bug report carries the repository's cost line under its pointers, from one read a session", { diff --git a/integrations/codex-plugin/hooks/loom-session-memory.mjs b/integrations/codex-plugin/hooks/loom-session-memory.mjs index 980c910a7a3..5a4544fbc0d 100644 --- a/integrations/codex-plugin/hooks/loom-session-memory.mjs +++ b/integrations/codex-plugin/hooks/loom-session-memory.mjs @@ -9,6 +9,7 @@ // not its turns are sent: one memory.set of the repository's test cost row, // where the session's runs of a test file say something the row one of its // prompts read does not (lib/test-cost.mjs; LOOM_TEST_REPORT=off stops it). +// The session's cost state is removed here, whatever is handed off. // // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget // through the detached flusher so the agent never waits on the request. @@ -30,7 +31,7 @@ import { sessionToolEchoes, transcriptTurns, } from "../lib/session-memory.mjs"; -import { costPost } from "../lib/test-cost.mjs"; +import { costPost, endCost } from "../lib/test-cost.mjs"; import { sessionStart } from "../lib/test-gate.mjs"; import { testReportOn } from "../lib/test-report.mjs"; import { editedFiles } from "../lib/working-memory.mjs"; @@ -52,11 +53,12 @@ async function main() { const recalledKeys = readRecalledStash(sid); const journal = readJournal(sid); removeFile(recalledStashPath(sid)); - if (planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken()) { - const posts = [ - await handOff(payload, journal, recalledKeys), - testReportOn() ? costPost(sid, payload.cwd, () => resolveScope(payload.cwd)) : null, - ].filter(Boolean); + const stores = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken(); + // Read for a session that stores, and removed for every session. + const cost = stores && testReportOn() ? costPost(sid, payload.cwd, () => resolveScope(payload.cwd)) : null; + endCost(sid); + if (stores) { + const posts = [await handOff(payload, journal, recalledKeys), cost].filter(Boolean); // Spawn failure: nothing is lost that the next session cannot say again. if (posts.length) dispatchFlush({ posts }); } diff --git a/integrations/codex-plugin/hooks/loom-test-report.mjs b/integrations/codex-plugin/hooks/loom-test-report.mjs index 274e67a77f3..cef2dddd018 100644 --- a/integrations/codex-plugin/hooks/loom-test-report.mjs +++ b/integrations/codex-plugin/hooks/loom-test-report.mjs @@ -21,10 +21,11 @@ // notes the refusal, so no later command and no later start of the session // gets the option. // -// Where the memory plane runs, the hook also notes what a pytest run of one -// test file cost, from the report's head, in the session's private state -// (lib/test-cost.mjs): the session's end hands the cost of a slow whole run -// to memory, and a later session's prompt carries it. +// Where the memory plane runs and session memory is not switched off, the +// hook also notes what a pytest run of one test file cost, from the report's +// head, in the session's private state (lib/test-cost.mjs): the session's end +// hands the cost of a slow whole run to memory, and a later session's prompt +// carries it. // // No request, a bounded read of one private file, and silence on every // error. It reads the session's own record of its test runs and sends @@ -34,6 +35,7 @@ import { commandText, + envSwitch, gitToplevel, planeEnabled, readStdinJson, @@ -56,8 +58,8 @@ import { } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); -// What a run cost is memory's: noted only where that plane runs. -const COST = planeEnabled("memory"); +// What a run cost is memory's: noted only where the session's end may store it. +const COST = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true); // True of a command the option did not reach too (one run in the sandbox). const REFUSED = "Loom: this command's pytest does not accept the report option Loom added (`--junitxml`), and a run that got it ended with `unrecognized arguments`. The option is removed for the rest of this session: run the command again if it ended that way."; diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index bba7998c991..f19db3a4a07 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -7,19 +7,21 @@ // (lib/test-report.mjs): its first testsuite holds the case count and the // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private -// state: for each file, the costliest whole run that passed and its latest -// runs filtered with -k. A run that outlives its shell call writes the file -// after that call's hook ran: a report read later is its when pytest began -// the run that wrote it before that call returned, and the launcher reads the -// file once more before it removes it at the session's end (`settleRun`). The -// file is one a session: a pytest run that ends before a hook read it -// replaces it, and the run that outlived its call is then not counted. +// state, for a session whose end may store them: for each file, the costliest +// whole run that passed and its latest runs filtered with -k. A run that +// outlives its shell call writes the file after that call's hook ran: a +// report read later is its when pytest began the run that wrote it before +// that call returned, and the launcher reads the file once more before it +// removes it at the session's end (`settleRun`). The file is one a session: a +// pytest run that ends before a hook read it replaces it, and the run that +// outlived its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers // (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the // row to the flusher (`costPost`), where the session's runs say something -// the row it read does not (`revised`). +// the row it read does not (`revised`), and removes the session's cost state +// whatever it stores (`endCost`). // // What leaves the machine is the file's path in the checkout, a case count // and seconds, under the repository's id. A path that holds a character @@ -239,10 +241,10 @@ const identity = (scope, agent) => ({ * folder moved to another checkout reads that one's row. `scopeOf()` is * asked only for that read, before it is sent: where the process has not * resolved the checkout's scope yet, its git calls run then, in the caller's - * thread. An answer that does not come and an error give - * no line, and a later prompt asks again. A row gives none whose value is - * not `claim`'s text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose - * file the checkout does not hold. + * thread. An answer that does not come and an error give no line, and a + * later prompt asks again. A row gives none whose value is not `claim`'s + * text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose file the + * checkout does not hold. */ export async function costLine(sessionId, root, scopeOf, options) { try { @@ -328,20 +330,19 @@ function measured(state, root) { } /** - * The flusher's post that stores what the session measured, or null; the - * session's cost state is removed either way. Only a session whose prompt - * read the row in the checkout of `cwd` stores, a miss included: it knows - * what it replaces, and where no prompt can read the row no session writes - * one. One `memory.set` of the repository's key follows where `revised` has - * a claim: a revision of the row as read (`if_match_sha256`, under the row's - * agent), else a first row (`absent`). The value names no file to the server - * (`files: []`), and its class says a tool measured it. + * The flusher's post that stores what the session measured, or null. Only a + * session whose prompt read the row in the checkout of `cwd` stores, a miss + * included: it knows what it replaces, and where no prompt can read the row + * no session writes one. One `memory.set` of the repository's key follows + * where `revised` has a claim: a revision of the row as read + * (`if_match_sha256`, under the row's agent), else a first row (`absent`). + * The value names no file to the server (`files: []`), and its class says a + * tool measured it. */ export function costPost(sessionId, cwd, scopeOf) { try { const state = readSessionState(RUNS, sessionId); const held = readSessionState(ROW, sessionId); - for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); const root = held.read && state.files ? gitToplevel(cwd) : ""; const runs = root && held.root === root ? measured(state, root) : {}; if (!Object.keys(runs).length) return null; @@ -362,3 +363,9 @@ export function costPost(sessionId, cwd, scopeOf) { return null; } } + +/** Remove the session's cost state. It goes with the session, as its report + * does, whatever the session stores: a resumed session reads the row again. */ +export function endCost(sessionId) { + for (const kind of [RUNS, ROW]) removeFile(sessionStatePath(kind, sessionId)); +} diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 56a7636badf..e461e922dff 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1394,7 +1394,11 @@ const counted = (line, kinds) => * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings file, * or written after `2>&1`, where the words end). Nor is a run pytest ended * before its last case, which the line above its last one says (`CUT_SHORT`): - * its last line and its result file count the cases it got to. + * its last line and its result file count the cases it got to. Nor is a run + * that anything follows in the command but `tail`, `head`, `grep` and `echo` + * (`onlyRuns`), a redirect to a file aside: a runner started after it + * (`&& make test`, `; tox`) writes the session's result file and prints the + * last line. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1415,6 +1419,9 @@ export function fileRun(command, output = "") { const runs = [...text.matchAll(PYTEST)]; const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; if (runs.length !== 1 || !ranHere(head)) return null; + // Only what reads the run's output may follow it. A redirect to a file is + // the run's own, and is left out of that reading. + if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "))) return null; const cd = [...head.matchAll(CD)]; const followed = cd.length < 2 && diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index 4cb7c63612c..bf6b17197f6 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -294,10 +294,9 @@ function scan(xml) { * first testsuite's case count, its seconds to the nearest one and as * written (`time`), how many cases failed or ended in an error, how many * were skipped (pytest counts them as cases, and an expected failure among - * the skipped), and the file of its first - * testcase, which pytest names in the family the option sets ("" where the - * head holds none). null for a head with no whole testsuite tag, no case or - * no time. */ + * the skipped), and the file of its first testcase, which pytest names in + * the family the option sets ("" where the head holds none). null for a head + * with no whole testsuite tag, no case or no time. */ export function runCost(head) { const first = (text, name) => { try { diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 718b2d8a878..8c20e3fbb4b 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "444fcf1ec3d13a041363c52b6a4ff9241571925cde72be8a23da8a774ef83a82", + "integrations/claude-code-plugin/lib/test-cost.mjs": "339caa74ea60aa7a6470674113f36ea90b277bc929feb3519a47b875a57748e2", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "444fcf1ec3d13a041363c52b6a4ff9241571925cde72be8a23da8a774ef83a82", + "integrations/codex-plugin/lib/test-cost.mjs": "339caa74ea60aa7a6470674113f36ea90b277bc929feb3519a47b875a57748e2", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From b8fcc98ef1966bebe386e851c31c87a6caaea670 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 23:07:26 +0530 Subject: [PATCH 10/24] A test run that ended in its call with its summary cut is not kept as an open run A pytest run of one file whose output shows no summary was kept as the session's pending run, also when it had ended in its call and the command cut the summary (`| head -30`, `| grep FAILED`). The next run that outlived its call was then dropped with it when it was of another file or of the file's other kind, so a slow whole run that was the session's last pytest run was not counted. Such a run is no longer kept where the report read with its command is of its file and no pending run's: the run wrote it in its call. An open run takes the place of a pending run of another file, and a report of another file leaves the pending run as it is. An open run of the other kind of the pending run's file still drops both. The docs name what is left: a run that ended in its call with no summary and no report is pending like an open one, and a run that went to the background after an earlier run of its file left the report unread is not counted. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 30 ++++++-- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 31 +++++--- .../claude-code-plugin/lib/test-cost.mjs | 74 ++++++++++++------- .../tests/test-cost.test.mjs | 43 +++++++++++ integrations/codex-plugin/lib/test-cost.mjs | 74 ++++++++++++------- tests/unit/session_content_senders.json | 4 +- 7 files changed, 182 insertions(+), 76 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 0a62a2bfeb9..5b94f508ebc 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1732,11 +1732,18 @@ file an earlier run left. A run that outlives its shell call writes the file after the hook ran: it is read after the next shell command that names a test runner, or when the session ends. That file is -the run's when pytest began the run that wrote it before the run's own command returned -(the time the file was written, less the seconds it holds): a run that any later command -started began after that, and its file counts for no run. The session has one result -file, so the next pytest run that ends replaces it: where that run ends before a hook -has read the file, the run that outlived its call is not counted. +the run's when its first case is in the run's test file and pytest began the run that +wrote it before the run's own command returned (the time the file was written, less the +seconds it holds): a run that any later command started began after that, and its file +counts for no run. The session has one result file, so the next pytest run that ends +replaces it: where that run ends before a hook has read the file, the run that outlived +its call is not counted. + +A run whose output shows no summary line is taken for one that outlives its call, and +the session keeps one such run. A run that ended in its call and whose command cut the +summary (`| head -30`, `| grep FAILED`) is not kept: the hook reads the result file it +wrote with the command, and that file counts for no run. A later run that outlives its +call takes the place of a kept run of another test file. **What is stored.** When the session ends, what it measured goes to the repository's one memory row, in the hand-off that carries the session's turns (`memory.set`, key @@ -1797,8 +1804,17 @@ What it does not do: and every session in `memory` mode, with the prompt pointers off or in a repository this Loom does not index; - a run that outlives its shell call is noted when it began before that call returned: a - run put in the background at once, before pytest began, is not, and neither is one - that was open together with a run of another kind of the same file; + run put in the background at once, before pytest began, is not; +- the session keeps one run that outlives its call. A later one of another test file + takes its place, and the earlier run is not counted. A later one of the same file and + the other kind, whole after `-k` or `-k` after whole, drops both, since the earlier + run's result file would be counted as the later run's. A run that ended in its call + with no summary line and no result file, such as one whose pytest refused an option of + the command, is kept as if it were open, and drops a later run in the same way; +- a run whose output shows no summary line is taken to have ended in its call when the + hook reads a result file of its test file with it. Where an earlier run of that file + left the result file unread and the run itself went to the background, the run is not + counted; - a run that outlives its shell call is not counted when the session's next pytest run ends before a hook has read the result file: that run writes the same file over it. So a whole run that went to the background is counted where it is the session's last diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index a2e184da9a3..68f97f29bc8 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 1377628c803..f471c5dd703 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1459,19 +1459,30 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that whose output shows no such line may not have ended: one that outlives its shell call writes the file after the hook ran. It is kept as the session's pending run, with the time its command returned. Any other - report the hook reads is the pending run's when the run that wrote it - began by that time, and no run's otherwise: pytest began it at the time - the file was written less the seconds of its `testsuite`, and a run that - a later command started, by any launcher and whether or not a hook ran - for that command, began after it. A run of the file that something else - started while the pending run was in its call, such as a script in the + report the hook reads is the pending run's when its first case is in + the pending run's file and the run that wrote it began by that time, + and no run's otherwise: pytest began it at the time the file was + written less the seconds of its `testsuite`, and a run that a later + command started, by any launcher and whether or not a hook ran for that + command, began after it. A run of the file that something else started + while the pending run was in its call, such as a script in the background, began before that time too: its report, read with a command that is not that run, is counted as the pending run's. The launcher reads the report once more at SessionEnd, before it removes the file, - without reading a token. A run of another kind left open while one is - pending drops both, since one would be counted as the other. A run put - in the background at once returns before pytest began, and is not - counted. + without reading a token. A run put in the background at once returns + before pytest began, and is not counted. + A run with no last line in sight is not kept where the report read + with its command is of its file and no pending run's: the run wrote it + in its call, and the command cut the line (`| head -30`, + `| grep FAILED`). That report is counted for no run. Where an earlier + run of the file left the report unread and the run itself outlived its + call, the run is not counted. A run that is kept takes the place of a + pending run of another file, whose report is then no run's. One of the + other kind of the pending run's file, whole after `-k` or `-k` after + whole, drops both, since the pending run's report would be counted as + the later run's. A run that ended in its call with no last line and no + report, such as one whose pytest refused an option of the command, is + pending like an open one, and drops a later run in the same way. The session has one result file, and no hook runs between two commands: where the session's next pytest run ends before a hook has read the file, that run's report replaces the pending run's, which is diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index f19db3a4a07..eeddb94c2d9 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -77,16 +77,21 @@ function located(run, cwd) { return { ...run, file: path.resolve(from, run.path) }; } +/** Whether the report of `cost` (`runCost`) is one a run of `run`'s file + * wrote: its first case is in that file. pytest names the file from its + * root, a folder at or above the file's. */ +const ofFile = (run, cost) => Boolean(cost.file) && run.file.split(path.sep).join("/").endsWith(`/${cost.file}`); + /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another - * run's (pytest names the file from its root, a folder at or above the - * file's). A run counts when no more than `MAX_SKIPPED_SHARE` of its cases - * were skipped, and a whole run when no case failed either: one that ran - * where its cases skip, or stopped at a failure, took less. The file is put - * last, and the bound drops the one least recently run that is not the one - * with the costliest whole run: that run is what the session's end stores. */ + * run's (`ofFile`). A run counts when no more than `MAX_SKIPPED_SHARE` of + * its cases were skipped, and a whole run when no case failed either: one + * that ran where its cases skip, or stopped at a failure, took less. The + * file is put last, and the bound drops the one least recently run that is + * not the one with the costliest whole run: that run is what the session's + * end stores. */ function add(state, run, cost) { - if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; + if (!ofFile(run, cost)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; const ran = cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; const whole = run.whole && ran && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); @@ -107,19 +112,23 @@ function add(state, run, cost) { state.files = Object.fromEntries(held.filter((entry) => entry !== dropped)); } -/** Count `report` (`newReport`) for the session's pending run when the run - * that wrote it began before the pending run's command returned: pytest - * began it at the time the file was written less the suite's seconds. A - * command that came later, whatever it is and whether or not a hook saw it, - * began its run after that. A run of the file that something else started - * while the pending run was in its call began before it too: its report, - * read with a command that is not that run, is taken for the pending run's. - * The pending run is then settled. */ +/** Count `report` (`newReport`) for the session's pending run, and say + * whether it was that run's: its first case is in the run's file (`ofFile`) + * and the run that wrote it began before the pending run's command + * returned. pytest began it at the time the file was written less the + * suite's seconds. A command that came later, whatever it is and whether or + * not a hook saw it, began its run after that. A run of the file that + * something else started while the pending run was in its call began before + * it too: its report, read with a command that is not that run, is taken + * for the pending run's. The pending run is then settled; any other report + * leaves it pending. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; - if (!cost || !state.pending || report.mtimeMs - cost.time * 1000 > state.pending.at) return; - add(state, state.pending, cost); + const pending = state.pending; + if (!cost || !pending || !ofFile(pending, cost) || report.mtimeMs - cost.time * 1000 > pending.at) return false; + add(state, pending, cost); state.pending = undefined; + return true; } /** @@ -131,13 +140,21 @@ function settle(state, report) { * file (`fileRun`) and its output shows pytest's summary with the cases, the * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The - * seconds alone do not tell two short runs apart. A run whose output shows - * no summary may not have ended: it is kept as the session's pending run, - * with the time its command returned. Any other report is the pending run's - * when its run began by that time (`settle`), and no run's otherwise. So a - * run that was put in the background before pytest began is not counted. An - * open run of another kind than the pending one drops both: one of the two - * would be counted as the other. + * seconds alone do not tell two short runs apart. Any other report is the + * pending run's when it is of that run's file and its run began by the time + * the run's command returned (`settle`), and no run's otherwise. So a run + * that was put in the background before pytest began is not counted. + * + * A run whose output shows no summary may not have ended: it is kept as the + * session's pending run, with the time its command returned. It is taken + * to have ended where the report read with it is of its file and no pending + * run's: the run wrote it in its call, so a command that cut the summary + * (`| head -30`, `| grep FAILED`) leaves nothing pending. That report is + * counted for no run, and where an earlier run of the file left it unread + * the run may still be open, and is then not counted. An open run takes the + * place of a pending run of another file, whose report is then no run's. An + * open run of the other kind of the pending run's file drops both: the + * pending run's report would be counted as the later run's. */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { @@ -156,11 +173,12 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); // The summary counts the skipped cases apart from the expected failures. if (own) add(state, run, { ...cost, skipped: run.skipped }); - else settle(state, report); - if (open) { + const settled = !own && settle(state, report); + // A report of the run's file that no pending run took: the run ended in its call. + if (open && (!cost || settled || !ofFile(run, cost))) { const pending = state.pending; - const free = !pending || (pending.file === run.file && pending.whole === run.whole); - state.pending = free ? { file: run.file, whole: run.whole, at: Date.now() } : undefined; + const other = pending && pending.file === run.file && pending.whole !== run.whole; + state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } writeSessionState(RUNS, sessionId, state); } catch { diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index fa798397286..73b3217faf3 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -636,6 +636,49 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS }); }); +test("a run that ended in its call with its summary cut is not pending, and the next open run is counted", { + skip: WINDOWS, +}, (t) => { + inTmp(t, (cwd, file) => { + const SMALL = "tests/test_small.py"; + const small = path.join(cwd, SMALL); + fs.writeFileSync(small, ""); + const note = (command, output, xml, after) => + noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); + const whole = { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }; + // A run of another file ended in its call, and the command cut its summary: + // the report read with it is its own, so nothing is pending. + note(`pytest ${SMALL} -q 2>&1 | head -30`, "....", report({ tests: 40, time: "1.2", file: SMALL })); + assert.deepEqual(runs(), {}); + // The whole run that outlives its call is the session's pending run, and its report is counted. + note(`pytest ${FILE} -q`, STARTED, null); + assert.deepEqual(runs(), { pending: { file, whole: true } }); + note("pgrep -f pytest", "", WHOLE); + assert.deepEqual(runs(), whole); + // The same with a selection of the file itself. + note(`pytest ${FILE} -k parse 2>&1 | grep FAILED`, "", FILTERED); + assert.deepEqual(runs(), whole); + note(`pytest ${FILE} -q`, STARTED, null); + assert.deepEqual(runs(), { ...whole, pending: { file, whole: true } }); + // A cut run of the file's other kind, begun after that command returned, + // ended in its call too: the open run stays. + note(`pytest ${FILE} -k parse 2>&1 | grep FAILED`, "", FILTERED, 3000); + assert.deepEqual(runs(), { ...whole, pending: { file, whole: true } }); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + + // A run of another file that wrote no report stays pending: the next open + // run takes its place, and a report of the other file leaves it pending. + note(`pytest ${SMALL} -q`, STARTED, null); + assert.deepEqual(runs(), { pending: { file: small, whole: true } }); + note(`pytest ${FILE} -q`, STARTED, null); + assert.deepEqual(runs(), { pending: { file, whole: true } }); + note("pgrep -f pytest", "", report({ tests: 40, time: "150.0", file: SMALL })); + assert.deepEqual(runs(), { pending: { file, whole: true } }); + note("pgrep -f pytest", "", WHOLE); + assert.deepEqual(runs(), whole); + }); +}); + // --- the hooks, started as the host starts them ---------------------------------- const SEARCH = { diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index f19db3a4a07..eeddb94c2d9 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -77,16 +77,21 @@ function located(run, cwd) { return { ...run, file: path.resolve(from, run.path) }; } +/** Whether the report of `cost` (`runCost`) is one a run of `run`'s file + * wrote: its first case is in that file. pytest names the file from its + * root, a folder at or above the file's. */ +const ofFile = (run, cost) => Boolean(cost.file) && run.file.split(path.sep).join("/").endsWith(`/${cost.file}`); + /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another - * run's (pytest names the file from its root, a folder at or above the - * file's). A run counts when no more than `MAX_SKIPPED_SHARE` of its cases - * were skipped, and a whole run when no case failed either: one that ran - * where its cases skip, or stopped at a failure, took less. The file is put - * last, and the bound drops the one least recently run that is not the one - * with the costliest whole run: that run is what the session's end stores. */ + * run's (`ofFile`). A run counts when no more than `MAX_SKIPPED_SHARE` of + * its cases were skipped, and a whole run when no case failed either: one + * that ran where its cases skip, or stopped at a failure, took less. The + * file is put last, and the bound drops the one least recently run that is + * not the one with the costliest whole run: that run is what the session's + * end stores. */ function add(state, run, cost) { - if (!cost.file || !run.file.split(path.sep).join("/").endsWith(`/${cost.file}`)) return; + if (!ofFile(run, cost)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; const ran = cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; const whole = run.whole && ran && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); @@ -107,19 +112,23 @@ function add(state, run, cost) { state.files = Object.fromEntries(held.filter((entry) => entry !== dropped)); } -/** Count `report` (`newReport`) for the session's pending run when the run - * that wrote it began before the pending run's command returned: pytest - * began it at the time the file was written less the suite's seconds. A - * command that came later, whatever it is and whether or not a hook saw it, - * began its run after that. A run of the file that something else started - * while the pending run was in its call began before it too: its report, - * read with a command that is not that run, is taken for the pending run's. - * The pending run is then settled. */ +/** Count `report` (`newReport`) for the session's pending run, and say + * whether it was that run's: its first case is in the run's file (`ofFile`) + * and the run that wrote it began before the pending run's command + * returned. pytest began it at the time the file was written less the + * suite's seconds. A command that came later, whatever it is and whether or + * not a hook saw it, began its run after that. A run of the file that + * something else started while the pending run was in its call began before + * it too: its report, read with a command that is not that run, is taken + * for the pending run's. The pending run is then settled; any other report + * leaves it pending. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; - if (!cost || !state.pending || report.mtimeMs - cost.time * 1000 > state.pending.at) return; - add(state, state.pending, cost); + const pending = state.pending; + if (!cost || !pending || !ofFile(pending, cost) || report.mtimeMs - cost.time * 1000 > pending.at) return false; + add(state, pending, cost); state.pending = undefined; + return true; } /** @@ -131,13 +140,21 @@ function settle(state, report) { * file (`fileRun`) and its output shows pytest's summary with the cases, the * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The - * seconds alone do not tell two short runs apart. A run whose output shows - * no summary may not have ended: it is kept as the session's pending run, - * with the time its command returned. Any other report is the pending run's - * when its run began by that time (`settle`), and no run's otherwise. So a - * run that was put in the background before pytest began is not counted. An - * open run of another kind than the pending one drops both: one of the two - * would be counted as the other. + * seconds alone do not tell two short runs apart. Any other report is the + * pending run's when it is of that run's file and its run began by the time + * the run's command returned (`settle`), and no run's otherwise. So a run + * that was put in the background before pytest began is not counted. + * + * A run whose output shows no summary may not have ended: it is kept as the + * session's pending run, with the time its command returned. It is taken + * to have ended where the report read with it is of its file and no pending + * run's: the run wrote it in its call, so a command that cut the summary + * (`| head -30`, `| grep FAILED`) leaves nothing pending. That report is + * counted for no run, and where an earlier run of the file left it unread + * the run may still be open, and is then not counted. An open run takes the + * place of a pending run of another file, whose report is then no run's. An + * open run of the other kind of the pending run's file drops both: the + * pending run's report would be counted as the later run's. */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { @@ -156,11 +173,12 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); // The summary counts the skipped cases apart from the expected failures. if (own) add(state, run, { ...cost, skipped: run.skipped }); - else settle(state, report); - if (open) { + const settled = !own && settle(state, report); + // A report of the run's file that no pending run took: the run ended in its call. + if (open && (!cost || settled || !ofFile(run, cost))) { const pending = state.pending; - const free = !pending || (pending.file === run.file && pending.whole === run.whole); - state.pending = free ? { file: run.file, whole: run.whole, at: Date.now() } : undefined; + const other = pending && pending.file === run.file && pending.whole !== run.whole; + state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } writeSessionState(RUNS, sessionId, state); } catch { diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 8c20e3fbb4b..67c759cb82d 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "339caa74ea60aa7a6470674113f36ea90b277bc929feb3519a47b875a57748e2", + "integrations/claude-code-plugin/lib/test-cost.mjs": "6c933800a63cbd1a20299b990b0f8114d9c3476047a41cc07420a4460b249303", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "339caa74ea60aa7a6470674113f36ea90b277bc929feb3519a47b875a57748e2", + "integrations/codex-plugin/lib/test-cost.mjs": "6c933800a63cbd1a20299b990b0f8114d9c3476047a41cc07420a4460b249303", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 4bb10dc5feeadc15b2e6e866a9e2166312165f16 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 23:39:23 +0530 Subject: [PATCH 11/24] A coloured pytest summary is read as the plain one A pytest told to colour its output (`--color=yes` in `addopts`, `PY_COLORS=1`) writes an escape sequence before each part of its last line and around the line it prints above it for a run it ended early. The escape ends in `m`, so the word boundary before the count did not match and the run read as one that had not ended: a run that finished in its call was counted as nothing, and the line between runs of `!` was not seen. fileRun now removes the colour escapes from the output before it reads the two lines. The docs and the module comment name one more limit: the SessionStart hook runs again after a compaction and empties the session's result file, so a run that outlived its shell call and ended before the compaction with its report unread is not counted. The comment above the branch of noteCommand that keeps an open run says what the branch does. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 3 +++ integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 7 +++++-- .../claude-code-plugin/lib/test-cost.mjs | 8 +++++--- .../claude-code-plugin/lib/test-gate.mjs | 14 +++++++++---- .../tests/test-cost.test.mjs | 20 +++++++++++++++++++ integrations/codex-plugin/lib/test-cost.mjs | 8 +++++--- integrations/codex-plugin/lib/test-gate.mjs | 14 +++++++++---- tests/unit/session_content_senders.json | 4 ++-- 9 files changed, 61 insertions(+), 19 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 5b94f508ebc..4f9be0814fe 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1821,6 +1821,9 @@ What it does not do: pytest run, or where a command that names a test runner and starts no pytest, such as `pgrep -f pytest`, comes after it ended and before the next pytest run ends, and not where a `-k` run follows its end at once; +- nor is such a run counted where the context is compacted after the run ended and + before a hook has read the result file: the SessionStart hook runs again after a + compaction and empties the file; - a run that outlives its shell call has no summary line, and the result file counts an expected failure (`xfail`) as skipped: such a run of a file where more than a tenth of the cases are expected failures is not counted. Nor does the result file count the diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 68f97f29bc8..5e8075e9057 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index f471c5dd703..038b07f70f5 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1455,7 +1455,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that the option did not reach writes no report, and the one read after it is an earlier run's, which the seconds of two short runs do not tell apart. The summary is pytest's last line, whatever it counts - (`8000 deselected in 1.20s` and `no tests ran in 0.01s` too). A run + (`8000 deselected in 1.20s` and `no tests ran in 0.01s` too), read + without the colours of a pytest told to colour its output. A run whose output shows no such line may not have ended: one that outlives its shell call writes the file after the hook ran. It is kept as the session's pending run, with the time its command returned. Any other @@ -1486,7 +1487,9 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that The session has one result file, and no hook runs between two commands: where the session's next pytest run ends before a hook has read the file, that run's report replaces the pending run's, which is - then not counted. + then not counted. The SessionStart hook runs again after a compaction + and empties the file: a pending run that ended before the compaction, + with its report not yet read, is not counted either. At SessionEnd `loom-session-memory` hands one `memory.set` to the flusher, beside the session's turns or alone where they are not sent, where a prompt of the session read the row, a miss included, and its diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index eeddb94c2d9..afd610b35b8 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -13,8 +13,9 @@ // report read later is its when pytest began the run that wrote it before // that call returned, and the launcher reads the file once more before it // removes it at the session's end (`settleRun`). The file is one a session: a -// pytest run that ends before a hook read it replaces it, and the run that -// outlived its call is then not counted. +// pytest run that ends before a hook read it replaces it, and the session's +// start after a compaction empties it (`startReport`). The run that outlived +// its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -174,7 +175,8 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { // The summary counts the skipped cases apart from the expected failures. if (own) add(state, run, { ...cost, skipped: run.skipped }); const settled = !own && settle(state, report); - // A report of the run's file that no pending run took: the run ended in its call. + // An open run is kept, but for one whose report is read with it: a report + // of its file that no pending run took says the run ended in its call. if (open && (!cost || settled || !ofFile(run, cost))) { const pending = state.pending; const other = pending && pending.file === run.file && pending.whole !== run.whole; diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index e461e922dff..7e57f4fcd84 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1372,6 +1372,9 @@ const LAST_LINE = // interrupt, `pytest.exit`. The message stands between two runs of `!`, of // one each where the message is as wide as the terminal. const CUT_SHORT = /^!+ .+ !+$/; +// What a pytest told to colour its output (`--color=yes`, `PY_COLORS`) writes +// around each part of those two lines. +const COLOURS = /\x1b\[[\d;]*m/g; /** The sum of the counts `line` gives for `kinds`, an alternation of the * words of pytest's last line. */ const counted = (line, kinds) => @@ -1384,9 +1387,10 @@ const counted = (line, kinds) => * else null. `path` is the file as the command spells it and `dir` the folder * of the one `cd` before the run, "" for none. `whole` is false for a run * filtered with `-k`. `seconds` is what pytest's last line in the visible - * `output` shows (`LAST_LINE`). `cases` is the cases that line counts, all - * but the deselected: the result file's `tests`, but for a case whose - * teardown raised an error, which the line counts twice and the file once. + * `output` shows (`LAST_LINE`), read without its colours. `cases` is the + * cases that line counts, all but the deselected: the result file's `tests`, + * but for a case whose teardown raised an error, which the line counts twice + * and the file once. * `failed` is the failures and errors among them and `skipped` the skipped * ones, apart from the expected failures. All four are null where the output * holds no such line: the run did not finish inside the call. A run with no @@ -1444,7 +1448,9 @@ export function fileRun(command, output = "") { const other = (word) => !BY_NAME.test(word) && (PARTIAL.test(word) || CLUSTER.test(word) || OWN_REPORT.test(word)); if (!followed || named.length !== 1 || !/^[^\s:]+\.py$/.test(named[0]) || words.some(other)) return null; if (values.some((word) => PYTHON_FILE.test(word))) return null; - const lines = String(output || "").split(/\r?\n/); + const lines = String(output || "") + .replace(COLOURS, "") + .split(/\r?\n/); if (lines.some((line) => CUT_SHORT.test(line.trim()))) return null; const summary = lines.findLast((line) => line.length < 300 && LAST_LINE.test(line)); const whole = !words.some((word) => BY_NAME.test(word)); diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 73b3217faf3..8960e392f6a 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -46,6 +46,8 @@ const WHOLE_OUTPUT = "8000 passed in 140.21s (0:02:20)"; const FILTERED = report({ tests: 12, time: "2.3" }); const FILTERED_COMMAND = `python -m pytest ${FILE} -k "parse and not slow" -q`; const FILTERED_OUTPUT = "12 passed, 7988 deselected in 2.31s"; +// The start of a colour escape, as pytest writes one with `--color=yes`. +const SGR = "\x1b["; const BOTH = `In the repository tagged repo:${REPO}, a whole run of ${FILE} collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s.`; // --- the parts ---------------------------------------------------------------- @@ -161,6 +163,20 @@ test("a command's one pytest run of one test file is whole or filtered with -k", const run = fileRun(`pytest ${FILE} -k parse -q`, `collected 8000 items\n${line}`); assert.deepEqual([run.seconds, run.cases, run.failed, run.skipped], [seconds, cases, failed, skipped], line); } + // A pytest told to colour its output writes an escape before each part of the line. + for (const [line, seconds, cases, failed] of [ + [`${SGR}32m${SGR}32m${SGR}1m8000 passed${SGR}0m${SGR}32m in 140.21s (0:02:20)${SGR}0m${SGR}0m`, 140.21, 8000, 0], + [ + `${SGR}31m=== ${SGR}31m${SGR}1m1 failed${SGR}0m, ${SGR}32m7999 passed${SGR}0m${SGR}31m in 300.00s${SGR}0m`, + 300, + 8000, + 1, + ], + [`${SGR}33m${SGR}33mno tests ran${SGR}0m${SGR}33m in 0.01s${SGR}0m${SGR}0m`, 0.01, 0, 0], + ]) { + const run = fileRun(`pytest ${FILE} -q 2>&1 | tail -3`, line); + assert.deepEqual([run.seconds, run.cases, run.failed], [seconds, cases, failed], line); + } }); test("a command with two pytest runs, two paths, another selection or no run of its own is no file run", () => { @@ -238,7 +254,11 @@ test("a command with two pytest runs, two paths, another selection or no run of ]) { assert.equal(fileRun(command, line).seconds > 0, true, command); assert.equal(fileRun(command, `collected 8000 items\n${banner}\n${line}`), null, banner); + assert.equal(fileRun(command, `${SGR}31m${banner}${SGR}0m\n${SGR}31m${line}${SGR}0m`), null, `coloured ${banner}`); } + // A selection the words do not show, in colour. + const deselected = `${SGR}32m${SGR}1m12 passed${SGR}0m, ${SGR}33m7988 deselected${SGR}0m${SGR}32m in 2.31s${SGR}0m`; + assert.equal(fileRun(`pytest ${FILE} -q`, deselected), null); }); test("the stored claim and the prompt's line, byte for byte", () => { diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index eeddb94c2d9..afd610b35b8 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -13,8 +13,9 @@ // report read later is its when pytest began the run that wrote it before // that call returned, and the launcher reads the file once more before it // removes it at the session's end (`settleRun`). The file is one a session: a -// pytest run that ends before a hook read it replaces it, and the run that -// outlived its call is then not counted. +// pytest run that ends before a hook read it replaces it, and the session's +// start after a compaction empties it (`startReport`). The run that outlived +// its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -174,7 +175,8 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { // The summary counts the skipped cases apart from the expected failures. if (own) add(state, run, { ...cost, skipped: run.skipped }); const settled = !own && settle(state, report); - // A report of the run's file that no pending run took: the run ended in its call. + // An open run is kept, but for one whose report is read with it: a report + // of its file that no pending run took says the run ended in its call. if (open && (!cost || settled || !ofFile(run, cost))) { const pending = state.pending; const other = pending && pending.file === run.file && pending.whole !== run.whole; diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index e461e922dff..7e57f4fcd84 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1372,6 +1372,9 @@ const LAST_LINE = // interrupt, `pytest.exit`. The message stands between two runs of `!`, of // one each where the message is as wide as the terminal. const CUT_SHORT = /^!+ .+ !+$/; +// What a pytest told to colour its output (`--color=yes`, `PY_COLORS`) writes +// around each part of those two lines. +const COLOURS = /\x1b\[[\d;]*m/g; /** The sum of the counts `line` gives for `kinds`, an alternation of the * words of pytest's last line. */ const counted = (line, kinds) => @@ -1384,9 +1387,10 @@ const counted = (line, kinds) => * else null. `path` is the file as the command spells it and `dir` the folder * of the one `cd` before the run, "" for none. `whole` is false for a run * filtered with `-k`. `seconds` is what pytest's last line in the visible - * `output` shows (`LAST_LINE`). `cases` is the cases that line counts, all - * but the deselected: the result file's `tests`, but for a case whose - * teardown raised an error, which the line counts twice and the file once. + * `output` shows (`LAST_LINE`), read without its colours. `cases` is the + * cases that line counts, all but the deselected: the result file's `tests`, + * but for a case whose teardown raised an error, which the line counts twice + * and the file once. * `failed` is the failures and errors among them and `skipped` the skipped * ones, apart from the expected failures. All four are null where the output * holds no such line: the run did not finish inside the call. A run with no @@ -1444,7 +1448,9 @@ export function fileRun(command, output = "") { const other = (word) => !BY_NAME.test(word) && (PARTIAL.test(word) || CLUSTER.test(word) || OWN_REPORT.test(word)); if (!followed || named.length !== 1 || !/^[^\s:]+\.py$/.test(named[0]) || words.some(other)) return null; if (values.some((word) => PYTHON_FILE.test(word))) return null; - const lines = String(output || "").split(/\r?\n/); + const lines = String(output || "") + .replace(COLOURS, "") + .split(/\r?\n/); if (lines.some((line) => CUT_SHORT.test(line.trim()))) return null; const summary = lines.findLast((line) => line.length < 300 && LAST_LINE.test(line)); const whole = !words.some((word) => BY_NAME.test(word)); diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 67c759cb82d..fe1e9e00ee5 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "6c933800a63cbd1a20299b990b0f8114d9c3476047a41cc07420a4460b249303", + "integrations/claude-code-plugin/lib/test-cost.mjs": "5f1b3f4aa42ffff9d3465b9488d239bdd32faba0718232c07d3660136105a7f7", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "6c933800a63cbd1a20299b990b0f8114d9c3476047a41cc07420a4460b249303", + "integrations/codex-plugin/lib/test-cost.mjs": "5f1b3f4aa42ffff9d3465b9488d239bdd32faba0718232c07d3660136105a7f7", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From cb88cf3bd528c9beba5bf678bbacd9efc68ff6b6 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 00:13:12 +0530 Subject: [PATCH 12/24] The test-cost rule says that quotes are not read and what the state holds A run piped into grep -E "passed|failed", or filtered with -k "parse and (empty or nested)", is no file run: a |, ;, &, <, backquote or parenthesis inside a quote counts as if unquoted. The docs page, HOOKS.md, the README and the comment on fileRun now say so, and the test of what is no file run holds both commands. The session's state holds the file with the costliest whole run and the seven others run last. The docs page said a file's runs are dropped after eight later files; it is seven where the costliest file ran earlier. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 8 +++++--- integrations/claude-code-plugin/README.md | 2 +- integrations/claude-code-plugin/hooks/HOOKS.md | 14 +++++++++----- integrations/claude-code-plugin/lib/test-gate.mjs | 4 +++- .../claude-code-plugin/tests/test-cost.test.mjs | 3 +++ integrations/codex-plugin/lib/test-gate.mjs | 4 +++- 6 files changed, 24 insertions(+), 11 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 4f9be0814fe..8994180767d 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1721,7 +1721,10 @@ session's private state, by the file: - a run that anything follows in its command but `tail`, `head`, `grep` and `echo` counts as neither (`pytest tests/test_big.py -q && make test`): a runner started after it writes the result file and prints the summary line. A redirect of the run to a file - may stand before them. + may stand before them. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or + parenthesis inside one counts as if unquoted: a run piped into + `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as + neither. The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the @@ -1794,8 +1797,7 @@ What it does not do: - it is one row a repository and names one test file, the costliest one a session ran whole; - the session's state holds eight test files, the one with the costliest whole run and - the ones run last: the runs of any other file are dropped once the session has run - eight files after it; + the seven others run last: the runs of any other file are dropped; - a whole run started with xdist workers (`-n`) counts with the seconds it took, and the row does not say how its run was started: a session that runs the file only in parallel lowers a row that a serial run made, a row under 60 s prints nothing, and the diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 5e8075e9057..d86bb181104 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 038b07f70f5..2b47ba8e90e 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1413,8 +1413,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that private state keeps, for each of eight files, the costliest whole run in which no case failed, and the case count and seconds of its last 15 runs filtered with `-k`. The eight are the file with the costliest - whole run, which is what the session's end stores, and the ones run - last. A run that skipped more than a tenth of its cases is not kept: it + whole run, which is what the session's end stores, and the seven + others run last. A run that skipped more than a tenth of its cases is not kept: it ran where the cases skip, and took less. The skipped cases are the ones pytest's last line counts, where the command's output shows it. The report counts an expected failure (`xfail`) as skipped too, and a run @@ -1435,9 +1435,13 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that command but `tail`, `head`, `grep` and `echo`, a redirect of the run to a file aside (`onlyRuns` in lib/test-gate.mjs): a runner started after it (`&& make test`, `; tox`) writes the result file and prints the last - line. So is a run with no `-k` among its words whose last line counts - deselected cases: a selection the words do not show left cases out, one - in `PYTEST_ADDOPTS` or the settings file, or one written after `2>&1`, + line. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or + parenthesis inside one counts as if unquoted: a run piped into + `grep -E "passed|failed"` and one with + `-k "parse and (empty or nested)"` are noted as nothing. So is a run + with no `-k` among its words whose last line counts deselected cases: + a selection the words do not show left cases out, one in + `PYTEST_ADDOPTS` or the settings file, or one written after `2>&1`, where the words end. A run that outlived its shell call shows no last line, and such a run is counted as a whole run with the cases it ran. A whole run started with xdist workers (`-n`) counts with the seconds it diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 7e57f4fcd84..b0e5fb45fec 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1402,7 +1402,9 @@ const counted = (line, kinds) => * that anything follows in the command but `tail`, `head`, `grep` and `echo` * (`onlyRuns`), a redirect to a file aside: a runner started after it * (`&& make test`, `; tox`) writes the session's result file and prints the - * last line. + * last line. Quotes are not read there or in the run's words (`PYTEST`), so + * a run piped into `grep -E "passed|failed"` is none, and neither is one + * with `-k "parse and (empty or nested)"`. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 8960e392f6a..6de1e88d656 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -220,6 +220,9 @@ test("a command with two pytest runs, two paths, another selection or no run of `pytest ${FILE} > /tmp/out.txt; ./run_tests.sh`, `pytest ${FILE} -q >/dev/null;make test`, `pytest ${FILE} -q | tee "$(make test)"`, + // Quotes are not read: a `|` or a parenthesis in one ends the run's part there. + `pytest ${FILE} -q 2>&1 | grep -E "passed|failed"`, + `pytest ${FILE} -k "parse and (empty or nested)" -q`, // Run elsewhere, or not run. `docker exec app pytest ${FILE}`, `echo "pytest ${FILE}"`, diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 7e57f4fcd84..b0e5fb45fec 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1402,7 +1402,9 @@ const counted = (line, kinds) => * that anything follows in the command but `tail`, `head`, `grep` and `echo` * (`onlyRuns`), a redirect to a file aside: a runner started after it * (`&& make test`, `; tox`) writes the session's result file and prints the - * last line. + * last line. Quotes are not read there or in the run's words (`PYTEST`), so + * a run piped into `grep -E "passed|failed"` is none, and neither is one + * with `-k "parse and (empty or nested)"`. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run From a48f260f1ffa17d2bced039cdd7a811f76f7fbc1 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 00:55:39 +0530 Subject: [PATCH 13/24] A run with a command before it is no file run, and a session's end writes to the key its prompt read A command before the named pytest run may start pytest itself. Where the named run then does not start (make test || pytest with a suite that passes, an interpreter with no pytest), the result file and the last line are that command's, and were counted as the file's whole run. fileRun now reads a run only where nothing stands before it but cd, export, source and "." (onlySetsUp): a wrapper is not known by its name, so a build step before the run is no file run either. costPost resolved the checkout's scope again at SessionEnd and built the row's key from it. Where that resolution named another remote than the prompt's (the index's match cached no longer, an upstream remote), the first row went under a key no prompt of the checkout reads. The row state now keeps the identity and the repository id of the read, and the write names them. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 10 ++- integrations/claude-code-plugin/README.md | 4 +- .../claude-code-plugin/hooks/HOOKS.md | 19 ++++-- .../hooks/loom-session-memory.mjs | 2 +- .../claude-code-plugin/lib/test-cost.mjs | 61 ++++++++++--------- .../claude-code-plugin/lib/test-gate.mjs | 19 +++++- .../tests/test-cost.test.mjs | 42 ++++++++++++- .../hooks/loom-session-memory.mjs | 2 +- integrations/codex-plugin/lib/test-cost.mjs | 61 ++++++++++--------- integrations/codex-plugin/lib/test-gate.mjs | 19 +++++- tests/unit/session_content_senders.json | 8 +-- 11 files changed, 170 insertions(+), 77 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 8994180767d..d6178e19822 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1724,7 +1724,12 @@ session's private state, by the file: may stand before them. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as - neither. + neither; +- a run that anything stands before in its command but `cd`, `export`, `source` and `.` + counts as neither (`make build && pytest tests/test_big.py`): a command before it may + start pytest too, and where the run then does not start, as in + `make test || pytest tests/test_big.py`, the result file and the summary line are that + command's. The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the @@ -1770,7 +1775,8 @@ bug report read the row writes, a miss included, so it knows what it replaces: The write names the value the session read (`if_match_sha256`), is create-only after a miss, and goes under the agent that wrote the row, so it replaces no row the session did -not see. Of the run, the file's path in the checkout, the number of cases and the seconds +not see. It goes to the key the session's prompt read: the repository is not named again +from the checkout's remotes at the session's end. Of the run, the file's path in the checkout, the number of cases and the seconds are sent; a path that holds a character outside letters, digits and `._/-`, is over 160 characters or would be changed by the secret redaction is not sent. diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index d86bb181104..d1fb3582112 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that anything stands before in its command but `cd`, `export`, `source` and `.` (`make test || pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. @@ -336,7 +336,7 @@ Only a session whose bug report read the row writes, a miss included. With no ro Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session and checkout, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session and checkout, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 2b47ba8e90e..e1f9c518667 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -980,8 +980,9 @@ default 120 s timeout of a shell call. A run filtered with -k takes about exits with the prompt's answer; a script started on its own prints the pointers and stays until the read has settled or its exit grace has passed. The row as it was read, a miss too, is kept in the session's - state with its hash, the agent that wrote it and the checkout it was read - in, so a session asks once in a checkout; a read that failed or came late + state with its hash, the agent that wrote it, the key and scope the read + named and the checkout it was read in, so a session asks once in a + checkout and its end writes to that key; a read that failed or came late is asked again at the next bug report. The line is made of the row's path and numbers and never of its text: a value that is not the stored sentence prints nothing. Nor does a row whose whole run is under 60 s, or @@ -1435,7 +1436,12 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that command but `tail`, `head`, `grep` and `echo`, a redirect of the run to a file aside (`onlyRuns` in lib/test-gate.mjs): a runner started after it (`&& make test`, `; tox`) writes the result file and prints the last - line. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or + line. So is a run that anything stands before in its command but `cd`, + `export`, `source` and `.` (`onlySetsUp`): a command before it may + start pytest too, and where the run does not start + (`make test || pytest `, an interpreter with no pytest) the + result file and the last line are that command's. Quotes are not read, + so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` are noted as nothing. So is a run @@ -1517,8 +1523,11 @@ about cases and takes about s; a run of it filtered with -k takes about s.` The write revises the row the session read (`if_match_sha256`), under the agent that wrote it, and is create-only (`absent`) after a miss, so it replaces no row the session did not see; a value that is - not that sentence is left as it is. A session none of whose prompts - read the row stores nothing. + not that sentence is left as it is. It names the key, the scope and + the repository id of that read, kept in the session's state: the + checkout's scope is not resolved again at the session's end, where it + may name another remote, whose key no prompt of the checkout reads. A + session none of whose prompts read the row stores nothing. What leaves the machine is the file's path in the checkout, the case count and the seconds. A path that holds a character outside letters, digits and `._/-`, is over 160 characters or is changed by the secret diff --git a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs index 5a4544fbc0d..1041b8c0f5e 100644 --- a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs @@ -55,7 +55,7 @@ async function main() { removeFile(recalledStashPath(sid)); const stores = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken(); // Read for a session that stores, and removed for every session. - const cost = stores && testReportOn() ? costPost(sid, payload.cwd, () => resolveScope(payload.cwd)) : null; + const cost = stores && testReportOn() ? costPost(sid, payload.cwd) : null; endCost(sid); if (stores) { const posts = [await handOff(payload, journal, recalledKeys), cost].filter(Boolean); diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index afd610b35b8..0abb092fd66 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -21,8 +21,8 @@ // beside a bug report's search and prints one line under the pointers // (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the // row to the flusher (`costPost`), where the session's runs say something -// the row it read does not (`revised`), and removes the session's cost state -// whatever it stores (`endCost`). +// the row it read does not (`revised`), under the key that read named, and +// removes the session's cost state whatever it stores (`endCost`). // // What leaves the machine is the file's path in the checkout, a case count // and seconds, under the repository's id. A path that holds a character @@ -51,7 +51,8 @@ const MAX_SAMPLES = 15; // The session's runs: `{ pending, files }`, by each file's absolute path. const RUNS = "test-cost"; // The repository's row as the session read it in the checkout at `root`: -// `{ read, root, row }`. +// `{ read, root, repo, asked, row }`, with the repository's id and the +// identity the read named (`identity`), which the session's end writes to. const ROW = "test-cost-row"; /** `file`, a path in the checkout, when it may be sent, else "". */ @@ -243,12 +244,12 @@ export function renderCost({ path: file, tests, seconds, filtered }) { * checkout with no remote: `//`, the runner as the id. */ export const costKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/test-cost/pytest` : ""); -/** The row's identity: under the agent that wrote the row, where the session - * read one. A read finds another agent's row, and a write names its own. */ -const identity = (scope, agent) => ({ +/** The identity a read of the row of `scope` names. The read finds another + * agent's row too, and a write to a row names the agent that wrote it. */ +const identity = (scope) => ({ org: scope.org, namespace: scope.namespace, - agent: agent || scope.agent, + agent: scope.agent, memory_key: costKey(scope), }); @@ -257,14 +258,14 @@ const identity = (scope, agent) => ({ * switched it off, in the checkout at `root`, or "": the repository's row, * read once a session and checkout (`memory.get` by key, bounded by * `options.timeoutMs`) and kept in the session's state, a miss too, with the - * agent that wrote it and the checkout it was read in: a session whose - * folder moved to another checkout reads that one's row. `scopeOf()` is - * asked only for that read, before it is sent: where the process has not - * resolved the checkout's scope yet, its git calls run then, in the caller's - * thread. An answer that does not come and an error give no line, and a - * later prompt asks again. A row gives none whose value is not `claim`'s - * text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose file the - * checkout does not hold. + * agent that wrote it, the identity the read named and the checkout it was + * read in: a session whose folder moved to another checkout reads that + * one's row. `scopeOf()` is asked only for that read, before it is sent: + * where the process has not resolved the checkout's scope yet, its git + * calls run then, in the caller's thread. An answer that does not come and + * an error give no line, and a later prompt asks again. A row gives none + * whose value is not `claim`'s text, whose whole run is under + * `MIN_WHOLE_SECONDS`, or whose file the checkout does not hold. */ export async function costLine(sessionId, root, scopeOf, options) { try { @@ -274,10 +275,12 @@ export async function costLine(sessionId, root, scopeOf, options) { const scope = scopeOf(); if (!costKey(scope)) return ""; const fields = ["value", "content_sha256", "agent"]; - const res = await postBounded("memory.get", { ...identity(scope), fields }, options); + const asked = identity(scope); + const res = await postBounded("memory.get", { ...asked, fields }, options); if (!res) return ""; + const repo = scope.repo.id; const found = { sha: String(res.content_sha256 || ""), agent: String(res.agent || "") }; - held = { read: true, root, row: res.found ? { ...parseClaim(scope.repo.id, res.value), ...found } : null }; + held = { read: true, root, repo, asked, row: res.found ? { ...parseClaim(repo, res.value), ...found } : null }; writeSessionState(ROW, sessionId, held); } const row = held.row; @@ -353,13 +356,15 @@ function measured(state, root) { * The flusher's post that stores what the session measured, or null. Only a * session whose prompt read the row in the checkout of `cwd` stores, a miss * included: it knows what it replaces, and where no prompt can read the row - * no session writes one. One `memory.set` of the repository's key follows - * where `revised` has a claim: a revision of the row as read - * (`if_match_sha256`, under the row's agent), else a first row (`absent`). - * The value names no file to the server (`files: []`), and its class says a - * tool measured it. + * no session writes one. One `memory.set` follows where `revised` has a + * claim: a revision of the row as read (`if_match_sha256`, under the row's + * agent), else a first row (`absent`). It names the key and the repository + * of that read, from the session's state: a scope resolved again here may + * name another remote of the checkout, whose key no prompt reads. The value + * names no file to the server (`files: []`), and its class says a tool + * measured it. */ -export function costPost(sessionId, cwd, scopeOf) { +export function costPost(sessionId, cwd) { try { const state = readSessionState(RUNS, sessionId); const held = readSessionState(ROW, sessionId); @@ -368,12 +373,12 @@ export function costPost(sessionId, cwd, scopeOf) { if (!Object.keys(runs).length) return null; const row = held.row?.path ? { ...held.row, gone: !isFile(path.join(root, held.row.path)) } : held.row; const next = revised(runs, row); - const scope = next ? scopeOf() : null; - if (!costKey(scope)) return null; + if (!next) return null; const body = { - ...identity(scope, row?.agent), - value: claim(scope.repo.id, next), - tags: [`repo:${scope.repo.id}`, `source:${hookClient()}`, "test-cost"], + ...held.asked, + agent: row?.agent || held.asked.agent, + value: claim(held.repo, next), + tags: [`repo:${held.repo}`, `source:${hookClient()}`, "test-cost"], files: [], source_class: "external", if_match_sha256: row?.sha || "absent", diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index b0e5fb45fec..e87a33e88e6 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1332,6 +1332,17 @@ const onlyRuns = (tail) => .replace(/\d?>(?:&\d|\s*\/dev\/null(?=[\s;&|)]|$))/g, " ") .split(/[;&|()\n]/) .every((part) => !/[<>`]/.test(part) && (OUTPUT.test(part) || part.match(PYTEST))); +// What a command may hold before the simple command of its pytest run: `cd`, +// `export`, `source` and `.`, with no backquote. Anything else may start +// pytest itself (`make test`, a script), and its last line and result file +// are read as the run's where the run did not start (`make test || pytest +// `, an interpreter with no pytest). +const SETS_UP = /^\s*(?:(?:cd|export|source|\.)\s[^`]*)?$/; +const onlySetsUp = (head) => + head + .split(/[;&|(\n]/) + .slice(0, -1) + .every((part) => SETS_UP.test(part)); /** True when the output holds a whole pytest summary for each of `runs` * and no other summary: `| tail -5; echo exit=$?` hides the exit status, @@ -1404,7 +1415,11 @@ const counted = (line, kinds) => * (`&& make test`, `; tox`) writes the session's result file and prints the * last line. Quotes are not read there or in the run's words (`PYTEST`), so * a run piped into `grep -E "passed|failed"` is none, and neither is one - * with `-k "parse and (empty or nested)"`. + * with `-k "parse and (empty or nested)"`. Nor is a run that anything stands + * before in the command but `cd`, `export`, `source` and `.` (`onlySetsUp`): + * a command before it may start pytest too (`make test || pytest `), + * and where the run does not start, the last line and the result file are + * that command's. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1424,7 +1439,7 @@ export function fileRun(command, output = "") { const text = String(command || "").replace(/\\\n/g, ""); const runs = [...text.matchAll(PYTEST)]; const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; - if (runs.length !== 1 || !ranHere(head)) return null; + if (runs.length !== 1 || !ranHere(head) || !onlySetsUp(head)) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "))) return null; diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 6de1e88d656..c40ff46a120 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -117,8 +117,11 @@ test("a command's one pytest run of one test file is whole or filtered with -k", `timeout 600 pytest ${FILE} -p no:cacheprovider`, // A short flag written with its value takes none after it. `pytest -rf -n4 ${FILE}`, + // What sets the shell up may stand before it. + `source .venv/bin/activate && export PYTHONPATH=src; pytest ${FILE}`, + `. .venv/bin/activate; pytest ${FILE} -q`, // What reads the run's output may follow it. - `make build && pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt; echo exit=$?`, + `pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt; echo exit=$?`, ]) { assert.deepEqual(fileRun(command), whole, command); } @@ -220,6 +223,14 @@ test("a command with two pytest runs, two paths, another selection or no run of `pytest ${FILE} > /tmp/out.txt; ./run_tests.sh`, `pytest ${FILE} -q >/dev/null;make test`, `pytest ${FILE} -q | tee "$(make test)"`, + // A command before the run may start pytest itself, and the run may not + // start: the last line and the result file are then that command's. + `make test || pytest ${FILE} -q`, + `make test; python3.9 -m pytest ${FILE} -q`, + `./scripts/check.sh && pytest ${FILE}`, + `make build && pytest ${FILE} -q`, + `export OUT=$(make test); pytest ${FILE}`, + `export OUT=\`make test\`; pytest ${FILE}`, // Quotes are not read: a `|` or a parenthesis in one ends the run's part there. `pytest ${FILE} -q 2>&1 | grep -E "passed|failed"`, `pytest ${FILE} -k "parse and (empty or nested)" -q`, @@ -987,7 +998,7 @@ test("the launcher at an agent's SessionEnd reads the pending run's report and e assert.equal(fs.existsSync(box.runs), false); }); -test("nothing is stored for a whole run under 60 s, a command of two runs or two paths, or with session memory off", { +test("nothing is stored for a whole run under 60 s, a command of two runs, two paths or a command before the run, or with session memory off", { skip: WINDOWS, }, async (t) => { const server = await loom(t); @@ -999,6 +1010,8 @@ test("nothing is stored for a whole run under 60 s, a command of two runs or two [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}, null], [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}, null], [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}, null], + // The suite's run passed, so the file's run did not start: the report is the suite's. + [`make test || pytest ${FILE} -q`, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), {}, null], // The session hands nothing to memory: nothing is noted for it. [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }, null], ]; @@ -1272,6 +1285,31 @@ test("a session whose folder moves to another checkout reads and writes that rep assert.deepEqual(none.sent("memory.set"), []); }); +test("a session's end writes to the key its prompt read, whatever remote the checkout's scope names by then", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + // The prompt names the repository by `origin`, the remote the index matched, and finds no row. + await ask(box); + assert.equal(server.sent("memory.get")[0].body.memory_key, KEY); + await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + // The index's match is cached no longer: a scope resolved now names the + // `upstream` remote, another repository id. + fs.rmSync(cachePathFor(box.cwd, box.tmp, { serverUrl: server.url, token: "t" })); + const upstream = "https://github.com/example/upstream.git"; + execFileSync("git", ["remote", "add", "upstream", upstream], { cwd: box.cwd, stdio: "ignore" }); + assert.notEqual(repoIdentity(upstream).id, REPO); + await endSession(box); + await arrived(server, box, "memory.set"); + const { body } = server.sent("memory.set")[0]; + // A first row under the key the prompt read, in that repository's name. + assert.equal(body.memory_key, KEY); + assert.equal(body.value, claim(REPO, { path: FILE, tests: 8000, seconds: 140 })); + assert.deepEqual(body.tags, [`repo:${REPO}`, "source:claude-code", "test-cost"]); + assert.equal(body.if_match_sha256, "absent"); +}); + test("a miss is kept for the session, and a row that is not the claim's text prints nothing", { skip: WINDOWS, }, async (t) => { diff --git a/integrations/codex-plugin/hooks/loom-session-memory.mjs b/integrations/codex-plugin/hooks/loom-session-memory.mjs index 5a4544fbc0d..1041b8c0f5e 100644 --- a/integrations/codex-plugin/hooks/loom-session-memory.mjs +++ b/integrations/codex-plugin/hooks/loom-session-memory.mjs @@ -55,7 +55,7 @@ async function main() { removeFile(recalledStashPath(sid)); const stores = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken(); // Read for a session that stores, and removed for every session. - const cost = stores && testReportOn() ? costPost(sid, payload.cwd, () => resolveScope(payload.cwd)) : null; + const cost = stores && testReportOn() ? costPost(sid, payload.cwd) : null; endCost(sid); if (stores) { const posts = [await handOff(payload, journal, recalledKeys), cost].filter(Boolean); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index afd610b35b8..0abb092fd66 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -21,8 +21,8 @@ // beside a bug report's search and prints one line under the pointers // (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the // row to the flusher (`costPost`), where the session's runs say something -// the row it read does not (`revised`), and removes the session's cost state -// whatever it stores (`endCost`). +// the row it read does not (`revised`), under the key that read named, and +// removes the session's cost state whatever it stores (`endCost`). // // What leaves the machine is the file's path in the checkout, a case count // and seconds, under the repository's id. A path that holds a character @@ -51,7 +51,8 @@ const MAX_SAMPLES = 15; // The session's runs: `{ pending, files }`, by each file's absolute path. const RUNS = "test-cost"; // The repository's row as the session read it in the checkout at `root`: -// `{ read, root, row }`. +// `{ read, root, repo, asked, row }`, with the repository's id and the +// identity the read named (`identity`), which the session's end writes to. const ROW = "test-cost-row"; /** `file`, a path in the checkout, when it may be sent, else "". */ @@ -243,12 +244,12 @@ export function renderCost({ path: file, tests, seconds, filtered }) { * checkout with no remote: `//`, the runner as the id. */ export const costKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/test-cost/pytest` : ""); -/** The row's identity: under the agent that wrote the row, where the session - * read one. A read finds another agent's row, and a write names its own. */ -const identity = (scope, agent) => ({ +/** The identity a read of the row of `scope` names. The read finds another + * agent's row too, and a write to a row names the agent that wrote it. */ +const identity = (scope) => ({ org: scope.org, namespace: scope.namespace, - agent: agent || scope.agent, + agent: scope.agent, memory_key: costKey(scope), }); @@ -257,14 +258,14 @@ const identity = (scope, agent) => ({ * switched it off, in the checkout at `root`, or "": the repository's row, * read once a session and checkout (`memory.get` by key, bounded by * `options.timeoutMs`) and kept in the session's state, a miss too, with the - * agent that wrote it and the checkout it was read in: a session whose - * folder moved to another checkout reads that one's row. `scopeOf()` is - * asked only for that read, before it is sent: where the process has not - * resolved the checkout's scope yet, its git calls run then, in the caller's - * thread. An answer that does not come and an error give no line, and a - * later prompt asks again. A row gives none whose value is not `claim`'s - * text, whose whole run is under `MIN_WHOLE_SECONDS`, or whose file the - * checkout does not hold. + * agent that wrote it, the identity the read named and the checkout it was + * read in: a session whose folder moved to another checkout reads that + * one's row. `scopeOf()` is asked only for that read, before it is sent: + * where the process has not resolved the checkout's scope yet, its git + * calls run then, in the caller's thread. An answer that does not come and + * an error give no line, and a later prompt asks again. A row gives none + * whose value is not `claim`'s text, whose whole run is under + * `MIN_WHOLE_SECONDS`, or whose file the checkout does not hold. */ export async function costLine(sessionId, root, scopeOf, options) { try { @@ -274,10 +275,12 @@ export async function costLine(sessionId, root, scopeOf, options) { const scope = scopeOf(); if (!costKey(scope)) return ""; const fields = ["value", "content_sha256", "agent"]; - const res = await postBounded("memory.get", { ...identity(scope), fields }, options); + const asked = identity(scope); + const res = await postBounded("memory.get", { ...asked, fields }, options); if (!res) return ""; + const repo = scope.repo.id; const found = { sha: String(res.content_sha256 || ""), agent: String(res.agent || "") }; - held = { read: true, root, row: res.found ? { ...parseClaim(scope.repo.id, res.value), ...found } : null }; + held = { read: true, root, repo, asked, row: res.found ? { ...parseClaim(repo, res.value), ...found } : null }; writeSessionState(ROW, sessionId, held); } const row = held.row; @@ -353,13 +356,15 @@ function measured(state, root) { * The flusher's post that stores what the session measured, or null. Only a * session whose prompt read the row in the checkout of `cwd` stores, a miss * included: it knows what it replaces, and where no prompt can read the row - * no session writes one. One `memory.set` of the repository's key follows - * where `revised` has a claim: a revision of the row as read - * (`if_match_sha256`, under the row's agent), else a first row (`absent`). - * The value names no file to the server (`files: []`), and its class says a - * tool measured it. + * no session writes one. One `memory.set` follows where `revised` has a + * claim: a revision of the row as read (`if_match_sha256`, under the row's + * agent), else a first row (`absent`). It names the key and the repository + * of that read, from the session's state: a scope resolved again here may + * name another remote of the checkout, whose key no prompt reads. The value + * names no file to the server (`files: []`), and its class says a tool + * measured it. */ -export function costPost(sessionId, cwd, scopeOf) { +export function costPost(sessionId, cwd) { try { const state = readSessionState(RUNS, sessionId); const held = readSessionState(ROW, sessionId); @@ -368,12 +373,12 @@ export function costPost(sessionId, cwd, scopeOf) { if (!Object.keys(runs).length) return null; const row = held.row?.path ? { ...held.row, gone: !isFile(path.join(root, held.row.path)) } : held.row; const next = revised(runs, row); - const scope = next ? scopeOf() : null; - if (!costKey(scope)) return null; + if (!next) return null; const body = { - ...identity(scope, row?.agent), - value: claim(scope.repo.id, next), - tags: [`repo:${scope.repo.id}`, `source:${hookClient()}`, "test-cost"], + ...held.asked, + agent: row?.agent || held.asked.agent, + value: claim(held.repo, next), + tags: [`repo:${held.repo}`, `source:${hookClient()}`, "test-cost"], files: [], source_class: "external", if_match_sha256: row?.sha || "absent", diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index b0e5fb45fec..e87a33e88e6 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1332,6 +1332,17 @@ const onlyRuns = (tail) => .replace(/\d?>(?:&\d|\s*\/dev\/null(?=[\s;&|)]|$))/g, " ") .split(/[;&|()\n]/) .every((part) => !/[<>`]/.test(part) && (OUTPUT.test(part) || part.match(PYTEST))); +// What a command may hold before the simple command of its pytest run: `cd`, +// `export`, `source` and `.`, with no backquote. Anything else may start +// pytest itself (`make test`, a script), and its last line and result file +// are read as the run's where the run did not start (`make test || pytest +// `, an interpreter with no pytest). +const SETS_UP = /^\s*(?:(?:cd|export|source|\.)\s[^`]*)?$/; +const onlySetsUp = (head) => + head + .split(/[;&|(\n]/) + .slice(0, -1) + .every((part) => SETS_UP.test(part)); /** True when the output holds a whole pytest summary for each of `runs` * and no other summary: `| tail -5; echo exit=$?` hides the exit status, @@ -1404,7 +1415,11 @@ const counted = (line, kinds) => * (`&& make test`, `; tox`) writes the session's result file and prints the * last line. Quotes are not read there or in the run's words (`PYTEST`), so * a run piped into `grep -E "passed|failed"` is none, and neither is one - * with `-k "parse and (empty or nested)"`. + * with `-k "parse and (empty or nested)"`. Nor is a run that anything stands + * before in the command but `cd`, `export`, `source` and `.` (`onlySetsUp`): + * a command before it may start pytest too (`make test || pytest `), + * and where the run does not start, the last line and the result file are + * that command's. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1424,7 +1439,7 @@ export function fileRun(command, output = "") { const text = String(command || "").replace(/\\\n/g, ""); const runs = [...text.matchAll(PYTEST)]; const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; - if (runs.length !== 1 || !ranHere(head)) return null; + if (runs.length !== 1 || !ranHere(head) || !onlySetsUp(head)) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "))) return null; diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index fe1e9e00ee5..36d2fb166cc 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -77,7 +77,7 @@ "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." }, - "integrations/claude-code-plugin/lib/test-cost.mjs:memory.get:b24b4138da905c52ed4a:1": { + "integrations/claude-code-plugin/lib/test-cost.mjs:memory.get:70d45112f23f65d4abe9:1": { "category": "reference", "reason": "Reads the repository's test cost row by its key, which is built from the repository's id, with the scoped identity and a fixed field list; no prompt, transcript, path or file content is sent." }, @@ -157,7 +157,7 @@ "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." }, - "integrations/codex-plugin/lib/test-cost.mjs:memory.get:b24b4138da905c52ed4a:1": { + "integrations/codex-plugin/lib/test-cost.mjs:memory.get:70d45112f23f65d4abe9:1": { "category": "reference", "reason": "Reads the repository's test cost row by its key, which is built from the repository's id, with the scoped identity and a fixed field list; no prompt, transcript, path or file content is sent." }, @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "5f1b3f4aa42ffff9d3465b9488d239bdd32faba0718232c07d3660136105a7f7", + "integrations/claude-code-plugin/lib/test-cost.mjs": "969858b366bf033e97c8d8c847ebc14c98ba2782e8442fa08080141b760236ab", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "5f1b3f4aa42ffff9d3465b9488d239bdd32faba0718232c07d3660136105a7f7", + "integrations/codex-plugin/lib/test-cost.mjs": "969858b366bf033e97c8d8c847ebc14c98ba2782e8442fa08080141b760236ab", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From b378ee6144eb2b82572ce670e2474e36900b2066 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:39:41 +0530 Subject: [PATCH 14/24] A report's seconds are compared with the summary's as written, and a session keeps the row it read last The check that a result file is the command's compared the summary's seconds with the file's seconds rounded to a whole one, so the tolerance of a second was off by up to half a second either way: `1.45s` against `time="0.49"` was refused and `2.00s` against `time="0.51"` accepted. It now compares with the seconds as the file writes them. The session's state holds one row, the one a bug report read last, with the checkout it was read in. The comments, the README, the hooks reference and the Claude Code page said the row is read once a session and checkout and stored where a prompt read it. They now say what the state does: a bug report in another checkout reads that repository's row in its place, a bug report back in the first checkout reads again, and the session's end stores only in the checkout of the row kept. A test holds both. The README's rule for the filtered time is the one the code has: the row's is replaced when it has none or the session's is more than a quarter and two seconds away. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 13 ++++-- integrations/claude-code-plugin/README.md | 4 +- .../claude-code-plugin/hooks/HOOKS.md | 29 +++++++----- .../hooks/loom-prompt-pack.mjs | 9 ++-- .../hooks/loom-session-memory.mjs | 5 +- .../claude-code-plugin/lib/test-cost.mjs | 46 +++++++++++-------- .../tests/test-cost.test.mjs | 21 +++++++++ .../codex-plugin/hooks/loom-prompt-pack.mjs | 9 ++-- .../hooks/loom-session-memory.mjs | 5 +- integrations/codex-plugin/lib/test-cost.mjs | 46 +++++++++++-------- tests/unit/session_content_senders.json | 8 ++-- 11 files changed, 121 insertions(+), 74 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index d6178e19822..a7a59bbc6ba 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1086,7 +1086,7 @@ The wiring is `hooks/hooks.json`; `hooks/HOOKS.md` has per-hook notes. | Event | Script | Effect | Off switch | | ------------------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | SessionStart | `loom-session-start.mjs` | one budgeted `context.pack` primer (working-memory note, profile, the session's memory stack, recent runs with `LOOM_CONTEXT_RUNS`; and the memories, decisions and procedures a search for the project finds or, where a new or cleared conversation's prompts get the recall, the pinned and newest ones, listed), one line naming an indexed checkout's code namespace and the repository's memory tag (left out in a new session whose MCP connection carries the checkout: the server then applies both), a line naming the project's saved session briefs, a task-inbox line (`task.counts`), a few lines naming the collections the token can read (`collection.list`), and a line when [the instruction block](#the-instruction-block) needs setup | `LOOM_INJECT_CONTEXT=false`, `LOOM_CODE_MAP=false`, `LOOM_TASK_INBOX_LINE=off`, `LOOM_COLLECTIONS_LINE=off`, `LOOM_SETUP_LINE=off` | -| UserPromptSubmit | `loom-prompt-pack.mjs` | no request with `prompt_pack` off; at its default no prompt text unless this Loom holds the checkout's own repository ([what a prompt gets](#what-a-prompt-gets)); otherwise up to three `code.search` pointers for the prompt, only when the index rates its answer low-risk (or it reaches `LOOM_PROMPT_PACK_MIN_CONF`) and then only the answer's places to edit, one pointer per place: a definition, a unit of a file the hook does not hold to definitions, a document or a test when the prompt names it or asks for documentation or tests, a Python migration or a release script only if named, and module-level code when it asks for tests; below them the test line for a pointer whose definition the prompt names ([the test gate](#the-test-gate)), and under a bug report's pointers the repository's test cost line, from one `memory.get` a session ([what a whole run costs](#what-a-whole-run-costs)) | off unless `prompt_pack` or `LOOM_PROMPT_PACK=on`; `LOOM_PROMPT_CONTEXT=off` | +| UserPromptSubmit | `loom-prompt-pack.mjs` | no request with `prompt_pack` off; at its default no prompt text unless this Loom holds the checkout's own repository ([what a prompt gets](#what-a-prompt-gets)); otherwise up to three `code.search` pointers for the prompt, only when the index rates its answer low-risk (or it reaches `LOOM_PROMPT_PACK_MIN_CONF`) and then only the answer's places to edit, one pointer per place: a definition, a unit of a file the hook does not hold to definitions, a document or a test when the prompt names it or asks for documentation or tests, a Python migration or a release script only if named, and module-level code when it asks for tests; below them the test line for a pointer whose definition the prompt names ([the test gate](#the-test-gate)), and under a bug report's pointers the repository's test cost line, from one `memory.get` if needed ([what a whole run costs](#what-a-whole-run-costs)) | off unless `prompt_pack` or `LOOM_PROMPT_PACK=on`; `LOOM_PROMPT_CONTEXT=off` | | UserPromptSubmit | `loom-prompt-recall.mjs` | one bounded `context.pack` recall for the prompt (memories, decisions, procedures), injected only when memory does not abstain: whole records, and none of code as it was before a commit the checkout already has; of a record linked to a file of the checkout that the prompt does not name, one line: its key and the file | `LOOM_PROMPT_RECALL=first` (default) / `on` / `off`; `LOOM_PROMPT_CONTEXT=off` | | UserPromptSubmit | `loom-run.mjs` | opens the session's run (`run.begin`, `run_id = cc-`, goal = the first prompt); the prompt does not wait for it | `LOOM_RUN_LEDGER=off` | | PreToolUse (Read, Grep; Bash for a command that runs `gh`) | `loom-code-shunt.mjs` | the code shunt and the tracker shunt ([next section](#the-code-shunt)) | `LOOM_CODE_SHUNT=off`, `LOOM_TRACKER_SHUNT=off` | @@ -1789,9 +1789,11 @@ Test cost in this repository (measured in earlier sessions): a whole run of test The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. The row is -read with one `memory.get` a session and checkout, sent beside the prompt's search and -never waited for past its answer: a read that fails or is slow adds nothing, and the -pointers are printed as they are. Before the read is sent the hook names the repository +read with one `memory.get`, sent beside the prompt's search and never waited for past its +answer: a read that fails or is slow adds nothing, and the pointers are printed as they +are. The session keeps the row it read last, with the checkout it was read in: a later +bug report in that checkout sends no read, and one in another checkout reads that +repository's row in its place. Before the read is sent the hook names the repository from the checkout's git remote. Where no other hook of the prompt has done so, that is one `git config` call as a rule, bounded at 1,500 ms, and the search's answer is taken after it. The line is made of the row's path and numbers, so a @@ -1811,6 +1813,9 @@ What it does not do: - a session none of whose prompts read the row stores nothing: one with no bug report, and every session in `memory` mode, with the prompt pointers off or in a repository this Loom does not index; +- a session stores only where it ends in the checkout of the row it read last: one that + ends in a checkout whose row it read before a bug report in another checkout stores + nothing; - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not; - the session keeps one run that outlives its call. A later one of another test file diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index d1fb3582112..af6cf3a407e 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -330,13 +330,13 @@ Loom adds no option on Windows, under Codex (which names no such file), with an In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. ``` -Only a session whose bug report read the row writes, a miss included. With no row, its costliest whole run is stored when it took 60 s or more. The row's own file is revised when the session's whole run of it is more than a quarter away from the stored seconds, down as well as up, or its filtered time is. Another file takes the row with a whole run of 60 s or more that is over a quarter longer, and any such run takes a row whose file the checkout no longer holds. The write names the value the session read and goes under the agent that wrote the row. Of the run, only the file's path in the checkout, the number of cases and the seconds are sent; a path the secret redaction would change is not sent. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: +Only a session whose bug report read the row writes, a miss included. With no row, its costliest whole run is stored when it took 60 s or more. The row's own file is revised by the session's whole run of it when that is more than a quarter away from the stored seconds, down as well as up, and by its filtered time when the row has none or the session's is more than a quarter and two seconds away. Another file takes the row with a whole run of 60 s or more that is over a quarter longer, and any such run takes a row whose file the checkout no longer holds. The write names the value the session read and goes under the agent that wrote the row. Of the run, only the file's path in the checkout, the number of cases and the seconds are sent; a path the secret redaction would change is not sent. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: ```text Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read once a session and checkout, beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that repository's row in its place. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index, and neither does a session that ends in another checkout than the one whose row it read last. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index e1f9c518667..069a66cda00 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -148,7 +148,7 @@ receives on stdout. | ------------------------------------------------------------- | --------------------- | ---------------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | | SessionStart | loom-session-start | cwd, session_id, source | primer text | context.pack, code.repos/index_status/map, task.counts, namespace.get, session.brief_list, collection.list; GET /v1/health: its round trip is cached as the RTT bound, its `version` feeds the server version warning; in a checkout that configures pytest, one line in the file `CLAUDE_ENV_FILE` names and an empty result file | `LOOM_INJECT_CONTEXT=false` | | UserPromptSubmit | loom-record | the payload | JSON additionalContext | keeps the run's begin in the run state; starts one detached process, which runs the event's `detached` rows; runs the event's `in loom-record` rows itself and prints their context as one answer | each script's own | -| UserPromptSubmit, in loom-record | loom-prompt-pack | prompt, cwd, session_id | its context | code.search, or code.symbol, code.callers or code.impact for a named definition; no request with the pointers off; under `auto` none of those unless the server holds the checkout's own repository, and one code.repos where no lookup has answered; for a test line one `git ls-files`, and the test is noted in the test gate's session state; under a bug report's pointers, in a session that has the test report, one memory.get of the repository's test cost row, once a session | `LOOM_PROMPT_PACK=off` | +| UserPromptSubmit, in loom-record | loom-prompt-pack | prompt, cwd, session_id | its context | code.search, or code.symbol, code.callers or code.impact for a named definition; no request with the pointers off; under `auto` none of those unless the server holds the checkout's own repository, and one code.repos where no lookup has answered; for a test line one `git ls-files`, and the test is noted in the test gate's session state; under a bug report's pointers, in a session that has the test report, one memory.get of the test cost row, unless the session keeps it | `LOOM_PROMPT_PACK=off` | | UserPromptSubmit, in loom-record | loom-prompt-recall | prompt, cwd, session_id | its context | context.pack | `LOOM_PROMPT_RECALL=off` | | UserPromptSubmit, detached | loom-run | prompt, session_id | none | run.begin on the first prompt; appends the turn journal | `LOOM_RUN_LEDGER=off` | | UserPromptSubmit, detached | loom-namespace-health | cwd, session_id | none | namespace.audit, once per session; the verdict goes to the session's state file | `LOOM_NAMESPACE_HEALTH=off` | @@ -981,13 +981,15 @@ default 120 s timeout of a shell call. A run filtered with -k takes about pointers and stays until the read has settled or its exit grace has passed. The row as it was read, a miss too, is kept in the session's state with its hash, the agent that wrote it, the key and scope the read - named and the checkout it was read in, so a session asks once in a - checkout and its end writes to that key; a read that failed or came late - is asked again at the next bug report. The line is made of the row's path - and numbers and never of its text: a value that is not the stored - sentence prints nothing. Nor does a row whose whole run is under 60 s, or - whose file the checkout does not hold. It needs the memory plane and a - session that has the test report. + named and the checkout it was read in. The state keeps one row, the one + read last: a later bug report in that checkout asks nothing, one in + another checkout reads that repository's row in its place, and the + session's end writes to the key of the row kept; a read that failed or + came late is asked again at the next bug report. The line is made of the + row's path and numbers and never of its text: a value that is not the + stored sentence prints nothing. Nor does a row whose whole run is under + 60 s, or whose file the checkout does not hold. It needs the memory plane + and a session that has the test report. **The listwise pick.** For a request that reads as a bug report (twelve words or more, or the vocabulary of a failure, as the search reads it) the search carries `rerank: "builtin:pick"`. On a server that names a pick @@ -1502,9 +1504,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that with its report not yet read, is not counted either. At SessionEnd `loom-session-memory` hands one `memory.set` to the flusher, beside the session's turns or alone where they are not sent, - where a prompt of the session read the row, a miss included, and its - runs say something the row does not (`revised`). With no row, the - costliest whole run is stored when it took 60 s or more. The row's own + where the session ends in the checkout of the row a prompt read last, + a miss included, and its runs say something the row does not + (`revised`). With no row, the costliest whole run is stored when it + took 60 s or more. The row's own file is revised by the session's whole run of it when that is more than a quarter away from the stored seconds, down as well as up, and by the middle of its filtered runs that ran fewer cases than the whole file, @@ -1527,7 +1530,9 @@ about s.` The write revises the row the session read (`if_match_sha256`), the repository id of that read, kept in the session's state: the checkout's scope is not resolved again at the session's end, where it may name another remote, whose key no prompt of the checkout reads. A - session none of whose prompts read the row stores nothing. + session none of whose prompts read the row stores nothing, and + neither does one that ends in another checkout than the one whose row + it read last. What leaves the machine is the file's path in the checkout, the case count and the seconds. A path that holds a character outside letters, digits and `._/-`, is over 160 characters or is changed by the secret diff --git a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index c663619a7eb..142373b396f 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -48,10 +48,11 @@ // what a whole run of a slow test file costs in this repository // (lib/test-cost.mjs): the file, its case count and seconds, the seconds of a // run filtered with -k, and to check a change with -k selections. The row is -// read by its key once a session and checkout, beside the search and inside -// the prompt's bound, and the line is sent only when that read has answered -// by the time the search has: under the launcher the read never holds the -// pointers back. The git calls that resolve the checkout's scope for it can. +// read by its key, beside the search and inside the prompt's bound, unless +// the session keeps it: it keeps the row it read last, with the checkout it +// was read in. The line is sent only when that read has answered by the +// time the search has: under the launcher the read never holds the pointers +// back. The git calls that resolve the checkout's scope for it can. // Where no script of the prompt has resolved the scope in the process, they // run in this thread before the read is sent, each bounded at 1,500 ms (one // `git config` where the index's match is cached), and the search's answer is diff --git a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs index 1041b8c0f5e..a606767e773 100644 --- a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs @@ -7,8 +7,9 @@ // // The same hand-off carries what the session's test runs cost, whether or // not its turns are sent: one memory.set of the repository's test cost row, -// where the session's runs of a test file say something the row one of its -// prompts read does not (lib/test-cost.mjs; LOOM_TEST_REPORT=off stops it). +// where the session's runs of a test file say something the row its prompts +// read last does not, in that row's checkout (lib/test-cost.mjs; +// LOOM_TEST_REPORT=off stops it). // The session's cost state is removed here, whatever is handed off. // // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 0abb092fd66..03280e85be7 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -20,9 +20,10 @@ // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers // (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the -// row to the flusher (`costPost`), where the session's runs say something -// the row it read does not (`revised`), under the key that read named, and -// removes the session's cost state whatever it stores (`endCost`). +// row to the flusher (`costPost`), where the session ends in the checkout of +// the row it read last and its runs say something that row does not +// (`revised`), under the key that read named, and removes the session's cost +// state whatever it stores (`endCost`). // // What leaves the machine is the file's path in the checkout, a case count // and seconds, under the repository's id. A path that holds a character @@ -50,9 +51,10 @@ const MAX_SAMPLES = 15; // The session's runs: `{ pending, files }`, by each file's absolute path. const RUNS = "test-cost"; -// The repository's row as the session read it in the checkout at `root`: -// `{ read, root, repo, asked, row }`, with the repository's id and the -// identity the read named (`identity`), which the session's end writes to. +// The repository's row as the session read it last, in the checkout at +// `root`: `{ read, root, repo, asked, row }`, with the repository's id and +// the identity the read named (`identity`), which the session's end writes +// to. It is one row: a read in another checkout takes its place. const ROW = "test-cost-row"; /** `file`, a path in the checkout, when it may be sent, else "". */ @@ -172,7 +174,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { cost && run.cases === cost.tests && run.failed === cost.failed && - Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); + Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); // The summary counts the skipped cases apart from the expected failures. if (own) add(state, run, { ...cost, skipped: run.skipped }); const settled = !own && settle(state, report); @@ -256,11 +258,13 @@ const identity = (scope) => ({ /** * The line for a prompt of a session that has the test report and has not * switched it off, in the checkout at `root`, or "": the repository's row, - * read once a session and checkout (`memory.get` by key, bounded by - * `options.timeoutMs`) and kept in the session's state, a miss too, with the - * agent that wrote it, the identity the read named and the checkout it was - * read in: a session whose folder moved to another checkout reads that - * one's row. `scopeOf()` is asked only for that read, before it is sent: + * read with `memory.get` by key (bounded by `options.timeoutMs`) and kept in + * the session's state, a miss too, with the agent that wrote it, the + * identity the read named and the checkout it was read in. The state keeps + * one row, the one read last, and a prompt in its checkout sends no read: a + * session whose folder moved to another checkout reads that one's row in + * its place, and one whose folder moved back reads the first one's again. + * `scopeOf()` is asked only for that read, before it is sent: * where the process has not resolved the checkout's scope yet, its git * calls run then, in the caller's thread. An answer that does not come and * an error give no line, and a later prompt asks again. A row gives none @@ -354,15 +358,17 @@ function measured(state, root) { /** * The flusher's post that stores what the session measured, or null. Only a - * session whose prompt read the row in the checkout of `cwd` stores, a miss + * session that keeps the row of the checkout of `cwd` stores, a miss * included: it knows what it replaces, and where no prompt can read the row - * no session writes one. One `memory.set` follows where `revised` has a - * claim: a revision of the row as read (`if_match_sha256`, under the row's - * agent), else a first row (`absent`). It names the key and the repository - * of that read, from the session's state: a scope resolved again here may - * name another remote of the checkout, whose key no prompt reads. The value - * names no file to the server (`files: []`), and its class says a tool - * measured it. + * no session writes one. The row kept is the one a prompt read last + * (`costLine`): a session that ends in a checkout whose row it read before + * the row of another one stores nothing. One `memory.set` follows where + * `revised` has a claim: a revision of the row as read (`if_match_sha256`, + * under the row's agent), else a first row (`absent`). It names the key and + * the repository of that read, from the session's state: a scope resolved + * again here may name another remote of the checkout, whose key no prompt + * reads. The value names no file to the server (`files: []`), and its class + * says a tool measured it. */ export function costPost(sessionId, cwd) { try { diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index c40ff46a120..32af85efbef 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -511,7 +511,12 @@ test("an earlier short run's report is not that of a later short run that wrote // The report's cases, and a failure the report does not hold. note("1 error in 0.52s", report({ tests: 1, time: "0.6" })); note("1 failed, 11 passed in 1.10s", earlier); + // The two clocks are compared as written, not to the whole second: 1.49 s apart. + note("12 passed in 2.00s", report({ tests: 12, time: "0.51" })); assert.deepEqual(runs(), {}); + // 0.96 s apart: the report is the run's. + note("12 passed in 1.45s", report({ tests: 12, time: "0.49" })); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 12, seconds: 0 } } } }); // The summary of the run that wrote the report counts its cases and failures. note("12 passed in 1.38s", earlier); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 12, seconds: 1 } } } }); @@ -1283,6 +1288,22 @@ test("a session whose folder moves to another checkout reads and writes that rep await endSession(second); await settled(first); assert.deepEqual(none.sent("memory.set"), []); + + // The session keeps one row, the one read last: a bug report back in the first checkout + // reads its row again, and a session that ends there after a bug report in the second + // stores nothing. + const both = await loom(t); + const one = sandbox(t, both); + const two = checkout(one, path.join(one.dir, "lib"), origin, both); + for (const at of [one, two, one, two]) await ask(at); + assert.deepEqual( + both.sent("memory.get").map((r) => r.body.memory_key), + [KEY, `repo:${repo}/test-cost/pytest`, KEY, `repo:${repo}/test-cost/pytest`], + ); + await afterCommand(one, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + await endSession(one); + await settled(one); + assert.deepEqual(both.sent("memory.set"), []); }); test("a session's end writes to the key its prompt read, whatever remote the checkout's scope names by then", { diff --git a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs index c663619a7eb..142373b396f 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -48,10 +48,11 @@ // what a whole run of a slow test file costs in this repository // (lib/test-cost.mjs): the file, its case count and seconds, the seconds of a // run filtered with -k, and to check a change with -k selections. The row is -// read by its key once a session and checkout, beside the search and inside -// the prompt's bound, and the line is sent only when that read has answered -// by the time the search has: under the launcher the read never holds the -// pointers back. The git calls that resolve the checkout's scope for it can. +// read by its key, beside the search and inside the prompt's bound, unless +// the session keeps it: it keeps the row it read last, with the checkout it +// was read in. The line is sent only when that read has answered by the +// time the search has: under the launcher the read never holds the pointers +// back. The git calls that resolve the checkout's scope for it can. // Where no script of the prompt has resolved the scope in the process, they // run in this thread before the read is sent, each bounded at 1,500 ms (one // `git config` where the index's match is cached), and the search's answer is diff --git a/integrations/codex-plugin/hooks/loom-session-memory.mjs b/integrations/codex-plugin/hooks/loom-session-memory.mjs index 1041b8c0f5e..a606767e773 100644 --- a/integrations/codex-plugin/hooks/loom-session-memory.mjs +++ b/integrations/codex-plugin/hooks/loom-session-memory.mjs @@ -7,8 +7,9 @@ // // The same hand-off carries what the session's test runs cost, whether or // not its turns are sent: one memory.set of the repository's test cost row, -// where the session's runs of a test file say something the row one of its -// prompts read does not (lib/test-cost.mjs; LOOM_TEST_REPORT=off stops it). +// where the session's runs of a test file say something the row its prompts +// read last does not, in that row's checkout (lib/test-cost.mjs; +// LOOM_TEST_REPORT=off stops it). // The session's cost state is removed here, whatever is handed off. // // Off-switch: LOOM_SESSION_MEMORY=off. Needs a writer token; fire-and-forget diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 0abb092fd66..03280e85be7 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -20,9 +20,10 @@ // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers // (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the -// row to the flusher (`costPost`), where the session's runs say something -// the row it read does not (`revised`), under the key that read named, and -// removes the session's cost state whatever it stores (`endCost`). +// row to the flusher (`costPost`), where the session ends in the checkout of +// the row it read last and its runs say something that row does not +// (`revised`), under the key that read named, and removes the session's cost +// state whatever it stores (`endCost`). // // What leaves the machine is the file's path in the checkout, a case count // and seconds, under the repository's id. A path that holds a character @@ -50,9 +51,10 @@ const MAX_SAMPLES = 15; // The session's runs: `{ pending, files }`, by each file's absolute path. const RUNS = "test-cost"; -// The repository's row as the session read it in the checkout at `root`: -// `{ read, root, repo, asked, row }`, with the repository's id and the -// identity the read named (`identity`), which the session's end writes to. +// The repository's row as the session read it last, in the checkout at +// `root`: `{ read, root, repo, asked, row }`, with the repository's id and +// the identity the read named (`identity`), which the session's end writes +// to. It is one row: a read in another checkout takes its place. const ROW = "test-cost-row"; /** `file`, a path in the checkout, when it may be sent, else "". */ @@ -172,7 +174,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { cost && run.cases === cost.tests && run.failed === cost.failed && - Math.abs(run.seconds - cost.seconds) <= Math.max(1, run.seconds / 20); + Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); // The summary counts the skipped cases apart from the expected failures. if (own) add(state, run, { ...cost, skipped: run.skipped }); const settled = !own && settle(state, report); @@ -256,11 +258,13 @@ const identity = (scope) => ({ /** * The line for a prompt of a session that has the test report and has not * switched it off, in the checkout at `root`, or "": the repository's row, - * read once a session and checkout (`memory.get` by key, bounded by - * `options.timeoutMs`) and kept in the session's state, a miss too, with the - * agent that wrote it, the identity the read named and the checkout it was - * read in: a session whose folder moved to another checkout reads that - * one's row. `scopeOf()` is asked only for that read, before it is sent: + * read with `memory.get` by key (bounded by `options.timeoutMs`) and kept in + * the session's state, a miss too, with the agent that wrote it, the + * identity the read named and the checkout it was read in. The state keeps + * one row, the one read last, and a prompt in its checkout sends no read: a + * session whose folder moved to another checkout reads that one's row in + * its place, and one whose folder moved back reads the first one's again. + * `scopeOf()` is asked only for that read, before it is sent: * where the process has not resolved the checkout's scope yet, its git * calls run then, in the caller's thread. An answer that does not come and * an error give no line, and a later prompt asks again. A row gives none @@ -354,15 +358,17 @@ function measured(state, root) { /** * The flusher's post that stores what the session measured, or null. Only a - * session whose prompt read the row in the checkout of `cwd` stores, a miss + * session that keeps the row of the checkout of `cwd` stores, a miss * included: it knows what it replaces, and where no prompt can read the row - * no session writes one. One `memory.set` follows where `revised` has a - * claim: a revision of the row as read (`if_match_sha256`, under the row's - * agent), else a first row (`absent`). It names the key and the repository - * of that read, from the session's state: a scope resolved again here may - * name another remote of the checkout, whose key no prompt reads. The value - * names no file to the server (`files: []`), and its class says a tool - * measured it. + * no session writes one. The row kept is the one a prompt read last + * (`costLine`): a session that ends in a checkout whose row it read before + * the row of another one stores nothing. One `memory.set` follows where + * `revised` has a claim: a revision of the row as read (`if_match_sha256`, + * under the row's agent), else a first row (`absent`). It names the key and + * the repository of that read, from the session's state: a scope resolved + * again here may name another remote of the checkout, whose key no prompt + * reads. The value names no file to the server (`files: []`), and its class + * says a tool measured it. */ export function costPost(sessionId, cwd) { try { diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 36d2fb166cc..9f31debd22b 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -398,7 +398,7 @@ "integrations/claude-code-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/claude-code-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/claude-code-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "8d594f4b2bdfc40ca02b6b0fc10d366d2563b98149f86a1a8499c7f16b8e5189", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "628f10e392c2878876891294fbb11943edc2461f804d1b3faae30fddc2994d65", "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "31ba0130495c6cbd40a3e4e673d9709deafb0cefb0b655b117d22a2437502b78", "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/claude-code-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -410,11 +410,11 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "969858b366bf033e97c8d8c847ebc14c98ba2782e8442fa08080141b760236ab", + "integrations/claude-code-plugin/lib/test-cost.mjs": "e6b42131bcb59d230fd3339eff9f3f6a30f73873c7185d4f4febf5f9af90ce68", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "8d594f4b2bdfc40ca02b6b0fc10d366d2563b98149f86a1a8499c7f16b8e5189", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "628f10e392c2878876891294fbb11943edc2461f804d1b3faae30fddc2994d65", "integrations/codex-plugin/hooks/loom-session-start.mjs": "31ba0130495c6cbd40a3e4e673d9709deafb0cefb0b655b117d22a2437502b78", "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "969858b366bf033e97c8d8c847ebc14c98ba2782e8442fa08080141b760236ab", + "integrations/codex-plugin/lib/test-cost.mjs": "e6b42131bcb59d230fd3339eff9f3f6a30f73873c7185d4f4febf5f9af90ce68", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From c59df7bb78ce35baeaaa33d5dd58965d4eaf0fbd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:13:13 +0530 Subject: [PATCH 15/24] A second pytest run written with no space before it, and a cd to a folder not written plainly, are no file run fileRun counted one run for a command such as `pytest -q;pytest ::test_one -q`: the pattern that finds a run does not start after `;`, `&`, `|` or `(`, and the check of what follows the run let that part through as a run. The second run's summary and result file were then kept as the whole run of the file. Only the run's own simple command may now be a pytest run; every part after it reads output. A `cd` is followed only to a folder written with letters, digits and `._/-`. A quoted or escaped name was cut at its space and an option (`-P`) was read as the folder, so the run was noted for the file of the same path in the session's folder. The hooks reference says that a result file over 2 MB gets no digest and that its first 4,096 bytes are read for the run's cost. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- .../claude-code-plugin/hooks/HOOKS.md | 8 +++-- .../claude-code-plugin/lib/test-gate.mjs | 31 ++++++++++++------- .../tests/test-cost.test.mjs | 14 +++++++++ integrations/codex-plugin/lib/test-gate.mjs | 31 ++++++++++++------- 4 files changed, 60 insertions(+), 24 deletions(-) diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 069a66cda00..e28eb743976 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1354,7 +1354,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that (PostToolUseFailure, which Claude Code runs instead), the hook reads the result file only when a run wrote it since the session last saw it (its modification time or size changed), so a command that ran no pytest prints nothing. It reads - at most 2 MB, and nothing of a larger file. It prints nothing where the + at most 2 MB: a larger file gets no digest, and its first 4,096 bytes + are read for the run's cost. It prints nothing where the visible output already names a reason (one of pytest's `E` lines, or `FAILED` or `ERROR` summary lines with their messages, none of them cut: pytest cuts a summary line's message to 80 columns in a pipe and ends @@ -1459,7 +1460,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that (`--no-header tests`), so a run with such a word that names a Python file or a folder is noted as nothing too. The file is the one the command names, from the payload's folder and the command's one `cd`, - where it is there. + where it is there. A run after a move the hook does not follow is + noted as nothing: a second `cd`, `pushd`, a `cd` in a subshell that + closed, or a `cd` to a folder written with anything but letters, + digits and `._/-` (a quoted or escaped name, an option, `$`, `~`). The report is the command's when the command's visible output shows pytest's summary line with the cases, the failures and the seconds the report holds, the seconds within a second or a twentieth of them, diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index e87a33e88e6..6e63e6c7c00 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1325,13 +1325,16 @@ function closesParen(text) { // head, grep and echo, with no backquote and no redirect but one between // descriptors or to /dev/null. Anything else may change a file, and the // command's result row is later than that change. Quotes are not read, so -// a `|` or `;` inside one ends the simple command there. +// a `|` or `;` inside one ends the simple command there. `runs` is how many +// of the simple commands, from the first, may be a pytest run: `fileRun` +// allows its own and no other, since `PYTEST` does not count a run written +// straight after `;`, `&`, `|` or `(` (`-q;pytest `). const OUTPUT = /^\s*(?:(?:tail|head|grep|echo)(?=\s|$)|$)/; -const onlyRuns = (tail) => +const onlyRuns = (tail, runs = Infinity) => tail .replace(/\d?>(?:&\d|\s*\/dev\/null(?=[\s;&|)]|$))/g, " ") .split(/[;&|()\n]/) - .every((part) => !/[<>`]/.test(part) && (OUTPUT.test(part) || part.match(PYTEST))); + .every((part, at) => !/[<>`]/.test(part) && (OUTPUT.test(part) || (at < runs && part.match(PYTEST)))); // What a command may hold before the simple command of its pytest run: `cd`, // `export`, `source` and `.`, with no backquote. Anything else may start // pytest itself (`make test`, a script), and its last line and result file @@ -1371,6 +1374,10 @@ const CLUSTER = /^-[A-Za-z]+[km]/; // A run that names its own result file, or turns the result file off, // does not write the session's. const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; +// A folder as `cd` is followed to it: letters, digits and `._/-`. A quoted +// or escaped name is cut at its space, an option (`-P`) is no folder, and +// the shell expands `$`, `~` and a pattern. +const PLAIN_FOLDER = /^(?!-)[\w./-]+$/; // A Python file, or a test in one, as a word of a pytest command. const PYTHON_FILE = /\.py(?:::|$)/; // pytest's last line of a run that ended, whatever it counts: a run that @@ -1412,7 +1419,8 @@ const counted = (line, kinds) => * its last line and its result file count the cases it got to. Nor is a run * that anything follows in the command but `tail`, `head`, `grep` and `echo` * (`onlyRuns`), a redirect to a file aside: a runner started after it - * (`&& make test`, `; tox`) writes the session's result file and prints the + * (`&& make test`, `; tox`, a second pytest with no space before it, which + * `PYTEST` does not count) writes the session's result file and prints the * last line. Quotes are not read there or in the run's words (`PYTEST`), so * a run piped into `grep -E "passed|failed"` is none, and neither is one * with `-k "parse and (empty or nested)"`. Nor is a run that anything stands @@ -1426,10 +1434,11 @@ const counted = (line, kinds) => * every case; the rest run none), or a cluster of short flags that may hold * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second - * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder the shell - * expands). The word after a flag that may take a value is that value and no - * path (`BARE`); a short flag written with its value (`-rf`, `-kparse`, - * `-n4`) takes none after it. A long flag may take none (`--no-header`), and + * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder that is + * not written plainly, `PLAIN_FOLDER`). The word after a flag that may take + * a value is that value and no path (`BARE`); a short flag written with its + * value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag may take + * none (`--no-header`), and * the word after it is then a second path: a run with such a word that names * a Python file is none, and the others are `values`. The caller drops a run * where one of them names a folder (`--no-header tests`, and `--cov src` @@ -1442,12 +1451,12 @@ export function fileRun(command, output = "") { if (runs.length !== 1 || !ranHere(head) || !onlySetsUp(head)) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. - if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "))) return null; + if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; const cd = [...head.matchAll(CD)]; const followed = cd.length < 2 && (head.match(MOVE) || []).length === cd.length && - cd.every((m) => !/^-$|[$~`*?]/.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); + cd.every((m) => PLAIN_FOLDER.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; const values = []; @@ -1474,7 +1483,7 @@ export function fileRun(command, output = "") { if (whole && summary && /\b\d+ deselected\b/.test(summary)) return null; return { path: named[0], - dir: cd.length ? unquoted(cd[0][1]) : "", + dir: cd.length ? cd[0][1] : "", whole, seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, cases: summary ? counted(summary, "passed|failed|errors?|skipped|xfailed|xpassed") : null, diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 32af85efbef..58d186c070a 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -185,6 +185,12 @@ test("a command's one pytest run of one test file is whole or filtered with -k", test("a command with two pytest runs, two paths, another selection or no run of its own is no file run", () => { for (const command of [ `pytest ${FILE} -q; pytest ${FILE} -k parse`, + // A second run with no space before it. + `pytest ${FILE} -q;pytest ${FILE}::test_one -q`, + `pytest ${FILE} -x -q||pytest ${FILE}::test_one -q`, + `pytest ${FILE} -q&&py.test ${FILE} -k parse`, + `pytest ${FILE} -q|pytest ${FILE}::test_one -q`, + `pytest ${FILE} -q; echo $(pytest ${FILE}::test_one -q)`, `pytest ${FILE} tests/test_small.py`, `pytest tests ${FILE}`, "pytest tests/", @@ -217,6 +223,11 @@ test("a command with two pytest runs, two paths, another selection or no run of `pushd pkg && pytest ${FILE}`, `(cd pkg && make build); pytest ${FILE}`, `cd "$PKG" && pytest ${FILE}`, + // A folder that is not written plainly: its name is cut at a space, or is an option. + `cd "/work/My Projects/app" && pytest ${FILE}`, + `cd /work/My\\ Projects/app && pytest ${FILE}`, + `cd 'My Projects' && pytest ${FILE}`, + `cd -P pkg && pytest ${FILE}`, // A runner started after the run writes the result file and prints the last line. `pytest ${FILE} -q && make test`, `pytest ${FILE} -q 2>&1 | tail -3; tox`, @@ -530,6 +541,7 @@ test("a command that is no file run, or names a file that is not there, leaves n const note = (command, output) => noteCommand(SESSION, { command, output, report: read(WHOLE), cwd }); note("make test", "8000 passed in 140.21s"); note(`pytest ${FILE} -q; pytest ${FILE} -k parse`, WHOLE_OUTPUT); + note(`pytest ${FILE} -q;pytest ${FILE}::test_one -q`, WHOLE_OUTPUT); note(`pytest ${FILE} tests/test_small.py`, WHOLE_OUTPUT); // The word after a long flag names a folder: pytest ran it too, where the flag takes no value. note(`pytest ${FILE} --no-header tests`, WHOLE_OUTPUT); @@ -537,6 +549,8 @@ test("a command that is no file run, or names a file that is not there, leaves n note(`pytest ${FILE} --lf -q`, WHOLE_OUTPUT); note("pytest tests/test_gone.py -q", WHOLE_OUTPUT); note(`cd elsewhere && pytest ${FILE.replace("big", "gone")} -q`, WHOLE_OUTPUT); + // A run in a folder whose name the command quotes is not the session folder's file of that path. + note(`cd "/elsewhere/My Projects/app" && pytest ${FILE} -q`, WHOLE_OUTPUT); assert.equal(runs(), null); }); }); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index e87a33e88e6..6e63e6c7c00 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1325,13 +1325,16 @@ function closesParen(text) { // head, grep and echo, with no backquote and no redirect but one between // descriptors or to /dev/null. Anything else may change a file, and the // command's result row is later than that change. Quotes are not read, so -// a `|` or `;` inside one ends the simple command there. +// a `|` or `;` inside one ends the simple command there. `runs` is how many +// of the simple commands, from the first, may be a pytest run: `fileRun` +// allows its own and no other, since `PYTEST` does not count a run written +// straight after `;`, `&`, `|` or `(` (`-q;pytest `). const OUTPUT = /^\s*(?:(?:tail|head|grep|echo)(?=\s|$)|$)/; -const onlyRuns = (tail) => +const onlyRuns = (tail, runs = Infinity) => tail .replace(/\d?>(?:&\d|\s*\/dev\/null(?=[\s;&|)]|$))/g, " ") .split(/[;&|()\n]/) - .every((part) => !/[<>`]/.test(part) && (OUTPUT.test(part) || part.match(PYTEST))); + .every((part, at) => !/[<>`]/.test(part) && (OUTPUT.test(part) || (at < runs && part.match(PYTEST)))); // What a command may hold before the simple command of its pytest run: `cd`, // `export`, `source` and `.`, with no backquote. Anything else may start // pytest itself (`make test`, a script), and its last line and result file @@ -1371,6 +1374,10 @@ const CLUSTER = /^-[A-Za-z]+[km]/; // A run that names its own result file, or turns the result file off, // does not write the session's. const OWN_REPORT = /^(?:--junit-?xml\b|no:junitxml$)/; +// A folder as `cd` is followed to it: letters, digits and `._/-`. A quoted +// or escaped name is cut at its space, an option (`-P`) is no folder, and +// the shell expands `$`, `~` and a pattern. +const PLAIN_FOLDER = /^(?!-)[\w./-]+$/; // A Python file, or a test in one, as a word of a pytest command. const PYTHON_FILE = /\.py(?:::|$)/; // pytest's last line of a run that ended, whatever it counts: a run that @@ -1412,7 +1419,8 @@ const counted = (line, kinds) => * its last line and its result file count the cases it got to. Nor is a run * that anything follows in the command but `tail`, `head`, `grep` and `echo` * (`onlyRuns`), a redirect to a file aside: a runner started after it - * (`&& make test`, `; tox`) writes the session's result file and prints the + * (`&& make test`, `; tox`, a second pytest with no space before it, which + * `PYTEST` does not count) writes the session's result file and prints the * last line. Quotes are not read there or in the run's words (`PYTEST`), so * a run piped into `grep -E "passed|failed"` is none, and neither is one * with `-k "parse and (empty or nested)"`. Nor is a run that anything stands @@ -1426,10 +1434,11 @@ const counted = (line, kinds) => * every case; the rest run none), or a cluster of short flags that may hold * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second - * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder the shell - * expands). The word after a flag that may take a value is that value and no - * path (`BARE`); a short flag written with its value (`-rf`, `-kparse`, - * `-n4`) takes none after it. A long flag may take none (`--no-header`), and + * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder that is + * not written plainly, `PLAIN_FOLDER`). The word after a flag that may take + * a value is that value and no path (`BARE`); a short flag written with its + * value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag may take + * none (`--no-header`), and * the word after it is then a second path: a run with such a word that names * a Python file is none, and the others are `values`. The caller drops a run * where one of them names a folder (`--no-header tests`, and `--cov src` @@ -1442,12 +1451,12 @@ export function fileRun(command, output = "") { if (runs.length !== 1 || !ranHere(head) || !onlySetsUp(head)) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. - if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "))) return null; + if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; const cd = [...head.matchAll(CD)]; const followed = cd.length < 2 && (head.match(MOVE) || []).length === cd.length && - cd.every((m) => !/^-$|[$~`*?]/.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); + cd.every((m) => PLAIN_FOLDER.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; const values = []; @@ -1474,7 +1483,7 @@ export function fileRun(command, output = "") { if (whole && summary && /\b\d+ deselected\b/.test(summary)) return null; return { path: named[0], - dir: cd.length ? unquoted(cd[0][1]) : "", + dir: cd.length ? cd[0][1] : "", whole, seconds: summary ? Number(/ in ([\d.]+)s\b/.exec(summary)[1]) : null, cases: summary ? counted(summary, "passed|failed|errors?|skipped|xfailed|xpassed") : null, From fd169071177e1dd625adb402717a3d085f82a361 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:50:06 +0530 Subject: [PATCH 16/24] A run of a file git does not list in the checkout is not stored The session's end kept every measured file that lies under the checkout root. A whole run started after `cd .claude/worktrees/fix`, or of a file in a submodule or a folder git ignores, was then stored as the repository's row under that path: the row printed nothing in a clone that does not hold the path, and in the checkout a whole run of the same length of the checkout's own file could not take it. `measured` now keeps only the paths git lists in the checkout, tracked or untracked: one `git ls-files` for all of them, bounded at 1,000 ms, in the detached copy. A call that fails stores nothing. A test notes a slow whole run in a worktree under the checkout and in an ignored folder, and ends with no `memory.set`. The README's hook table and the Claude Code page said the cost line costs one `memory.get` a session. They now say what the hook does: one read, unless the session keeps the row it read in that checkout. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 7 ++- integrations/claude-code-plugin/README.md | 56 +++++++++---------- .../claude-code-plugin/hooks/HOOKS.md | 5 +- .../claude-code-plugin/lib/test-cost.mjs | 21 +++++-- .../tests/test-cost.test.mjs | 42 +++++++++++++- integrations/codex-plugin/lib/test-cost.mjs | 21 +++++-- tests/unit/session_content_senders.json | 4 +- 7 files changed, 114 insertions(+), 42 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index a7a59bbc6ba..0c604ff0602 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -94,7 +94,7 @@ end of this section are the exceptions. The plugin sends: the number of cases it collected and the seconds it and a filtered run of it took, to `memory.set` at the session's end, as one memory row a repository, which a run of a minute or more starts; a session that has the test report reads that row with one - `memory.get` at its first bug report + `memory.get` at a bug report, unless it keeps the row it read in that checkout ([what a whole run costs](#what-a-whole-run-costs); `LOOM_TEST_REPORT=off` stops both, `LOOM_SESSION_MEMORY=off` the write; Claude Code only); - a run record (the first prompt as its goal, the last reply) and a working-memory note @@ -1778,7 +1778,10 @@ miss, and goes under the agent that wrote the row, so it replaces no row the ses not see. It goes to the key the session's prompt read: the repository is not named again from the checkout's remotes at the session's end. Of the run, the file's path in the checkout, the number of cases and the seconds are sent; a path that holds a character outside letters, digits and `._/-`, is over 160 -characters or would be changed by the secret redaction is not sent. +characters or would be changed by the secret redaction is not sent. Neither is a file +git does not list in the checkout, tracked or untracked (one `git ls-files` at the +session's end): a file of a worktree or a submodule under the checkout is another +checkout's, and one git ignores is not the repository's. **What a prompt gets.** A prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index af6cf3a407e..8f6057368b0 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -276,33 +276,33 @@ 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`, `PreCompact`, `Stop`, `SessionEnd` | `loom-record.mjs` | The event's one process. Runs the scripts whose answer the session waits for in the hook itself, each for the tools its row below names and only where the [mode](#modes) runs its plane: after a tool call `loom-file-context`, `loom-mentor-hint`, `loom-blast-radius`, `loom-test-gate` (only after a shell command that may have written a file) and `loom-test-report` (only after one that starts a test runner), at `Stop` the gates the install runs. It prints their answers as one, each script's text on a line of its own: a file's memory and then its test line as one `additionalContext`, the gates' reasons as one block. 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 `loom-capture` records something of, at `Stop` and at `SessionEnd` that process is detached, so the session does not wait for their requests and the client, which ends a SessionEnd hook after 1.5 s, cannot cancel them. Before a compaction it is the hook itself, which exits when they have returned: the compaction's primer reads the note they write. | -| `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 via `context.pack`: the project's working-memory note, the profile, the session's memory stack and a few memories. In a new or cleared conversation whose prompts get the recall (`loom-prompt-recall.mjs`, which this plugin and Codex's wire, where it is on) the primer runs no memory search: the memories are the namespace's pinned rows and then its newest, five at most, and the recall searches with the prompt. Any other row arrives only when a prompt's recall finds it: a session whose recall abstains gets none. A resumed or compacted session, a session with `LOOM_PROMPT_RECALL=off` or `LOOM_PROMPT_CONTEXT=off` and a hand-wired client get the memories, decisions and procedures a search for the project finds instead. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index is read: no checkout, no remote, no answer, a repository this Loom does not index, one the session's principal is not a reader of, or one whose namespace the token does not name; an index still being built says so too. A new session whose MCP connection carries the checkout is told neither: the header helper sent the namespace, the server applies it to every `loom_code_*` call and adds the tag to a save, and a session with nothing else to hear starts with no text from the hook. 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. | -| `PostToolUse` (Read / Grep / Bash), `PreCompact` | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about a file the call read (its files facet) and attaches the rendered block to the read's result, at no model request: the first local read of a file in the checkout — `Read`, a `Grep` of one file, or a shell `cat` / `sed -n` / `head` / `tail` / `grep pattern file` — brings its memory, so a session that only reads, or that edits through the shell, gets it too. One lookup per session, agent context and file (a subagent's read does not use up the main agent's block); a compaction clears what was shown. A record the session already holds, given whole with the prompt or printed with the same line in another file's block, is left out, and a block with nothing new is not attached; a team rule, a decision and a constraint are printed under every file they name. A file with no memory adds nothing. Reads ask about at most three files per call and 40 per session, give the request 1 s and the call 2 s in all, and stop asking after three unanswered lookups. Where the mode runs the code index, a read or an edit that asks first renews a repository lookup that is ten minutes old, which brings the repository's shared rules; a read that this takes past its 2 s leaves the file for its next read or its edit. | -| `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Before an edit of a file this agent context has not been shown, the same lookup and block — a constraint arrives **before** the edit, not as a review comment. A file shown more than 30 min ago is asked about again, and a record handed more than 30 min ago is printed again; a team rule, a decision and a constraint are printed with every block. 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 test, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | -| `PostToolUse` (Bash / PowerShell) | `loom-test-gate.mjs` | **A changed file's own test is 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, for a file that has a test of its own, attaches its command and what the index knows of it: `Loom test for src/router.py: .venv/bin/python -m pytest -q -rf tests/test_router.py`, then `It is the one test file named for that file.` and what the checkout proves of the command. 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, a runner the checkout does not configure, a comment-only change and a prompt that ruled a test run out get nothing, and a command that only reads (`grep`, `cat`, `sed -n`, `git diff`) starts no git process and asks nothing (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | -| `PostToolUse`, `PostToolUseFailure` (Bash) | `loom-test-report.mjs` | **Why a test failed, on the run whose output was cut.** In a checkout that configures pytest, SessionStart adds its result-file option to `PYTEST_ADDOPTS` for the session's shell commands, so every pytest run writes a private result file. After a test command whose visible output names no failure's reason (`pytest ... \| tail -3`), the hook adds a digest of that file to the tool result: the totals, up to three groups of failures by message, each with its first test and where it was raised; at most 700 characters. The hook sends no request; it notes what a pytest run of one test file cost, which the session's end stores for a slow whole run (**The test report**, below). `LOOM_TEST_REPORT=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` (or the install option `prompt_recall`) for every prompt, `off` to disable; `LOOM_PROMPT_CONTEXT=off` disables it too ([what a prompt gets](#what-a-prompt-gets)). One `context.pack` per prompt restricted to `memories`, `decisions`, `procedures` with the prompt as the query; injects the records the session has not seen (each plane's under its tag; memories that answer alone under none), only when memory is not abstaining and `retrieval_confidence ≥ 0.5`, whole records within 1,600 chars (`LOOM_PROMPT_RECALL_MAX_CHARS`; one that does not fit is left out; a block's only record that the pack cut, or the first when none fits, is cut at its last whole sentence and names the call that reads it whole, the one the server's mark on the line names, or else the key to read it whole by). A record of code as it was before a commit the checkout's `HEAD` already has is left out, and a fix record whose commit it has is added as one line that names the commit. A record linked to a file of the checkout is added as one line, its key and that file, unless the prompt names the file or the definition, or asks memory: `loom-file-context` adds the record's own line after a local read of the file or before an edit of it. With `LOOM_FILE_CONTEXT=off`, or outside a checkout of a repository this Loom indexes, the prompt gets the record whole. 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` | Runs where the Loom the session talks to holds the checkout's own repository in its code index (`LOOM_PROMPT_PACK=off` stops it; [what a prompt gets](#what-a-prompt-gets)). One bounded lookup: `code.symbol`, `code.callers` or `code.impact` for an explicit named question, otherwise `code.search` (top 3, no bodies). The repository lookup and the answer share one bound (`LOOM_PROMPT_PACK_TIMEOUT_MS`, 2.5 s; a searched bug report asks for the server's pick and has 6 s): what comes later is skipped. 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), without abstention, and sends only the answer's places to edit, one pointer per place: a definition, a unit of a file the hook does not hold to definitions, a document or a test when the prompt names it or asks for documentation or tests, a Python migration or a release script only if named, and module-level code when it asks for tests; 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. Below the pointers of a search answer goes the test gate's line (**Tests at edit time**, below) when a pointer's definition is named in the prompt and its Python file has exactly one test file named after it, in a checkout that configures pytest; it adds no request and a session gets a test once. Below a bug report's pointers goes the repository's test cost line where an earlier session stored one (**The test report**, below, **What a whole run costs**): one `memory.get` a session, never waited for past the search. | -| `Stop` | `loom-test-gate.mjs` | **Off by default; with the `stop_test_gate` option (or `LOOM_TEST_GATE=stop`), holds a session that ran no test since its last code change.** A held stop costs the session at least one more model request, so it is yours to turn on. Then, 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 to run, in evidence order with a `run` command when the harness is derivable, and the touched definitions a coverage run measured unexecuted — and blocks the stop **once** per distinct change with a reason that names them. The second stop on the same change passes. 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 the gate at both events. | -| `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. A new or cleared conversation whose checkout is on another branch than the note names gets its primer without the note. 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. The body also names the files the session changed in its checkout (each path and the time it was last written, never its content), which decide the session's fix record whatever tool wrote them, and `HEAD` as the commit that holds them, when its history has a commit of the session's that touches every file its edit tool wrote (the tag `change:`). 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. The same hand-off carries one `memory.set` of what a slow whole run of one test file cost, where the session measured one and its bug report read the repository's row, whether or not its turns are sent (**The test report**, below). `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`, `PreCompact`, `Stop`, `SessionEnd` | `loom-record.mjs` | The event's one process. Runs the scripts whose answer the session waits for in the hook itself, each for the tools its row below names and only where the [mode](#modes) runs its plane: after a tool call `loom-file-context`, `loom-mentor-hint`, `loom-blast-radius`, `loom-test-gate` (only after a shell command that may have written a file) and `loom-test-report` (only after one that starts a test runner), at `Stop` the gates the install runs. It prints their answers as one, each script's text on a line of its own: a file's memory and then its test line as one `additionalContext`, the gates' reasons as one block. 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 `loom-capture` records something of, at `Stop` and at `SessionEnd` that process is detached, so the session does not wait for their requests and the client, which ends a SessionEnd hook after 1.5 s, cannot cancel them. Before a compaction it is the hook itself, which exits when they have returned: the compaction's primer reads the note they write. | +| `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 via `context.pack`: the project's working-memory note, the profile, the session's memory stack and a few memories. In a new or cleared conversation whose prompts get the recall (`loom-prompt-recall.mjs`, which this plugin and Codex's wire, where it is on) the primer runs no memory search: the memories are the namespace's pinned rows and then its newest, five at most, and the recall searches with the prompt. Any other row arrives only when a prompt's recall finds it: a session whose recall abstains gets none. A resumed or compacted session, a session with `LOOM_PROMPT_RECALL=off` or `LOOM_PROMPT_CONTEXT=off` and a hand-wired client get the memories, decisions and procedures a search for the project finds instead. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index is read: no checkout, no remote, no answer, a repository this Loom does not index, one the session's principal is not a reader of, or one whose namespace the token does not name; an index still being built says so too. A new session whose MCP connection carries the checkout is told neither: the header helper sent the namespace, the server applies it to every `loom_code_*` call and adds the tag to a save, and a session with nothing else to hear starts with no text from the hook. 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. | +| `PostToolUse` (Read / Grep / Bash), `PreCompact` | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about a file the call read (its files facet) and attaches the rendered block to the read's result, at no model request: the first local read of a file in the checkout — `Read`, a `Grep` of one file, or a shell `cat` / `sed -n` / `head` / `tail` / `grep pattern file` — brings its memory, so a session that only reads, or that edits through the shell, gets it too. One lookup per session, agent context and file (a subagent's read does not use up the main agent's block); a compaction clears what was shown. A record the session already holds, given whole with the prompt or printed with the same line in another file's block, is left out, and a block with nothing new is not attached; a team rule, a decision and a constraint are printed under every file they name. A file with no memory adds nothing. Reads ask about at most three files per call and 40 per session, give the request 1 s and the call 2 s in all, and stop asking after three unanswered lookups. Where the mode runs the code index, a read or an edit that asks first renews a repository lookup that is ten minutes old, which brings the repository's shared rules; a read that this takes past its 2 s leaves the file for its next read or its edit. | +| `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Before an edit of a file this agent context has not been shown, the same lookup and block — a constraint arrives **before** the edit, not as a review comment. A file shown more than 30 min ago is asked about again, and a record handed more than 30 min ago is printed again; a team rule, a decision and a constraint are printed with every block. 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 test, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | +| `PostToolUse` (Bash / PowerShell) | `loom-test-gate.mjs` | **A changed file's own test is 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, for a file that has a test of its own, attaches its command and what the index knows of it: `Loom test for src/router.py: .venv/bin/python -m pytest -q -rf tests/test_router.py`, then `It is the one test file named for that file.` and what the checkout proves of the command. 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, a runner the checkout does not configure, a comment-only change and a prompt that ruled a test run out get nothing, and a command that only reads (`grep`, `cat`, `sed -n`, `git diff`) starts no git process and asks nothing (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | +| `PostToolUse`, `PostToolUseFailure` (Bash) | `loom-test-report.mjs` | **Why a test failed, on the run whose output was cut.** In a checkout that configures pytest, SessionStart adds its result-file option to `PYTEST_ADDOPTS` for the session's shell commands, so every pytest run writes a private result file. After a test command whose visible output names no failure's reason (`pytest ... \| tail -3`), the hook adds a digest of that file to the tool result: the totals, up to three groups of failures by message, each with its first test and where it was raised; at most 700 characters. The hook sends no request; it notes what a pytest run of one test file cost, which the session's end stores for a slow whole run (**The test report**, below). `LOOM_TEST_REPORT=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` (or the install option `prompt_recall`) for every prompt, `off` to disable; `LOOM_PROMPT_CONTEXT=off` disables it too ([what a prompt gets](#what-a-prompt-gets)). One `context.pack` per prompt restricted to `memories`, `decisions`, `procedures` with the prompt as the query; injects the records the session has not seen (each plane's under its tag; memories that answer alone under none), only when memory is not abstaining and `retrieval_confidence ≥ 0.5`, whole records within 1,600 chars (`LOOM_PROMPT_RECALL_MAX_CHARS`; one that does not fit is left out; a block's only record that the pack cut, or the first when none fits, is cut at its last whole sentence and names the call that reads it whole, the one the server's mark on the line names, or else the key to read it whole by). A record of code as it was before a commit the checkout's `HEAD` already has is left out, and a fix record whose commit it has is added as one line that names the commit. A record linked to a file of the checkout is added as one line, its key and that file, unless the prompt names the file or the definition, or asks memory: `loom-file-context` adds the record's own line after a local read of the file or before an edit of it. With `LOOM_FILE_CONTEXT=off`, or outside a checkout of a repository this Loom indexes, the prompt gets the record whole. 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` | Runs where the Loom the session talks to holds the checkout's own repository in its code index (`LOOM_PROMPT_PACK=off` stops it; [what a prompt gets](#what-a-prompt-gets)). One bounded lookup: `code.symbol`, `code.callers` or `code.impact` for an explicit named question, otherwise `code.search` (top 3, no bodies). The repository lookup and the answer share one bound (`LOOM_PROMPT_PACK_TIMEOUT_MS`, 2.5 s; a searched bug report asks for the server's pick and has 6 s): what comes later is skipped. 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), without abstention, and sends only the answer's places to edit, one pointer per place: a definition, a unit of a file the hook does not hold to definitions, a document or a test when the prompt names it or asks for documentation or tests, a Python migration or a release script only if named, and module-level code when it asks for tests; 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. Below the pointers of a search answer goes the test gate's line (**Tests at edit time**, below) when a pointer's definition is named in the prompt and its Python file has exactly one test file named after it, in a checkout that configures pytest; it adds no request and a session gets a test once. Below a bug report's pointers goes the repository's test cost line where an earlier session stored one (**The test report**, below, **What a whole run costs**): one `memory.get`, unless the session keeps the row it read in that checkout, never waited for past the search. | +| `Stop` | `loom-test-gate.mjs` | **Off by default; with the `stop_test_gate` option (or `LOOM_TEST_GATE=stop`), holds a session that ran no test since its last code change.** A held stop costs the session at least one more model request, so it is yours to turn on. Then, 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 to run, in evidence order with a `run` command when the harness is derivable, and the touched definitions a coverage run measured unexecuted — and blocks the stop **once** per distinct change with a reason that names them. The second stop on the same change passes. 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 the gate at both events. | +| `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. A new or cleared conversation whose checkout is on another branch than the note names gets its primer without the note. 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. The body also names the files the session changed in its checkout (each path and the time it was last written, never its content), which decide the session's fix record whatever tool wrote them, and `HEAD` as the commit that holds them, when its history has a commit of the session's that touches every file its edit tool wrote (the tag `change:`). 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. The same hand-off carries one `memory.set` of what a slow whole run of one test file cost, where the session measured one and its bug report read the repository's row, whether or not its turns are sent (**The test report**, below). `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 names 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. On a server whose default scope is `all_mine`, the request of a checkout with a remote is also answered with the rows you wrote in your other namespaces; such a row reads ` (namespace ""): …`. 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. @@ -330,7 +330,7 @@ Loom adds no option on Windows, under Codex (which names no such file), with an In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. ``` -Only a session whose bug report read the row writes, a miss included. With no row, its costliest whole run is stored when it took 60 s or more. The row's own file is revised by the session's whole run of it when that is more than a quarter away from the stored seconds, down as well as up, and by its filtered time when the row has none or the session's is more than a quarter and two seconds away. Another file takes the row with a whole run of 60 s or more that is over a quarter longer, and any such run takes a row whose file the checkout no longer holds. The write names the value the session read and goes under the agent that wrote the row. Of the run, only the file's path in the checkout, the number of cases and the seconds are sent; a path the secret redaction would change is not sent. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: +Only a session whose bug report read the row writes, a miss included. With no row, its costliest whole run is stored when it took 60 s or more. The row's own file is revised by the session's whole run of it when that is more than a quarter away from the stored seconds, down as well as up, and by its filtered time when the row has none or the session's is more than a quarter and two seconds away. Another file takes the row with a whole run of 60 s or more that is over a quarter longer, and any such run takes a row whose file the checkout no longer holds. The write names the value the session read and goes under the agent that wrote the row. Of the run, only the file's path in the checkout, the number of cases and the seconds are sent; a path the secret redaction would change is not sent, and neither is a file git does not list in the checkout, tracked or untracked: one of a worktree or a submodule under it, or one git ignores. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: ```text Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index e28eb743976..1e99d2425fc 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1541,7 +1541,10 @@ about s.` The write revises the row the session read (`if_match_sha256`), count and the seconds. A path that holds a character outside letters, digits and `._/-`, is over 160 characters or is changed by the secret redaction is not sent, and neither is a file that is gone by the - session's end. + session's end or one git does not list in the checkout, tracked or + untracked (one `git ls-files` at the session's end, 1,000 ms at most): + a file of a worktree or a submodule under the checkout is another + checkout's, and one git ignores is not the repository's. `loom-prompt-pack` prints the row under a bug report's pointers (**The test cost line**, above). `LOOM_SESSION_MEMORY=off` stops the note and the write, and a session in code-only mode notes, stores and prints diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 03280e85be7..e4887aa0588 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -28,10 +28,12 @@ // What leaves the machine is the file's path in the checkout, a case count // and seconds, under the repository's id. A path that holds a character // outside letters, digits and `._/-`, is over 160 characters or is changed by -// the secret redaction is not sent. +// the secret redaction is not sent, and neither is a file git does not list +// in the checkout: one of a worktree or a submodule under it, or one it +// ignores (`measured`). import path from "node:path"; -import { gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; +import { git, gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; import { fileRun, isFile } from "./test-gate.mjs"; import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; @@ -346,14 +348,25 @@ export function revised(runs, row) { } /** What the session measured, by each file's path in the checkout at - * `root`, for the files that are still there and may be sent. */ + * `root`, for the files that are still there, may be sent and are the + * checkout's own: the ones git lists there, tracked or untracked (one + * bounded `git ls-files` for all of them). A file of another checkout under + * the root (a worktree, a submodule) and one git ignores are not listed. A + * git call that fails keeps none. */ function measured(state, root) { const runs = {}; for (const [file, seen] of Object.entries(state.files || {})) { const rel = isFile(file) ? sendable(pathUnder(root, file)) : ""; if (rel) runs[rel] = seen; } - return runs; + const paths = Object.keys(runs); + if (!paths.length) return runs; + const listed = git( + ["--literal-pathspecs", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], + root, + { timeoutMs: 1000, raw: true }, + ).split("\0"); + return Object.fromEntries(paths.filter((rel) => listed.includes(rel)).map((rel) => [rel, runs[rel]])); } /** diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 58d186c070a..2d51b1e35ea 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -1077,6 +1077,46 @@ test("a slow whole run of a file whose path is not sent stores nothing", { skip: assert.deepEqual(server.sent("memory.set"), []); }); +test("a slow whole run of a file that git does not list in the checkout stores nothing", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const trees = [ + // A worktree of the repository under the root: the file is that checkout's. + [ + ".claude/worktrees/fix", + (cwd, tree) => { + const git = (...a) => execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...a], { cwd }); + git("add", "."); + git("commit", "-qm", "c"); + git("worktree", "add", "-q", tree); + }, + ], + // A folder git ignores. + ["build", (cwd, tree) => fs.writeFileSync(path.join(cwd, ".gitignore"), `${tree}/\n`)], + ]; + for (const [at, [tree, make]] of trees.entries()) { + const box = sandbox(t, server); + make(box.cwd, tree); + const file = path.join(box.cwd, tree, FILE); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, ""); + // The session's prompt read the row, a miss: its end may store a first one. + await ask(box); + assert.equal(server.sent("memory.get").length, at + 1, tree); + await afterCommand(box, `cd ${tree} && python -m pytest ${FILE} -q`, WHOLE_OUTPUT, WHOLE); + assert.deepEqual( + readJsonFile(box.runs, null), + { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, + tree, + ); + await endSession(box); + await settled(box); + assert.equal(fs.existsSync(box.runs), false, tree); + } + assert.deepEqual(server.sent("memory.set"), []); +}); + test("a session's end with the test report switched off stores nothing and removes the session's cost state", { skip: WINDOWS, }, async (t) => { @@ -1182,7 +1222,7 @@ test("code-only mode notes nothing, stores nothing and prints no line", { skip: assert.deepEqual([box.runs, box.row].filter(fs.existsSync), []); }); -test("a bug report carries the repository's cost line under its pointers, from one read a session", { +test("a bug report carries the repository's cost line under its pointers, from one read while the session stays in the checkout", { skip: WINDOWS, }, async (t) => { const server = await loom(t, { get: row() }); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 03280e85be7..e4887aa0588 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -28,10 +28,12 @@ // What leaves the machine is the file's path in the checkout, a case count // and seconds, under the repository's id. A path that holds a character // outside letters, digits and `._/-`, is over 160 characters or is changed by -// the secret redaction is not sent. +// the secret redaction is not sent, and neither is a file git does not list +// in the checkout: one of a worktree or a submodule under it, or one it +// ignores (`measured`). import path from "node:path"; -import { gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; +import { git, gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; import { fileRun, isFile } from "./test-gate.mjs"; import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; @@ -346,14 +348,25 @@ export function revised(runs, row) { } /** What the session measured, by each file's path in the checkout at - * `root`, for the files that are still there and may be sent. */ + * `root`, for the files that are still there, may be sent and are the + * checkout's own: the ones git lists there, tracked or untracked (one + * bounded `git ls-files` for all of them). A file of another checkout under + * the root (a worktree, a submodule) and one git ignores are not listed. A + * git call that fails keeps none. */ function measured(state, root) { const runs = {}; for (const [file, seen] of Object.entries(state.files || {})) { const rel = isFile(file) ? sendable(pathUnder(root, file)) : ""; if (rel) runs[rel] = seen; } - return runs; + const paths = Object.keys(runs); + if (!paths.length) return runs; + const listed = git( + ["--literal-pathspecs", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], + root, + { timeoutMs: 1000, raw: true }, + ).split("\0"); + return Object.fromEntries(paths.filter((rel) => listed.includes(rel)).map((rel) => [rel, runs[rel]])); } /** diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 9f31debd22b..f494b4089be 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "e6b42131bcb59d230fd3339eff9f3f6a30f73873c7185d4f4febf5f9af90ce68", + "integrations/claude-code-plugin/lib/test-cost.mjs": "c007d5594b27569afb6c2b796df60629e1598834302651be007c1d821709eef7", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "e6b42131bcb59d230fd3339eff9f3f6a30f73873c7185d4f4febf5f9af90ce68", + "integrations/codex-plugin/lib/test-cost.mjs": "c007d5594b27569afb6c2b796df60629e1598834302651be007c1d821709eef7", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From ccb61e98b286b2442a18e618246a7134a1d0ad81 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:34:16 +0530 Subject: [PATCH 17/24] namespace.audit leaves reads of a repository's test cost row out of its exact-key counts The prompt hook reads the repository's test cost row with `memory.get` by its key, once in a session and checkout, whatever the session's agent does. The audit counted that read as an agent's exact-key read. In a namespace whose sessions sent 200 of them in a day and fewer than a twentieth as many `memory.search` or `memory.ask` calls, `exact_key_store` turned critical: the namespace-health hook then held one Stop in every session with the `/loom-optimize` line, and `context.pack` carried the health block. The audit now leaves reads of a key like `repo:%/test-cost/pytest` out of `gets`, `typed_gets` and the hot-key listing of `exact_key_store` (`HOOK_READ_KEYS`). The read is matched by its key: the hook's request names no consumer. `exact_key_store` is rule version 3 and `intentional_exact_key_reads` version 2. The reads still count as calls the ledger recorded. A test runs the summary and the check over 250 such reads, three other reads and one `memory.bulk_get`, and a contract test holds the key the hook's fixture names to the audit's pattern. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 15 +++--- docs/guides/optimize-namespace.md | 5 +- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 6 ++- server/identity/app/namespace_audit.py | 35 ++++++++++---- tests/unit/test_namespace_audit.py | 48 +++++++++++++++++-- tests/unit/test_plugin_memory_contract.py | 14 ++++++ 7 files changed, 104 insertions(+), 21 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 0c604ff0602..13a453e3a51 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1796,12 +1796,15 @@ read with one `memory.get`, sent beside the prompt's search and never waited for answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that -repository's row in its place. Before the read is sent the hook names the repository -from the checkout's git remote. Where no other hook of the prompt has done so, that is -one `git config` call as a rule, bounded at 1,500 ms, and the search's answer is taken -after it. The line is made of the row's path and numbers, so a -value someone rewrote is neither printed nor overwritten. A row whose whole run is under -60 s, or whose file the checkout does not hold, prints nothing. +repository's row in its place. `namespace.audit` leaves reads of the row's key out of its +exact-key count (`exact_key_store` from rule version 3), so the sessions that run the +plugin do not make their namespace read as a key-value store; a server whose rule is +older counts one read a session and checkout. Before the read is sent the hook names the +repository from the checkout's git remote. Where no other hook of the prompt has done so, +that is one `git config` call as a rule, bounded at 1,500 ms, and the search's answer is +taken after it. The line is made of the row's path and numbers, so a value someone rewrote +is neither printed nor overwritten. A row whose whole run is under 60 s, or whose file the +checkout does not hold, prints nothing. What it does not do: diff --git a/docs/guides/optimize-namespace.md b/docs/guides/optimize-namespace.md index bcf139a5e94..f9fe610694c 100644 --- a/docs/guides/optimize-namespace.md +++ b/docs/guides/optimize-namespace.md @@ -63,7 +63,10 @@ namespace is not healthy. From anywhere else, call `namespace.audit` over HTTP o Read `summary` first: - a `get_search_ratio` in the hundreds means the namespace is used as a key-value store - (reads of procedures, which are read back by key on purpose, are left out of it); + (reads of procedures, which are read back by key on purpose, are left out of it, and + `gets` leaves out the reads of a repository's test cost row, key + `repo:/test-cost/pytest`, which a coding-agent plugin's prompt hook sends in a + session whatever its agent does); - `unembedded_rows` above zero means rows search can never find. Then read the findings. Stop when `healthy` is true and nothing is `warning` or diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 8f6057368b0..779409811c4 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -336,7 +336,7 @@ Only a session whose bug report read the row writes, a miss included. With no ro Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that repository's row in its place. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index, and neither does a session that ends in another checkout than the one whose row it read last. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that repository's row in its place. `namespace.audit` leaves reads of the row's key out of its exact-key count (`exact_key_store` from rule version 3), so the read does not bring the namespace-health line; a server whose rule is older counts it. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index, and neither does a session that ends in another checkout than the one whose row it read last. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 1e99d2425fc..61824fa00b0 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -985,7 +985,11 @@ default 120 s timeout of a shell call. A run filtered with -k takes about read last: a later bug report in that checkout asks nothing, one in another checkout reads that repository's row in its place, and the session's end writes to the key of the row kept; a read that failed or - came late is asked again at the next bug report. The line is made of the + came late is asked again at the next bug report. namespace.audit leaves + reads of the row's key out of its exact-key count (`HOOK_READ_KEYS` in + server/identity/app/namespace_audit.py; `exact_key_store` from rule + version 3), so the read does not bring the namespace-health line; a + server whose rule is older counts it. The line is made of the row's path and numbers and never of its text: a value that is not the stored sentence prints nothing. Nor does a row whose whole run is under 60 s, or whose file the checkout does not hold. It needs the memory plane diff --git a/server/identity/app/namespace_audit.py b/server/identity/app/namespace_audit.py index e845a371809..a2647b6d362 100644 --- a/server/identity/app/namespace_audit.py +++ b/server/identity/app/namespace_audit.py @@ -127,6 +127,14 @@ # The key a ledger read names: the column over HTTP, the argument over MCP (whose rows # leave the column empty). A `memory.bulk_get` names no single key. _READ_KEY = "if(memory_key != '', memory_key, args['memory_key'])" +# A coding-agent plugin's prompt hook reads a repository's test cost row by its key in a +# session, whatever the session's agent does (`costKey` in +# integrations/claude-code-plugin/lib/test-cost.mjs): counting that read would grade the +# namespace by the plugin its sessions run. The hook's request names no consumer, so the +# read is known by its key: a LIKE pattern. +HOOK_READ_KEYS = "repo:%/test-cost/pytest" +# An exact-key read the object-store gauge counts. +_GET = f"operation IN {_LEDGER_GETS} AND {_READ_KEY} NOT LIKE {{hook_keys:String}}" # The reports on a namespace: their own ledger rows say nothing about whether the window's # calls were recorded. _REPORT_OPS = ( @@ -308,11 +316,14 @@ "exact_key_store": RuleContract( "usage_heuristic", # 2: reads of structured-by-design rows are left out of the gauge. - 2, + # 3: so is a coding-agent plugin's read of a repository's test cost row. + 3, windowed=True, exceptions=( "Reads of rows whose type is structured by design are not counted " - "(intentional_exact_key_reads)." + "(intentional_exact_key_reads), nor are reads of a repository's test cost row " + "(`repo:/test-cost/pytest`), which a coding-agent plugin's prompt hook reads " + "by its key in a session: such a read is matched by its key, whoever sent it." ), uncertainty=( "A workflow that reads known keys on purpose shows the same ratio, and the ledger " @@ -321,12 +332,17 @@ ), "intentional_exact_key_reads": RuleContract( "usage_heuristic", - 1, + # 2: a read of a test cost row, which exact_key_store leaves out, is not counted here. + 2, windowed=True, + exceptions=( + "A read of a repository's test cost row is not counted, whatever the row's type " + "(exact_key_store)." + ), uncertainty=( - "Only the structured-by-design types are recognised; other workflows that read by " - "key on purpose still count in exact_key_store. A read is matched by key, so a " - "read of another writer's row under a procedure's key counts as one. A " + "Only the structured-by-design types are recognised; an agent's other workflows " + "that read by key on purpose still count in exact_key_store. A read is matched by " + "key, so a read of another writer's row under a procedure's key counts as one. A " "`memory.bulk_get` (which names no single key) is not matched, nor is an MCP read " "of a key longer than the 200 characters its ledger row keeps." ), @@ -515,6 +531,7 @@ def __init__(self, ch: Any, inp: NamespaceAuditInput) -> None: "win": int(inp.window_seconds), "hot": int(HOT_KEY_READS), "inspectors": list(INSPECTOR_CONSUMERS), + "hook_keys": HOOK_READ_KEYS, "ns_types": sorted(NON_SEARCHABLE_TYPES), "structured": sorted(STRUCTURED_TYPES), "clip": int(EXCERPT_LIMIT), @@ -649,8 +666,8 @@ async def summary_ledger(self) -> None: SELECT countIf(operation NOT IN {_REPORT_OPS} AND kind != 'worker' AND ({_AGENT_CALL} OR operation IN {{state_changes:Array(String)}})) AS ledger_calls, - countIf(operation IN {_LEDGER_GETS} AND {_AGENT_CALL}) AS gets, - countIf(operation IN {_LEDGER_GETS} AND {_AGENT_CALL} + countIf({_GET} AND {_AGENT_CALL}) AS gets, + countIf({_GET} AND {_AGENT_CALL} AND {_READ_KEY} IN ({_TYPED_KEYS})) AS typed_gets, countIf(operation IN {_LEDGER_SEARCHES} AND {_AGENT_CALL}) AS searches, -- a write from the dashboard is a person using the namespace @@ -762,7 +779,7 @@ async def exact_key_store(self) -> None: SELECT read_key AS memory_key, reads, window_gets, sum(reads) OVER () AS hot_reads FROM (SELECT {_READ_KEY} AS read_key, count() AS reads, sum(count()) OVER () AS window_gets - {_LEDGER} AND operation IN {_LEDGER_GETS} + {_LEDGER} AND {_GET} AND {_READ_KEY} NOT IN ({_TYPED_KEYS}) GROUP BY read_key) WHERE {_HOT_KEY} diff --git a/tests/unit/test_namespace_audit.py b/tests/unit/test_namespace_audit.py index 596bbcc7450..e230a562b4e 100644 --- a/tests/unit/test_namespace_audit.py +++ b/tests/unit/test_namespace_audit.py @@ -1150,16 +1150,21 @@ async def test_hot_key_completeness_compares_counts_of_one_statement( # code: (rule version, its built-in thresholds now, the thresholds at that version) _THRESHOLDS = { "exact_key_store": ( - 2, + 3, ( na.EXACT_KEY_STORE_RATIO, na.EXACT_KEY_STORE_MIN_GETS, na.HOT_KEY_READS, tuple(sorted(na.STRUCTURED_TYPES)), + na.HOOK_READ_KEYS, ), - (20.0, 200, 20, ("procedural",)), + (20.0, 200, 20, ("procedural",), "repo:%/test-cost/pytest"), + ), + "intentional_exact_key_reads": ( + 2, + (tuple(sorted(na.STRUCTURED_TYPES)), na.HOOK_READ_KEYS), + (("procedural",), "repo:%/test-cost/pytest"), ), - "intentional_exact_key_reads": (1, (tuple(sorted(na.STRUCTURED_TYPES)),), (("procedural",),)), "hand_rolled_index_rows": ( 1, (na.INDEX_ROW_MIN_KEYS, na.INDEX_ROW_VALUE_CLIP, na._TOKEN_SPLIT_RE.pattern), @@ -1669,6 +1674,43 @@ async def test_a_procedure_read_over_mcp_is_left_out_of_the_object_store_gauge() assert exact.count == 21 and exact.samples == [{"memory_key": "team/fact", "reads": 21}] +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +@pytest.mark.asyncio +async def test_a_hooks_read_of_a_test_cost_row_is_left_out_of_the_object_store_gauge() -> None: + cost = "repo:315f533aed/test-cost/pytest" + rows = [ + _memory_row(cost, minutes_ago=10, value="a whole run of tests/test_big.py takes 140 s"), + # One read a session, over HTTP: the key in the column, a hit or a miss alike. + *(_ledger_row("memory.get", key=cost) for _ in range(150)), + *(_ledger_row("memory.get", key="repo:9f3c2a71be/test-cost/pytest") for _ in range(100)), + *(_ledger_row("memory.get", key="team/fact") for _ in range(3)), + # A read of several keys names none, and stays counted. + _ledger_row("memory.bulk_get"), + ] + audit = na.new_audit( + _inp(window_seconds=3600), + ch=_LocalCH(["memory", "agent_events", "agent_events_private"], rows), + ) + await audit.summary_ledger() + await audit.exact_key_store() + s = audit.summary + assert (s.gets, s.typed_gets, s.searches) == (4, 0, 0) + # The window's calls were recorded all the same. + assert s.ledger_calls == 254 + exact = _finding(audit, "exact_key_store") + assert exact.count == 4 and exact.severity == "info" and exact.samples == [] + # Counted, the same reads are an object store: 254 gets and no search. + counted = na.new_audit( + _inp(window_seconds=3600), + ch=_LocalCH(["memory", "agent_events", "agent_events_private"], rows), + ) + counted.params["hook_keys"] = "no/such/key" + await counted.summary_ledger() + await counted.exact_key_store() + assert counted.summary.gets == 254 + assert _finding(counted, "exact_key_store").severity == "critical" + + @pytest.mark.asyncio async def test_an_unpublished_projection_reads_on_and_marks_the_report_incomplete( monkeypatch: pytest.MonkeyPatch, diff --git a/tests/unit/test_plugin_memory_contract.py b/tests/unit/test_plugin_memory_contract.py index bcc47d88ea5..8130aca5823 100644 --- a/tests/unit/test_plugin_memory_contract.py +++ b/tests/unit/test_plugin_memory_contract.py @@ -1,8 +1,10 @@ """The test cost hooks send requests, and read a reply, that the memory wire models serve.""" import json +from fnmatch import fnmatchcase from pathlib import Path +from server.identity.app.namespace_audit import HOOK_READ_KEYS from server.memory.api.models_crud import MemoryGetInput, MemoryGetOutput, MemorySetInput from server.memory.domain.provenance import source_class_for from server.operations import read_projection @@ -36,3 +38,15 @@ def test_test_cost_requests_and_reply_match_the_memory_wire_models(): assert stored.files == [] # A class a request body may declare. assert source_class_for(default="asserted", requested=stored.source_class) == "external" + + +def test_the_audit_knows_the_key_the_prompt_hook_reads(): + """`namespace.audit` leaves the hook's read out of its exact-key gauge by the key it + names. A key the plugin changes fails here: the audit would count a read in every + session against the namespace.""" + wire = json.loads(_WIRE.read_text()) + key = wire["requests"]["memory.get"]["memory_key"] + assert key == wire["requests"]["memory.set"]["memory_key"] + # The pattern is a LIKE with no `_` and no escape: `%` is its only wildcard. + assert "_" not in HOOK_READ_KEYS and "\\" not in HOOK_READ_KEYS + assert fnmatchcase(key, HOOK_READ_KEYS.replace("%", "*")) From 46b8fc72270f6babc40c5a7021aa9b7f06e86ea2 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:16:57 +0530 Subject: [PATCH 18/24] The audit test reads a test cost row of a structured type The test of the audit's test cost exception wrote its one cost row as `semantic`, so `typed_gets` was 0 whether or not the typed count left the key out. It now also writes a second repository's cost row as `procedural` and reads it 30 times: the typed count stays 0, and with the pattern set to match no key those 30 reads are typed gets. The hooks reference names `fileRun` in lib/test-gate.mjs for the runs of a part of a file, of two runs and of two paths, which is where they are refused. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- integrations/claude-code-plugin/hooks/HOOKS.md | 6 +++--- tests/unit/test_namespace_audit.py | 12 +++++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 61824fa00b0..ebc6c459e3c 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1439,9 +1439,9 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`, which may run every case), a run that only collects or prints, and a command with two pytest runs or two paths are noted as - nothing (lib/test-cost.mjs). So is a run that anything follows in its - command but `tail`, `head`, `grep` and `echo`, a redirect of the run to - a file aside (`onlyRuns` in lib/test-gate.mjs): a runner started after + nothing (`fileRun` in lib/test-gate.mjs). So is a run that anything + follows in its command but `tail`, `head`, `grep` and `echo`, a + redirect of the run to a file aside (`onlyRuns`): a runner started after it (`&& make test`, `; tox`) writes the result file and prints the last line. So is a run that anything stands before in its command but `cd`, `export`, `source` and `.` (`onlySetsUp`): a command before it may diff --git a/tests/unit/test_namespace_audit.py b/tests/unit/test_namespace_audit.py index e230a562b4e..940c8700284 100644 --- a/tests/unit/test_namespace_audit.py +++ b/tests/unit/test_namespace_audit.py @@ -1678,10 +1678,16 @@ async def test_a_procedure_read_over_mcp_is_left_out_of_the_object_store_gauge() @pytest.mark.asyncio async def test_a_hooks_read_of_a_test_cost_row_is_left_out_of_the_object_store_gauge() -> None: cost = "repo:315f533aed/test-cost/pytest" + typed = "repo:4be07d21c6/test-cost/pytest" rows = [ _memory_row(cost, minutes_ago=10, value="a whole run of tests/test_big.py takes 140 s"), + # A cost row of a structured type: its reads are no typed reads either. + _memory_row( + typed, minutes_ago=10, memory_type="procedural", value="a whole run takes 90 s" + ), # One read a session, over HTTP: the key in the column, a hit or a miss alike. *(_ledger_row("memory.get", key=cost) for _ in range(150)), + *(_ledger_row("memory.get", key=typed) for _ in range(30)), *(_ledger_row("memory.get", key="repo:9f3c2a71be/test-cost/pytest") for _ in range(100)), *(_ledger_row("memory.get", key="team/fact") for _ in range(3)), # A read of several keys names none, and stays counted. @@ -1696,10 +1702,10 @@ async def test_a_hooks_read_of_a_test_cost_row_is_left_out_of_the_object_store_g s = audit.summary assert (s.gets, s.typed_gets, s.searches) == (4, 0, 0) # The window's calls were recorded all the same. - assert s.ledger_calls == 254 + assert s.ledger_calls == 284 exact = _finding(audit, "exact_key_store") assert exact.count == 4 and exact.severity == "info" and exact.samples == [] - # Counted, the same reads are an object store: 254 gets and no search. + # Counted, the same reads are an object store: 254 gets beside the typed 30, no search. counted = na.new_audit( _inp(window_seconds=3600), ch=_LocalCH(["memory", "agent_events", "agent_events_private"], rows), @@ -1707,7 +1713,7 @@ async def test_a_hooks_read_of_a_test_cost_row_is_left_out_of_the_object_store_g counted.params["hook_keys"] = "no/such/key" await counted.summary_ledger() await counted.exact_key_store() - assert counted.summary.gets == 254 + assert (counted.summary.gets, counted.summary.typed_gets) == (284, 30) assert _finding(counted, "exact_key_store").severity == "critical" From b4d39dfc2868a73e6c26c6e80578c875505fefbe Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:02:52 +0530 Subject: [PATCH 19/24] The mentor leaves reads of a repository's test cost row out of an agent's exact-key reads The prompt hook's memory.get names the session's agent and no consumer, so the mentor profile counted it among that agent's calls: 50 sessions in a week that each missed the row gave the agent the recall_by_key_only and reads_miss warnings, which grade it by the plugin it runs. The profile's operation counts and its keys asked and missed now leave out a memory.get whose key is like HOOK_READ_KEYS, the pattern namespace.audit already matches. The pattern moves to the module the audit and the mentor share, so the two read one value. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 7 ++- docs/features/namespaces-and-sharing.md | 9 ++- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 17 ++--- server/identity/app/namespace_audit.py | 9 +-- server/insights/store/mentor.py | 20 ++++-- server/memory/domain/namespace_shapes.py | 10 ++- tests/unit/test_mentor.py | 63 +++++++++++++++++++ tests/unit/test_plugin_memory_contract.py | 10 +-- 9 files changed, 115 insertions(+), 32 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 13a453e3a51..3391d1bc24d 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1797,9 +1797,10 @@ answer: a read that fails or is slow adds nothing, and the pointers are printed are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that repository's row in its place. `namespace.audit` leaves reads of the row's key out of its -exact-key count (`exact_key_store` from rule version 3), so the sessions that run the -plugin do not make their namespace read as a key-value store; a server whose rule is -older counts one read a session and checkout. Before the read is sent the hook names the +exact-key count (`exact_key_store` from rule version 3) and the mentor out of the agent's +exact-key reads, so the sessions that run the plugin make neither their namespace read as +a key-value store nor their agent as one that recalls by key alone; an older server +counts one read a session and checkout in both. Before the read is sent the hook names the repository from the checkout's git remote. Where no other hook of the prompt has done so, that is one `git config` call as a rule, bounded at 1,500 ms, and the search's answer is taken after it. The line is made of the row's path and numbers, so a value someone rewrote diff --git a/docs/features/namespaces-and-sharing.md b/docs/features/namespaces-and-sharing.md index 04d9efa95c0..1c6df8c43ec 100644 --- a/docs/features/namespaces-and-sharing.md +++ b/docs/features/namespaces-and-sharing.md @@ -432,9 +432,12 @@ erasure deletes every revision of its guide. ## The mentor `mentor.brief` returns advice for one agent with the evidence behind it: its calls over a window (default 7 days), -the planes the namespace offers, and each hint with the counts that fired it. `context.pack` renders up to three hints -at session start, and a successful response carries at most one (`hint` on MCP, `X-Loom-Hint` on HTTP), capped by -`LOOM_MENTOR_MAX_HINTS_PER_SESSION`. `loom mentor --org … --namespace … --agent …` prints the whole brief. See the +the planes the namespace offers, and each hint with the counts that fired it. The calls and the exact-key read counts +leave out a coding-agent plugin's read of a repository's test cost row (key `repo:/test-cost/pytest`), which its +prompt hook sends under the session's agent; the ladder below counts it, as a row the ledger records under the agent. +`context.pack` renders up to three hints at session start, and a successful response carries at most one (`hint` on +MCP, `X-Loom-Hint` on HTTP), capped by `LOOM_MENTOR_MAX_HINTS_PER_SESSION`. +`loom mentor --org … --namespace … --agent …` prints the whole brief. See the [mentor ops](../reference/operations/mentor.md). A brief's `usage_evidence` lists what the agent's use of Loom shows, one rung each, with diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 779409811c4..2d423bcd2bb 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -336,7 +336,7 @@ Only a session whose bug report read the row writes, a miss included. With no ro Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that repository's row in its place. `namespace.audit` leaves reads of the row's key out of its exact-key count (`exact_key_store` from rule version 3), so the read does not bring the namespace-health line; a server whose rule is older counts it. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index, and neither does a session that ends in another checkout than the one whose row it read last. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that repository's row in its place. `namespace.audit` leaves reads of the row's key out of its exact-key count (`exact_key_store` from rule version 3) and the mentor out of the agent's exact-key reads, so the read brings neither the namespace-health line nor the mentor's `recall_by_key_only` and `reads_miss` hints; an older server counts it in both. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index, and neither does a session that ends in another checkout than the one whose row it read last. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index ebc6c459e3c..fe05d3e5569 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -986,14 +986,15 @@ default 120 s timeout of a shell call. A run filtered with -k takes about another checkout reads that repository's row in its place, and the session's end writes to the key of the row kept; a read that failed or came late is asked again at the next bug report. namespace.audit leaves - reads of the row's key out of its exact-key count (`HOOK_READ_KEYS` in - server/identity/app/namespace_audit.py; `exact_key_store` from rule - version 3), so the read does not bring the namespace-health line; a - server whose rule is older counts it. The line is made of the - row's path and numbers and never of its text: a value that is not the - stored sentence prints nothing. Nor does a row whose whole run is under - 60 s, or whose file the checkout does not hold. It needs the memory plane - and a session that has the test report. + reads of the row's key out of its exact-key count (`exact_key_store` + from rule version 3) and the mentor out of the agent's exact-key reads + (`HOOK_READ_KEYS` in server/memory/domain/namespace_shapes.py), so the + read brings neither the namespace-health line nor the mentor's + `recall_by_key_only` and `reads_miss` hints; an older server counts it + in both. The line is made of the row's path and numbers and never of its + text: a value that is not the stored sentence prints nothing. Nor does a + row whose whole run is under 60 s, or whose file the checkout does not + hold. It needs the memory plane and a session that has the test report. **The listwise pick.** For a request that reads as a bug report (twelve words or more, or the vocabulary of a failure, as the search reads it) the search carries `rerank: "builtin:pick"`. On a server that names a pick diff --git a/server/identity/app/namespace_audit.py b/server/identity/app/namespace_audit.py index a2647b6d362..a26dfe95ea9 100644 --- a/server/identity/app/namespace_audit.py +++ b/server/identity/app/namespace_audit.py @@ -54,6 +54,7 @@ COORDINATION_SEGMENTS, COORDINATION_VALUE_CHARS, EPISODIC_BLOB_CHARS, + HOOK_READ_KEYS, STRUCTURED_TYPES, ) from server.observability.consumer import INSPECTOR_CONSUMERS @@ -127,13 +128,7 @@ # The key a ledger read names: the column over HTTP, the argument over MCP (whose rows # leave the column empty). A `memory.bulk_get` names no single key. _READ_KEY = "if(memory_key != '', memory_key, args['memory_key'])" -# A coding-agent plugin's prompt hook reads a repository's test cost row by its key in a -# session, whatever the session's agent does (`costKey` in -# integrations/claude-code-plugin/lib/test-cost.mjs): counting that read would grade the -# namespace by the plugin its sessions run. The hook's request names no consumer, so the -# read is known by its key: a LIKE pattern. -HOOK_READ_KEYS = "repo:%/test-cost/pytest" -# An exact-key read the object-store gauge counts. +# An exact-key read the object-store gauge counts: not a plugin hook's read of a test cost row. _GET = f"operation IN {_LEDGER_GETS} AND {_READ_KEY} NOT LIKE {{hook_keys:String}}" # The reports on a namespace: their own ledger rows say nothing about whether the window's # calls were recorded. diff --git a/server/insights/store/mentor.py b/server/insights/store/mentor.py index e0508e102b4..f98e09d2cb1 100644 --- a/server/insights/store/mentor.py +++ b/server/insights/store/mentor.py @@ -13,7 +13,7 @@ from server.core.grant_sql import LIVE_GRANT from server.core.repo_base import _CHClient, _default_client from server.memory.domain.memory_types import NON_SEARCHABLE_TYPES -from server.memory.domain.namespace_shapes import STRUCTURED_TYPES +from server.memory.domain.namespace_shapes import HOOK_READ_KEYS, STRUCTURED_TYPES from server.memory.domain.temporal_sql import served_status_sql from server.memory.domain.transcript_rows import TRANSCRIPT_ROW_SQL as _TRANSCRIPT_ROW from server.observability.consumer import INSPECTOR_CONSUMERS @@ -40,6 +40,15 @@ _LEDGER_NS = ( f"FROM {MASKED_EVENTS} WHERE {_SCOPE} AND {_WIN} AND kind != 'worker' AND {_AGENT_CALL}" ) +# A coding-agent plugin's prompt hook reads a repository's test cost row by its key under +# the session's agent, whatever that agent does (`HOOK_READ_KEYS`): counted among the +# agent's exact-key reads it would grade the agent by the plugin it runs. The read is known +# by the key it names, as in `namespace.audit`: the column over HTTP, the argument over +# MCP. The hook names no session, so the reads grouped by session do not hold it. +_NOT_HOOK_READ = ( + "NOT (operation = 'memory.get' " + "AND if(memory_key != '', memory_key, args['memory_key']) LIKE {hook_keys:String})" +) # A session the client named. '-' and '*' are what the transports write # when a call names none; a week of such calls is not one session. _REAL_SESSION = "session_id NOT IN ('', '-', '*')" @@ -89,6 +98,7 @@ def __init__( "ns": namespace, "agent": agent, "inspectors": list(INSPECTOR_CONSUMERS), + "hook_keys": HOOK_READ_KEYS, "win": int(window_seconds), "ttl": int(limits["ttl"]), "tracker_re": _TRACKER_TAG_RE, @@ -115,8 +125,9 @@ async def _one(self, sql: str, **extra: Any) -> dict[str, Any]: # -- the agent's own calls ------------------------------------------------ async def op_counts(self) -> dict[str, int]: + """The agent's calls by operation, a plugin hook's read of a test cost row left out.""" rows = await self._rows( - f"SELECT operation, count() AS n {_LEDGER_AGENT} " + f"SELECT operation, count() AS n {_LEDGER_AGENT} AND {_NOT_HOOK_READ} " "GROUP BY operation ORDER BY n DESC LIMIT 400" ) return {str(r["operation"]): int(r["n"]) for r in rows} @@ -215,7 +226,8 @@ async def credited_keys(self) -> dict[str, int]: async def key_reads(self) -> dict[str, int]: """Keys the agent's successful gets asked for and missed (the ledger's - `out_found`, `out_found_n` / `out_missing_n`).""" + `out_found`, `out_found_n` / `out_missing_n`), a plugin hook's read of a test + cost row left out.""" m = await self._one( f""" SELECT sumIf(if(args['out_found'] != '', 1, @@ -225,7 +237,7 @@ async def key_reads(self) -> dict[str, int]: sumIf(if(args['out_found'] = 'false', 1, toUInt64OrZero(args['out_missing_n'])), operation IN {_in(self.gets)}) AS keys_missed - {_LEDGER_AGENT} AND success = 1 + {_LEDGER_AGENT} AND success = 1 AND {_NOT_HOOK_READ} """ ) return {k: int(m.get(k) or 0) for k in ("keys_asked", "keys_missed")} diff --git a/server/memory/domain/namespace_shapes.py b/server/memory/domain/namespace_shapes.py index 333ee0c0aad..822dc80c2e7 100644 --- a/server/memory/domain/namespace_shapes.py +++ b/server/memory/domain/namespace_shapes.py @@ -4,7 +4,8 @@ namespace's rows by shape — a short hot value is coordination state, a huge episodic value is a blob, a procedural value is structured by design — and the mentor (insights/app/mentor.py) names the same shapes in its hints. Both -read the bounds from here so a hint and an audit finding never disagree. +read the bounds from here so a hint and an audit finding never disagree. The +key both know a plugin hook's read by (`HOOK_READ_KEYS`) is here for the same reason. """ from __future__ import annotations @@ -33,3 +34,10 @@ # be a document" is wrong about them, and would tell a namespace owner to # knowledge.upsert the procedures the plugin's own hooks captured. STRUCTURED_TYPES: frozenset[str] = frozenset({"procedural"}) + +# A coding-agent plugin's prompt hook reads a repository's test cost row by its key in a +# session, whatever the session's agent does (`costKey` in +# integrations/claude-code-plugin/lib/test-cost.mjs): counting that read would grade a +# namespace, or an agent, by the plugin its sessions run. The hook's request names no +# consumer, so the read is known by its key: a LIKE pattern. +HOOK_READ_KEYS = "repo:%/test-cost/pytest" diff --git a/tests/unit/test_mentor.py b/tests/unit/test_mentor.py index 763cd06077c..11576d5f8de 100644 --- a/tests/unit/test_mentor.py +++ b/tests/unit/test_mentor.py @@ -495,6 +495,69 @@ def test_reliance_rules_stay_quiet_below_their_floors(monkeypatch: pytest.Monkey assert not ({"relied_on_chunk_ids", "relied_on_missing_keys", "reads_miss"} & codes) +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_a_hooks_read_of_a_test_cost_row_is_not_one_of_the_agents_exact_key_reads() -> None: + from server.insights.store import mentor as store + + def call(operation: str, key: str = "", **args: str) -> str: + # A request id of its own: the table drops a repeat of an identical insert. + pairs = ", ".join(f"'{k}', '{v}'" for k, v in args.items()) + return ( + "INSERT INTO loom.agent_events (org, namespace, agent, operation, memory_key, " + f"kind, success, args, request_id, ts) VALUES ('o', 'ns', 'claude-code', " + f"'{operation}', '{key}', 'request', 1, map({pairs}), generateUUIDv4(), now())" + ) + + class _Local: + async def query_all(self, sql: str, params: dict[str, Any] | None = None) -> Any: + tables = [ddl("agent_events"), ddl("agent_events_private")] + return run([*tables, *rows], sql, params) + + async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> Any: + found = await self.query_all(sql, params) + return found[0] if found else None + + cost = "repo:315f533aed/test-cost/pytest" + rows = [ + # One read a session over HTTP, the key in the column: no row yet, so each misses. + *(call("memory.get", cost, out_found="false") for _ in range(50)), + # Another repository's row answers. + *(call("memory.get", "repo:9f3c2a71be/test-cost/pytest", out_found="true") for _ in "ab"), + # The same key over MCP, which records it in `args`. + call("memory.get", memory_key=cost, out_found="false"), + # The agent's own reads stay counted, and so does a read that names no single key. + call("memory.get", "team/fact", out_found="true"), + call("memory.get", "team/gone", out_found="false"), + call("memory.bulk_get", out_found_n="4", out_missing_n="1"), + call("memory.search"), + ] + + def profile(hook_keys: str | None = None) -> tuple[dict[str, int], dict[str, int], set[str]]: + reads = store.ProfileReads( + "o", + "ns", + "claude-code", + 7 * 86400, + ops={"sets": (), "gets": mentor_rules.GETS, "searches": (), "packs": ()}, + limits=dict.fromkeys(("ttl", "large", "huge", "advisory", "clip", "episodic_chars"), 1), + ch=_Local(), + ) + if hook_keys is not None: + reads.params["hook_keys"] = hook_keys + usage, facts = asyncio.run(reads.op_counts()), asyncio.run(reads.key_reads()) + hints = mentor_rules.evaluate_rules(usage, 50, facts, agent="claude-code", max_hints=32) + return usage, facts, {h.code for h in hints} + + usage, facts, codes = profile() + assert usage == {"memory.get": 2, "memory.bulk_get": 1, "memory.search": 1} + assert facts == {"keys_asked": 7, "keys_missed": 2} + assert not ({"recall_by_key_only", "reads_miss"} & codes) + # Counted, the same rows are an agent that reads by key alone and misses. + usage, facts, codes = profile(hook_keys="no/such/key") + assert usage["memory.get"] == 55 and facts == {"keys_asked": 60, "keys_missed": 53} + assert {"recall_by_key_only", "reads_miss"} <= codes + + def test_a_missing_fact_keeps_its_rule_quiet_and_lands_in_skipped( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/tests/unit/test_plugin_memory_contract.py b/tests/unit/test_plugin_memory_contract.py index 8130aca5823..218c15e034b 100644 --- a/tests/unit/test_plugin_memory_contract.py +++ b/tests/unit/test_plugin_memory_contract.py @@ -4,8 +4,8 @@ from fnmatch import fnmatchcase from pathlib import Path -from server.identity.app.namespace_audit import HOOK_READ_KEYS from server.memory.api.models_crud import MemoryGetInput, MemoryGetOutput, MemorySetInput +from server.memory.domain.namespace_shapes import HOOK_READ_KEYS from server.memory.domain.provenance import source_class_for from server.operations import read_projection @@ -40,10 +40,10 @@ def test_test_cost_requests_and_reply_match_the_memory_wire_models(): assert source_class_for(default="asserted", requested=stored.source_class) == "external" -def test_the_audit_knows_the_key_the_prompt_hook_reads(): - """`namespace.audit` leaves the hook's read out of its exact-key gauge by the key it - names. A key the plugin changes fails here: the audit would count a read in every - session against the namespace.""" +def test_the_audit_and_the_mentor_know_the_key_the_prompt_hook_reads(): + """`namespace.audit` and the mentor leave the hook's read out of their exact-key counts + by the key it names. A key the plugin changes fails here: they would count a read in + every session against the namespace and the session's agent.""" wire = json.loads(_WIRE.read_text()) key = wire["requests"]["memory.get"]["memory_key"] assert key == wire["requests"]["memory.set"]["memory_key"] From 31fc92da5f12e1b4811c194bc2eb1ad82cc87904 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:42:43 +0530 Subject: [PATCH 20/24] The wire comments name the test cost reads the counts leave out `mentor.brief` `usage` and the `gets` of the `namespace.audit` summary leave out a `memory.get` of a repository's test cost row, and their field comments still read as counts of every call. Both now name the exception, the comment on `planes` says its calls are summed from `usage`, and the mentor reference page is regenerated. The prompt hook's `testLine` comment said the test gate's library is loaded only for a prompt that has a test file. A bug report's cost line loads it too, with lib/test-cost.mjs, whether or not the session has a test report: the two comments say so. No behaviour changes; the file pins follow the new bytes. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/reference/operations/mentor.md | 4 ++-- .../claude-code-plugin/hooks/loom-prompt-pack.mjs | 10 ++++++---- integrations/codex-plugin/hooks/loom-prompt-pack.mjs | 10 ++++++---- server/identity/api/models_namespace_catalog.py | 4 +++- server/insights/api/models_mentor.py | 7 +++++-- tests/unit/session_content_senders.json | 4 ++-- 6 files changed, 24 insertions(+), 15 deletions(-) diff --git a/docs/reference/operations/mentor.md b/docs/reference/operations/mentor.md index 09a9522089c..b698e97fcde 100644 --- a/docs/reference/operations/mentor.md +++ b/docs/reference/operations/mentor.md @@ -29,8 +29,8 @@ One agent's usage profile and the store's hints. | `window_seconds` | `int` | The window the profile was computed over, in seconds; a profile served from the cache keeps the window it was computed with. | | `computed_at` | `datetime` | When the profile was computed (UTC); older than the call when served from the cache. | | `sessions` | `int` | Distinct client-named sessions of this agent in the window (`-` and `*` not counted). | -| `usage` | `dict[str, int]` | Calls per operation by this agent in the window. | -| `planes` | `list[MentorPlane]` | Every plane the mentor knows, with this agent's calls to it and whether it is available. | +| `usage` | `dict[str, int]` | Calls per operation by this agent in the window, leaving out a `memory.get` of a repository's test cost row (key `repo:/test-cost/pytest`), which a coding-agent plugin's prompt hook sends under the agent. | +| `planes` | `list[MentorPlane]` | Every plane the mentor knows, with this agent's calls to it (the sum of its ops' `usage` counts) and whether it is available. | | `hints` | `list[MentorHint]` | The rules that fired for this agent, each with the counts that fired it; empty when none. | | `adoption` | `list[MentorAdoption]` | Per hint code, sessions it was shown in and followed in, most shown first; empty when no hint reached the agent or the read failed. | | `usage_evidence` | `list[UsageRung]` | The agent's use of Loom in the window, one rung each, weakest claim first: from a call made to a graded run. | diff --git a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index 142373b396f..95081cc37e3 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -219,9 +219,9 @@ function renderLookup(lookup, body, response, repo) { /** The test line for the pointers of a search answer that were sent, or "": * for the file `checkPointer` reads from them, inside what is left of the - * prompt's bound, which ends at `until`. The test gate's library is loaded only - * for a prompt that has such a file, and the test is noted so the gate does not - * name it again. */ + * prompt's bound, which ends at `until`. It loads the test gate's library only + * for a prompt that has such a file (a bug report's cost line loads it too: + * `costNote`), and the test is noted so the gate does not name it again. */ async function testLine(pointers, prompt, root, payload, until) { const rel = checkPointer(pointers, prompt); const left = until - Date.now(); @@ -234,7 +234,9 @@ async function testLine(pointers, prompt, root, payload, until) { } /** The test cost line of the session's repository, or "" (`costLine` in - * lib/test-cost.mjs, loaded only for a bug report). Never rejects. `main` + * lib/test-cost.mjs, loaded only for a bug report, with the test gate's and + * the test report's libraries it imports, whether or not the session has a + * test report). Never rejects. `main` * does not wait for it when the search answers first, and neither does the * launcher, which exits with the answer; a script started on its own stays * until the read has settled or the exit grace has passed (`scheduleExit`). */ diff --git a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs index 142373b396f..95081cc37e3 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -219,9 +219,9 @@ function renderLookup(lookup, body, response, repo) { /** The test line for the pointers of a search answer that were sent, or "": * for the file `checkPointer` reads from them, inside what is left of the - * prompt's bound, which ends at `until`. The test gate's library is loaded only - * for a prompt that has such a file, and the test is noted so the gate does not - * name it again. */ + * prompt's bound, which ends at `until`. It loads the test gate's library only + * for a prompt that has such a file (a bug report's cost line loads it too: + * `costNote`), and the test is noted so the gate does not name it again. */ async function testLine(pointers, prompt, root, payload, until) { const rel = checkPointer(pointers, prompt); const left = until - Date.now(); @@ -234,7 +234,9 @@ async function testLine(pointers, prompt, root, payload, until) { } /** The test cost line of the session's repository, or "" (`costLine` in - * lib/test-cost.mjs, loaded only for a bug report). Never rejects. `main` + * lib/test-cost.mjs, loaded only for a bug report, with the test gate's and + * the test report's libraries it imports, whether or not the session has a + * test report). Never rejects. `main` * does not wait for it when the search answers first, and neither does the * launcher, which exits with the answer; a script started on its own stays * until the read has settled or the exit grace has passed (`scheduleExit`). */ diff --git a/server/identity/api/models_namespace_catalog.py b/server/identity/api/models_namespace_catalog.py index 89a51d48e47..0eb5b0e1c1e 100644 --- a/server/identity/api/models_namespace_catalog.py +++ b/server/identity/api/models_namespace_catalog.py @@ -347,7 +347,9 @@ class NamespaceAuditSummary(BaseModel): # Searchable-type embedding rows the worker gave up on with an error of their own (a # row still being retried, or whose model call was held or unbilled, is index_backlog). unembedded_rows: int = 0 - # Ledger counts over `window_seconds`. + # Ledger counts over `window_seconds`. `gets` leaves out the reads of a repository's test + # cost row (key `repo:/test-cost/pytest`), which a coding-agent plugin's prompt hook + # sends in a session whatever its agent does. gets: int = 0 searches: int = 0 sets: int = 0 diff --git a/server/insights/api/models_mentor.py b/server/insights/api/models_mentor.py index 75eddb9019c..c398ac05030 100644 --- a/server/insights/api/models_mentor.py +++ b/server/insights/api/models_mentor.py @@ -103,9 +103,12 @@ class MentorBriefOutput(BaseModel): computed_at: datetime # Distinct client-named sessions of this agent in the window (`-` and `*` not counted). sessions: int - # Calls per operation by this agent in the window. + # Calls per operation by this agent in the window, leaving out a `memory.get` of a + # repository's test cost row (key `repo:/test-cost/pytest`), which a coding-agent + # plugin's prompt hook sends under the agent. usage: dict[str, int] = Field(default_factory=dict) - # Every plane the mentor knows, with this agent's calls to it and whether it is available. + # Every plane the mentor knows, with this agent's calls to it (the sum of its ops' `usage` + # counts) and whether it is available. planes: list[MentorPlane] = Field(default_factory=list) # The rules that fired for this agent, each with the counts that fired it; empty when none. hints: list[MentorHint] = Field(default_factory=list) diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index f494b4089be..2820b7fb3db 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -398,7 +398,7 @@ "integrations/claude-code-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/claude-code-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/claude-code-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "628f10e392c2878876891294fbb11943edc2461f804d1b3faae30fddc2994d65", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "d993b1bb9819f14595314bc41b3edfe98f894bfbd46c2e516c6846d7e8e9828c", "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "31ba0130495c6cbd40a3e4e673d9709deafb0cefb0b655b117d22a2437502b78", "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/claude-code-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", @@ -414,7 +414,7 @@ "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", - "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "628f10e392c2878876891294fbb11943edc2461f804d1b3faae30fddc2994d65", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "d993b1bb9819f14595314bc41b3edfe98f894bfbd46c2e516c6846d7e8e9828c", "integrations/codex-plugin/hooks/loom-session-start.mjs": "31ba0130495c6cbd40a3e4e673d9709deafb0cefb0b655b117d22a2437502b78", "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", From 3fca7678d61fe514f1f9d9f90a721b96c97d371f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:28:27 +0530 Subject: [PATCH 21/24] A report of a run that lost its place as the pending run is counted for no later run The session's cost state keeps the time by which a pending run that was replaced or dropped had begun, and `settle` counts no report of a run that began by then. Without it the late report of a dropped `-k` run was stored as the whole run of the file's next pending run, and a whole run's as a filtered time. `fileRun` leaves a redirect between descriptors (`2>&1`) out of the command before it reads the run's words: `PYTEST` ended them at the `&`, so a second path written after one was not read and both files' cases counted as the first file's whole run. Such a command is now no file run, and a `-k` written there makes a filtered run. The settings table of HOOKS.md names the test report hook as a reader of `LOOM_SESSION_MEMORY`. The Codex copy and the file pins follow the new bytes. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 10 +-- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 12 ++-- .../claude-code-plugin/lib/test-cost.mjs | 21 +++++-- .../claude-code-plugin/lib/test-gate.mjs | 12 ++-- .../tests/test-cost.test.mjs | 63 +++++++++++++++---- integrations/codex-plugin/lib/test-cost.mjs | 21 +++++-- integrations/codex-plugin/lib/test-gate.mjs | 12 ++-- tests/unit/session_content_senders.json | 4 +- 9 files changed, 116 insertions(+), 41 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 3391d1bc24d..d83072d5b5f 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1707,7 +1707,7 @@ session's private state, by the file: counts, apart from the expected failures (`xfail`); - a run with no `-k` in its command whose summary line counts deselected cases counts as neither: a selection the command does not show left cases out (one in `PYTEST_ADDOPTS` - or the repository's pytest settings, or one written after `2>&1`); + or the repository's pytest settings); - a run pytest ended before its last case counts as neither: at a failure limit (`-x`, `--maxfail`), at an error during collection, at an interrupt or at `pytest.exit`. The line pytest prints above its summary line says so (`stopping after 1 failures` between @@ -1828,9 +1828,11 @@ What it does not do: - the session keeps one run that outlives its call. A later one of another test file takes its place, and the earlier run is not counted. A later one of the same file and the other kind, whole after `-k` or `-k` after whole, drops both, since the earlier - run's result file would be counted as the later run's. A run that ended in its call - with no summary line and no result file, such as one whose pytest refused an option of - the command, is kept as if it were open, and drops a later run in the same way; + run's result file would be counted as the later run's. The result file of a run that + was replaced or dropped counts for no run the session keeps later. A run that ended in + its call with no summary line and no result file, such as one whose pytest refused an + option of the command, is kept as if it were open, and drops a later run in the same + way; - a run whose output shows no summary line is taken to have ended in its call when the hook reads a result file of its test file with it. Where an earlier run of that file left the result file unread and the run itself went to the background, the run is not diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 2d423bcd2bb..45c6192b43e 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that anything stands before in its command but `cd`, `export`, `source` and `.` (`make test || pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that anything stands before in its command but `cd`, `export`, `source` and `.` (`make test || pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index fe05d3e5569..55104a97d02 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1455,8 +1455,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that `-k "parse and (empty or nested)"` are noted as nothing. So is a run with no `-k` among its words whose last line counts deselected cases: a selection the words do not show left cases out, one in - `PYTEST_ADDOPTS` or the settings file, or one written after `2>&1`, - where the words end. A run that outlived its shell call shows no last + `PYTEST_ADDOPTS` or the settings file. A run that outlived its shell + call shows no last line, and such a run is counted as a whole run with the cases it ran. A whole run started with xdist workers (`-n`) counts with the seconds it took: the row does not say how its run was started, so a session that @@ -1502,7 +1502,11 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that pending run of another file, whose report is then no run's. One of the other kind of the pending run's file, whole after `-k` or `-k` after whole, drops both, since the pending run's report would be counted as - the later run's. A run that ended in its call with no last line and no + the later run's. A run that lost its place may still write its report: + the state keeps the time by which it had begun (the time the replaced + run's command returned, or the later run's where both are dropped), and + a report of a run that began by then is no later pending run's. A run + that ended in its call with no last line and no report, such as one whose pytest refused an option of the command, is pending like an open one, and drops a later run in the same way. The session has one result file, and no hook runs between two @@ -1765,7 +1769,7 @@ Switches read on/true/1/yes and off/false/0/no. Defaults in parentheses. | `LOOM_CAPTURE_CONVERSATIONS` (on), `LOOM_CONV_SETTLE_MS` (350) | conversation | capture; wait for the last reply to flush | | `LOOM_USAGE` (on) | usage | usage counters | | `LOOM_WORKING_MEMORY` (on), `LOOM_PLUGIN_SCRATCHPAD` (off) | working-memory | the note; the per-turn scratchpad | -| `LOOM_SESSION_MEMORY` (on) | session-memory | the session hand-off | +| `LOOM_SESSION_MEMORY` (on) | session-memory, test-report | the session hand-off; the test cost note | | `LOOM_MENTOR_HINTS` (on) | mentor-hint | mentor hints | | `LOOM_NAMESPACE_HEALTH` (on) | namespace-health | the session's namespace audit | | `LOOM_MCP_CODE_SCOPE` (on) | headers helper, session-start | the X-Loom-Code-Scope header | diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index e4887aa0588..c15850a6672 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -51,7 +51,9 @@ const MAX_PATH = 160; const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, files }`, by each file's absolute path. +// The session's runs: `{ pending, dropped, files }`, by each file's absolute +// path. `dropped` is the time by which a run that lost its place as the +// pending one had begun. const RUNS = "test-cost"; // The repository's row as the session read it last, in the checkout at // `root`: `{ read, root, repo, asked, row }`, with the repository's id and @@ -126,12 +128,15 @@ function add(state, run, cost) { * not a hook saw it, began its run after that. A run of the file that * something else started while the pending run was in its call began before * it too: its report, read with a command that is not that run, is taken - * for the pending run's. The pending run is then settled; any other report - * leaves it pending. */ + * for the pending run's. A run that began by the time an earlier pending + * run had (`dropped`) may be that run, whose report is no later run's. The + * pending run is then settled; any other report leaves it pending. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; const pending = state.pending; - if (!cost || !pending || !ofFile(pending, cost) || report.mtimeMs - cost.time * 1000 > pending.at) return false; + if (!cost || !pending || !ofFile(pending, cost)) return false; + const began = report.mtimeMs - cost.time * 1000; + if (began > pending.at || began <= (state.dropped ?? 0)) return false; add(state, pending, cost); state.pending = undefined; return true; @@ -160,7 +165,11 @@ function settle(state, report) { * the run may still be open, and is then not counted. An open run takes the * place of a pending run of another file, whose report is then no run's. An * open run of the other kind of the pending run's file drops both: the - * pending run's report would be counted as the later run's. + * pending run's report would be counted as the later run's. A run that lost + * its place may still write its report, so the state keeps the time by which + * it had begun (`dropped`): the time the replaced run's command returned, or + * this one's where both are dropped. A report of a run that began by then is + * no later pending run's (`settle`). */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { @@ -185,6 +194,8 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { if (open && (!cost || settled || !ofFile(run, cost))) { const pending = state.pending; const other = pending && pending.file === run.file && pending.whole !== run.whole; + if (other) state.dropped = Date.now(); + else if (pending && pending.file !== run.file) state.dropped = pending.at; state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } writeSessionState(RUNS, sessionId, state); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 6e63e6c7c00..a99a8e1081b 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1413,9 +1413,9 @@ const counted = (line, kinds) => * ones, apart from the expected failures. All four are null where the output * holds no such line: the run did not finish inside the call. A run with no * `-k` whose last line counts deselected cases is none: a selection its words - * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings file, - * or written after `2>&1`, where the words end). Nor is a run pytest ended - * before its last case, which the line above its last one says (`CUT_SHORT`): + * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings + * file). Nor is a run pytest ended before its last case, which the line + * above its last one says (`CUT_SHORT`): * its last line and its result file count the cases it got to. Nor is a run * that anything follows in the command but `tail`, `head`, `grep` and `echo` * (`onlyRuns`), a redirect to a file aside: a runner started after it @@ -1445,7 +1445,11 @@ const counted = (line, kinds) => * too): the flag may take no value. */ export function fileRun(command, output = "") { - const text = String(command || "").replace(/\\\n/g, ""); + // A redirect between descriptors is left out: `PYTEST` ends a run's words + // at its `&`, and a path or a `-k` may stand after it. + const text = String(command || "") + .replace(/\\\n/g, "") + .replace(/\d?>&\d/g, " "); const runs = [...text.matchAll(PYTEST)]; const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; if (runs.length !== 1 || !ranHere(head) || !onlySetsUp(head)) return null; diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 2d51b1e35ea..e19d3f67db4 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -130,6 +130,8 @@ test("a command's one pytest run of one test file is whole or filtered with -k", `pytest ${FILE} -k parse`, `pytest ${FILE} -k "parse and not slow" -q`, `pytest -kparse ${FILE}`, + // A redirect between descriptors does not end the run's words. + `pytest ${FILE} 2>&1 -k parse | tail -3`, ]) { assert.deepEqual(fileRun(command), part, command); } @@ -193,6 +195,7 @@ test("a command with two pytest runs, two paths, another selection or no run of `pytest ${FILE} -q; echo $(pytest ${FILE}::test_one -q)`, `pytest ${FILE} tests/test_small.py`, `pytest tests ${FILE}`, + `pytest ${FILE} 2>&1 tests/test_small.py | tail -3`, "pytest tests/", "pytest -q", // The word after a flag that may take a value is that value. @@ -255,11 +258,7 @@ test("a command with two pytest runs, two paths, another selection or no run of assert.equal(fileRun(command), null, command); } // A selection the run's words do not show: the last line counts deselected cases. - for (const command of [ - `pytest ${FILE} -q`, - `pytest ${FILE} 2>&1 -k parse | tail -3`, - `export PYTEST_ADDOPTS="$PYTEST_ADDOPTS -k parse"; pytest ${FILE}`, - ]) { + for (const command of [`pytest ${FILE} -q`, `export PYTEST_ADDOPTS="$PYTEST_ADDOPTS -k parse"; pytest ${FILE}`]) { assert.equal(fileRun(command, WHOLE_OUTPUT).whole, true, command); assert.equal(fileRun(command, FILTERED_OUTPUT), null, command); assert.equal(fileRun(command, "8000 deselected in 1.20s"), null, command); @@ -425,15 +424,25 @@ function inTmp(t, fn) { fs.writeFileSync(path.join(cwd, FILE), ""); return withTmpdir(tmp, () => fn(cwd, path.join(cwd, FILE))); } -/** A session's cost state as `file` holds it; a pending run has the time its command returned. */ +/** A session's cost state as `file` holds it; a pending run has the time its + * command returned, and `dropped` is true for a time that is not after now. */ function noted(file) { const state = readJsonFile(file, null); + if (state?.dropped) state.dropped = state.dropped <= Date.now(); if (!state?.pending) return state; const { at, ...pending } = state.pending; assert.ok(Math.abs(Date.now() - at) < 60000, `the pending run was noted at ${at}`); return { ...state, pending }; } const runs = () => noted(sessionStatePath("test-cost", SESSION)); +/** Move the times the session's cost state holds `ms` back: its commands returned that long ago. */ +function aged(ms) { + const file = sessionStatePath("test-cost", SESSION); + const state = readJsonFile(file, null); + if (state.pending) state.pending.at -= ms; + if (state.dropped) state.dropped -= ms; + writeJsonFile(file, state); +} /** What `newReport` reads of a report `xml` that was written `after` ms from now. */ const read = (xml, after = 0) => (xml === null ? null : { head: xml.slice(0, 4096), mtimeMs: Date.now() + after }); /** Write the report `xml` to `file` as a run that ends `after` ms from now writes it. */ @@ -543,6 +552,7 @@ test("a command that is no file run, or names a file that is not there, leaves n note(`pytest ${FILE} -q; pytest ${FILE} -k parse`, WHOLE_OUTPUT); note(`pytest ${FILE} -q;pytest ${FILE}::test_one -q`, WHOLE_OUTPUT); note(`pytest ${FILE} tests/test_small.py`, WHOLE_OUTPUT); + note(`pytest ${FILE} 2>&1 tests/test_small.py | tail -3`, WHOLE_OUTPUT); // The word after a long flag names a folder: pytest ran it too, where the flag takes no value. note(`pytest ${FILE} --no-header tests`, WHOLE_OUTPUT); note(`cd tests && pytest test_big.py --disable-warnings ../tests -q`, WHOLE_OUTPUT); @@ -675,7 +685,20 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS // two would be counted as the other. pending(); note(`pytest ${FILE} -k parse`, STARTED, null); - assert.deepEqual(runs(), {}); + assert.deepEqual(runs(), { dropped: true }); + // The two were dropped 200 s ago, and the whole run started again is + // pending. The report the selection wrote late, of a run that began + // before the two were dropped, is not its. + aged(200000); + pending(); + assert.deepEqual(runs(), { ...open, dropped: true }); + note("pgrep -f pytest", "", report({ tests: 12, time: "400.0" })); + assert.deepEqual(runs(), { ...open, dropped: true }); + // Its own report, of a run that began after that, is. + note("pgrep -f pytest", "", WHOLE); + assert.deepEqual(runs(), { dropped: true, files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + // A run whose summary is in sight takes its own report, and the open run stays. pending(); note(FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED, 3000); @@ -686,6 +709,19 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS written(reportPath(SESSION), report({ tests: 30, time: "70.0" }), 71000); settleRun(SESSION); assert.deepEqual(runs(), { files: { [file]: { filtered: [[12, 2]] } } }); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + + // A selection that a run of another file replaced as the pending run: its + // late report is not the whole run's that replaced that one in turn. + const SMALL = "tests/test_small.py"; + fs.writeFileSync(path.join(cwd, SMALL), ""); + note(`pytest ${FILE} -k parse`, STARTED, null); + note(`pytest ${SMALL} -q`, STARTED, null); + pending(); + assert.deepEqual(runs(), { ...open, dropped: true }); + written(reportPath(SESSION), report({ tests: 12, time: "400.0" }), 0); + settleRun(SESSION); + assert.deepEqual(runs(), { dropped: true }); }); }); @@ -723,12 +759,14 @@ test("a run that ended in its call with its summary cut is not pending, and the // run takes its place, and a report of the other file leaves it pending. note(`pytest ${SMALL} -q`, STARTED, null); assert.deepEqual(runs(), { pending: { file: small, whole: true } }); + // That command returned 200 s ago: the whole run's 140 s began after it. + aged(200000); note(`pytest ${FILE} -q`, STARTED, null); - assert.deepEqual(runs(), { pending: { file, whole: true } }); + assert.deepEqual(runs(), { pending: { file, whole: true }, dropped: true }); note("pgrep -f pytest", "", report({ tests: 40, time: "150.0", file: SMALL })); - assert.deepEqual(runs(), { pending: { file, whole: true } }); + assert.deepEqual(runs(), { pending: { file, whole: true }, dropped: true }); note("pgrep -f pytest", "", WHOLE); - assert.deepEqual(runs(), whole); + assert.deepEqual(runs(), { ...whole, dropped: true }); }); }); @@ -1173,8 +1211,9 @@ test("a run that pytest ended early, that skipped most of its cases, or that lef const early = `!!!!!!!! KeyboardInterrupt !!!!!!!!\n${FILE}:4: KeyboardInterrupt\n120 passed in 30.00s`; await afterCommand(box, `python -m pytest ${FILE} -q`, early, report({ tests: 120, time: "30.0" })); assert.equal(readJsonFile(box.runs, null), null); - // The command's words end at `2>&1`: its last line says cases were left out. - await afterCommand(box, `python -m pytest ${FILE} 2>&1 -k parse | tail -3`, FILTERED_OUTPUT, FILTERED); + // The selection is not among the run's words: its last line says cases were left out. + const selected = `export PYTEST_ADDOPTS="$PYTEST_ADDOPTS -k parse"; python -m pytest ${FILE}`; + await afterCommand(box, selected, FILTERED_OUTPUT, FILTERED); assert.equal(readJsonFile(box.runs, null), null); // The cases need a service this machine does not run. const xml = report({ tests: 8000, time: "2.3", skipped: 7988 }); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index e4887aa0588..c15850a6672 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -51,7 +51,9 @@ const MAX_PATH = 160; const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, files }`, by each file's absolute path. +// The session's runs: `{ pending, dropped, files }`, by each file's absolute +// path. `dropped` is the time by which a run that lost its place as the +// pending one had begun. const RUNS = "test-cost"; // The repository's row as the session read it last, in the checkout at // `root`: `{ read, root, repo, asked, row }`, with the repository's id and @@ -126,12 +128,15 @@ function add(state, run, cost) { * not a hook saw it, began its run after that. A run of the file that * something else started while the pending run was in its call began before * it too: its report, read with a command that is not that run, is taken - * for the pending run's. The pending run is then settled; any other report - * leaves it pending. */ + * for the pending run's. A run that began by the time an earlier pending + * run had (`dropped`) may be that run, whose report is no later run's. The + * pending run is then settled; any other report leaves it pending. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; const pending = state.pending; - if (!cost || !pending || !ofFile(pending, cost) || report.mtimeMs - cost.time * 1000 > pending.at) return false; + if (!cost || !pending || !ofFile(pending, cost)) return false; + const began = report.mtimeMs - cost.time * 1000; + if (began > pending.at || began <= (state.dropped ?? 0)) return false; add(state, pending, cost); state.pending = undefined; return true; @@ -160,7 +165,11 @@ function settle(state, report) { * the run may still be open, and is then not counted. An open run takes the * place of a pending run of another file, whose report is then no run's. An * open run of the other kind of the pending run's file drops both: the - * pending run's report would be counted as the later run's. + * pending run's report would be counted as the later run's. A run that lost + * its place may still write its report, so the state keeps the time by which + * it had begun (`dropped`): the time the replaced run's command returned, or + * this one's where both are dropped. A report of a run that began by then is + * no later pending run's (`settle`). */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { @@ -185,6 +194,8 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { if (open && (!cost || settled || !ofFile(run, cost))) { const pending = state.pending; const other = pending && pending.file === run.file && pending.whole !== run.whole; + if (other) state.dropped = Date.now(); + else if (pending && pending.file !== run.file) state.dropped = pending.at; state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } writeSessionState(RUNS, sessionId, state); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 6e63e6c7c00..a99a8e1081b 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1413,9 +1413,9 @@ const counted = (line, kinds) => * ones, apart from the expected failures. All four are null where the output * holds no such line: the run did not finish inside the call. A run with no * `-k` whose last line counts deselected cases is none: a selection its words - * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings file, - * or written after `2>&1`, where the words end). Nor is a run pytest ended - * before its last case, which the line above its last one says (`CUT_SHORT`): + * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings + * file). Nor is a run pytest ended before its last case, which the line + * above its last one says (`CUT_SHORT`): * its last line and its result file count the cases it got to. Nor is a run * that anything follows in the command but `tail`, `head`, `grep` and `echo` * (`onlyRuns`), a redirect to a file aside: a runner started after it @@ -1445,7 +1445,11 @@ const counted = (line, kinds) => * too): the flag may take no value. */ export function fileRun(command, output = "") { - const text = String(command || "").replace(/\\\n/g, ""); + // A redirect between descriptors is left out: `PYTEST` ends a run's words + // at its `&`, and a path or a `-k` may stand after it. + const text = String(command || "") + .replace(/\\\n/g, "") + .replace(/\d?>&\d/g, " "); const runs = [...text.matchAll(PYTEST)]; const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; if (runs.length !== 1 || !ranHere(head) || !onlySetsUp(head)) return null; diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 2820b7fb3db..3a90a22c8da 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "c007d5594b27569afb6c2b796df60629e1598834302651be007c1d821709eef7", + "integrations/claude-code-plugin/lib/test-cost.mjs": "4a0224dbdc52ad725ff76535a69a59639ff45d1ed0c6091ea71ada65f1428cea", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "c007d5594b27569afb6c2b796df60629e1598834302651be007c1d821709eef7", + "integrations/codex-plugin/lib/test-cost.mjs": "4a0224dbdc52ad725ff76535a69a59639ff45d1ed0c6091ea71ada65f1428cea", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 4c385cd99e1d10e8f295ba8b604d8109eeefaa58 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 07:11:56 +0530 Subject: [PATCH 22/24] A whole run of one case is not kept as a test file's cost A file of one case has no -k selection smaller than itself, and the prompt line tells a session to check a change with one. `add` now keeps a whole run only from two cases, so a run that ends `1 passed in 300.00s` writes no first row, takes no row from a slower file and revises none. The docs now say three things the code already did: - the whole run's revision rule has the two-second floor of the filtered time (`apart`); - a read of the row that answers after the search and before the process exits is kept, and the next bug report prints its line with no read; - a session open for more than a day loses its cost state to the sweep of day-old state files, and then stores nothing or prints no line. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 18 +++++++--- integrations/claude-code-plugin/README.md | 6 ++-- .../claude-code-plugin/hooks/HOOKS.md | 35 ++++++++++++------- .../claude-code-plugin/lib/test-cost.mjs | 30 +++++++++------- .../tests/test-cost.test.mjs | 12 +++++-- integrations/codex-plugin/lib/test-cost.mjs | 30 +++++++++------- tests/unit/session_content_senders.json | 4 +-- 7 files changed, 87 insertions(+), 48 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index d83072d5b5f..d26bdb22992 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1699,7 +1699,8 @@ checkout, that names one test file and nothing else to run, the hook reads the n cases and the seconds pytest writes at the head of the result file, and keeps them in the session's private state, by the file: -- a whole run counts when no case failed, and the costliest one of each file is kept; +- a whole run of two cases or more counts when no case failed, and the costliest one of + each file is kept. A file of one case has no `-k` selection smaller than itself; - a run filtered with `-k` counts as filtered, and a file's filtered time is the middle of the session's last 15 filtered runs of it that ran fewer cases than the whole file; - a run that skipped more than a tenth of its cases counts as neither: a run on a machine @@ -1767,8 +1768,9 @@ bug report read the row writes, a miss included, so it knows what it replaces: - with no row, the session's costliest whole run is stored when it took 60 s or more; - the row's own file is revised by the session's whole run of it when that is more than - a quarter away from the stored seconds, down as well as up, and by its filtered time - when the row has none or the session's is more than a quarter and two seconds away; + a quarter and two seconds away from the stored seconds, down as well as up, and by its + filtered time when the row has none or the session's is more than a quarter and two + seconds away; - another file takes the row with a whole run of 60 s or more that is over a quarter longer than the row's file takes, and any such run takes a row whose file the checkout no longer holds. @@ -1823,6 +1825,13 @@ What it does not do: - a session stores only where it ends in the checkout of the row it read last: one that ends in a checkout whose row it read before a bug report in another checkout stores nothing; +- a session that stays open for more than a day loses what it keeps for this: any + session's start removes the state files untouched for a day. The row is written when a + bug report reads it and not again: once it is removed, the session stores nothing + unless a later bug report reads the row again. What the session noted of its runs goes + a day after the last run it noted. A session that runs no pytest for a day has no test + report after that: its bug reports read no row and print no line, and its runs are not + noted; - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not; - the session keeps one run that outlives its call. A later one of another test file @@ -1870,7 +1879,8 @@ What it does not do: `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and [`code` mode](#modes) all three. What a session noted and the row it -read are removed from its private state when it ends, whatever it stores. +read are removed from its private state when it ends, whatever it stores, and a day after +their last write where it has not ended by then. `memory.delete` on the row's key removes the row. ## The code shunt diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 45c6192b43e..bccb4b337d2 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,19 +324,19 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run counts when no case failed, and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that anything stands before in its command but `cd`, `export`, `source` and `.` (`make test || pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that anything stands before in its command but `cd`, `export`, `source` and `.` (`make test || pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. ``` -Only a session whose bug report read the row writes, a miss included. With no row, its costliest whole run is stored when it took 60 s or more. The row's own file is revised by the session's whole run of it when that is more than a quarter away from the stored seconds, down as well as up, and by its filtered time when the row has none or the session's is more than a quarter and two seconds away. Another file takes the row with a whole run of 60 s or more that is over a quarter longer, and any such run takes a row whose file the checkout no longer holds. The write names the value the session read and goes under the agent that wrote the row. Of the run, only the file's path in the checkout, the number of cases and the seconds are sent; a path the secret redaction would change is not sent, and neither is a file git does not list in the checkout, tracked or untracked: one of a worktree or a submodule under it, or one git ignores. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: +Only a session whose bug report read the row writes, a miss included. With no row, its costliest whole run is stored when it took 60 s or more. The row's own file is revised by the session's whole run of it when that is more than a quarter and two seconds away from the stored seconds, down as well as up, and by its filtered time when the row has none or the session's is more than a quarter and two seconds away. Another file takes the row with a whole run of 60 s or more that is over a quarter longer, and any such run takes a row whose file the checkout no longer holds. The write names the value the session read and goes under the agent that wrote the row. Of the run, only the file's path in the checkout, the number of cases and the seconds are sent; a path the secret redaction would change is not sent, and neither is a file git does not list in the checkout, tracked or untracked: one of a worktree or a submodule under it, or one git ignores. In a later session in that repository, a prompt that reads as a bug report and gets code pointers ([what a prompt gets](#what-a-prompt-gets)) carries one more line under them: ```text Test cost in this repository (measured in earlier sessions): a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s, longer than the default 120 s timeout of a shell call. A run filtered with -k takes about 2 s. Check a change with -k selections of the cases it affects. ``` -The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that repository's row in its place. `namespace.audit` leaves reads of the row's key out of its exact-key count (`exact_key_store` from rule version 3) and the mentor out of the agent's exact-key reads, so the read brings neither the namespace-health line nor the mentor's `recall_by_key_only` and `reads_miss` hints; an older server counts it in both. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index, and neither does a session that ends in another checkout than the one whose row it read last. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. +The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. A row whose whole run is under 60 s, or whose file the checkout does not hold, prints nothing. The row is read beside the prompt's search and never waited for past its answer: a read that fails or is slow adds nothing, and the pointers are printed as they are. The session keeps the row it read last, with the checkout it was read in: a later bug report in that checkout sends no read, and one in another checkout reads that repository's row in its place. `namespace.audit` leaves reads of the row's key out of its exact-key count (`exact_key_store` from rule version 3) and the mentor out of the agent's exact-key reads, so the read brings neither the namespace-health line nor the mentor's `recall_by_key_only` and `reads_miss` hints; an older server counts it in both. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three; the write goes to the key the session's prompt read; what a session noted and the row it read are removed when it ends, whatever it stores, and with the other state files a day after their last write where it has not ended by then: the row is written when a bug report reads it and not again, so once it is removed the session stores nothing unless a later bug report reads the row again, and a session that runs no pytest for a day has no test report, so it reads no row, prints no line and notes no run; a session none of whose prompts read the row stores nothing, so nothing is stored in `memory` mode, with the prompt pointers off or in a repository this Loom does not index, and neither does a session that ends in another checkout than the one whose row it read last. The row is an ordinary memory: recall can serve its sentence, which names the repository by its tag; `memory.delete` on its key removes it, and a value someone rewrote is neither printed nor overwritten. Two repositories' rows in one namespace read alike, so the server's conflict check can mark one `conflicted`; both are still read by key. Where the other repository's row is pinned, the check refuses the write (409 `PINNED_CONFLICT`), and the repository has no row and no line until that row is unpinned. **Stops that pass.** By default no stop is held: a session that changed code and ran no test ends without being asked to run one. `--config stop_test_gate=true` turns the gate's stop on, as does `LOOM_TEST_GATE=stop` for one session (`LOOM_TEST_GATE=advise` turns it off for one). Turned on, the test gate holds the end of a session only when the session ran no test since its last code change. Whether a session ran the right tests, and how they went, cannot be read reliably from its shell commands: a session that runs the whole suite, compares against a stashed tree in one command or pipes pytest through `grep` has run the tests in a way no fixed rule reads, and a gate that holds the stop on that reading holds sessions that did the work. So the stop passes, before anything is asked of the server, when the transcript holds a shell command that starts a test runner and finished no earlier than the newest write among the code files the session changed. A changed file that is documentation or prose by its name is left out of that comparison, so a note written after the run holds nothing; so is a deleted file. Such a name ends in `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc` or `.asciidoc`, or is `CHANGELOG`, `CHANGES`, `HISTORY` or `NEWS`. A `.txt` file is one when it has one of those four names or is `README.txt`, `LICENSE.txt`, `NOTICE.txt` or `AUTHORS.txt`, or lies under a `docs` or `doc` directory with no `requirements` or `constraints` in its path below it (`docs/releases/5.2.txt`); any other `.txt` file is code, as a requirements file or a test fixture is. A `git stash pop` in a later command than the run rewrites the changed files, so that stop is held. A runner is `pytest`, `unittest`, `tox`, `nox`, `jest`, `vitest`, `mocha`, `nextest`, `rspec`, `phpunit`, `ctest` or `clickhouse-test`, or `go`, `cargo`, `npm`, `pnpm`, `yarn`, `bun`, `deno`, `make`, `mvn`, `gradle`, `gradlew`, `dotnet`, `swift`, `bazel`, `mix`, `rake` or `node` with an argument in which `test` or `tests` follows no letter and no lower-case letter follows it (`make test-unit`, `node --test`, `gradle :app:test`, `gradlew testDebugUnitTest`, but not `make latest`, `go vet ./internal/testutil/...` or `cargo build -p testcontainers`); or `make`, `npm`, `pnpm`, `yarn`, `bun` or `rake` with a target or a script whose name starts with `test` (`make testall`, `npm run testci`); or `gradle` or `gradlew` with a task that ends in `Test` after a lower-case letter (`gradlew integrationTest`, but not `gradlew compileTestJava`). A repository's own runner counts when the command starts it: a script named `runtests`, `run_tests` or `run-tests` (with any extension), or `bin/test`, as the command's first word or handed to `python`, `sh` or `bash` (`python tests/runtests.py app.tests`, `./runtests.py`, `bin/test pkg/core`), and a package's own test function called inside the quotes of an inline script (`python -c "import pkg; pkg.test('pkg/core')"`); a command that reads such a script (`head tests/runtests.py`) does not, and `/usr/bin/test` and `/bin/test` are the shell's file test. A name after `install`, `uninstall`, `add`, `i`, `ci`, `get`, `remove`, `rm`, `update`, `upgrade`, `download` or `require` in the same simple command is a package, not a run (`pip install -U pytest`, `npm i -D @types/jest`, `yarn remove jest`), and neither the word after `-x` (`gradle build -x test`) nor `test.skip` (`mvn package -Dmaven.test.skip=true`) is one. A backslash at a line's end joins the next line to the command. A tool and its argument, and a verb and the name after it, are read no more than 256 characters apart in one simple command, so a line of any length is read in time proportional to its length. Two shapes are misread: a build tool's target that has a verb's name hides the run after it, so `make install test` and `mvn clean install test` are taken for no run and that stop is held once; and a target that only builds counts when its name reads as a run (`gradlew assembleAndroidTest`, `make testdata`). The command's output is not read: a run that failed, ran other tests or ran in a container passes, and so does a command that only names a runner, such as `grep -rn pytest .`. A session that wrote a changed code file after its last such command, or that ran none, is held once per distinct change with the tests to run and the functions the index links no test to; a harness the list does not name is not seen, and that stop is held once too. A latest prompt that ends with "Do not run the tests" passes when the gate names tests the checkout has. With no transcript the stop is not held. In a Codex rollout the session's changes are read from `apply_patch` and from the shell tool under each of its names (`exec`, `exec_command`, `shell`, `shell_command`, `container.exec`), so a rollout that changed a file through any of them is held, with `LOOM_TEST_GATE=block` too. A team that wants the stop held until the named tests ran on the final tree sets `LOOM_TEST_GATE=block` in the environment Claude Code starts in; the two paragraphs below describe that mode, which names nothing at edit time. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 55104a97d02..8d4ba14ef5f 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -984,9 +984,11 @@ default 120 s timeout of a shell call. A run filtered with -k takes about named and the checkout it was read in. The state keeps one row, the one read last: a later bug report in that checkout asks nothing, one in another checkout reads that repository's row in its place, and the - session's end writes to the key of the row kept; a read that failed or - came late is asked again at the next bug report. namespace.audit leaves - reads of the row's key out of its exact-key count (`exact_key_store` + session's end writes to the key of the row kept. A read that failed, or + had not answered when the process exited, is asked again at the next bug + report; one that answered after the search and before the exit is kept, + and the next bug report prints its line with no read. namespace.audit + leaves reads of the row's key out of its exact-key count (`exact_key_store` from rule version 3) and the mentor out of the agent's exact-key reads (`HOOK_READ_KEYS` in server/memory/domain/namespace_shapes.py), so the read brings neither the namespace-health line nor the mentor's @@ -1420,9 +1422,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that the report's first `testsuite` (`runCost`, read from the file's first 4,096 bytes, also for a file over the 2 MB bound). The session's private state keeps, for each of eight files, the costliest whole run - in which no case failed, and the case count and seconds of its last 15 - runs filtered with `-k`. The eight are the file with the costliest - whole run, which is what the session's end stores, and the seven + of two cases or more in which no case failed (a file of one case has + no selection smaller than itself), and the case count and seconds of + its last 15 runs filtered with `-k`. The eight are the file with the + costliest whole run, which is what the session's end stores, and the seven others run last. A run that skipped more than a tenth of its cases is not kept: it ran where the cases skip, and took less. The skipped cases are the ones pytest's last line counts, where the command's output shows it. The @@ -1522,12 +1525,12 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that (`revised`). With no row, the costliest whole run is stored when it took 60 s or more. The row's own file is revised by the session's whole run of it when that is more than - a quarter away from the stored seconds, down as well as up, and by the - middle of its filtered runs that ran fewer cases than the whole file, - when the row has no such time or one more than a quarter and two seconds - away. Another file takes the row with a whole run of 60 s or more that - is over a quarter longer than the row's file takes, and any such run - takes a row whose file the checkout no longer holds. The key is + a quarter and two seconds away from the stored seconds, down as well as + up, and by the middle of its filtered runs that ran fewer cases than the + whole file, when the row has no such time or one more than a quarter and + two seconds away. Another file takes the row with a whole run of 60 s + or more that is over a quarter longer than the row's file takes, and + any such run takes a row whose file the checkout no longer holds. The key is `repo:/test-cost/pytest`, one row a repository in the session's namespace, tagged `repo:`, `source:` and `test-cost`, with `files: []`, so that no file's memory serves it, and @@ -1559,7 +1562,13 @@ about s.` The write revises the row the session read (`if_match_sha256`), the write, and a session in code-only mode notes, stores and prints nothing. At SessionEnd `loom-session-memory` removes what the session noted and the row it read from the session's state, whatever it - stores. + stores. In a session that stays open they go with the other state + files, at any session's start a day after their last write. The row + is written when a bug report reads it and not again: once it is gone, + the session stores nothing unless a later bug report reads the row + again. The runs go a day after the last one was noted. A session + whose report state went that way (**The file's end**, above) reads no + row, prints no line and notes no run. - LOOM_TEST_REPORT=off, or the `test_report` option set to false, stops all of it from the session's next start. - **loom-usage.** Reads the transcript's last MiB, dedupes assistant turns diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index c15850a6672..e02ed483edc 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -40,6 +40,8 @@ import { readSessionState, removeFile, sessionStatePath, writeSessionState } fro // A whole run shorter than this is not worth a line in a prompt. const MIN_WHOLE_SECONDS = 60; +// A file of one case has no -k selection smaller than itself. +const MIN_WHOLE_TESTS = 2; // The default timeout of one shell call under Claude Code. const CALL_TIMEOUT_SECONDS = 120; // A run that skipped a larger share of its cases did not run them. @@ -58,7 +60,10 @@ const RUNS = "test-cost"; // The repository's row as the session read it last, in the checkout at // `root`: `{ read, root, repo, asked, row }`, with the repository's id and // the identity the read named (`identity`), which the session's end writes -// to. It is one row: a read in another checkout takes its place. +// to. It is one row: a read in another checkout takes its place. It is +// written at that read alone, and the sweep of day-old state files +// (`sweepStaleStateFiles`) removes it like any other: a session with no +// bug report after that stores nothing. const ROW = "test-cost-row"; /** `file`, a path in the checkout, when it may be sent, else "". */ @@ -93,16 +98,17 @@ const ofFile = (run, cost) => Boolean(cost.file) && run.file.split(path.sep).joi /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another * run's (`ofFile`). A run counts when no more than `MAX_SKIPPED_SHARE` of - * its cases were skipped, and a whole run when no case failed either: one - * that ran where its cases skip, or stopped at a failure, took less. The - * file is put last, and the bound drops the one least recently run that is - * not the one with the costliest whole run: that run is what the session's - * end stores. */ + * its cases were skipped, and a whole run when no case failed either and + * it ran `MIN_WHOLE_TESTS` cases or more: one that ran where its cases + * skip, or stopped at a failure, took less. The file is put last, and the + * bound drops the one least recently run that is not the one with the + * costliest whole run: that run is what the session's end stores. */ function add(state, run, cost) { if (!ofFile(run, cost)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; const ran = cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; - const whole = run.whole && ran && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); + const counts = run.whole && ran && !cost.failed && cost.tests >= MIN_WHOLE_TESTS; + const whole = counts && cost.seconds > (seen.whole?.seconds ?? -1); const next = { ...seen, ...(whole ? { whole: { tests: cost.tests, seconds: cost.seconds } } : {}), @@ -329,11 +335,11 @@ function median(samples, tests) { * whole run then replaces. * * The row's own file is revised by the session's runs of it: its whole run, - * where that is more than a quarter away from the stored seconds, down as - * well as up, and the middle of its filtered runs, where the row has none or - * one more than a quarter away. Another file takes the row with a whole run - * of `MIN_WHOLE_SECONDS` or more that is over a quarter longer than the - * row's file takes. + * where that is more than a quarter and two seconds away from the stored + * seconds (`apart`), down as well as up, and the middle of its filtered + * runs, where the row has none or one that far away. Another file takes the + * row with a whole run of `MIN_WHOLE_SECONDS` or more that is over a quarter + * longer than the row's file takes. */ export function revised(runs, row) { if (row && !row.path) return null; diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index e19d3f67db4..00c22f07fef 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -459,6 +459,11 @@ test("a report is the command's whose output shows the summary with the report's inTmp(t, (cwd, file) => { const note = (command, output, xml) => noteCommand(SESSION, { command, output, report: read(xml), cwd }); const whole = (seconds) => ({ tests: 8000, seconds }); + // A file of one case has no selection smaller than itself: its whole run is not kept. + note(WHOLE_COMMAND, "1 passed in 300.00s", report({ tests: 1, time: "300.0" })); + assert.deepEqual(runs(), { files: {} }); + note(WHOLE_COMMAND, "2 passed in 61.00s", report({ tests: 2, time: "61.0" })); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 2, seconds: 61 } } } }); note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); assert.deepEqual(runs(), { files: { [file]: { whole: whole(140) } } }); note(FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED); @@ -1055,7 +1060,7 @@ test("the launcher at an agent's SessionEnd reads the pending run's report and e assert.equal(fs.existsSync(box.runs), false); }); -test("nothing is stored for a whole run under 60 s, a command of two runs, two paths or a command before the run, or with session memory off", { +test("nothing is stored for a whole run under 60 s or of one case, a command of two runs, two paths or a command before the run, or with session memory off", { skip: WINDOWS, }, async (t) => { const server = await loom(t); @@ -1063,6 +1068,8 @@ test("nothing is stored for a whole run under 60 s, a command of two runs, two p const cases = [ // Under 60 s: noted, and no first row. [`python -m pytest ${FILE} -q`, "8000 passed in 59.40s", report({ tests: 8000, time: "59.4" }), {}, whole(59)], + // One case: no -k selection is smaller than the file, and its whole run is not kept. + [`python -m pytest ${FILE} -q`, "1 passed in 300.00s", report({ tests: 1, time: "300.0" }), {}, {}], // Two runs, two paths, and a selection that is not by name: nothing is noted. [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}, null], [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}, null], @@ -1078,7 +1085,8 @@ test("nothing is stored for a whole run under 60 s, a command of two runs, two p // The session's prompt read the row, a miss: its end may store a first one. assert.equal(server.sent("memory.get").length, at + 1, command); await afterCommand(box, command, output, xml, extra); - assert.deepEqual(readJsonFile(box.runs, null), seen && { files: { [box.file]: seen } }, command); + const files = seen?.whole ? { [box.file]: seen } : {}; + assert.deepEqual(readJsonFile(box.runs, null), seen && { files }, command); assert.equal(readJsonFile(box.row, {}).row, null, command); await endSession(box, extra); await settled(box); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index c15850a6672..e02ed483edc 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -40,6 +40,8 @@ import { readSessionState, removeFile, sessionStatePath, writeSessionState } fro // A whole run shorter than this is not worth a line in a prompt. const MIN_WHOLE_SECONDS = 60; +// A file of one case has no -k selection smaller than itself. +const MIN_WHOLE_TESTS = 2; // The default timeout of one shell call under Claude Code. const CALL_TIMEOUT_SECONDS = 120; // A run that skipped a larger share of its cases did not run them. @@ -58,7 +60,10 @@ const RUNS = "test-cost"; // The repository's row as the session read it last, in the checkout at // `root`: `{ read, root, repo, asked, row }`, with the repository's id and // the identity the read named (`identity`), which the session's end writes -// to. It is one row: a read in another checkout takes its place. +// to. It is one row: a read in another checkout takes its place. It is +// written at that read alone, and the sweep of day-old state files +// (`sweepStaleStateFiles`) removes it like any other: a session with no +// bug report after that stores nothing. const ROW = "test-cost-row"; /** `file`, a path in the checkout, when it may be sent, else "". */ @@ -93,16 +98,17 @@ const ofFile = (run, cost) => Boolean(cost.file) && run.file.split(path.sep).joi /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another * run's (`ofFile`). A run counts when no more than `MAX_SKIPPED_SHARE` of - * its cases were skipped, and a whole run when no case failed either: one - * that ran where its cases skip, or stopped at a failure, took less. The - * file is put last, and the bound drops the one least recently run that is - * not the one with the costliest whole run: that run is what the session's - * end stores. */ + * its cases were skipped, and a whole run when no case failed either and + * it ran `MIN_WHOLE_TESTS` cases or more: one that ran where its cases + * skip, or stopped at a failure, took less. The file is put last, and the + * bound drops the one least recently run that is not the one with the + * costliest whole run: that run is what the session's end stores. */ function add(state, run, cost) { if (!ofFile(run, cost)) return; const { [run.file]: seen = {}, ...files } = state.files || {}; const ran = cost.skipped <= cost.tests * MAX_SKIPPED_SHARE; - const whole = run.whole && ran && !cost.failed && cost.seconds > (seen.whole?.seconds ?? -1); + const counts = run.whole && ran && !cost.failed && cost.tests >= MIN_WHOLE_TESTS; + const whole = counts && cost.seconds > (seen.whole?.seconds ?? -1); const next = { ...seen, ...(whole ? { whole: { tests: cost.tests, seconds: cost.seconds } } : {}), @@ -329,11 +335,11 @@ function median(samples, tests) { * whole run then replaces. * * The row's own file is revised by the session's runs of it: its whole run, - * where that is more than a quarter away from the stored seconds, down as - * well as up, and the middle of its filtered runs, where the row has none or - * one more than a quarter away. Another file takes the row with a whole run - * of `MIN_WHOLE_SECONDS` or more that is over a quarter longer than the - * row's file takes. + * where that is more than a quarter and two seconds away from the stored + * seconds (`apart`), down as well as up, and the middle of its filtered + * runs, where the row has none or one that far away. Another file takes the + * row with a whole run of `MIN_WHOLE_SECONDS` or more that is over a quarter + * longer than the row's file takes. */ export function revised(runs, row) { if (row && !row.path) return null; diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 3a90a22c8da..3baf38d5dcd 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -410,7 +410,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "4a0224dbdc52ad725ff76535a69a59639ff45d1ed0c6091ea71ada65f1428cea", + "integrations/claude-code-plugin/lib/test-cost.mjs": "a922d00d775029d852a6329112a2f8d1e791e1eb864a21ce7609a4ca95bf7a1c", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -426,7 +426,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "4a0224dbdc52ad725ff76535a69a59639ff45d1ed0c6091ea71ada65f1428cea", + "integrations/codex-plugin/lib/test-cost.mjs": "a922d00d775029d852a6329112a2f8d1e791e1eb864a21ce7609a4ca95bf7a1c", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From bbc53d550eec61e33abbb70cb1b56a9f072aed1d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 08:08:09 +0530 Subject: [PATCH 23/24] The hooks reference says which hooks read the test result file The test report's section said that no hook runs between two commands. The launcher runs after every tool call, and a PreToolUse hook runs before a `gh` shell command. What limits the read is narrower: the test report hook reads the result file after a shell command that starts a test runner, and the launcher reads it at SessionEnd. The section now says that, as the Claude Code page and the plugin's README do. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- integrations/claude-code-plugin/hooks/HOOKS.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 1c708680d02..412d93af775 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1532,10 +1532,13 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that that ended in its call with no last line and no report, such as one whose pytest refused an option of the command, is pending like an open one, and drops a later run in the same way. - The session has one result file, and no hook runs between two - commands: where the session's next pytest run ends before a hook has - read the file, that run's report replaces the pending run's, which is - then not counted. The SessionStart hook runs again after a compaction + The session has one result file, read at two points: by this hook + after a shell command that starts a test runner, and by the launcher + at SessionEnd. The launcher runs after every tool call and reads the + file after no other. Where the session's next pytest run ends before + the hook has read the file, that run's report replaces the pending + run's, which is then not counted. The SessionStart hook runs again + after a compaction and empties the file: a pending run that ended before the compaction, with its report not yet read, is not counted either. At SessionEnd `loom-session-memory` hands one `memory.set` to the From b55c8b22262b4a4a539a651edea2f60b06d7b808 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 08:42:03 +0530 Subject: [PATCH 24/24] The test cost row's tag is not one the mentor reads as a write about tests The session-end hook tagged its `memory.set` `test-cost`. The mentor counts a write whose tag holds the word `test` among the agent's test writes, and one such write gives an agent that made no tracker call the `tracker_unused` warning where the deployment has a tracker source. The tag is `pytest-cost`, which the pattern does not match. A mentor test reads the tags from the plugin's fixture and runs the profile's statement over the ledger row of that request. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- .../claude-code-plugin/hooks/HOOKS.md | 7 +- .../claude-code-plugin/lib/test-cost.mjs | 6 +- .../tests/fixtures/test-cost-wire.json | 2 +- .../tests/test-cost.test.mjs | 2 +- integrations/codex-plugin/lib/test-cost.mjs | 6 +- tests/unit/session_content_senders.json | 4 +- tests/unit/test_mentor.py | 77 ++++++++++++++----- 7 files changed, 74 insertions(+), 30 deletions(-) diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 8fbdc6dd64d..cbcd88b8466 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1563,9 +1563,12 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that or more that is over a quarter longer than the row's file takes, and any such run takes a row whose file the checkout no longer holds. The key is `repo:/test-cost/pytest`, one row a repository in the session's - namespace, tagged `repo:`, `source:` and `test-cost`, with + namespace, tagged `repo:`, `source:` and `pytest-cost`, with `files: []`, so that no file's memory serves it, and - `source_class: "external"`. The value is one sentence, which names the + `source_class: "external"`. The tag is not `test-cost`: the mentor counts + a write whose tag holds the word `test` as one about tests, and from one + such write advises an agent that made no tracker call to ask the tracker + (`tracker_unused`). The value is one sentence, which names the repository by its tag because recall can serve the row in another repository of the namespace: `In the repository tagged repo:, a whole run of collects diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index e02ed483edc..ef209e4c865 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -398,7 +398,9 @@ function measured(state, root) { * the repository of that read, from the session's state: a scope resolved * again here may name another remote of the checkout, whose key no prompt * reads. The value names no file to the server (`files: []`), and its class - * says a tool measured it. + * says a tool measured it. The tag of its kind is `pytest-cost`: the mentor + * takes a tag with the word `test` in it for a write about tests, and would + * advise the session's agent to ask the tracker (`tracker_unused`). */ export function costPost(sessionId, cwd) { try { @@ -414,7 +416,7 @@ export function costPost(sessionId, cwd) { ...held.asked, agent: row?.agent || held.asked.agent, value: claim(held.repo, next), - tags: [`repo:${held.repo}`, `source:${hookClient()}`, "test-cost"], + tags: [`repo:${held.repo}`, `source:${hookClient()}`, "pytest-cost"], files: [], source_class: "external", if_match_sha256: row?.sha || "absent", diff --git a/integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json b/integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json index 055f31494a3..16d34e1c92d 100644 --- a/integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json +++ b/integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json @@ -13,7 +13,7 @@ "agent": "claude-code", "memory_key": "repo:315f533aed/test-cost/pytest", "value": "In the repository tagged repo:315f533aed, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s.", - "tags": ["repo:315f533aed", "source:claude-code", "test-cost"], + "tags": ["repo:315f533aed", "source:claude-code", "pytest-cost"], "files": [], "source_class": "external", "if_match_sha256": "absent" diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 00c22f07fef..21f575ba6c6 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -1428,7 +1428,7 @@ test("a session's end writes to the key its prompt read, whatever remote the che // A first row under the key the prompt read, in that repository's name. assert.equal(body.memory_key, KEY); assert.equal(body.value, claim(REPO, { path: FILE, tests: 8000, seconds: 140 })); - assert.deepEqual(body.tags, [`repo:${REPO}`, "source:claude-code", "test-cost"]); + assert.deepEqual(body.tags, [`repo:${REPO}`, "source:claude-code", "pytest-cost"]); assert.equal(body.if_match_sha256, "absent"); }); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index e02ed483edc..ef209e4c865 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -398,7 +398,9 @@ function measured(state, root) { * the repository of that read, from the session's state: a scope resolved * again here may name another remote of the checkout, whose key no prompt * reads. The value names no file to the server (`files: []`), and its class - * says a tool measured it. + * says a tool measured it. The tag of its kind is `pytest-cost`: the mentor + * takes a tag with the word `test` in it for a write about tests, and would + * advise the session's agent to ask the tracker (`tracker_unused`). */ export function costPost(sessionId, cwd) { try { @@ -414,7 +416,7 @@ export function costPost(sessionId, cwd) { ...held.asked, agent: row?.agent || held.asked.agent, value: claim(held.repo, next), - tags: [`repo:${held.repo}`, `source:${hookClient()}`, "test-cost"], + tags: [`repo:${held.repo}`, `source:${hookClient()}`, "pytest-cost"], files: [], source_class: "external", if_match_sha256: row?.sha || "absent", diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index a556868d35f..add4fa34fd7 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -414,7 +414,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "a922d00d775029d852a6329112a2f8d1e791e1eb864a21ce7609a4ca95bf7a1c", + "integrations/claude-code-plugin/lib/test-cost.mjs": "872a5c986dc1ddbcc9bccc47f77925a45030a858069784efbf5cb61b1cf738bf", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -430,7 +430,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "a922d00d775029d852a6329112a2f8d1e791e1eb864a21ce7609a4ca95bf7a1c", + "integrations/codex-plugin/lib/test-cost.mjs": "872a5c986dc1ddbcc9bccc47f77925a45030a858069784efbf5cb61b1cf738bf", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", diff --git a/tests/unit/test_mentor.py b/tests/unit/test_mentor.py index 11576d5f8de..4cad1dfe048 100644 --- a/tests/unit/test_mentor.py +++ b/tests/unit/test_mentor.py @@ -13,6 +13,7 @@ import ast import asyncio import inspect +import json import re import textwrap from collections.abc import Callable @@ -27,12 +28,19 @@ from server.insights.app import mentor_brief as handler from server.insights.app import mentor_rules from server.observability import degradations, ledger +from server.observability.event_args import project_args from server.settings import settings from server.transport import mcp_call, mcp_op, mcp_outcome, mcp_primer, mcp_tools from server.transport.mcp_op import OP_MENTION from tests.unit.clickhouse_local import CLICKHOUSE, ddl, run from tests.unit.loom_op_marks import assert_marked_once_outside_parentheses +# The requests the plugin's test cost hooks send (the plugin's tests hold the hooks to it). +_TEST_COST_WIRE = ( + Path(__file__).resolve().parents[2] + / "integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json" +) + class _CH: """Answers `query_all` / `query_one` by the first marker found in the SQL.""" @@ -495,18 +503,20 @@ def test_reliance_rules_stay_quiet_below_their_floors(monkeypatch: pytest.Monkey assert not ({"relied_on_chunk_ids", "relied_on_missing_keys", "reads_miss"} & codes) -@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_a_hooks_read_of_a_test_cost_row_is_not_one_of_the_agents_exact_key_reads() -> None: - from server.insights.store import mentor as store +def _ledger_call(operation: str, key: str = "", **args: str) -> str: + """One call of the agent `claude-code`, as an insert into the ledger.""" + # A request id of its own: the table drops a repeat of an identical insert. + pairs = ", ".join(f"'{k}', '{v}'" for k, v in args.items()) + return ( + "INSERT INTO loom.agent_events (org, namespace, agent, operation, memory_key, " + f"kind, success, args, request_id, ts) VALUES ('o', 'ns', 'claude-code', " + f"'{operation}', '{key}', 'request', 1, map({pairs}), generateUUIDv4(), now())" + ) - def call(operation: str, key: str = "", **args: str) -> str: - # A request id of its own: the table drops a repeat of an identical insert. - pairs = ", ".join(f"'{k}', '{v}'" for k, v in args.items()) - return ( - "INSERT INTO loom.agent_events (org, namespace, agent, operation, memory_key, " - f"kind, success, args, request_id, ts) VALUES ('o', 'ns', 'claude-code', " - f"'{operation}', '{key}', 'request', 1, map({pairs}), generateUUIDv4(), now())" - ) + +def _ledger_reads(rows: list[str], sets: tuple[str, ...] = ()) -> Any: + """The profile reads of `claude-code` over those calls, run by clickhouse-local.""" + from server.insights.store import mentor as store class _Local: async def query_all(self, sql: str, params: dict[str, Any] | None = None) -> Any: @@ -517,6 +527,20 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> Any found = await self.query_all(sql, params) return found[0] if found else None + return store.ProfileReads( + "o", + "ns", + "claude-code", + 7 * 86400, + ops={"sets": sets, "gets": mentor_rules.GETS, "searches": (), "packs": ()}, + limits=dict.fromkeys(("ttl", "large", "huge", "advisory", "clip", "episodic_chars"), 1), + ch=_Local(), + ) + + +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_a_hooks_read_of_a_test_cost_row_is_not_one_of_the_agents_exact_key_reads() -> None: + call = _ledger_call cost = "repo:315f533aed/test-cost/pytest" rows = [ # One read a session over HTTP, the key in the column: no row yet, so each misses. @@ -533,15 +557,7 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> Any ] def profile(hook_keys: str | None = None) -> tuple[dict[str, int], dict[str, int], set[str]]: - reads = store.ProfileReads( - "o", - "ns", - "claude-code", - 7 * 86400, - ops={"sets": (), "gets": mentor_rules.GETS, "searches": (), "packs": ()}, - limits=dict.fromkeys(("ttl", "large", "huge", "advisory", "clip", "episodic_chars"), 1), - ch=_Local(), - ) + reads = _ledger_reads(rows) if hook_keys is not None: reads.params["hook_keys"] = hook_keys usage, facts = asyncio.run(reads.op_counts()), asyncio.run(reads.key_reads()) @@ -558,6 +574,27 @@ def profile(hook_keys: str | None = None) -> tuple[dict[str, int], dict[str, int assert {"recall_by_key_only", "reads_miss"} <= codes +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_a_hooks_write_of_a_test_cost_row_is_not_a_write_about_tests() -> None: + """The session-end hook stores the row under the session's agent, with the tags of the + fixture the plugin's tests hold it to. A tag the plugin changes to one the mentor reads + as a test tag fails here: one stored row would advise the agent to ask the tracker.""" + sent = json.loads(_TEST_COST_WIRE.read_text())["requests"]["memory.set"] + + def profile(body: dict[str, Any]) -> tuple[int, set[str]]: + # The ledger's row of the request: its key, and its arguments as the ledger keeps them. + rows = [_ledger_call("memory.set", body["memory_key"], **project_args(body))] + reads = _ledger_reads(rows, sets=mentor_rules.SETS) + usage, counted = asyncio.run(reads.op_counts()), asyncio.run(reads.outcomes()) + facts = {"tracker_tagged_sets": counted["tracker_tagged_sets"], "tracker_sources": ["qa"]} + hints = mentor_rules.evaluate_rules(usage, 1, facts, agent="claude-code", max_hints=32) + return counted["tracker_tagged_sets"], {h.code for h in hints} + + assert profile(sent) == (0, set()) + # The same write under a tag that holds the word, as the row's key does. + assert profile({**sent, "tags": [*sent["tags"], "test-cost"]}) == (1, {"tracker_unused"}) + + def test_a_missing_fact_keeps_its_rule_quiet_and_lands_in_skipped( monkeypatch: pytest.MonkeyPatch, ) -> None: