diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index dfba5adfcc..c1154a8c4c 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -90,6 +90,13 @@ 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 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 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 (goal, git status, files edited, last reply); - a session brief at each compaction and at session end: the client's compaction summary @@ -121,7 +128,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 +174,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 +273,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. @@ -1087,32 +1096,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 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 the pick worded it `high` or `medium` (with `LOOM_PROMPT_PACK_MIN_CONF` set, from that confidence instead) 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 one, a Python migration or a release script only if named, and module-level code when it asks for tests or as a first pick; 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 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 the pick worded it `high` or `medium` (with `LOOM_PROMPT_PACK_MIN_CONF` set, from that confidence instead) 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 one, a Python migration or a release script only if named, and module-level code when it asks for tests or as a first pick; 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` | +| 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; 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 @@ -1483,7 +1492,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 | @@ -1619,8 +1628,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 @@ -1707,6 +1718,202 @@ 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 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 +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 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 + 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); +- 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 + 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; +- 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. 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 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 +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 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 +`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. +``` + +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 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. + +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. 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. 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: + +```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. The row is +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. `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 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 +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; +- the session's state holds eight test files, the one with the costliest whole run and + 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 + 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; +- 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 + 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. 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 + 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 + 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 + 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 + 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 + 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; +- 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 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, 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 Inside an indexed checkout, `loom-code-shunt.mjs` denies a bulk read and puts the diff --git a/docs/features/namespaces-and-sharing.md b/docs/features/namespaces-and-sharing.md index 04d9efa95c..1c6df8c43e 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/docs/guides/optimize-namespace.md b/docs/guides/optimize-namespace.md index bcf139a5e9..f9fe610694 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/docs/reference/operations/mentor.md b/docs/reference/operations/mentor.md index 09a9522089..b698e97fcd 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/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 015e2f689a..4613b26748 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.185", + "version": "1.2.186", "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" @@ -70,8 +70,8 @@ }, "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).", + "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 }, "code_repo": { diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 2bb81e6d8b..e5307751ab 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 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 @@ -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 the server's pick worded it `high` or `medium` (with `LOOM_PROMPT_PACK_MIN_CONF` set, from that confidence instead), 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 one, a Python migration or a release script only if named, and module-level code when it asks for tests or as a first pick; 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 the server's pick worded it `high` or `medium` (with `LOOM_PROMPT_PACK_MIN_CONF` set, from that confidence instead), 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 one, a Python migration or a release script only if named, and module-level code when it asks for tests or as a first pick; 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. @@ -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 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 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, 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. **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. @@ -686,7 +705,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 fe584b0bd1..dba0085e05 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 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` | +| 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 @@ -969,6 +969,45 @@ 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 +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. 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, the key and scope the read + 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 + 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 + `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 @@ -1310,8 +1349,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` @@ -1349,7 +1389,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 @@ -1399,8 +1440,171 @@ 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 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 + 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 + 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 + 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 + 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 + 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 + 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. 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. 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, + 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), 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 + 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 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 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, 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 + flusher, beside the session's turns or alone where they are not sent, + 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 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 `pytest-cost`, with + `files: []`, so that no file's memory serves it, and + `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 +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. 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, 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 + redaction is not sent, and neither is a file that is gone by the + 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 + nothing. At SessionEnd `loom-session-memory` removes what the session + noted and the row it read from the session's state, whatever it + 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 - 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 @@ -1608,7 +1812,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/hooks/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index 684d45d476..5033a80277 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -45,6 +45,24 @@ // 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 (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, 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 +// 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 // 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 @@ -98,6 +116,7 @@ import { postBounded, promptPointersMode, readStdinJson, + resolveScope, resolveServerUrl, resolveToken, runHookMain, @@ -132,6 +151,10 @@ 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 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"; // The lookups a session makes as it starts: SessionStart's, and the MCP headers helper's. @@ -203,9 +226,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(); @@ -217,6 +240,19 @@ 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, 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`). */ +function costNote(payload, root, cwd, options) { + return import("../lib/test-cost.mjs") + .then(({ costLine }) => costLine(payload.session_id, root, () => resolveScope(cwd), options)) + .catch(() => ""); +} + async function main() { if (POINTERS === "off") { scheduleExit(0); @@ -263,18 +299,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, 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 = 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 7e04f7e2a1..1cb9c638e6 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"; @@ -229,8 +230,15 @@ 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. The library + // that reads it is loaded for this event only. + if (event === "SessionEnd") { + const sessionId = parsePayload(raw).session_id; + if (planeEnabled("memory") && testReportOn()) (await import("../lib/test-cost.mjs")).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 03bf03840b..a606767e77 100644 --- a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs @@ -5,6 +5,13 @@ // the turns as the facts' source evidence; the hook itself runs no model (see // lib/session-memory.mjs). // +// 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 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 // through the detached flusher so the agent never waits on the request. @@ -25,7 +32,9 @@ import { sessionToolEchoes, transcriptTurns, } from "../lib/session-memory.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"; import { readRecalledStash, recalledStashPath } from "../lib/run-hook.mjs"; import { fileSize, parseLines, readTail } from "../lib/transcript.mjs"; @@ -45,12 +54,20 @@ async function main() { const recalledKeys = readRecalledStash(sid); const journal = readJournal(sid); removeFile(recalledStashPath(sid)); - if (planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken()) { - await handOff(payload, journal, recalledKeys); + 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) : 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 }); } 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 +93,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 da8bcbd2e5..cef2dddd01 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-report.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-report.mjs @@ -21,14 +21,21 @@ // 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 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 +// nothing, so it runs in every mode. // // LOOM_TEST_REPORT=off disable (or the `test_report` install option) import { commandText, + envSwitch, gitToplevel, planeEnabled, readStdinJson, @@ -36,6 +43,7 @@ import { runHookMain, scheduleExit, } from "../lib/loom-client.mjs"; +import { noteCommand } from "../lib/test-cost.mjs"; import { digest, newReport, @@ -50,6 +58,8 @@ import { } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); +// 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."; @@ -60,14 +70,16 @@ 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 (!report || shownAlready(output)) return null; const cwd = payload.cwd || process.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/loom-client.mjs b/integrations/claude-code-plugin/lib/loom-client.mjs index ff4ced71cb..85e670c020 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 new file mode 100644 index 0000000000..ef209e4c86 --- /dev/null +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -0,0 +1,434 @@ +// 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, 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 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 +// (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the +// 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 +// outside letters, digits and `._/-`, is over 160 characters or is changed by +// 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 { 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"; + +// 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. +// 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. +const MAX_FILES = 8; +const MAX_SAMPLES = 15; + +// 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 +// 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. 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 "". */ +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 : ""; +} + +/** 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. 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 from = [path.resolve(cwd, run.dir), path.resolve(cwd)].find((dir) => isFile(path.resolve(dir, run.path))); + if (!from || run.values.some((word) => isDirectory(path.resolve(from, word)))) return null; + 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 (`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 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 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 } } : {}), + ...(run.whole || !ran + ? {} + : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), + }; + if (next.whole || next.filtered) files[run.file] = next; + 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, 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. 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)) 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; +} + +/** + * Note a shell command the test report was read for: its text, its visible + * `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 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. 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. 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 { + const run = located(fileRun(command, output), cwd); + const state = readSessionState(RUNS, sessionId); + 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 && + run.cases === cost.tests && + run.failed === cost.failed && + 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); + // 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; + 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); + } catch { + /* nothing noted */ + } +} + +/** At the session's end, before its report is removed: a report written + * 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); + settle(state, seen && newReport(sessionId, seen)); + state.pending = undefined; + writeSessionState(RUNS, sessionId, state); + } catch { + /* nothing noted */ + } +} + +/** 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 = + /^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 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 || 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: 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 ${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." + ); +} + +/** 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` : ""); + +/** 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: scope.agent, + memory_key: costKey(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 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 + * 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 (!testReportOn() || !seenReport(sessionId)) return ""; + let held = readSessionState(ROW, sessionId); + if (!held.read || held.root !== root) { + const scope = scopeOf(); + if (!costKey(scope)) return ""; + const fields = ["value", "content_sha256", "agent"]; + 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, repo, asked, row: res.found ? { ...parseClaim(repo, res.value), ...found } : null }; + writeSessionState(ROW, sessionId, held); + } + 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 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, 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 row's own file is revised by the session's runs of it: its whole run, + * 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; + 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, 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; + } + 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]])); +} + +/** + * The flusher's post that stores what the session measured, or null. Only a + * 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. 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. 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 { + const state = readSessionState(RUNS, sessionId); + const held = readSessionState(ROW, 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; + const row = held.row?.path ? { ...held.row, gone: !isFile(path.join(root, held.row.path)) } : held.row; + const next = revised(runs, row); + if (!next) return null; + const body = { + ...held.asked, + agent: row?.agent || held.asked.agent, + value: claim(held.repo, next), + tags: [`repo:${held.repo}`, `source:${hookClient()}`, "pytest-cost"], + files: [], + source_class: "external", + if_match_sha256: row?.sha || "absent", + }; + return { op: "memory.set", body }; + } catch { + 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 4c24d67e5b..a99a8e1081 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 { @@ -1325,13 +1325,27 @@ 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 +// 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, @@ -1352,6 +1366,137 @@ function allRan(output, runs) { ); } +// 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$)/; +// 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 +// 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 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 = /^!+ .+ !+$/; +// 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) => + [...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, 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`), 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 + * `-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). 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 + * (`&& 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 + * 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 + * 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 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` + * too): the flag may take no value. + */ +export function fileRun(command, output = "") { + // 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; + // 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, " "), 1)) return null; + const cd = [...head.matchAll(CD)]; + const followed = + cd.length < 2 && + (head.match(MOVE) || []).length === cd.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 = []; + // The flag before a word, where the word may be its value. + let flag = ""; + for (const word of words) { + 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 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)); + if (whole && summary && /\b\d+ deselected\b/.test(summary)) return null; + return { + path: named[0], + 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, + failed: summary ? counted(summary, "failed|errors?") : null, + skipped: summary ? counted(summary, "skipped") : null, + values, + }; +} + /** * 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 d803e04c82..bf6b17197f 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,10 @@ 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, 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 { @@ -128,9 +132,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), mtimeMs: st.mtimeMs }; } catch { return null; } finally { @@ -285,6 +290,39 @@ 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 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. */ +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), + time: seconds, + failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), + skipped: Number(has.skipped) || 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/fixtures/test-cost-wire.json b/integrations/claude-code-plugin/tests/fixtures/test-cost-wire.json new file mode 100644 index 0000000000..16d34e1c92 --- /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", "pytest-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 new file mode 100644 index 0000000000..21f575ba6c --- /dev/null +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -0,0 +1,1495 @@ +// 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 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`. */ +function report({ tests, time, file = FILE, failures = 0, skipped = 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"; +// 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 ---------------------------------------------------------------- + +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, skipped: 0, file: FILE }; + assert.deepEqual(runCost(WHOLE.slice(0, 4096)), whole); + 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. + 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.equal(read.mtimeMs, fs.statSync(reportPath(SESSION)).mtimeMs); + assert.deepEqual(runCost(read.head), { + tests: 8000, + seconds: 140, + time: 140.2, + failed: 0, + skipped: 0, + file: FILE, + }); + }); +}); + +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, + cases: null, + failed: null, + skipped: null, + values: [], + }; + for (const command of [ + `pytest ${FILE}`, + `python -m pytest ${FILE} -q`, + `.venv/bin/python -m pytest -x -q ${FILE} 2>&1 | tail -5`, + `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. + `pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt; echo exit=$?`, + ]) { + assert.deepEqual(fileRun(command), whole, command); + } + const part = { ...whole, whole: false }; + for (const command of [ + `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); + } + // 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 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); + 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: 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.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", () => { + 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 ${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. + `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`, + `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`, + `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}`, + // 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}`, + // 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`, + `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`, + // 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); + } + // A selection the run's words do not show: the last line counts deselected cases. + 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); + } + // 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); + 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", () => { + const whole = { path: FILE, tests: 8000, seconds: 140 }; + 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 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${slow}. A run filtered with -k takes about 2 s.${check}`, + ); + 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}`, + ); + 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 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(`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"), + BOTH.replace(FILE, `${"t/".repeat(90)}test_big.py`), + { path: FILE, tests: 8000, seconds: 140 }, + null, + ]) { + assert.equal(parseClaim(REPO, value), null, JSON.stringify(value)); + } +}); + +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(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(ran(seconds), stored(140)), null, String(seconds)); + for (const seconds of [104, 176]) { + 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(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(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", () => { + 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(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 })); + 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))); +} +/** 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. */ +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, 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); + 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. + 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. + 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(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)); + // 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 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" })); + note(WHOLE_COMMAND, "8000 passed in 2.31s", report({ tests: 8000, time: "600.0" })); + assert.deepEqual(runs(), { files: { [file]: { whole: whole(180), filtered } } }); + }); +}); + +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); + // 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 } } } }); + }); +}); + +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, 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); + 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); + 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); + }); +}); + +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) => { + const note = (name, tests = 12) => { + fs.writeFileSync(path.join(cwd, name), ""); + const xml = report({ tests, time: "2.3", file: name }); + 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`); + // 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], + ]); + // 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]), + ); + // 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 }); + }); +}); + +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, report: read(xml), cwd }); + writePrivateFile(reportPath(SESSION), ""); + writeJsonFile(sessionStatePath("test-report", SESSION), { mtimeMs: 1, size: 0 }); + 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. + note(report({ tests: 8000, time: "130.0" })); + assert.deepEqual(runs(), { + pending: { file, whole: true }, + files: { [file]: { whole: { tests: 8000, seconds: 130 } } }, + }); + fs.writeFileSync(reportPath(SESSION), WHOLE); + settleRun(SESSION); + 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().files[file].whole.seconds, 140); + }); +}); + +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, report: read(xml), cwd }); + note(`pytest ${FILE} -q`, STARTED, null); + // 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 } }); + // 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 } } } }); + }); +}); + +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, after) => + noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); + const pending = () => note(`pytest ${FILE} -q`, STARTED, null); + 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(); + 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, null); + 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); + 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]] } } }); + 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 }); + }); +}); + +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 } }); + // 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 }, dropped: true }); + note("pgrep -f pytest", "", report({ tests: 40, time: "150.0", file: SMALL })); + assert.deepEqual(runs(), { pending: { file, whole: true }, dropped: true }); + note("pgrep -f pytest", "", WHOLE); + assert.deepEqual(runs(), { ...whole, dropped: true }); + }); +}); + +// --- 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."; + +// 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") => ({ ...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 + * 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 = () => ({}) } = {}) { + 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, ...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" ? 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. + 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 }; +} + +/** `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); + const repo = new URL(origin).pathname.slice(1).replace(/\.git$/, ""); + fs.writeFileSync( + cachePathFor(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, + 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, + 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: "" }; + // 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), { + 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.equal(server.sent("memory.get").length, 1); + + 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); + // 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); + 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); + // 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); + await settled(box); + assert.deepEqual(server.sent("memory.get"), []); + assert.deepEqual(server.sent("memory.set"), []); + 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 ask(box); + await afterCommand(box, `python -m pytest ${FILE} -q`, STARTED); + 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); + await arrived(server, box, "memory.set"); + 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("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) => { + 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); + 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); + // 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), + ); + // 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 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); + const whole = (seconds) => ({ whole: { tests: 8000, seconds } }); + 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], + [`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], + ]; + 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); + 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); + // 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"), []); +}); + +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 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) => { + 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); + // 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", { + 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 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 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 }); + 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("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); + const code = { LOOM_MODE: "code" }; + // 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.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 while the session stays in the checkout", { + skip: WINDOWS, +}, async (t) => { + 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: "" }); + assert.equal(context(first), `${BLOCK}\n${LINE}`); + const [read] = server.sent("memory.get"); + 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}`); + 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 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 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 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( + 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 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"), []); + + // 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", { + 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", "pytest-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) => { + 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: 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. + 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, or with it switched off, reads no row", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t, { get: row() }); + const box = sandbox(t, server); + 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", { + 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: row(), 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 746921d35e..9da33aba97 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.185", + "version": "1.2.186", "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 684d45d476..5033a80277 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -45,6 +45,24 @@ // 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 (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, 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 +// 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 // 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 @@ -98,6 +116,7 @@ import { postBounded, promptPointersMode, readStdinJson, + resolveScope, resolveServerUrl, resolveToken, runHookMain, @@ -132,6 +151,10 @@ 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 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"; // The lookups a session makes as it starts: SessionStart's, and the MCP headers helper's. @@ -203,9 +226,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(); @@ -217,6 +240,19 @@ 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, 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`). */ +function costNote(payload, root, cwd, options) { + return import("../lib/test-cost.mjs") + .then(({ costLine }) => costLine(payload.session_id, root, () => resolveScope(cwd), options)) + .catch(() => ""); +} + async function main() { if (POINTERS === "off") { scheduleExit(0); @@ -263,18 +299,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, 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 = 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 7e04f7e2a1..1cb9c638e6 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"; @@ -229,8 +230,15 @@ 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. The library + // that reads it is loaded for this event only. + if (event === "SessionEnd") { + const sessionId = parsePayload(raw).session_id; + if (planeEnabled("memory") && testReportOn()) (await import("../lib/test-cost.mjs")).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 03bf03840b..a606767e77 100644 --- a/integrations/codex-plugin/hooks/loom-session-memory.mjs +++ b/integrations/codex-plugin/hooks/loom-session-memory.mjs @@ -5,6 +5,13 @@ // the turns as the facts' source evidence; the hook itself runs no model (see // lib/session-memory.mjs). // +// 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 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 // through the detached flusher so the agent never waits on the request. @@ -25,7 +32,9 @@ import { sessionToolEchoes, transcriptTurns, } from "../lib/session-memory.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"; import { readRecalledStash, recalledStashPath } from "../lib/run-hook.mjs"; import { fileSize, parseLines, readTail } from "../lib/transcript.mjs"; @@ -45,12 +54,20 @@ async function main() { const recalledKeys = readRecalledStash(sid); const journal = readJournal(sid); removeFile(recalledStashPath(sid)); - if (planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken()) { - await handOff(payload, journal, recalledKeys); + 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) : 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 }); } 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 +93,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 da8bcbd2e5..cef2dddd01 100644 --- a/integrations/codex-plugin/hooks/loom-test-report.mjs +++ b/integrations/codex-plugin/hooks/loom-test-report.mjs @@ -21,14 +21,21 @@ // 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 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 +// nothing, so it runs in every mode. // // LOOM_TEST_REPORT=off disable (or the `test_report` install option) import { commandText, + envSwitch, gitToplevel, planeEnabled, readStdinJson, @@ -36,6 +43,7 @@ import { runHookMain, scheduleExit, } from "../lib/loom-client.mjs"; +import { noteCommand } from "../lib/test-cost.mjs"; import { digest, newReport, @@ -50,6 +58,8 @@ import { } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); +// 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."; @@ -60,14 +70,16 @@ 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 (!report || shownAlready(output)) return null; const cwd = payload.cwd || process.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/loom-client.mjs b/integrations/codex-plugin/lib/loom-client.mjs index ff4ced71cb..85e670c020 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 new file mode 100644 index 0000000000..ef209e4c86 --- /dev/null +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -0,0 +1,434 @@ +// 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, 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 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 +// (`costLine`). At the session's end hooks/loom-session-memory.mjs hands the +// 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 +// outside letters, digits and `._/-`, is over 160 characters or is changed by +// 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 { 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"; + +// 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. +// 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. +const MAX_FILES = 8; +const MAX_SAMPLES = 15; + +// 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 +// 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. 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 "". */ +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 : ""; +} + +/** 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. 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 from = [path.resolve(cwd, run.dir), path.resolve(cwd)].find((dir) => isFile(path.resolve(dir, run.path))); + if (!from || run.values.some((word) => isDirectory(path.resolve(from, word)))) return null; + 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 (`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 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 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 } } : {}), + ...(run.whole || !ran + ? {} + : { filtered: [...(seen.filtered || []), [cost.tests, cost.seconds]].slice(-MAX_SAMPLES) }), + }; + if (next.whole || next.filtered) files[run.file] = next; + 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, 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. 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)) 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; +} + +/** + * Note a shell command the test report was read for: its text, its visible + * `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 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. 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. 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 { + const run = located(fileRun(command, output), cwd); + const state = readSessionState(RUNS, sessionId); + 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 && + run.cases === cost.tests && + run.failed === cost.failed && + 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); + // 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; + 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); + } catch { + /* nothing noted */ + } +} + +/** At the session's end, before its report is removed: a report written + * 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); + settle(state, seen && newReport(sessionId, seen)); + state.pending = undefined; + writeSessionState(RUNS, sessionId, state); + } catch { + /* nothing noted */ + } +} + +/** 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 = + /^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 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 || 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: 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 ${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." + ); +} + +/** 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` : ""); + +/** 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: scope.agent, + memory_key: costKey(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 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 + * 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 (!testReportOn() || !seenReport(sessionId)) return ""; + let held = readSessionState(ROW, sessionId); + if (!held.read || held.root !== root) { + const scope = scopeOf(); + if (!costKey(scope)) return ""; + const fields = ["value", "content_sha256", "agent"]; + 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, repo, asked, row: res.found ? { ...parseClaim(repo, res.value), ...found } : null }; + writeSessionState(ROW, sessionId, held); + } + 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 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, 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 row's own file is revised by the session's runs of it: its whole run, + * 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; + 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, 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; + } + 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]])); +} + +/** + * The flusher's post that stores what the session measured, or null. Only a + * 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. 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. 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 { + const state = readSessionState(RUNS, sessionId); + const held = readSessionState(ROW, 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; + const row = held.row?.path ? { ...held.row, gone: !isFile(path.join(root, held.row.path)) } : held.row; + const next = revised(runs, row); + if (!next) return null; + const body = { + ...held.asked, + agent: row?.agent || held.asked.agent, + value: claim(held.repo, next), + tags: [`repo:${held.repo}`, `source:${hookClient()}`, "pytest-cost"], + files: [], + source_class: "external", + if_match_sha256: row?.sha || "absent", + }; + return { op: "memory.set", body }; + } catch { + 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 4c24d67e5b..a99a8e1081 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 { @@ -1325,13 +1325,27 @@ 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 +// 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, @@ -1352,6 +1366,137 @@ function allRan(output, runs) { ); } +// 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$)/; +// 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 +// 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 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 = /^!+ .+ !+$/; +// 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) => + [...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, 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`), 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 + * `-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). 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 + * (`&& 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 + * 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 + * 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 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` + * too): the flag may take no value. + */ +export function fileRun(command, output = "") { + // 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; + // 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, " "), 1)) return null; + const cd = [...head.matchAll(CD)]; + const followed = + cd.length < 2 && + (head.match(MOVE) || []).length === cd.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 = []; + // The flag before a word, where the word may be its value. + let flag = ""; + for (const word of words) { + 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 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)); + if (whole && summary && /\b\d+ deselected\b/.test(summary)) return null; + return { + path: named[0], + 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, + failed: summary ? counted(summary, "failed|errors?") : null, + skipped: summary ? counted(summary, "skipped") : null, + values, + }; +} + /** * 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 d803e04c82..bf6b17197f 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,10 @@ 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, 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 { @@ -128,9 +132,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), mtimeMs: st.mtimeMs }; } catch { return null; } finally { @@ -285,6 +290,39 @@ 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 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. */ +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), + time: seconds, + failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), + skipped: Number(has.skipped) || 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/server/identity/api/models_namespace_catalog.py b/server/identity/api/models_namespace_catalog.py index 89a51d48e4..0eb5b0e1c1 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/identity/app/namespace_audit.py b/server/identity/app/namespace_audit.py index e845a37180..a26dfe95ea 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,6 +128,8 @@ # 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'])" +# 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. _REPORT_OPS = ( @@ -308,11 +311,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 +327,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 +526,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 +661,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 +774,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/server/insights/api/models_mentor.py b/server/insights/api/models_mentor.py index 75eddb9019..c398ac0503 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/server/insights/store/mentor.py b/server/insights/store/mentor.py index e0508e102b..f98e09d2cb 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 333ee0c0aa..822dc80c2e 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/session_content_senders.json b/tests/unit/session_content_senders.json index 357a95aee2..94e320c571 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: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." + }, "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: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." + }, "integrations/cursor/cursor-session-hook.sh::d26a86f07b41aa77289e:0": { "category": "delivery", "reason": "Delegates transcript ingestion to the separately scanned CLI entry point." @@ -394,33 +402,35 @@ "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": "07b43e1073ae2ab6a9a6c4530ef1d197c35b232f6ac31e455555f538b5e99834", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "680a09763971ff6d2dfc1f682bf0a0f30839d52af7016e85aca7a7ea07073e40", "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "4394ac465b4efc5898f03143b38112aaa8015489ac7dc03fa458966bb46b9f16", "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": "cb5a69d5baa078d7dbfb7873140809dc13b5145f5fe7eae1d6a621ba7ea0c19a", "integrations/claude-code-plugin/lib/repo-scope.mjs": "1fe69b8ecaf5637dc778fb1c8593336afc74d5029f5487b9419f87bc832dd07c", "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": "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", - "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "07b43e1073ae2ab6a9a6c4530ef1d197c35b232f6ac31e455555f538b5e99834", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "680a09763971ff6d2dfc1f682bf0a0f30839d52af7016e85aca7a7ea07073e40", "integrations/codex-plugin/hooks/loom-session-start.mjs": "4394ac465b4efc5898f03143b38112aaa8015489ac7dc03fa458966bb46b9f16", "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": "cb5a69d5baa078d7dbfb7873140809dc13b5145f5fe7eae1d6a621ba7ea0c19a", "integrations/codex-plugin/lib/repo-scope.mjs": "1fe69b8ecaf5637dc778fb1c8593336afc74d5029f5487b9419f87bc832dd07c", "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": "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 763cd06077..4cad1dfe04 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,6 +503,98 @@ 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) +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 _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: + 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 + + 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. + *(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 = _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()) + 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 + + +@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: diff --git a/tests/unit/test_namespace_audit.py b/tests/unit/test_namespace_audit.py index bc963209a8..8cc54c1287 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,49 @@ 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" + 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. + _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 == 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 beside the typed 30, 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, counted.summary.typed_gets) == (284, 30) + 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 new file mode 100644 index 0000000000..218c15e034 --- /dev/null +++ b/tests/unit/test_plugin_memory_contract.py @@ -0,0 +1,52 @@ +"""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.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 + +_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" + + +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"] + # 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("%", "*"))