diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 487323f6e76..c275d31d3bc 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -98,6 +98,12 @@ end of this section are the exceptions. The plugin sends: `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); +- for a flag a session added to a command it had already run, the program's name, three + counts of sessions and the flag's word or a hash of the program's name and the word, + to `memory.set` at the session's end, as one memory row a repository; a session reads + that row with one `memory.get` at a bug report, unless it keeps the row it read in + that checkout ([command conventions](#command-conventions); the same switches; + Claude Code on a POSIX host 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 @@ -283,7 +289,7 @@ plugin, not the server. | `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)) | +| `test_report` | `true` | `false` stops the result-file option in `PYTEST_ADDOPTS`, the failure digest, the test cost note and command conventions (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. @@ -1097,32 +1103,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 (the guide and pinned rows of the other namespaces the user has taken up, on top of the budget: [what a session is given from other namespaces](../namespaces-and-sharing.md#what-a-session-is-given-from-other-namespaces); 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` | -| PreCompact, Stop, 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, in windows: the turns since the last window before every compaction, at a Stop once 40 user and assistant turns follow it (`LOOM_SESSION_MEMORY_EVERY_TURNS`) or once two do and it is 30 minutes old (`LOOM_SESSION_MEMORY_IDLE_MINUTES`), and the rest at SessionEnd, so a session that is never ended has had its turns extracted up to its last window. Up to 20 turns before a window ride as `last_messages`. A window with under 40 bytes (UTF-8) of user and assistant text is not sent and its turns join the next one; a session that ends with only that much gets no facts and no summary. The changed files ride the hand-off at SessionEnd alone, and a session whose last turns went in an earlier window names none. A per-session cursor in the temp directory marks where the next window starts. It moves before the post goes to the detached flusher, which puts it back when the post fails. No lock is taken: a flusher killed after a failed post and before it restores the cursor loses that window, and two hooks of one session that overlap between reading the cursor and moving it send one window twice, which the write path's duplicate handling absorbs. The summary keeps the facts of the session's earlier windows ahead of a later one's; a server that predates windows writes each window's own summary. The hand-off at SessionEnd 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` | +| Event | Script | Effect | Off switch | +| ------------------------------------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| SessionStart | `loom-session-start.mjs` | one budgeted `context.pack` primer (the guide and pinned rows of the other namespaces the user has taken up, on top of the budget: [what a session is given from other namespaces](../namespaces-and-sharing.md#what-a-session-is-given-from-other-namespaces); 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 and command conventions lines, from one `memory.get` each if needed ([what a whole run costs](#what-a-whole-run-costs), [command conventions](#command-conventions)) | 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` | +| PreCompact, Stop, 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, in windows: the turns since the last window before every compaction, at a Stop once 40 user and assistant turns follow it (`LOOM_SESSION_MEMORY_EVERY_TURNS`) or once two do and it is 30 minutes old (`LOOM_SESSION_MEMORY_IDLE_MINUTES`), and the rest at SessionEnd, so a session that is never ended has had its turns extracted up to its last window. Up to 20 turns before a window ride as `last_messages`. A window with under 40 bytes (UTF-8) of user and assistant text is not sent and its turns join the next one; a session that ends with only that much gets no facts and no summary. The changed files ride the hand-off at SessionEnd alone, and a session whose last turns went in an earlier window names none. A per-session cursor in the temp directory marks where the next window starts. It moves before the post goes to the detached flusher, which puts it back when the post fails. No lock is taken: a flusher killed after a failed post and before it restores the cursor loses that window, and two hooks of one session that overlap between reading the cursor and moving it send one window twice, which the write path's duplicate handling absorbs. The summary keeps the facts of the session's earlier windows ahead of a later one's; a server that predates windows writes each window's own summary. The hand-off at SessionEnd carries one `memory.set` of what a slow whole run of one test file cost and one of the repository's command conventions row, whether or not the turns are sent ([what a whole run costs](#what-a-whole-run-costs), [command conventions](#command-conventions)) | `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 @@ -1500,7 +1506,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`, no failure digest after a cut pytest run and no test cost noted or printed (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 or command convention 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 | @@ -2038,6 +2044,307 @@ read are removed from its private state when it ends, whatever it stores, and a their last write where it has not ended by then. `memory.delete` on the row's key removes the row. +### Command conventions + +A repository can need a flag on a command that nothing in it names, such as a type +checker that must be run without its incremental cache. A session that does not know +runs the command, reads a result it cannot use, and runs it again with the flag. With the +memory plane on and session memory not switched off, the plugin counts the flags that +sessions add this way from their shell commands, with no model call, and a later session +in the repository is told before its first run. It does so in a Claude Code session on a +POSIX host, in any checkout that gets code pointers: the session needs no test report. + +The reader refuses a shape it does not know. A missed convention costs nothing. A wrong +line is read by every later session. + +**What is read.** After each shell command, failed or not, the launcher reads the +command's text and notes its runs in the session's private state. No run of a call is +read where the call holds one of these: + +- a backquote, `$(` or `$'` outside single quotes; +- a backslash outside quotes, or before a double quote inside double quotes; +- a quote left open; +- a parenthesis or a brace outside quotes; +- a `|` at a line's end. The pipeline goes on in the next line; +- a simple command that starts with `if`, `then`, `else`, `elif`, `fi`, `for`, `while`, + `until`, `do`, `done`, `case`, `esac`, `select` or `function`; +- a here-document whose word is not a plain word, alone or in one pair of quotes, or + whose body has no end line. + +In a call that is read: + +- the lines of a here-document's body and comments are left out; +- a run is a simple command of the call. The call is cut at `;`, `&&`, `||`, `|` and + line ends; +- a later stage of a pipeline is no run; +- a simple command that holds `&`, `<` or `>` outside quotes is no run. A redirect + between descriptors (`2>&1`) or to `/dev/null` is passed over; +- a simple command of more than 24 words is no run; +- a run is noted where its folder is in the checkout of the row the session read. Its + folder is the command's, or the one a `cd` of the call to one plain path changed to. + After any other `cd`, a `pushd` or a `popd`, the rest of the call is not read; +- a run in another checkout under that one is not noted. A folder that holds a `.git`, + and every folder below it, is a submodule's, a worktree's or another clone's. + +**The program.** The program of a run is the first word after its variable assignments: + +- it is a bare name of 40 characters at most: a letter or `_`, then letters, digits and + `_+-`; +- or it is the module of `python -m` or `pypy -m`. The interpreter is named by its bare + name, with or without a version, and `-m` is its first word; +- a path is no program, so a script named by its path never is one. A name with a dot + is no program either: a module named with one (`python -m scripts.sync`) is a file + inside a package. Nor is a name that every JavaScript object has, such as + `constructor`; +- a module with no dot is a program wherever its file lies. One at the root of the + checkout (`python -m sync`, with a `sync.py` there) is counted like an installed one: + the command does not say which it is, and a tool run in its own checkout is such a + module; +- a word that starts another command is no program, since the flags after it are not + its own: `time`, `env`, `exec`, `command`, `nohup`, `nice`, `timeout`, `gtimeout`, + `xargs`, `eval`, `watch`, `sudo`, `doas`, `su`, `uv`, `poetry`, `pipx`, `npx`, `pdm`, + `hatch`, `pipenv`, `bunx`, `stdbuf`, `strace`, `ltrace`, `parallel`, `caffeinate`, + `xvfb-run`, `valgrind`, `unbuffer`, `mpiexec`, `mpirun`, `ionice`, `taskset` and + `setsid`. A wrapper that is not on this list is a program, and a flag after a script + it runs by its path is counted as its own; +- an interpreter that is given a script is no program: `bash`, `sh`, `zsh`, `dash`, + `ksh`, `csh`, `tcsh`, `fish`, `ash`, `busybox`, `pwsh`, `powershell`, `node`, + `nodejs`, `deno`, `bun`, `tsx`, `ts-node`, `coffee`, `ruby`, `jruby`, `perl`, `php`, + `lua`, `luajit`, `java`, `kotlin`, `scala`, `groovy`, `Rscript`, `R`, `julia`, + `swift`, `dart`, `elixir`, `escript`, `erl`, `racket`, `guile`, `clojure`, `clj`, + `bb`, `tclsh`, `wish`, `expect`, `awk`, `gawk`, `mawk`, `nawk`, `osascript`, `raku`, + `octave`, `runghc`, `runhaskell`, `ipython`, `jython` and `py`. Nor is a module that + runs one: `cProfile`, `profile`, `pdb`, `trace`, `timeit` and `runpy`. An interpreter + that is not on this list is a program, and a flag after its script is counted as its + own; +- a program of this list is never counted. It acts outside the checkout, as a release + tool and a database client do, moves or writes the files its operands name, or runs + what a file of recipes names: `git`, `gh`, + `hg`, `svn`, `rm`, `rmdir`, `mv`, `cp`, `ln`, `install`, `dd`, `shred`, `truncate`, + `chmod`, `chown`, `chgrp`, `touch`, `mkdir`, `mktemp`, `unlink`, `link`, `tee`, `tar`, + `unzip`, `zip`, `gzip`, `gunzip`, `bzip2`, `xz`, `zstd`, `cpio`, `patch`, `kill`, + `pkill`, `killall`, `mount`, `umount`, `crontab`, `shutdown`, `reboot`, `ssh`, `scp`, + `sftp`, `ftp`, `rsync`, `nc`, `ncat`, `telnet`, `open`, `xdg-open`, + `docker`, `docker-compose`, `podman`, `kubectl`, `helm`, `terraform`, `pulumi`, + `ansible`, `ansible-playbook`, `aws`, `gcloud`, `az`, `vercel`, `netlify`, `heroku`, + `fly`, `flyctl`, `firebase`, `serverless`, `systemctl`, `service`, `launchctl`, `curl`, + `wget`, `pip`, `pip3`, `npm`, `pnpm`, `yarn`, `conda`, `brew`, `apt`, `apt-get`, + `twine`, `cargo`, `gem`, `composer`, `go`, `dnf`, `yum`, `semantic-release`, + `release-it`, `release-please`, `standard-version`, `np`, `lerna`, `changeset`, + `goreleaser`, `bumpversion`, `bump2version`, `cz`, `flit`, `maturin`, `vsce`, `psql`, + `mysql`, `sqlite3`, `mongosh`, `redis-cli`, `clickhouse`, `clickhouse-client`, + `clickhouse-local`, `dropdb`, `createdb`, `pg_dump`, `pg_restore`, `prisma`, `dbt`, + `alembic`, `django-admin`, `make`, `just`, `rake`, `tox`, `nox`, `invoke`, `ninja`, + `gradle`, `mvn` and `bazel`; +- the programs the plugin reads as writing no file are left out by their names, + whatever their arguments: `cat`, `grep`, `ls`, `sed`, `find` and the others of that + list. + +**The flag.** A flag is a word of the run: + +- it is two dashes and lower-case words joined by dashes, 5 to 40 characters; +- a flag written with its value (`--name=value`) is no flag, and neither is a short flag + (`-x`); +- a flag of one or two letters (`--lf`, `--co`) is no flag. It is an abbreviation, and + none of the words below can be read in it; +- it is counted as added only before the run's first bare word, and before a lone `--`. + A bare word starts with no dash and holds no dot and no slash. It can be a subcommand, + or the command a wrapper runs, and the flags after it are that one's: `--preview` in + `ruff check --preview` is not counted as added to `ruff`; +- a run that holds the flag's word after that still carries the flag. A session whose + first run holds it there had the flag on its first run; +- a flag whose word holds one of these words is never counted: `force`, `yes`, `yolo`, + `confirm`, `accept`, `approve`, `assume`, `input`, `interact`, `prompt`, `ask`, + `auto`, `override`, `batch`, `attend`, `agree`, `consent`, `always`, `hard`, `delete`, + `remove`, `purge`, `prune`, `destroy`, `overwrite`, `reset`, `clear`, `clean`, + `clobber`, `wipe`, `erase`, `drop`, `zero`, `truncate`, `create`, `replace`, + `discard`, `revert`, `rollback`, `migrat`, `kill`, `flush`, `cascade`, `destruct`, + `reverse`, `bless`, `nuke`, `undo`, `restore`, `amend`, `rebase`, `squash`, `unlink`, + `expunge`, `trash`, `empty`, `modify`, `mutate`, `rename`, `merge`, `init`, `record`, + `snapshot`, `baseline`, `abort`, `terminate`, `cancel`, `restart`, `update`, `fix`, + `write`, `place`, `correct`, `gen`, `refresh`, `apply`, `noqa`, `format`, `save`, + `commit`, `exec`, `dry`, `run`, `real`, `live`, `plan`, `skip`, `only`, `collect`, + `stepwise`, `ignore`, `verif`, `check`, `strict`, `unsafe`, `insecure`, `allow`, + `disable`, `bypass`, `danger`, `bail`, `changed`, `quick`, `exclude`, `select`, + `filter`, `partial`, `subset`, `sample`, `suppress`, `lenient`, `permi`, `loose`, + `tolera`, `waive`, `exempt`, `exit`, `fail`, `never`, `warn`, `quiet`, `silent`, + `fast`, `test`, `lint`, `valid`, `error`, `continue`, `keep`, `audit`, `sign`, `hook`, + `lock`, `lax`, `cov`, `sandbox`, `privileged`, `trust`, `install`, `grade`, `prod`, + `deploy`, `publish`, `push`, `upload`, `release`, `remote`, `global`, `send`, + `submit`, `download`, `fetch`, `pull`, `sync`, `public`, `share`, `expose`, `tunnel`, + `cloud`, `proxy`, `telemetry`, `notify`, `mail`, `sudo`, `admin`, `system`, `pdb`, + `watch`, `serve`, `daemon`, `follow`, `open`, `edit`, `wait`, `pause`, `shell`, + `reload`, `repl`, `browse`, `gui`, `attach`, `inspect`, `stdin`, `help`, `version`, + `verbose`, `debug`, `trace`, `usage`, `list`, `print` and `dump`. Such a flag forces or + confirms, destroys or rewrites, turns a trial run into a real one or back, skips, + narrows or weakens a check, reaches outside the checkout, waits for a person, or only + prints what the program is; +- the lists of programs and of words are the whole of that rule. A flag of a program + that is on neither list can be counted, whatever it does: a session that reruns a + command with one more flag may be making a trial run real. The line states what + earlier sessions did and gives no instruction; +- a flag followed by its value is counted only where an earlier run held that value as a + word of its own: the command without the flag's word still holds the value. The value + is never kept. + +**What a session counts.** For each program and each of its flags the session is one of +three: + +- it had the flag on its first run, when its first run of the program carries the flag; +- it converged on the flag, when its first run of the program does not carry it, a run + that carries it where it is counted as added has an earlier run with the same words + but for the flag's word, and from the first run that carries it more than half of its + runs of the program carry it; +- it only ran the program. + +Runs are compared by a hash of their folder and their words: + +- the same words in another folder are another command; +- the folder is the command's own, or the absolute path a `cd` of the call named; +- after a `cd` to a relative path, a run is the same as another only after the same `cd` + from the same folder. The hook is told the session's folder before the command or + after it, so that run's folder is not known by any other name. + +The state holds the program's name, the flag's word and those hashes, and no other text +of a command. It holds the session's first 32 programs and the first 48 runs of each. + +A program is not counted where its first run may be unknown: + +- the session may have run it in a shape that is not read, such as after `timeout`, by + its path, with its output in a file or inside a `$(`. So every shell command is read + for the names it holds, whether or not its runs are read. A name is a word of letters, + digits and `_+-`, alone or as the last part of a path, in any place of the command's + text: in quotes, in a here-document's body or after another command. A word of one + dash and letters also names what follows its first `m`: `python -mmypy` names `mypy`; +- a program is not counted when a command names it before its first noted run, or names + it more often than it runs it in the command of that run. `pip install mypy`, + `grep -rn Final mypy` and a `mypy` run in a folder outside the checkout each end the + count of `mypy` for the session; +- the state holds a hash of each such name, 512 at most. Once it holds 512, no program + the session has not run yet is counted; +- a run the session starts another way, such as through a script or a build target, is + not seen. + +A session is counted only while its private state holds what its start wrote, and stores +nothing where it cannot tell at all: + +- the start of a new session writes that state. A session whose start the hooks did not + see has none; +- a session that is resumed gets none: it knows what its earlier part learned. A start + after a compaction is the same session's and changes nothing; +- a session that starts with no credential gets none, also where a credential comes + later: its shell commands are not noted; +- runs and names are noted from the prompt that read the repository's row on. A session + that ran a shell command before that prompt stores nothing; +- a session that ran a shell command of more than 64 KiB stores nothing; +- a session that reads a row after it noted a run or a name stores nothing. The row is a + second checkout's, or the session's copy of its own row was removed; +- the state is removed a day after its last write, at any session's start. A session + that lost it so stores nothing, and neither does one that lost its copy of the row: + that copy is written once, when the row is read. + +The state is a file of lines. The session's start writes the first. Each shell command +that changes the state adds one line after the others and rewrites none. So two shell +commands whose hooks run at the same time are both noted, in the order their lines were +written. A command that changes nothing adds no line. + +**What is stored.** When the session ends, its counts go to the repository's one memory +row, in the hand-off that carries the session's turns (`memory.set`, key +`repo:/command-flags/shell`, in the session's namespace, tagged `repo:`, +`source:` and `command-flags`): + +```text +In the repository tagged repo:, flags that sessions added to a command they had already run: mypy --no-incremental in 3 of 5 sessions that ran mypy, on the first run in 0; pytest flag:5d0c9a41e7b2 in 1 of 4 sessions that ran pytest, on the first run in 0. +``` + +- a pair of a program and a flag enters the row with the first session that converged on + it, and its counts start there. A session before it that ran the program, with the + flag or without, is not counted; +- for a pair the row holds, a session that ran the program counts one more session that + ran it, and one more that converged or had the flag on its first run; +- the row names a flag by its word only for a pair it hands. Any other pair holds a hash + of the program's name and the word, which a session matches against its own flags. So + recall of the row, and the session primer's list of the newest memories, tell no + session a flag that the line would not; +- a session that was handed a pair's line adds nothing to that pair's counts: it starts + with the flag because it was told to. The counts of a pair stay as they are while the + row hands it. A pair that a third pair overtakes is handed no more: the row names it + by its hash again, and it counts sessions again; +- a pair counts sessions until 30 have run its program. A pair the row does not hand by + then stays as it is: no later session writes the row for it, and it does not enter the + row again while the row holds it; +- the row holds eight pairs. A new pair takes the place of a pair that one session + converged on, or that counts no more and is not handed: the one whose program the most + sessions ran. It is not stored where the row has no such pair. A pair that lost its + place enters the row again as any other pair does; +- 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. A row that another session wrote + after this one read it refuses the write, and the session's counts are dropped. A + session reads the row at its first bug report, so a long session loses its counts more + often than a short one; +- a row whose value is not that sentence is left as it is. So is one with counts that no + sessions give, such as more than 30 sessions that ran a program; +- a pair of the row whose program or flag is not counted is read as not there, as in a + row written before a word joined a list. It prints no line, and the next write of the + row leaves it out. + +What leaves the machine is the program's name, three counts and the flag's word for a +pair the row hands, or a hash of the program's name and that word for any other pair, +under the repository's id. The hash has no secret part: who can read the row can try the +program's flags against it and find the word. A value the secret redaction would change +is not sent. + +**What a prompt gets.** A prompt that reads as a bug report and gets code pointers +([what a prompt gets](#what-a-prompt-gets)) carries a line under them, below the test +cost line, for each pair the row hands: + +```text +Command conventions in this repository (counted in earlier sessions, from the first that added the flag): of the 5 sessions that ran mypy, 3 first ran it without --no-incremental and then added that flag to a mypy command they had already run; none had the flag on its first mypy run. +``` + +- the lines go to a Claude Code session on a POSIX host, with or without the test + report; +- a pair is handed when three sessions or more converged on it, and more converged on it + than had the flag on their first run. A pair counts 30 sessions at most, so those + that converged are a tenth or more of the sessions that ran the program. Those counts + start at the first session that converged on the pair, and the line says so; +- a prompt gets two lines at most, for the pairs with the most converged sessions; +- the line gives the counts and no instruction; +- 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; +- the session keeps the row it read, with the checkout it was read in. A later bug + report in that checkout sends no read; +- the line is made of the row's program, flag and counts. A value that is not the stored + sentence prints nothing and is not overwritten; +- `namespace.audit` and the mentor leave that read out of the exact-key reads of the + namespace and of the agent, as they do the test cost row's. A server of an earlier + release counts it, one a session and checkout. + +What it does not do: + +- the line names no time. The hooks hold no duration of a shell call; +- a session none of whose prompts read the row stores nothing: one with no bug report, + one in a checkout with no remote, and every session in `memory` mode, with the prompt + pointers off or in a repository this Loom does not index; +- a convention that no longer holds stays in the row while the row hands it, since the + sessions that are handed it do not count. So does a pair that 30 sessions did not + hand, until a new pair takes its place in a full row: while the row holds it, a + convention that starts to hold later is not counted. `memory.delete` on the row's key + removes the row; +- the row is an ordinary memory row, so recall can serve its sentence and the server's + conflict check reads it, as with the test cost row. The sentence names the flags of + the pairs the row hands, and no other; +- it is Claude Code only: the launcher that reads the shell commands is Claude Code's, + and a Codex session reads no row and notes no run; +- it does nothing on Windows: a `cd` there can name a folder by a path the reader does + not resolve (`/c/...`), so no run is noted and no row is read. + +`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. A session with no credential notes +nothing and reads no row. What a session noted and the row it read are removed from its +private state when it ends, whatever it stores and with or without a credential, and a +day after their last write where it has not ended by then. + ## The code shunt Inside an indexed checkout, `loom-code-shunt.mjs` denies a bulk read and puts the diff --git a/docs/features/integrations/codex.md b/docs/features/integrations/codex.md index cce3c1e0213..a10a269a409 100644 --- a/docs/features/integrations/codex.md +++ b/docs/features/integrations/codex.md @@ -118,6 +118,7 @@ such an override with `bearer_token_env_var` and `?toolset=coding`, and writes ` | edits go through `apply_patch` | file context and blast radius read the target paths out of the patch text (`*** Update File:` / `*** Add File:`) | | `transcript_path` may be missing or in Codex's own shape | the hooks keep a turn journal: `loom-run` records each prompt, `loom-conversation` each reply (`last_assistant_message`) at Stop; the working-memory note, the run close, the conversation plane and session memory read it | | no per-turn token counters in the payload | `loom-usage` is not wired | +| `loom-record`, which reads a shell command's text, is not wired | no [command conventions](claude-code.md#command-conventions): no run is noted, no row is read and no line is printed | | no file for the session's shell environment | no [test report](claude-code.md#the-test-report): no option is added to `PYTEST_ADDOPTS`, and `loom-test-report` is not wired | | `SessionEnd` hooks get about one second | only fire-and-forget scripts run there (capture, run close, session memory, session brief); conversation turns are sent at Stop | | no `PostToolUseFailure` event | a `PostToolUse` result flagged as an error (`is_error`, `isError` or `error`) is observed as type `error` | diff --git a/docs/features/namespaces-and-sharing.md b/docs/features/namespaces-and-sharing.md index 6397b394a2d..4ff207b6b49 100644 --- a/docs/features/namespaces-and-sharing.md +++ b/docs/features/namespaces-and-sharing.md @@ -872,8 +872,9 @@ erasure deletes every revision of its guide. `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. 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. +leave out a coding-agent plugin's reads of a repository's test cost row (key `repo:/test-cost/pytest`) and +command conventions row (key `repo:/command-flags/shell`), which its prompt hook sends under the session's agent; +the ladder below counts them, as rows 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 diff --git a/docs/guides/optimize-namespace.md b/docs/guides/optimize-namespace.md index 5709e460252..8e735cdfa49 100644 --- a/docs/guides/optimize-namespace.md +++ b/docs/guides/optimize-namespace.md @@ -66,7 +66,8 @@ 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, 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 + `repo:/test-cost/pytest`, and command conventions row, key + `repo:/command-flags/shell`, 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. diff --git a/docs/reference/operations/mentor.md b/docs/reference/operations/mentor.md index d6d95ea9104..924f0dc5744 100644 --- a/docs/reference/operations/mentor.md +++ b/docs/reference/operations/mentor.md @@ -29,7 +29,7 @@ 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, 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]` | Calls per operation by this agent in the window, leaving out a coding-agent plugin's reads of a repository's test cost and command conventions rows (`repo:/test-cost/pytest`, `repo:/command-flags/shell`). | | `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. | diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 3713cd5752c..1b889e78c42 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.190", + "version": "1.2.191", "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": "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).", + "title": "pytest failure reasons, test cost and command conventions", + "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. Also with the memory plane on, on a POSIX host, the flags that sessions add to a command they had already run are counted from the session's shell commands, with or without pytest (a program's name, a flag's word or a hash of the program's name and the word, and three counts of sessions, one memory row a repository), and a later bug report carries a line for a flag three or more sessions added. Off: no option, no digest, no test cost and no command conventions, 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 1480862fb39..a6136801ec3 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -137,6 +137,10 @@ space on the server that your token writes to. The hooks and scripts send: 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); +- for a flag a session added to a command it had already run, the program's + name, three counts of sessions and the flag's word or a hash of the + program's name and the word, kept as one memory row a repository + (**Command conventions**, below; the same switches stop 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 @@ -276,33 +280,33 @@ the duplicate, run `claude mcp remove -s user`. ## What it wires -| Lifecycle event | Script | What it does | -| ----------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `UserPromptSubmit` | `loom-record.mjs` | The prompt's one process. Runs the two lookups the prompt waits for (`loom-prompt-pack`, `loom-prompt-recall`) in the hook itself and prints what they found as one `additionalContext`; writes the run's begin to the session's run state and hands the prompt's recording scripts (`loom-run`, `loom-namespace-health`'s audit) to a detached process and exits, as after a tool call. | -| `PostToolUse`, `PostToolUseFailure`, `PreCompact`, `Stop`, `SessionEnd` | `loom-record.mjs` | The event's one process. Runs the scripts whose answer the session waits for in the hook itself, each for the tools its row below names and only where the [mode](#modes) runs its plane: after a tool call `loom-file-context`, `loom-mentor-hint`, `loom-blast-radius`, `loom-test-gate` (only after a shell command that may have written a file) and `loom-test-report` (only after one that starts a test runner), at `Stop` the gates the install runs. It prints their answers as one, each script's text on a line of its own: a file's memory and then its test line as one `additionalContext`, the gates' reasons as one block. Runs the event's recording scripts (`loom-capture`, `loom-conversation`, `loom-usage`, `loom-working-memory`, `loom-run`'s close, `loom-session-memory`, `loom-session-brief`) in one process. After a tool call `loom-capture` records something of, at `Stop` and at `SessionEnd` that process is detached, so the session does not wait for their requests and the client, which ends a SessionEnd hook after 1.5 s, cannot cancel them. Before a compaction it is the hook itself, which exits when they have returned: the compaction's primer reads the note they write. | -| `PostToolUse` | `loom-capture.mjs` | Records one episodic observation of the tool action (heuristic type, file list). | -| `PostToolUseFailure` | `loom-capture.mjs` | Same, typed `error` — the bug-triage signal (errors + the subsequent fix). | -| `SessionStart` | `loom-session-start.mjs` | **First session, no credential:** signs this machine up (see `LOOM_AUTO_SIGNUP`) and points the user to the claim page for the namespace; nothing to paste. Then: injects a token-budgeted context primer via `context.pack`: the project's working-memory note, the profile, the session's memory stack and a few memories. In a new or cleared conversation whose prompts get the recall (`loom-prompt-recall.mjs`, which this plugin and Codex's wire, where it is on) the primer runs no memory search: the memories are the namespace's pinned rows and then its newest, five at most, and the recall searches with the prompt. Any other row arrives only when a prompt's recall finds it: a session whose recall abstains gets none. A resumed or compacted session, a session with `LOOM_PROMPT_RECALL=off` or `LOOM_PROMPT_CONTEXT=off` and a hand-wired client get the memories, decisions and procedures a search for the project finds instead. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index is read: no checkout, no remote, no answer, a repository this Loom does not index, one the session's principal is not a reader of, or one whose namespace the token does not name; an index still being built says so too. A new session whose MCP connection carries the checkout is told neither: the header helper sent the namespace, the server applies it to every `loom_code_*` call and adds the tag to a save, and a session with nothing else to hear starts with no text from the hook. How to route a lookup is in the MCP entry's startup instructions on a toolset with a `coding` part; any other toolset, and a wiring whose entry the plugin does not mount (Codex, a hand-wired client), gets it in the primer. **On by default**, once per session; `LOOM_INJECT_CONTEXT=false` to disable. | -| `PostToolUse` (Read / Grep / Bash), `PreCompact` | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about a file the call read (its files facet) and attaches the rendered block to the read's result, at no model request: the first local read of a file in the checkout — `Read`, a `Grep` of one file, or a shell `cat` / `sed -n` / `head` / `tail` / `grep pattern file` — brings its memory, so a session that only reads, or that edits through the shell, gets it too. One lookup per session, agent context and file (a subagent's read does not use up the main agent's block); a compaction clears what was shown. A record the session already holds, given whole with the prompt or printed with the same line in another file's block, is left out, and a block with nothing new is not attached; a team rule, a decision and a constraint are printed under every file they name. A file with no memory adds nothing. Reads ask about at most three files per call and 40 per session, give the request 1 s and the call 2 s in all, and stop asking after three unanswered lookups. Where the mode runs the code index, a read or an edit that asks first renews a repository lookup that is ten minutes old, which brings the repository's shared rules; a read that this takes past its 2 s leaves the file for its next read or its edit. | -| `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Before an edit of a file this agent context has not been shown, the same lookup and block — a constraint arrives **before** the edit, not as a review comment. A file shown more than 30 min ago is asked about again, and a record handed more than 30 min ago is printed again; a team rule, a decision and a constraint are printed with every block. Never a permission decision. `LOOM_FILE_CONTEXT=off` disables. | -| `PostToolUse` (loom tools) | `loom-mentor-hint.mjs` | **The store's advice reaches the model**: a loom tool result may carry one `hint` — the plane this agent is not using, named from the call it just made (a `memory.get` that missed, a search that abstained where the code index answers, a stack trace written as a memory, a duplicate write). The hook lifts it out of the result JSON into additional context, once per code per session. No request of its own. `LOOM_MENTOR_HINTS=off` disables. | -| `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which stands in for the radius's count of tests where it names the file's test, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | -| `PostToolUse` (Bash / PowerShell) | `loom-test-gate.mjs` | **A changed file's own test is named when the file changes.** After a shell command in a loom-indexed repo, asks `code.test_gate` about each file the command changed (a dirty path it names, written since the session began) and, for a file that has a test of its own, attaches its command and what the index knows of it: `Loom test for src/router.py: .venv/bin/python -m pytest -q -rf tests/test_router.py`, then `It is the one test file named for that file.` and what the checkout proves of the command. Once per file and once per test per session, on the tool result, so it costs no model request; an edit tool's call gets the same line from `loom-blast-radius.mjs`. A file with no such test, a runner the checkout does not configure, a comment-only change and a prompt that ruled a test run out get nothing, and a command that only reads (`grep`, `cat`, `sed -n`, `git diff`) starts no git process and asks nothing (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | -| `PostToolUse`, `PostToolUseFailure` (Bash) | `loom-test-report.mjs` | **Why a test failed, on the run whose output was cut.** In a checkout that configures pytest, SessionStart adds its result-file option to `PYTEST_ADDOPTS` for the session's shell commands, so every pytest run writes a private result file. After a test command whose visible output names no failure's reason (`pytest ... \| tail -3`), the hook adds a digest of that file to the tool result: the totals, up to three groups of failures by message, each with its first test and where it was raised; at most 700 characters. The hook sends no request; it notes what a pytest run of one test file cost, which the session's end stores for a slow whole run (**The test report**, below). `LOOM_TEST_REPORT=off` disables. | -| `UserPromptSubmit` | `loom-prompt-recall.mjs` | **Default `first`**: one bounded recall on the first qualifying prompt of a session, including empty or abstaining answers. Clear named code-only questions skip default recall without consuming the attempt; mixed memory requests still qualify. `LOOM_PROMPT_RECALL=on` (or the install option `prompt_recall`) for every prompt, `off` to disable; `LOOM_PROMPT_CONTEXT=off` disables it too ([what a prompt gets](#what-a-prompt-gets)). One `context.pack` per prompt restricted to `memories`, `decisions`, `procedures` with the prompt as the query; injects the records the session has not seen (each plane's under its tag; memories that answer alone under none), only when memory is not abstaining and `retrieval_confidence ≥ 0.5`, whole records within 1,600 chars (`LOOM_PROMPT_RECALL_MAX_CHARS`; one that does not fit is left out; a block's only record that the pack cut, or the first when none fits, is cut at its last whole sentence and names the call that reads it whole, the one the server's mark on the line names, or else the key to read it whole by). A record of code as it was before a commit the checkout's `HEAD` already has is left out, and a fix record whose commit it has is added as one line that names the commit. A record linked to a file of the checkout is added as one line, its key and that file, unless the prompt names the file or the definition, or asks memory: `loom-file-context` adds the record's own line after a local read of the file or before an edit of it. With `LOOM_FILE_CONTEXT=off`, or outside a checkout of a repository this Loom indexes, the prompt gets the record whole. The memory-side sibling of the prompt pack: active retrieval — the model gets what memory knows about the prompt without asking — done per prompt, never per tool turn. | -| `UserPromptSubmit` | `loom-prompt-pack.mjs` | Runs where the Loom the session talks to holds the checkout's own repository in its code index (`LOOM_PROMPT_PACK=off` stops it; [what a prompt gets](#what-a-prompt-gets)). One bounded lookup: `code.symbol`, `code.callers` or `code.impact` for an explicit named question, otherwise `code.search` (top 3, no bodies). The repository lookup and the answer share one bound (`LOOM_PROMPT_PACK_TIMEOUT_MS`, 2.5 s; a searched bug report asks for the server's pick and has 6 s): what comes later is skipped. Self-contained requests, local-only changes and explicit memory questions skip code retrieval. Search emits only where the index labels its own answer low-risk or 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. | -| `PreCompact`, `Stop`, `SessionEnd` | `loom-session-memory.mjs` | Hands the session's real turns to `memory.set_from_messages(defer=true)` in windows, each the turns since the one before (at most 200, each cut at 6,000 characters, the oldest dropped until the text fits 120,000 characters), so loom extracts the facts, writes the **session summary**, judges the outcome and distils reflections. A window goes before every compaction, at a `Stop` once 40 user and assistant turns follow the last window (`LOOM_SESSION_MEMORY_EVERY_TURNS`) or once two do and the last window is 30 minutes old (`LOOM_SESSION_MEMORY_IDLE_MINUTES`), and at `SessionEnd`, which sends the rest: a session that is never ended, or whose host is killed, has had its turns extracted up to its last window. Up to 20 turns before a window ride as `last_messages`, which the extractor reads and does not extract again. The turns are kept as the facts' source evidence. The hand-off at `SessionEnd` 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 whose last turns went in an earlier window sends nothing at its end and names no files. A window with fewer than two turns, no prompt or 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: its turns join the next window, and a session that ends with only that much gets no rule extracted from it and no session summary, outcome judgement or reflections. A per-session cursor in the temp directory marks where the next window starts. It moves before the post goes to the detached flusher, which puts it back when the post fails. No lock is taken: a flusher killed after a failed post and before it restores the cursor loses that window, and two hooks of one session that overlap between reading the cursor and moving it send one window twice, which the write path's duplicate handling absorbs. The session summary keeps the facts of the session's earlier windows ahead of a later one's; a server that predates windows writes each window's own summary, so the session's summary there holds its last window's facts. The hand-off at `SessionEnd` carries one `memory.set` of what a slow whole run of one test file cost, where the session measured one and its bug report read the repository's row, whether or not its turns are sent (**The test report**, below). `LOOM_SESSION_MEMORY=off` disables. | -| `Stop` / `SessionEnd` | `loom-conversation.mjs` | Appends new chat turns from the transcript to the conversation plane (→ the dashboard's Conversations page). Deterministic, every turn; per-session cursor + `msg_id`=transcript uuid dedup. Text blocks only — an image the user pasted becomes a `[image: ]` placeholder beside its text, and a tool result that returned images leaves one `tool` turn `[image: N image results returned by a tool]`; the bytes never leave the machine. Off-switch: `LOOM_CAPTURE_CONVERSATIONS=false`. | +| Lifecycle event | Script | What it does | +| ----------------------------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `UserPromptSubmit` | `loom-record.mjs` | The prompt's one process. Runs the two lookups the prompt waits for (`loom-prompt-pack`, `loom-prompt-recall`) in the hook itself and prints what they found as one `additionalContext`; writes the run's begin to the session's run state and hands the prompt's recording scripts (`loom-run`, `loom-namespace-health`'s audit) to a detached process and exits, as after a tool call. | +| `PostToolUse`, `PostToolUseFailure`, `PreCompact`, `Stop`, `SessionEnd` | `loom-record.mjs` | The event's one process. Runs the scripts whose answer the session waits for in the hook itself, each for the tools its row below names and only where the [mode](#modes) runs its plane: after a tool call `loom-file-context`, `loom-mentor-hint`, `loom-blast-radius`, `loom-test-gate` (only after a shell command that may have written a file) and `loom-test-report` (only after one that starts a test runner), at `Stop` the gates the install runs. It prints their answers as one, each script's text on a line of its own: a file's memory and then its test line as one `additionalContext`, the gates' reasons as one block. Runs the event's recording scripts (`loom-capture`, `loom-conversation`, `loom-usage`, `loom-working-memory`, `loom-run`'s close, `loom-session-memory`, `loom-session-brief`) in one process. After a tool call `loom-capture` records something of, at `Stop` and at `SessionEnd` that process is detached, so the session does not wait for their requests and the client, which ends a SessionEnd hook after 1.5 s, cannot cancel them. Before a compaction it is the hook itself, which exits when they have returned: the compaction's primer reads the note they write. | +| `PostToolUse` | `loom-capture.mjs` | Records one episodic observation of the tool action (heuristic type, file list). | +| `PostToolUseFailure` | `loom-capture.mjs` | Same, typed `error` — the bug-triage signal (errors + the subsequent fix). | +| `SessionStart` | `loom-session-start.mjs` | **First session, no credential:** signs this machine up (see `LOOM_AUTO_SIGNUP`) and points the user to the claim page for the namespace; nothing to paste. Then: injects a token-budgeted context primer via `context.pack`: the project's working-memory note, the profile, the session's memory stack and a few memories. In a new or cleared conversation whose prompts get the recall (`loom-prompt-recall.mjs`, which this plugin and Codex's wire, where it is on) the primer runs no memory search: the memories are the namespace's pinned rows and then its newest, five at most, and the recall searches with the prompt. Any other row arrives only when a prompt's recall finds it: a session whose recall abstains gets none. A resumed or compacted session, a session with `LOOM_PROMPT_RECALL=off` or `LOOM_PROMPT_CONTEXT=off` and a hand-wired client get the memories, decisions and procedures a search for the project finds instead. Beside it, one line names the checkout's code namespace and the repository's memory tag, or says why no index is read: no checkout, no remote, no answer, a repository this Loom does not index, one the session's principal is not a reader of, or one whose namespace the token does not name; an index still being built says so too. A new session whose MCP connection carries the checkout is told neither: the header helper sent the namespace, the server applies it to every `loom_code_*` call and adds the tag to a save, and a session with nothing else to hear starts with no text from the hook. How to route a lookup is in the MCP entry's startup instructions on a toolset with a `coding` part; any other toolset, and a wiring whose entry the plugin does not mount (Codex, a hand-wired client), gets it in the primer. **On by default**, once per session; `LOOM_INJECT_CONTEXT=false` to disable. | +| `PostToolUse` (Read / Grep / Bash), `PreCompact` | `loom-file-context.mjs` | Asks `memory.for_file` what loom knows about a file the call read (its files facet) and attaches the rendered block to the read's result, at no model request: the first local read of a file in the checkout — `Read`, a `Grep` of one file, or a shell `cat` / `sed -n` / `head` / `tail` / `grep pattern file` — brings its memory, so a session that only reads, or that edits through the shell, gets it too. One lookup per session, agent context and file (a subagent's read does not use up the main agent's block); a compaction clears what was shown. A record the session already holds, given whole with the prompt or printed with the same line in another file's block, is left out, and a block with nothing new is not attached; a team rule, a decision and a constraint are printed under every file they name. A file with no memory adds nothing. Reads ask about at most three files per call and 40 per session, give the request 1 s and the call 2 s in all, and stop asking after three unanswered lookups. Where the mode runs the code index, a read or an edit that asks first renews a repository lookup that is ten minutes old, which brings the repository's shared rules; a read that this takes past its 2 s leaves the file for its next read or its edit. | +| `PreToolUse` (Edit / Write / MultiEdit / NotebookEdit) | `loom-file-context.mjs` | Before an edit of a file this agent context has not been shown, the same lookup and block — a constraint arrives **before** the edit, not as a review comment. A file shown more than 30 min ago is asked about again, and a record handed more than 30 min ago is printed again; a team rule, a decision and a constraint are printed with every block. Never a permission decision. `LOOM_FILE_CONTEXT=off` disables. | +| `PostToolUse` (loom tools) | `loom-mentor-hint.mjs` | **The store's advice reaches the model**: a loom tool result may carry one `hint` — the plane this agent is not using, named from the call it just made (a `memory.get` that missed, a search that abstained where the code index answers, a stack trace written as a memory, a duplicate write). The hook lifts it out of the result JSON into additional context, once per code per session. No request of its own. `LOOM_MENTOR_HINTS=off` disables. | +| `PostToolUse` (Edit / Write / MultiEdit) | `loom-blast-radius.mjs` | In a loom-indexed repo, diffs the edited file against HEAD and asks `code.impact` (depth 1) what the touched symbols reach. Injects **one line**: callers, tests reaching the change, and the co-change partner files this session has not touched — the sibling-file miss, surfaced while the edit is still open. Same touched set reported once per session. The first edit of a file in a session also carries the test gate's line (next row), which stands in for the radius's count of tests where it names the file's test, so an edit gets one line. `LOOM_BLAST_RADIUS=off` disables the radius. | +| `PostToolUse` (Bash / PowerShell) | `loom-test-gate.mjs` | **A changed file's own test is named when the file changes.** After a shell command in a loom-indexed repo, asks `code.test_gate` about each file the command changed (a dirty path it names, written since the session began) and, for a file that has a test of its own, attaches its command and what the index knows of it: `Loom test for src/router.py: .venv/bin/python -m pytest -q -rf tests/test_router.py`, then `It is the one test file named for that file.` and what the checkout proves of the command. Once per file and once per test per session, on the tool result, so it costs no model request; an edit tool's call gets the same line from `loom-blast-radius.mjs`. A file with no such test, a runner the checkout does not configure, a comment-only change and a prompt that ruled a test run out get nothing, and a command that only reads (`grep`, `cat`, `sed -n`, `git diff`) starts no git process and asks nothing (**Tests at edit time**, below). `LOOM_TEST_GATE=off` disables; `LOOM_TEST_GATE_DEPTH` sets the hops (1–3). | +| `PostToolUse`, `PostToolUseFailure` (Bash) | `loom-test-report.mjs` | **Why a test failed, on the run whose output was cut.** In a checkout that configures pytest, SessionStart adds its result-file option to `PYTEST_ADDOPTS` for the session's shell commands, so every pytest run writes a private result file. After a test command whose visible output names no failure's reason (`pytest ... \| tail -3`), the hook adds a digest of that file to the tool result: the totals, up to three groups of failures by message, each with its first test and where it was raised; at most 700 characters. The hook sends no request; it notes what a pytest run of one test file cost, which the session's end stores for a slow whole run (**The test report**, below). `LOOM_TEST_REPORT=off` disables. | +| `UserPromptSubmit` | `loom-prompt-recall.mjs` | **Default `first`**: one bounded recall on the first qualifying prompt of a session, including empty or abstaining answers. Clear named code-only questions skip default recall without consuming the attempt; mixed memory requests still qualify. `LOOM_PROMPT_RECALL=on` (or the install option `prompt_recall`) for every prompt, `off` to disable; `LOOM_PROMPT_CONTEXT=off` disables it too ([what a prompt gets](#what-a-prompt-gets)). One `context.pack` per prompt restricted to `memories`, `decisions`, `procedures` with the prompt as the query; injects the records the session has not seen (each plane's under its tag; memories that answer alone under none), only when memory is not abstaining and `retrieval_confidence ≥ 0.5`, whole records within 1,600 chars (`LOOM_PROMPT_RECALL_MAX_CHARS`; one that does not fit is left out; a block's only record that the pack cut, or the first when none fits, is cut at its last whole sentence and names the call that reads it whole, the one the server's mark on the line names, or else the key to read it whole by). A record of code as it was before a commit the checkout's `HEAD` already has is left out, and a fix record whose commit it has is added as one line that names the commit. A record linked to a file of the checkout is added as one line, its key and that file, unless the prompt names the file or the definition, or asks memory: `loom-file-context` adds the record's own line after a local read of the file or before an edit of it. With `LOOM_FILE_CONTEXT=off`, or outside a checkout of a repository this Loom indexes, the prompt gets the record whole. The memory-side sibling of the prompt pack: active retrieval — the model gets what memory knows about the prompt without asking — done per prompt, never per tool turn. | +| `UserPromptSubmit` | `loom-prompt-pack.mjs` | Runs where the Loom the session talks to holds the checkout's own repository in its code index (`LOOM_PROMPT_PACK=off` stops it; [what a prompt gets](#what-a-prompt-gets)). One bounded lookup: `code.symbol`, `code.callers` or `code.impact` for an explicit named question, otherwise `code.search` (top 3, no bodies). The repository lookup and the answer share one bound (`LOOM_PROMPT_PACK_TIMEOUT_MS`, 2.5 s; a searched bug report asks for the server's pick and has 6 s): what comes later is skipped. Self-contained requests, local-only changes and explicit memory questions skip code retrieval. Search emits only where the index labels its own answer low-risk or 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. Below it go the command conventions lines, from a second such `memory.get` (**Command conventions**, below). | +| `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. | +| `PreCompact`, `Stop`, `SessionEnd` | `loom-session-memory.mjs` | Hands the session's real turns to `memory.set_from_messages(defer=true)` in windows, each the turns since the one before (at most 200, each cut at 6,000 characters, the oldest dropped until the text fits 120,000 characters), so loom extracts the facts, writes the **session summary**, judges the outcome and distils reflections. A window goes before every compaction, at a `Stop` once 40 user and assistant turns follow the last window (`LOOM_SESSION_MEMORY_EVERY_TURNS`) or once two do and the last window is 30 minutes old (`LOOM_SESSION_MEMORY_IDLE_MINUTES`), and at `SessionEnd`, which sends the rest: a session that is never ended, or whose host is killed, has had its turns extracted up to its last window. Up to 20 turns before a window ride as `last_messages`, which the extractor reads and does not extract again. The turns are kept as the facts' source evidence. The hand-off at `SessionEnd` 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 whose last turns went in an earlier window sends nothing at its end and names no files. A window with fewer than two turns, no prompt or 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: its turns join the next window, and a session that ends with only that much gets no rule extracted from it and no session summary, outcome judgement or reflections. A per-session cursor in the temp directory marks where the next window starts. It moves before the post goes to the detached flusher, which puts it back when the post fails. No lock is taken: a flusher killed after a failed post and before it restores the cursor loses that window, and two hooks of one session that overlap between reading the cursor and moving it send one window twice, which the write path's duplicate handling absorbs. The session summary keeps the facts of the session's earlier windows ahead of a later one's; a server that predates windows writes each window's own summary, so the session's summary there holds its last window's facts. The hand-off at `SessionEnd` 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), and one of the repository's command conventions row (**Command conventions**, 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. @@ -338,6 +342,28 @@ Test cost in this repository (measured in earlier sessions): a whole run of test The clause about the timeout is printed for a run over 120 s, the default of a shell call under Claude Code, and the middle sentence where a filtered run was measured. 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. +**Command conventions.** A repository can need a flag on a command that nothing in it names, such as a type checker that must be run without its incremental cache. A session that does not know runs the command, reads a result it cannot use, and runs it again with the flag. With the memory plane on and session memory not switched off, the plugin counts the flags that sessions add this way from their shell commands, with no model call, and a later session in the repository is told before its first run. It does so in a Claude Code session on a POSIX host, in any checkout that gets code pointers: the session needs no test report. The reader refuses a shape it does not know: a missed convention costs nothing, and a wrong line is read by every later session. The [feature page](../../docs/features/integrations/claude-code.md#command-conventions) writes out every rule and list named here. + +No run of a call is read where it holds a backquote, `$(` or `$'` outside single quotes, a backslash outside quotes or before a double quote inside double quotes, a quote left open, a parenthesis or a brace outside quotes, a `|` at a line's end, a simple command that starts with a shell keyword, or a here-document whose word is not a plain word or whose body has no end line. In a call that is read, the lines of a here-document's body and comments are left out. A run is a simple command of the call, cut at `;`, `&&`, `||`, `|` and line ends, that is no later stage of a pipeline. A simple command that holds `&`, `<` or `>` outside quotes, or more than 24 words, is no run; a redirect between descriptors (`2>&1`) or to `/dev/null` is passed over. A run is noted where its folder is in the checkout: the command's folder, or the one a `cd` to one plain path changed to. After any other `cd`, a `pushd` or a `popd`, the rest of the call is not read. A run in another checkout under that one is not noted: a folder that holds a `.git`, and every folder below it, is a submodule's, a worktree's or another clone's. + +The program is the first word after the variable assignments: a bare name, or the module of `python -m` or `pypy -m`. A path is no program, so a script named by its path never is one, and neither is a name with a dot: a module named with one (`python -m scripts.sync`) is a file inside a package. A module with no dot is a program wherever its file lies, at the checkout's root too (`python -m sync`, with a `sync.py` there): the command does not say where. A word that starts another command is no program (`env`, `timeout`, `xargs`, `sudo`, `uv`, `npx` and the like), and neither is an interpreter that is given a script (`bash`, `node`, `ruby`, `perl`, `julia` and the others of that list). An interpreter or a wrapper that is not on its list is a program, and a flag after the script it runs is counted as its own. A program that acts outside the checkout, moves or writes the files its operands name, or runs what a file of recipes names, is never counted: `git`, `rm`, `cp`, `tar`, `ssh`, `docker`, `kubectl`, `curl`, `pip`, `npm`, `psql`, `make` and the others of that list. The programs the plugin reads as writing no file, such as `cat`, `grep`, `ls` and `sed`, are left out by their names, whatever their arguments. + +A flag is a word of the run that is two dashes and lower-case words joined by dashes, 5 to 40 characters. A flag written with its value (`--name=value`) and a short flag are no flags, and neither is a flag of one or two letters (`--lf`): it is an abbreviation, and no refused word can be read in it. A flag is counted as added only before the run's first bare word and before a lone `--`. A bare word starts with no dash and holds no dot and no slash: it can be a subcommand, or the command a wrapper runs, and the flags after it are that one's. A run that holds the flag's word after that still carries the flag. A flag whose word holds a refused word is never counted: `force`, `yes`, `hard`, `delete`, `skip`, `ignore`, `verif`, `check`, `only`, `fix`, `write`, `format`, `exec`, `run`, `test`, `install`, `help`, `verbose` and the others of that list. Such a flag forces or confirms, destroys or rewrites, turns a trial run into a real one or back, skips, narrows or weakens a check, reaches outside the checkout, waits for a person, or only prints what the program is. The two lists are the whole of that rule: a flag of a program that is on neither can be counted, whatever it does. A flag followed by its value is counted only where an earlier run held that value as a word of its own, and the value is never kept. + +A session had a flag on its first run when its first run of the program carries it. It converged on the flag when its first run does not carry it, a run that carries it where it is counted as added has an earlier run with the same words but for the flag's word, and from the first run that carries it more than half of its runs of the program carry it. Runs are compared by a hash of their folder and their words, so the same words in another folder are another command: the folder is the command's own or the absolute path a `cd` named, and after a `cd` to a relative path a run is the same as another only after the same `cd` from the same folder. The session's private state holds the program's name, the flag's word and those hashes, and no other text of a command. Each shell command that changes the state adds one line to it and rewrites none, so two commands whose hooks run at the same time are both noted, in the order their lines were written. A program is not counted where its first run may be unknown. The session may have run it in a shape that is not read, such as after `timeout`, by its path or inside a `$(`, so every shell command is read for the names it holds: a word of letters, digits and `_+-`, alone or as the last part of a path, in any place of the command's text. A word of one dash and letters also names what follows its first `m`: `python -mmypy` names `mypy`. A program is not counted when a command names it before its first noted run, or names it more often than it runs it in the command of that run: `pip install mypy`, `grep -rn Final mypy` and a `mypy` run in a folder outside the checkout each end the count of `mypy` for the session. The state holds a hash of each such name. Runs and names are noted from the prompt that read the repository's row on. A session is counted only while its private state holds what its start wrote, and stores nothing where it cannot tell at all: one whose start the hooks did not see, one that is resumed, one that started with no credential, one that ran a shell command before that prompt, one that ran a shell command of more than 64 KiB, one that reads a row after it noted a run or a name (a second checkout's row, or its own after its copy was removed), and one whose state the day-old sweep of state files removed. When the session ends, its counts go to the repository's one memory row (`memory.set`, key `repo:/command-flags/shell`, in the session's namespace): + +```text +In the repository tagged repo:, flags that sessions added to a command they had already run: mypy --no-incremental in 3 of 5 sessions that ran mypy, on the first run in 0; pytest flag:5d0c9a41e7b2 in 1 of 4 sessions that ran pytest, on the first run in 0. +``` + +A pair of a program and a flag enters the row with the first session that converged on it, and its counts start there. For a pair the row holds, a session that ran the program counts one more session that ran it, and one more that converged or had the flag on its first run. The row names a flag by its word only for a pair it hands, and by a hash of the program's name and the word before, so recall of the row tells no session a flag that the line would not. A session that was handed a pair's line adds nothing to that pair's counts, since it starts with the flag because it was told to: the counts of a pair stay as they are while the row hands it, and `memory.delete` on the row's key removes a convention that no longer holds. A pair that a third pair overtakes is handed no more: the row names it by its hash again, and it counts sessions again. A pair counts sessions until 30 have run its program: one the row does not hand by then stays as it is, so no later session writes the row for it. The row holds eight pairs, and a new pair takes the place of one that one session converged on, or that counts no more and is not handed. A pair whose program or flag is not counted, in a row written before a word joined a list, is read as not there, and the next write of the row leaves it out. The write names the value the session read and goes under the agent that wrote the row; a row that another session wrote after this one read it refuses the write, and the session's counts are dropped. What leaves the machine is the program's name, three counts and the flag's word for a pair the row hands, or a hash of the program's name and that word for any other pair, under the repository's id. The hash has no secret part: who can read the row can try the program's flags against it and find the word. A prompt that reads as a bug report and gets code pointers carries a line under them, below the test cost line, for each pair the row hands: + +```text +Command conventions in this repository (counted in earlier sessions, from the first that added the flag): of the 5 sessions that ran mypy, 3 first ran it without --no-incremental and then added that flag to a mypy command they had already run; none had the flag on its first mypy run. +``` + +A pair is handed when three sessions or more converged on it, and more converged on it than had the flag on their first run. A pair counts 30 sessions at most, so those that converged are a tenth or more of the sessions that ran the program. A prompt gets two lines at most, for the pairs with the most converged sessions. The line gives the counts and no instruction, and names no time: the hooks hold no duration of a shell call. The row is read with one `memory.get`, beside the prompt's search and never waited for past its answer, and the session keeps the row it read in that checkout. `namespace.audit` and the mentor leave that read out of their exact-key reads, as they do the test cost row's; a server of an earlier release counts it. The lines go to a Claude Code session on a POSIX host, with or without the test report: the launcher that reads the shell commands is Claude Code's, and on Windows a `cd` can name a folder by a path the reader does not resolve. `LOOM_TEST_REPORT=off` stops the note and the line, `LOOM_SESSION_MEMORY=off` the note and the write, and `code` mode all three. A session with no credential notes nothing and reads no row, and one that started with none stores nothing where a credential comes later. What a session noted and the row it read are removed from its private state when it ends. + **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. @@ -705,7 +731,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`, no failure digest after a cut pytest run and no test cost noted or printed (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 or command convention 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 3f01858ca1a..ce2280cf7c4 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -144,41 +144,41 @@ 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; 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-memory | transcript, cwd | none | memory.set_from_messages of the turns since the last hand-off, via the flusher | `LOOM_SESSION_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` | -| Stop, detached | loom-session-memory | transcript, cwd | none | memory.set_from_messages via the flusher, once 40 turns follow the last hand-off or two do and it is 30 minutes old | `LOOM_SESSION_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 of the turns since the last hand-off 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` | +| 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; at a new session's start, the session's state for the command conventions, which a resume removes | `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, one memory.get each for the test cost row (with a test report) and command conventions row, unless kept | `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; after a shell command it notes its runs, and at a SessionEnd with no credential it removes the session's command conventions state (**loom-record, command conventions**) | 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-memory | transcript, cwd | none | memory.set_from_messages of the turns since the last hand-off, via the flusher | `LOOM_SESSION_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` | +| Stop, detached | loom-session-memory | transcript, cwd | none | memory.set_from_messages via the flusher, once 40 turns follow the last hand-off or two do and it is 30 minutes old | `LOOM_SESSION_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 of the turns since the last hand-off and, for a slow whole run of one test file and for the command conventions row, one memory.set each, 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 @@ -266,13 +266,13 @@ record: the run and its usage counters. | 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-pack | code; memory for the test cost line and the command conventions lines 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-record | ledger (keeps the run's begin); memory (a late run's cost at SessionEnd, each shell command's runs); 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-session-start | memory (pack, tag, task, brief, collections and recording lines, the command conventions state); 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 | @@ -1010,6 +1010,33 @@ default 120 s timeout of a shell call. A run filtered with -k takes about 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 command conventions lines.** Below that line the same prompt + carries a line for each pair of a program and a flag that the + repository's command conventions row hands (**loom-record, command + conventions**, below), two at most: + `Command conventions in this repository (counted in earlier sessions, from +the first that added the flag): of the sessions that ran , +first ran it without and then added that flag to a command +they had already run; none had the flag on its first run.` The + last clause reads ` had the flag on their first run` where + some did (`renderFlag` in lib/command-flags.mjs). A pair is handed when + the row names its flag by its word, three sessions or more converged on + it, and more converged on it than had the flag on their first run. A + pair counts 30 sessions at most, so those that converged are a tenth or + more of the sessions that ran the program. The counts + start at the first session that converged on the pair, and the line says + so. The two pairs with the most converged sessions are printed. The line + gives counts and no instruction. The row is a second `memory.get` by + key, sent, bounded, kept in the session's state and asked again as the + test cost row is, and the two reads share one resolution of the + checkout's scope. The line is made of the row's program, flag and counts + and never of its text: a value that is not the stored sentence prints + nothing. namespace.audit leaves reads of the row's key out of its + exact-key count (`exact_key_store` from rule version 4) and the mentor + out of the agent's exact-key reads, as with the test cost row + (`HOOK_READ_KEYS`); a server of an earlier release counts it in both, one + a session and checkout. The lines need the memory plane and a Claude Code + session on a POSIX host, with or without 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 @@ -1704,6 +1731,210 @@ about s.` The write revises the row the session read (`if_match_sha256`), row, prints no line and notes no run. - LOOM_TEST_REPORT=off, or the `test_report` option set to false, stops all of it from the session's next start. +- **loom-record, command conventions.** A repository can need a flag on a + command that nothing in it names, such as a type checker that must be run + without its incremental cache. A session that does not know runs the + command, reads a result it cannot use, and runs it again with the flag. + The launcher counts such flags from the session's shell commands, with no + model call (lib/command-flags.mjs). It reads the command of every Bash + PostToolUse and PostToolUseFailure itself, where the session's shell + commands are counted (`countsRuns` in lib/test-report.mjs, which the + launcher asks first, to leave the library unloaded, and + `loom-session-start` asks at the session's start). They are counted where + its prompts are told, with LOOM_TEST_REPORT not off, in Claude Code on a + POSIX host (`conventionsOn`), and where its end can store them: with the + memory plane on, LOOM_SESSION_MEMORY not off and a credential. Any other + session notes no run, and its start writes no state. One whose prompts + are told still reads the row at a bug report and keeps its copy. The + session needs no test report. The reader refuses a shape it does not + know: a missed convention costs nothing, and a wrong line is read by + every later session. The lists named here are written out in the feature + page + ([command conventions](../../../docs/features/integrations/claude-code.md#command-conventions)). + - **A call that is not read.** No run of a call is read where it holds a + backquote, `$(` or `$'` outside single quotes, a backslash outside + quotes or before a double quote inside double quotes, a quote left open + (`unquotedText` in lib/shell-command.mjs), a parenthesis or a brace + outside quotes, or a `|` at a line's end, whose pipeline goes on in the + next line (`OPEN_PIPE`). Nor is one with a simple command that starts + with a shell keyword (`KEYWORDS`), or one with a here-document whose + word is not a plain word, alone or in one pair of quotes, or whose body + has no end line. + - **A run.** The lines of a here-document's body and comments are left + out. A run is a simple command of the call, which is cut at `;`, `&&`, + `||`, `|` and line ends (`splitOutsideQuotes`). A later stage of a + pipeline is no run. A simple command that holds `&`, `<` or `>` outside + quotes is no run; a redirect between descriptors (`2>&1`) or to + `/dev/null` is passed over (`NO_FILE_REDIRECT`). A simple command of + more than 24 words is no run. + - **The folder.** A run is noted where its folder is in the checkout of + the row the session read. Its folder is the payload's `cwd`, or the one + a `cd` of the call to one plain path changed to. After any other `cd`, + a `pushd` or a `popd`, the rest of the call is not read. A run in + another checkout under that one is not noted: a folder that holds a + `.git`, and every folder below it, is a submodule's, a worktree's or + another clone's (`own`). The payload's `cwd` is the session's folder + before the command or after it. So after a `cd` to a relative path both + the `cwd` and the path from it are the checkout's own, and the run's + folder is named by the two (`place`). + - **The program.** The program is the first word after the variable + assignments. It is a bare name of 40 characters at most, or the module + of `python -m` or `pypy -m`, where the interpreter is named by its bare + name, with or without a version, and `-m` is its first word. A path is + no program, so a script named by its path never is one. A name with a + dot is no program either: a module named with one is a file inside a + package (`PROGRAM`). Nor is a name every JavaScript object has, such as + `constructor` (`counted`). A module with no dot is a program wherever + its file lies, at the checkout's root too: the command does not say + where. A word that starts another command, an interpreter that is + given a script and a module that runs one are no programs + (`OTHER_COMMAND`). An interpreter or a wrapper that is not on that list + is a program, and a flag after the script it runs is counted as its + own. A program that acts outside the checkout, moves or writes the + files its operands name, or runs what a file of recipes names, is never + counted (`OUTSIDE`). The programs of + `READ_PROGRAMS` in lib/shell-command.mjs are left out by their names, + whatever their arguments. + - **The flag.** A flag is a word of the run that is two dashes and + lower-case words joined by dashes, 5 to 40 characters. A flag written + with its value (`--name=value`) and a short flag are no flags. Nor is a + flag of one or two letters (`--lf`): it is an abbreviation, and no word + of `REFUSED` can be read in it. A flag is counted as added only before + the run's first bare word and before a lone `--`. A bare word starts + with no dash and holds no dot and no slash: it can be a subcommand, or + the command a wrapper runs, and the flags after it are that one's. A + run that holds the flag's word after that still carries the flag + (`entry`). A flag whose word holds one of `REFUSED` is never counted. + Such a flag forces or confirms, destroys or rewrites, turns a trial run + into a real one or back, skips, narrows or weakens a check, reaches + outside the checkout, waits for a person, or only prints what the + program is. A test holds the feature page's lists to the library's. + `OUTSIDE` and `REFUSED` are the whole of that rule: a flag of a program + that is on neither list can be counted, whatever it does. A flag + followed by its value is counted only where an earlier run held that + value as a word of its own; the value is never kept. + - **What a session counts.** A session had a flag on its first run when + its first run of the program carries it. It converged on the flag when + its first run does not carry it, a run that carries it where it is + counted as added has an earlier run with the same words but for the + flag's word, and from the first run that carries it more than half of + its runs of the program carry it (`sessionCounts`). Runs are compared + by a hash of their folder and their words: the same words in another + folder are another command. The folder is the payload's `cwd`, or the + absolute path a `cd` named. After a `cd` to a relative path a run is + the same as another only after the same `cd` from the same `cwd`. The + state holds the program's name, the flag's word and those hashes, and + no other text of a command. It holds the session's first 32 programs + and the first 48 runs of each. + - **A program whose first run is unknown.** The session may have run a + program in a shape that is not read: after `timeout`, by its path, with + its output in a file, inside a `$(`. So every shell command is read for + the names it holds, whether or not its runs are read (`names`). A name + is a word of letters, digits and `_+-`, alone or as the last part of a + path, in any place of the command's text. A word of one dash and + letters also names what follows its first `m` (`MODULE_OPTION`): + `python -mmypy` names `mypy`. A program is not counted when + a command names it before its first noted run, or names it more often + than it runs it in the command of that run: a run in a folder outside + the checkout only names its program. The state holds a hash of each + such name, 512 at most, and once it holds 512 no program the session + has not run yet is counted. A run the session starts another way, such + as through a script, is not seen. + - **A session that stores nothing.** A session is counted only while its + state holds what its start wrote. `loom-session-start` writes it for a + new session (`source` is `startup` or `clear`) whose shell commands are + counted, and removes what an earlier part of the session left + (`startFlags`). A session that is resumed gets no state: it knows what + its earlier part learned. Nor does one that starts with no credential, + which the hook reads before it signs the session up: its shell commands + are not noted, so its first run after a credential comes is no first + run. Nor does one whose start the hooks did not see. A start after a + compaction changes nothing. Runs and names are noted from the prompt + that read the repository's row on. A session that ran a shell command + before that prompt loses its state and stores nothing: its first run of + a program is unknown. So does one that ran a shell command of more than + 64 KiB, and one that reads a row after it noted a run or a name: the + row is a second checkout's, or the session's copy of its own was + removed. The day-old sweep of state files, at any session's start, + removes the state and the row's copy a day after their last write, and + the copy is written once: a session that lost either stores nothing. + With no credential no hand-off runs at SessionEnd, and the launcher + removes the state (`endFlags`). + - **The state's lines.** The state is a file of lines. The session's + start writes the first. Each shell command that changes the state adds + one line after the others and rewrites none (`noteRuns`). So two shell + commands whose hooks run at the same time are both noted, in the order + their lines were written. A command that changes nothing adds no line. + The state is read as the first line with every later one folded in + (`stateOf`). A last line with no line end is being written, and is not + read. A file whose first line is not the start's is no state: a hook + that read the state before another removed it adds its line to a new + file. + - **The row.** At SessionEnd `loom-session-memory` hands one + `memory.set` to the flusher with the turns' hand-off, whether or not + the turns are sent (`flagsPost`). The key is + `repo:/command-flags/shell`, one row a repository in the session's + namespace, tagged `repo:`, `source:` and `command-flags`, + with `files: []` and `source_class: "external"`. The value is one + sentence: + `In the repository tagged repo:, flags that sessions added to a +command they had already run: in of sessions that +ran , on the first run in .` Its pairs are joined by `; `. A + pair enters the row with the first session that converged on it, and + its counts start there: a session before it that ran the program is not + counted. For a pair the row holds, a session that ran the program + counts one more session that ran it, and one more that converged or had + the flag on its first run (`revised`). The row names a flag by its word + only for a pair it hands (`handed`). Any other pair holds + `flag:`, a hash of the program's name and the word, which a session + matches against its own flags. So recall of the row, and the primer's + list of the newest memories, tell no session a flag that the line would + not. A session that was handed a pair's line adds nothing to that + pair's counts: it starts with the flag because it was told to. The + counts of a pair therefore stay as they are while the row hands it, and + a convention that no longer holds leaves the row only by + `memory.delete` on its key. A pair that a third pair overtakes is + handed no more: the row names it by its hash again, and it counts + sessions again. A pair counts sessions until 30 have run + its program: one the row does not hand by then stays as it is, so no + later session writes the row for it, and it does not enter the row + again while the row holds it. The row holds eight pairs: a new pair + takes the place of a pair that one session converged on, or that counts + no more and is not handed, the one whose program the most sessions ran, + and is not stored where the row has no such pair. A pair that lost its + place enters again as any other does. 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. A row that another session wrote + after this one read it refuses the write, and the session's counts are + dropped: a session reads the row at its first bug report, so a long + session loses its counts more often than a short one. A value that is + not that sentence is left as it is, and so is one with counts that no + sessions give, such as more than 30 that ran a program. A pair of the + row whose program or flag is not counted is read as not there + (`parseClaim`): a row written before a word joined a list prints no + line for it, and the next write of the row leaves it out. + - **What leaves the machine.** The program's name, three counts and the + flag's word for a pair the row hands, or a hash of the program's name + and that word for any other pair (`hidden`), under the repository's id. + The hash has no secret part: who can read the row can try the program's + flags against it and find the word. A value the secret redaction would + change is not sent. + - **What it does not do.** The line names no time: the hooks hold no + duration of a shell call. A session none of whose prompts read the row + stores nothing. It is Claude Code only: the launcher that reads the + shell commands is Claude Code's, and a Codex session reads no row and + notes no run. It does nothing on Windows, where a `cd` can name a + folder by a path the reader does not resolve (`/c/...`). The row is an + ordinary memory row, so recall can serve its sentence and the server's + conflict check reads it, as with the test cost row. + - **Switches and state.** LOOM_TEST_REPORT=off stops the note and the + lines, LOOM_SESSION_MEMORY=off the note and the write, and a session + in code-only mode notes, stores and prints nothing. A session with no + credential notes nothing and reads no row. At SessionEnd + `loom-session-memory` removes the runs and the row from the session's + state, whatever it stores, and the launcher removes them for a session + that ends with no credential (`endFlags`). In a session that stays open + they go with the other state files, a day after their last write. - **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 @@ -1904,43 +2135,43 @@ either; SessionStart says so once. Switches read on/true/1/yes and off/false/0/no. Defaults in parentheses. -| Setting | Read by | Meaning | -| --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------- | -| `LOOM_API_KEY`, `LOOM_BASE_URL` | every hook | the credential and the server | -| `LOOM_ORG`, `LOOM_NAMESPACE`, `LOOM_AGENT` | every hook | identity; default from the token's claims (`coding` namespace) | -| `LOOM_PROJECT_NAME`, `LOOM_PROJECT_SCOPE` (tag) | every hook | project name override (file memory is asked by repository); `namespace` makes it the namespace | -| `LOOM_REPO_REMOTE` | every hook | the remote the `repo:` tag hashes; file memory is then asked by that id alone | -| `LOOM_MODE` (both) | every hook, headers helper | Hook mode for Codex and hand-wired clients. The Claude Code plugin uses its `server_url` query. | -| `LOOM_CLIENT` (claude-code) | every hook | the client name when no argument names it | -| `LOOM_HOOK_TIMEOUT_MS`, `LOOM_HOOK_EXIT_MS` | every hook | request bound and exit grace overrides | -| `LOOM_HOOK_DEBUG` (off) | hooks ending in `runHookMain` | swallowed errors to stderr, redacted | -| `LOOM_AUTO_SIGNUP` (on) | session-start, headers helper | first-session sign-up | -| `LOOM_INJECT_CONTEXT` (on) | session-start | the primer | -| `LOOM_CONTEXT_TOKEN_BUDGET` (1200), `LOOM_CONTEXT_RUNS` (off), `LOOM_CONTEXT_RUNS_LIMIT` (8) | session-start | primer budget, kept within the 200 to 12,000 `context.pack` takes, and the runs shortlist | -| `LOOM_CODE_MAP` (on), `LOOM_CODE_MAP_TOKEN_BUDGET` (0 = no map) | session-start | the repo map | -| `LOOM_TASK_INBOX_LINE` (on) | session-start | the task inbox line | -| `LOOM_COLLECTIONS_LINE` (on) | session-start | the collections line | -| `LOOM_SETUP_LINE` (on) | session-start | the setup line | -| `LOOM_SESSION_BRIEF` (on), `LOOM_SESSION_BRIEF_PRIMER` (off), `LOOM_SESSION_BRIEF_KEY`, `LOOM_SESSION_BRIEF_TIMEOUT_MS` (90000) | session-brief, session-start | briefs, the primer line, a fixed key, the flusher's bound | -| `LOOM_PROMPT_CONTEXT` (on) | prompt-pack, prompt-recall | off: the plugin adds nothing to a prompt, neither code pointers nor recall | -| `LOOM_PROMPT_RECALL` (first) | prompt-recall | first, on or off; a value that names none is off; off leaves the memory search to the primer | -| `LOOM_PROMPT_RECALL_MIN_CONF` (0.5), `LOOM_PROMPT_RECALL_TOP_K` (3), `LOOM_PROMPT_RECALL_BUDGET` (600), `LOOM_PROMPT_RECALL_MAX_CHARS` (1600) | prompt-recall | the confidence bar, hits per plane, pack budget, injected cap | -| `LOOM_PROMPT_PACK` (auto), `LOOM_PROMPT_PACK_MIN_CONF` (unset: low-risk, or a pick worded `high` or `medium`), `LOOM_PROMPT_PACK_TOP_K` (3) | prompt-pack | per-prompt code pointers (`auto`, `on`, `off`); their confidence gate and count | -| `LOOM_PROMPT_PACK_TIMEOUT_MS` (2500) | prompt-pack | the bound for a prompt that asks for no pick: its repository lookup and its answer, together | -| `LOOM_PROMPT_PACK_PICK_TIMEOUT_MS` (6000) | prompt-pack | a searched bug report's bound, in place of the one above: its search asks for the listwise pick | -| `LOOM_RUN_LEDGER` (on), `LOOM_PLUGIN_RUN_RETAIN` (server default) | run | the run ledger; keep, demote or expire the run's rows | -| `LOOM_SESSION_END_WAIT` (off) | loom-record | on: the SessionEnd hook sends the session's close itself, for a host that ends with the client | -| `LOOM_OBSERVE_SKIP_TOOLS`, `LOOM_OBSERVE_DEDUPE_S` (60) | capture | tools never observed; read dedupe window | -| `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), `LOOM_SESSION_MEMORY_EVERY_TURNS` (40), `LOOM_SESSION_MEMORY_IDLE_MINUTES` (30) | session-memory, test-report | the session hand-off and when a Stop makes one (0 turns a rule 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 | -| `LOOM_MCP_HOOK_WAIT_MS` (5000) | headers helper | how long a helper with no token waits for the hook to save one | -| `LOOM_MCP_CONTEXT_WAIT_MS` (1500) | headers helper | how long the helper waits for the checkout context SessionStart publishes | -| `LOOM_CODE_REPO` (unset), the `code_repo` option / config key | repo-scope, every code hook | the fallback repository for the index: outside a checkout, or when the checkout has none | +| Setting | Read by | Meaning | +| --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `LOOM_API_KEY`, `LOOM_BASE_URL` | every hook | the credential and the server | +| `LOOM_ORG`, `LOOM_NAMESPACE`, `LOOM_AGENT` | every hook | identity; default from the token's claims (`coding` namespace) | +| `LOOM_PROJECT_NAME`, `LOOM_PROJECT_SCOPE` (tag) | every hook | project name override (file memory is asked by repository); `namespace` makes it the namespace | +| `LOOM_REPO_REMOTE` | every hook | the remote the `repo:` tag hashes; file memory is then asked by that id alone | +| `LOOM_MODE` (both) | every hook, headers helper | Hook mode for Codex and hand-wired clients. The Claude Code plugin uses its `server_url` query. | +| `LOOM_CLIENT` (claude-code) | every hook | the client name when no argument names it | +| `LOOM_HOOK_TIMEOUT_MS`, `LOOM_HOOK_EXIT_MS` | every hook | request bound and exit grace overrides | +| `LOOM_HOOK_DEBUG` (off) | hooks ending in `runHookMain` | swallowed errors to stderr, redacted | +| `LOOM_AUTO_SIGNUP` (on) | session-start, headers helper | first-session sign-up | +| `LOOM_INJECT_CONTEXT` (on) | session-start | the primer | +| `LOOM_CONTEXT_TOKEN_BUDGET` (1200), `LOOM_CONTEXT_RUNS` (off), `LOOM_CONTEXT_RUNS_LIMIT` (8) | session-start | primer budget, kept within the 200 to 12,000 `context.pack` takes, and the runs shortlist | +| `LOOM_CODE_MAP` (on), `LOOM_CODE_MAP_TOKEN_BUDGET` (0 = no map) | session-start | the repo map | +| `LOOM_TASK_INBOX_LINE` (on) | session-start | the task inbox line | +| `LOOM_COLLECTIONS_LINE` (on) | session-start | the collections line | +| `LOOM_SETUP_LINE` (on) | session-start | the setup line | +| `LOOM_SESSION_BRIEF` (on), `LOOM_SESSION_BRIEF_PRIMER` (off), `LOOM_SESSION_BRIEF_KEY`, `LOOM_SESSION_BRIEF_TIMEOUT_MS` (90000) | session-brief, session-start | briefs, the primer line, a fixed key, the flusher's bound | +| `LOOM_PROMPT_CONTEXT` (on) | prompt-pack, prompt-recall | off: the plugin adds nothing to a prompt, neither code pointers nor recall | +| `LOOM_PROMPT_RECALL` (first) | prompt-recall | first, on or off; a value that names none is off; off leaves the memory search to the primer | +| `LOOM_PROMPT_RECALL_MIN_CONF` (0.5), `LOOM_PROMPT_RECALL_TOP_K` (3), `LOOM_PROMPT_RECALL_BUDGET` (600), `LOOM_PROMPT_RECALL_MAX_CHARS` (1600) | prompt-recall | the confidence bar, hits per plane, pack budget, injected cap | +| `LOOM_PROMPT_PACK` (auto), `LOOM_PROMPT_PACK_MIN_CONF` (unset: low-risk, or a pick worded `high` or `medium`), `LOOM_PROMPT_PACK_TOP_K` (3) | prompt-pack | per-prompt code pointers (`auto`, `on`, `off`); their confidence gate and count | +| `LOOM_PROMPT_PACK_TIMEOUT_MS` (2500) | prompt-pack | the bound for a prompt that asks for no pick: its repository lookup and its answer, together | +| `LOOM_PROMPT_PACK_PICK_TIMEOUT_MS` (6000) | prompt-pack | a searched bug report's bound, in place of the one above: its search asks for the listwise pick | +| `LOOM_RUN_LEDGER` (on), `LOOM_PLUGIN_RUN_RETAIN` (server default) | run | the run ledger; keep, demote or expire the run's rows | +| `LOOM_SESSION_END_WAIT` (off) | loom-record | on: the SessionEnd hook sends the session's close itself, for a host that ends with the client | +| `LOOM_OBSERVE_SKIP_TOOLS`, `LOOM_OBSERVE_DEDUPE_S` (60) | capture | tools never observed; read dedupe window | +| `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), `LOOM_SESSION_MEMORY_EVERY_TURNS` (40), `LOOM_SESSION_MEMORY_IDLE_MINUTES` (30) | session-memory, test-report, loom-record, session-start | the session hand-off and when a Stop makes one (0 turns a rule off); the test cost note and the command conventions 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 | +| `LOOM_MCP_HOOK_WAIT_MS` (5000) | headers helper | how long a helper with no token waits for the hook to save one | +| `LOOM_MCP_CONTEXT_WAIT_MS` (1500) | headers helper | how long the helper waits for the checkout context SessionStart publishes | +| `LOOM_CODE_REPO` (unset), the `code_repo` option / config key | repo-scope, every code hook | the fallback repository for the index: outside a checkout, or when the checkout has none | The code-plane hooks' own settings (`LOOM_CODE_SHUNT`, `LOOM_SHUNT_*`, `LOOM_FILE_CONTEXT*`, `LOOM_BLAST_*`, `LOOM_TEST_GATE*`, `LOOM_VALIDATE_GATE`, diff --git a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs index 5033a802771..0b63a62cdbf 100644 --- a/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs @@ -63,6 +63,15 @@ // stays until the read has settled or the exit grace has passed. A row whose // file the checkout does not hold prints nothing. // +// Below that go at most two command conventions lines, for a bug report in a +// Claude Code session on a POSIX host, with or without the test report, where +// the memory plane runs (LOOM_TEST_REPORT=off stops them too): for each flag +// that three or more earlier sessions in the repository added to a command of +// a program they had already run, the sessions that did, the ones that had it +// on their first run of the program and the ones that ran the program +// (lib/command-flags.mjs). Its row is a second read by key, sent and waited +// for as the test cost row's is. +// // 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 @@ -151,10 +160,16 @@ 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 +// The test cost line and the command conventions lines are read from memory, +// only where that plane runs: the library of each and its function that reads +// the row. The test report's switch is read with each line, in the library a // bug report loads. -const COST_LINE = planeEnabled("memory"); +const ROW_LINES = planeEnabled("memory") + ? [ + ["../lib/test-cost.mjs", "costLine"], + ["../lib/command-flags.mjs", "flagsLine"], + ] + : []; const CONSUMER = "claude-code-prompt-pack"; // The lookups a session makes as it starts: SessionStart's, and the MCP headers helper's. @@ -228,7 +243,7 @@ function renderLookup(lookup, body, response, repo) { * for the file `checkPointer` reads from them, inside what is left of the * 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. */ + * `rowNote`), 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(); @@ -240,17 +255,17 @@ 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(() => ""); +/** The line of one row of the session's repository, or "": the test cost + * line (`costLine` in lib/test-cost.mjs) or the command conventions lines + * (`flagsLine` in lib/command-flags.mjs). The library is 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`). `scopeOf` resolves the checkout's scope once for both. */ +function rowNote([library, line], payload, root, scopeOf, options) { + return import(library).then((lib) => lib[line](payload.session_id, root, scopeOf, options)).catch(() => ""); } async function main() { @@ -302,17 +317,20 @@ async function main() { const options = { token, serverUrl: resolveServerUrl(), timeoutMs: left }; const asked = requestLookup(lookup.op, body, options); // Started beside the search, once that is sent, and not waited for after it. - const cost = COST_LINE && pick && payload.session_id ? costNote(payload, root, cwd, options) : null; + let scope = null; + const scopeOf = () => (scope ??= resolveScope(cwd)); + const rows = pick && payload.session_id ? ROW_LINES : []; + const lines = rows.map((row) => rowNote(row, payload, root, scopeOf, options)); 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("")]) : ""; + // What each read has answered by now, or nothing: a settled promise wins the race. + const notes = text && sent ? await Promise.all(lines.map((line) => Promise.race([line, Promise.resolve("")]))) : []; scheduleExit(0); - return text ? packPayload([text, check, note].filter(Boolean).join("\n")) : undefined; + return text ? packPayload([text, check, ...notes].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 a98ac53f6db..3be5256f922 100644 --- a/integrations/claude-code-plugin/hooks/loom-record.mjs +++ b/integrations/claude-code-plugin/hooks/loom-record.mjs @@ -57,7 +57,8 @@ // launcher reads the planes and switches of the scripts the host waits for // (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. +// at SessionEnd for the cost of a run that outlived its command, and noting +// the runs of a shell command for the repository's command conventions. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -81,7 +82,7 @@ import { keepRunBegin, runLedgerEnabled } from "../lib/run-hook.mjs"; import { readsOnly } from "../lib/shell-command.mjs"; import { useHooksServer } from "../lib/plugin-options.mjs"; import { startsRunner } from "../lib/test-gate.mjs"; -import { endReport, reportPath, showsRefusal, testReportOn, visibleOutput } from "../lib/test-report.mjs"; +import { countsRuns, endReport, reportPath, showsRefusal, testReportOn, visibleOutput } from "../lib/test-report.mjs"; import { readPrivateFile, removeFile } from "../lib/tmp-state.mjs"; /** The scripts each event records with, in the order they start. At @@ -253,11 +254,22 @@ async function hook(script, event, client) { const names = rows.map((row) => row.script); const waits = rows.map((row) => row.waitMs); const waited = names.length ? run(raw, names, payload, waits) : null; + // The runs of a shell command, failed or not, where the session's commands + // are counted for the command conventions (`countsRuns`), asked here to + // leave the library unloaded where they are not. + if (event.startsWith("PostToolUse") && payload.tool_name === "Bash" && countsRuns()) { + const { noteRuns } = await import("../lib/command-flags.mjs"); + noteRuns(payload.session_id, commandText(payload.tool_input), payload.cwd); + } // An agent's token is left to the copy, or at a prompt to what the hook runs // anyway: renewing one is a request. if (records(event, payload) && (agentMode() || resolveToken())) { if (event === "UserPromptSubmit") keepBegin(payload); spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` }); + } else if (event === "SessionEnd") { + // No copy runs with no credential, so loom-session-memory does not remove + // the command conventions state of a session that lost its own. + (await import("../lib/command-flags.mjs")).endFlags(payload.session_id); } const answer = waited ? mergedAnswer(event, await waited) : null; // Exits itself: a host that never closes stdin would hold the process open. diff --git a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs index aba50ceb961..5c78f812575 100644 --- a/integrations/claude-code-plugin/hooks/loom-session-memory.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-memory.mjs @@ -27,7 +27,10 @@ // 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 there, whatever is handed off. +// The session's cost state is removed there, whatever is handed off. So it is +// with the repository's command conventions row: one memory.set of the counts +// of the flags the session added to commands it had already run +// (lib/command-flags.mjs), under the same switches. // // Off-switch: LOOM_SESSION_MEMORY=off. LOOM_SESSION_MEMORY_EVERY_TURNS (40) // and LOOM_SESSION_MEMORY_IDLE_MINUTES (30) set when a Stop hands off; 0 turns @@ -46,6 +49,7 @@ import { runHookMain, scheduleExit, } from "../lib/loom-client.mjs"; +import { endFlags, flagsPost } from "../lib/command-flags.mjs"; import { dispatchFlush } from "../lib/flush-job.mjs"; import { changeCommit, @@ -149,11 +153,13 @@ async function main() { const stores = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken(); // Read for a session that stores, and removed for every session. const cost = ends && stores && testReportOn() ? costPost(sid, payload.cwd) : null; + const flags = ends && stores && testReportOn() ? flagsPost(sid) : null; if (ends) endCost(sid); + if (ends) endFlags(sid); if (stores) { const window = await handOff(event, payload, from, handedOffAt, recalledKeys); if (ends) { - const posts = [window && window.post, cost].filter(Boolean); + const posts = [window && window.post, cost, flags].filter(Boolean); // Spawn failure: nothing is lost that the next session cannot say again. if (posts.length) dispatchFlush({ posts }); } else if (window) { diff --git a/integrations/claude-code-plugin/hooks/loom-session-start.mjs b/integrations/claude-code-plugin/hooks/loom-session-start.mjs index bef7865c8ae..7af43611774 100755 --- a/integrations/claude-code-plugin/hooks/loom-session-start.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-start.mjs @@ -86,6 +86,7 @@ import { import { cacheIsFresh, countsBody, renderTaskLine, summarizeCounts } from "../lib/task-inbox.mjs"; import { listBody, listsCollections, renderCollectionsLine } from "../lib/collections-line.mjs"; import { briefPrimerEnabled, primerLine } from "../lib/session-brief.mjs"; +import { startFlags } from "../lib/command-flags.mjs"; import { startReport } from "../lib/test-report.mjs"; import { readJsonFile, sweepStaleStateFiles, tmpStatePath, writeJsonFile } from "../lib/tmp-state.mjs"; @@ -116,6 +117,12 @@ async function main() { // An invalid endpoint has stopped the hook at saveInstall, so neither this // nor loom-record's digest and end runs: nothing is left half set up. startReport(payload); + // A session is counted for the repository's command conventions only from + // the state this writes (lib/command-flags.mjs): for a new session whose + // shell commands are noted, and not for a resumed one, which knows what its + // earlier part learned. Before the sign-up below: a session it signs up + // started with no credential, and its commands so far were not noted. + if (payload.session_id) startFlags(payload.session_id, payload.source); // Default ON; opt out with LOOM_INJECT_CONTEXT=false (see header). if (!envSwitch("LOOM_INJECT_CONTEXT", true)) { scheduleExit(0); diff --git a/integrations/claude-code-plugin/lib/command-flags.mjs b/integrations/claude-code-plugin/lib/command-flags.mjs new file mode 100644 index 00000000000..597a3dd7891 --- /dev/null +++ b/integrations/claude-code-plugin/lib/command-flags.mjs @@ -0,0 +1,763 @@ +// The command conventions of a repository: a flag that sessions add to a +// command of a program after they have run that command without it, told to a +// later session before its first run of the program. A session that does not +// know the convention runs the command, reads a result it cannot use, and +// runs it again with the flag. +// +// It is counted from the session's shell commands, with no model call, in a +// Claude Code session on a POSIX host (`conventionsOn`). A session is counted +// only while it holds the state its start wrote (`startFlags`): one whose +// state is not there, or was removed, stores nothing. The launcher +// (hooks/loom-record.mjs) notes the runs of each shell command in that state +// (`noteRuns`), from the prompt that read the repository's row on. A +// command adds one line to the state and rewrites none, so commands whose +// hooks run at the same time are all noted, in the order their lines were +// written. +// hooks/loom-prompt-pack.mjs reads that one memory row by its key beside a +// bug report's search and prints a line for at most two of its pairs under +// the pointers (`flagsLine`). At the session's end +// hooks/loom-session-memory.mjs hands the row with the session's counts to +// the flusher (`flagsPost`) and removes the session's state (`endFlags`). +// +// The reader refuses a shape it does not know: a missed convention costs +// nothing, and a wrong line is read by every later session. +// +// A call is not read (`runs`) where it holds a backquote, `$(` or `$'` +// outside single quotes, a backslash outside quotes or before a double quote +// inside them, a quote left open, a parenthesis or a brace outside quotes, a +// `|` at a line's end, a simple command that starts with a shell keyword, or +// a here-document whose word is not a plain one or whose body has no end +// line. A here-document's body and a comment are left out. +// +// A run is a simple command of the call, cut at `;`, `&&`, `||`, `|` and line +// ends, that is no later stage of a pipeline, holds no `&`, `<` or `>` +// outside quotes but for a redirect between descriptors or to the null +// device, and has 24 words at most. After a `cd` to one plain path the runs +// are that folder's (`dir`); after any other `cd`, a `pushd` or a `popd` the +// rest of the call is not read. A run is noted where its folder is the +// checkout's own (`place`): in the checkout of the row the session read, and +// in no other checkout under it. +// +// The program is the first word after the variable assignments: a bare name +// with no dot, or the module of `python -m` or `pypy -m`, where the +// interpreter is named by its bare name and `-m` is its first word. A path +// is no program, so a script named by its path never is, and neither is a +// module named with a dot, a file inside a package. A module with no dot is a +// program wherever its file lies, at the checkout's root too: the command +// does not say where. A program of `OTHER_COMMAND`, of `OUTSIDE` or of +// `READ_PROGRAMS` is no run. A wrapper or an interpreter that `OTHER_COMMAND` does not hold is a +// program, and a flag after the script it runs is counted as its own. +// +// A flag is a word of the run that is two dashes and lower-case words joined +// by dashes, 5 to 40 characters. A flag written with its value +// (`--name=value`), a short flag and a flag of one or two letters (`--lf`) +// are not flags: no word of `REFUSED` can be read in an abbreviation. A flag +// whose word holds one of `REFUSED` is never counted. A flag is counted as +// added only before the run's first bare word (one that starts with no dash +// and holds no dot and no slash) and before a lone `--`: a bare word can be +// a subcommand or the command a wrapper runs, and the flags after it are +// that one's. A run that holds the flag's word after that still carries the +// flag. +// +// A program has no first run the session knows where a call names it before +// the first run that is noted (`names`). The run may have been in a shape +// this does not read, with the flag. Such a program is not counted. A name +// is a word of the call's text, the last part of a path there, or what +// follows the first `m` of a word of one dash and letters (`python -mmypy`), +// and no program of a run noted from that call. Every call is read for its +// names, whether or not its runs are. +// +// The state holds, for each program, a hash of each run's folder and words +// and, for each of its flags, a hash of them without the flag, and a hash of +// each name that is not counted: no other text of a command. What leaves the +// machine is the program's name, three counts and the flag's word for a pair +// the row hands, or a hash of the program's name and that word for any other +// pair, under the repository's id. The hash has no secret part: who reads the +// row can try the program's flags against it. + +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +import { pathUnder, redactSecrets } from "./loom-client.mjs"; +import { heldRow, rowPost } from "./repo-row.mjs"; +import { + LIST_SEPARATORS, + NO_FILE_REDIRECT, + READ_PROGRAMS, + shellWords, + splitOutsideQuotes, + unquotedText, +} from "./shell-command.mjs"; +import { conventionsOn, countsRuns } from "./test-report.mjs"; +import { readPrivateFile, readSessionState, removeFile, sessionStatePath, writePrivateFile } from "./tmp-state.mjs"; + +/** The words of `lines`, each a list of words with a space between them. */ +const wordList = (...lines) => lines.join(" ").split(" "); + +// A call that holds a command starting with one of these is not read: the +// commands of a loop, a condition or a function are not the call's own runs. +export const KEYWORDS = new Set(wordList("if then else elif fi for while until do done case esac select function")); +// A word that starts another command, an interpreter given a script, and a +// module that runs one: the flags after it are not its own. +export const OTHER_COMMAND = new Set( + wordList( + "time env exec command nohup nice timeout gtimeout xargs eval watch sudo doas su", + "uv poetry pipx npx pdm hatch pipenv bunx stdbuf strace ltrace parallel", + "caffeinate xvfb-run valgrind unbuffer mpiexec mpirun ionice taskset setsid", + "bash sh zsh dash ksh csh tcsh fish ash busybox pwsh powershell", + "node nodejs deno bun tsx ts-node coffee ruby jruby perl php lua luajit java kotlin scala groovy", + "Rscript R julia swift dart elixir escript erl racket guile clojure clj bb tclsh wish expect", + "awk gawk mawk nawk osascript raku octave runghc runhaskell ipython jython py", + "cProfile profile pdb trace timeit runpy", + ), +); +// A program that acts outside the checkout (a release tool and a database +// client do), moves or writes the files its operands name, or runs what a +// file of recipes names. +export const OUTSIDE = new Set( + wordList( + "git gh hg svn rm rmdir mv cp ln install dd shred truncate chmod chown chgrp touch mkdir mktemp unlink link tee", + "tar unzip zip gzip gunzip bzip2 xz zstd cpio patch kill pkill killall mount umount crontab shutdown reboot", + "ssh scp sftp ftp rsync nc ncat telnet open xdg-open", + "docker docker-compose podman kubectl helm terraform pulumi ansible ansible-playbook aws gcloud az", + "vercel netlify heroku fly flyctl firebase serverless systemctl service launchctl curl wget", + "pip pip3 npm pnpm yarn conda brew apt apt-get twine cargo gem composer go dnf yum", + "semantic-release release-it release-please standard-version np lerna changeset goreleaser", + "bumpversion bump2version cz flit maturin vsce", + "psql mysql sqlite3 mongosh redis-cli clickhouse clickhouse-client clickhouse-local", + "dropdb createdb pg_dump pg_restore prisma dbt alembic django-admin", + "make just rake tox nox invoke ninja gradle mvn bazel", + ), +); +// What the word of a refused flag holds: it forces or confirms, destroys or +// rewrites, turns a trial run into a real one or back, skips, narrows or +// weakens a check, reaches outside the checkout, waits for a person, or only +// prints what the program is. The list is the rule: a word that holds none +// of these can be counted, whatever its flag does. +export const REFUSED = wordList( + "force yes yolo confirm accept approve assume input interact prompt ask auto", + "override batch attend agree consent always", + "hard delete remove purge prune destroy overwrite reset clear clean clobber wipe erase drop zero", + "truncate create replace discard revert rollback migrat", + "kill flush cascade destruct reverse bless nuke undo restore amend rebase squash unlink expunge trash empty", + "modify mutate rename merge init record snapshot baseline abort terminate cancel restart", + "update fix write place correct gen refresh apply noqa format save commit", + "exec dry run real live plan", + "skip only collect stepwise ignore verif check strict unsafe insecure allow disable bypass danger", + "bail changed quick exclude select filter partial subset sample", + "suppress lenient permi loose tolera waive exempt", + "exit fail never warn quiet silent fast test lint valid error continue keep audit sign hook lock lax", + "cov sandbox privileged trust", + "install grade prod deploy publish push upload release remote global send submit download fetch pull sync", + "public share expose tunnel cloud proxy telemetry notify mail sudo admin system", + "pdb watch serve daemon follow open edit wait pause shell reload repl browse gui attach inspect stdin", + "help version verbose debug trace usage list print dump", +); + +const PROGRAM = /^[A-Za-z_][\w+-]{0,39}$/; +const FLAG = /^--[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/; +// A flag of one or two letters is an abbreviation (`--lf`, `--co`): no word +// of `REFUSED`, three letters at least, can be read in it. +const MIN_FLAG = 5; +const MAX_FLAG = 40; +// A `|` that ends a line: the pipeline goes on in the next one. +const OPEN_PIPE = /(?()]*)/g; +// The word of a here-document this reads, without its quotes. +const BODY_WORD = /^[A-Za-z_][\w.-]*$/; +// The option letters a module can follow in one word: `-mmypy`, `-Bmmypy`. +const MODULE_OPTION = /^-[A-Za-z]*?m/; +// The one operand of a `cd` whose folder is read. +const PLAIN_PATH = /^[\w./][\w./+@-]*$/; +const MAX_CALL = 64 * 1024; +const MAX_WORDS = 24; +// The programs a session's state holds, the runs of each, and the names that +// are not counted. +const MAX_PROGRAMS = 32; +const MAX_RUNS = 48; +const MAX_NAMES = 512; +// The pairs a row holds, and the lines a prompt gets. +const MAX_PAIRS = 8; +const MAX_LINES = 2; +// A pair is handed from this many sessions that converged on it. +const MIN_CONVERGED = 3; +// A pair counts sessions until this many ran its program: the most among +// which `MIN_CONVERGED` are a tenth, so the sessions that converged on a pair +// the row hands are a tenth or more of those that ran its program. +const MAX_RAN = 30; +const MAX_VALUE = 4096; + +// The session's runs: `{ programs, named }`, each program's runs in order as +// `[hash of the folder and the words, { flag: hash of them without it }]`, +// with "" for a flag that stands where it is not counted as added. `named` +// holds a hash of each name whose program is not counted (`folded`). The +// state is kept as lines (`stateOf`): the session's start writes the first, +// a state with no program (`startFlags`), and each shell call that changes +// the state adds one, of what the state takes of it (`taken`). A session +// whose first run of a program may not be among its runs has no state: it +// stores nothing. The sweep of day-old state files (`sweepStaleStateFiles`) +// removes the state like any other, and a session that lost it stores +// nothing either. +const RUNS = "command-flags"; +const runsPath = (sessionId) => sessionStatePath(RUNS, sessionId, { ext: ".jsonl" }); +// The repository's row as the session read it (`heldRow` in +// lib/repo-row.mjs). Its `pairs` are null for a value that is not `claim`'s +// text. +const ROW = "command-flags-row"; + +/** Whether runs of `program` are counted. A name every object has + * (`constructor`) is none: programs are the keys of the state's objects. */ +const counted = (program) => + PROGRAM.test(program) && + !(program in Object.prototype) && + !OTHER_COMMAND.has(program) && + !OUTSIDE.has(program) && + !READ_PROGRAMS.has(program); + +/** Whether `word` is a flag that is counted. */ +const countedFlag = (word) => + FLAG.test(word) && word.length >= MIN_FLAG && word.length <= MAX_FLAG && !REFUSED.some((part) => word.includes(part)); + +/** Whether `word` is a bare word: a subcommand, or the command a wrapper runs. */ +const bare = (word) => !word.startsWith("-") && !word.includes(".") && !word.includes("/"); + +/** `text` without the lines of its here-document bodies, up to the line that + * is the body's word (after its leading tabs for `<<-`); null where a word + * is not a plain one, alone or in one pair of quotes, or a body has no such + * line. Quotes around an opener are not read. */ +function withoutBodies(text) { + const lines = text.split("\n"); + const kept = []; + for (let i = 0; i < lines.length; i++) { + kept.push(lines[i]); + for (const found of lines[i].matchAll(OPENER)) { + const raw = found[2]; + const quoted = raw.length > 2 && raw[0] === raw.at(-1) && (raw[0] === "'" || raw[0] === '"'); + const word = quoted ? raw.slice(1, -1) : raw; + if (!BODY_WORD.test(word)) return null; + do i += 1; + while (i < lines.length && (found[1] ? lines[i].replace(/^\t+/, "") : lines[i]) !== word); + if (i === lines.length) return null; + } + } + return kept.join("\n"); +} + +/** `text` without its comments: from a `#` that starts a word outside quotes + * to the line's end. A call whose quotes this misreads holds a backslash, + * and is not read. */ +function withoutComments(text) { + let out = ""; + let quote = ""; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote) quote = ch === quote ? "" : quote; + else if (ch === "'" || ch === '"') quote = ch; + else if (ch === "#" && (!i || " \t\n;&|".includes(text[i - 1]))) { + while (i < text.length && text[i] !== "\n") i += 1; + if (i === text.length) break; + } + out += text[i]; + } + return out; +} + +/** The simple commands of `text`, a shell call without its here-document + * bodies and comments: the words of each one's first stage and whether it is + * `read`; null for a call that is not read. */ +function simpleCommands(text) { + const open = unquotedText(text); + if (open === null || /[(){}]/.test(open) || OPEN_PIPE.test(open)) return null; + return splitOutsideQuotes(text, LIST_SEPARATORS).map((part) => { + const stage = splitOutsideQuotes(part, ["|"])[0]; + return { words: shellWords(stage), read: !/[&<>]/.test(unquotedText(stage)) }; + }); +} + +/** The run of the words of one simple command from its program on, + * `{ program, words, flags }` with the words after the program and its + * distinct flags; null for none. */ +function runOf(all) { + if (!all.length || all.length > MAX_WORDS) return null; + let [program, ...words] = all; + if (INTERPRETER.test(program)) { + if (words[0] !== "-m" || !words[1]) return null; + [program, words] = [words[1], words.slice(2)]; + } + if (!counted(program)) return null; + const end = words.findIndex((word) => word === "--" || bare(word)); + const flags = (end < 0 ? words : words.slice(0, end)).filter(countedFlag); + return { program, words, flags: [...new Set(flags)] }; +} + +/** The runs of the shell call `command`, in order (the rules are above). A + * run after a `cd` names the folder it changed to as `dir`, as the call + * wrote it. */ +export function runs(command) { + const text = withoutBodies(String(command || "").replace(/\\\n/g, "")); + const commands = text === null ? null : simpleCommands(withoutComments(text.replace(NO_FILE_REDIRECT, " "))); + const found = []; + let dir = ""; + for (const { words, read } of commands || []) { + const all = words.slice( + Math.max( + 0, + words.findIndex((word) => !ASSIGNMENT.test(word)), + ), + ); + if (KEYWORDS.has(all[0])) return []; + if (["cd", "pushd", "popd"].includes(all[0])) { + // The folder of what follows is known only after a `cd` to one plain path. + if (all[0] !== "cd" || !read || all.length !== 2 || !PLAIN_PATH.test(all[1])) break; + // The call's paths are a POSIX shell's, whatever the host. + dir = path.posix.isAbsolute(all[1]) ? all[1] : path.posix.join(dir, all[1]); + continue; + } + const run = read ? runOf(all) : null; + if (run) found.push(dir ? { ...run, dir } : run); + } + return found; +} + +/** The names the text of the shell call `command` holds, each with how often: + * a word of letters, digits and `_+-`, alone or as the last part of a path, + * that could be a counted program. The text is cut at every other + * character, so a name in quotes, in a substitution, after a wrapper or in + * a here-document's body is one too. So is the module an interpreter is + * given in the word of its `-m` (`MODULE_OPTION`). */ +export function names(command) { + const found = new Map(); + for (const word of String(command || "").split(/[^\w.+/-]+/)) { + const name = word.slice(word.lastIndexOf("/") + 1).replace(MODULE_OPTION, ""); + if (counted(name)) found.set(name, (found.get(name) || 0) + 1); + } + return found; +} + +/** A short hash of `words`, joined by a character none of them holds. Two + * runs are compared by the hash of their folder and their words. */ +const digest = (words) => crypto.createHash("sha1").update(words.join("\0")).digest("hex").slice(0, 12); + +/** What a row holds in place of the word of `flag` of `program` until it + * hands the pair. */ +const hidden = (program, flag) => `flag:${digest([program, flag])}`; +const HIDDEN = /^flag:[0-9a-f]{12}$/; + +/** The line a shell call adds to the state, `{ runs, names }`: `found` are + * its runs to note (`runs`) and `nameCounts` the names its text holds + * (`names`). A run is `[program, hash, { flag: hash }]` and carries each + * counted flag it holds: one that stands where it is not counted as added + * has no hash. A run's hashes are of its folder (`at`, the two parts + * `place` gives) and its words: the same words in another folder are + * another command. `names` holds a hash of each name the call holds more + * often than `found` runs it. */ +export function entry(found, nameCounts) { + const ran = (name) => found.filter((run) => run.program === name).length; + return { + runs: found.map(({ program, words, flags, at = ["", ""] }) => { + const less = Object.fromEntries([ + ...words.filter(countedFlag).map((flag) => [flag, ""]), + ...flags.map((flag) => [flag, digest([...at, ...words.filter((word) => word !== flag)])]), + ]); + const whole = digest([...at, ...words]); + return Object.keys(less).length ? [program, whole, less] : [program, whole]; + }), + names: [...nameCounts].filter(([name, times]) => times > ran(name)).map(([name]) => digest([name])), + }; +} + +/** `state` after the line of a shell call (`entry`), or `state` itself for + * no change. A program with no run yet that the line names has no first run + * the session knows: its name is kept, and no run of it is noted from then + * on. A program's first `MAX_RUNS` runs and the first `MAX_PROGRAMS` + * programs are kept, and no program starts once `MAX_NAMES` names are. */ +export function folded(state, line) { + const programs = { ...state.programs }; + const named = new Set(state.named); + const before = named.size; + const started = (name) => Object.keys(programs).some((program) => digest([program]) === name); + for (const name of line.names) { + if (!named.has(name) && named.size < MAX_NAMES && !started(name)) named.add(name); + } + let added = false; + for (const [program, ...run] of line.runs) { + const history = programs[program] || []; + const closed = + named.has(digest([program])) || named.size >= MAX_NAMES || Object.keys(programs).length >= MAX_PROGRAMS; + if (history.length >= MAX_RUNS || (!history.length && closed)) continue; + programs[program] = [...history, run]; + added = true; + } + return added || named.size > before ? { ...state, programs, named: [...named] } : state; +} + +/** The state the text of a session's state file holds: its first line, the + * start's, with every later line folded in (`folded`). {} for a text whose + * first line is not the start's, as one a call added to after the state was + * removed, or with a line that does not parse. A last line with no line end + * is being written, and is not read. */ +export function stateOf(text) { + try { + const [first, ...lines] = text + .split("\n") + .slice(0, -1) + .map((line) => JSON.parse(line)); + return first?.programs ? lines.reduce((state, line) => folded(state, line), first) : {}; + } catch { + return {}; + } +} + +/** The line that takes `state` to `next`, the state after a call's line + * (`folded`): the runs and the names of that line that the state took. */ +const taken = (state, next) => ({ + runs: Object.entries(next.programs).flatMap(([program, history]) => + history.slice(state.programs[program]?.length || 0).map((run) => [program, ...run]), + ), + names: next.named.slice(state.named?.length || 0), +}); + +/** The session's state (`stateOf`), {} for none. */ +function readRuns(sessionId) { + try { + return stateOf(readPrivateFile(runsPath(sessionId))); + } catch { + return {}; + } +} + +/** Whether the folder at `rel` under the checkout at `root` is the + * checkout's own: it is in the checkout (`rel` is no null), and no folder + * from below the root down to it holds a `.git`, as the root of a submodule, + * a worktree or another clone does. */ +const own = (root, rel) => + rel !== null && + rel.split("/").every((_, i, parts) => !rel || !fs.existsSync(path.join(root, ...parts.slice(0, i + 1), ".git"))); + +/** + * Where a run of a shell call ran, as its hashes hold it (a folder under the + * root, and a relative `cd` from it or ""), or null for a folder that is not + * the own one (`own`) of the checkout at `root`: a run there is another + * repository's. `cwd` is the payload's folder and `dir` the path the call's + * `cd` changed to, "" for none. + * + * The payload's folder is the session's before the call or after it. With + * no `cd` the two are one, and after a `cd` to an absolute path the run's + * folder is that path: either is named by its path under the root. After a + * `cd` to a relative path the run's folder is that path from the session's + * folder before the call, which the payload may not hold. It is then named + * by the payload's folder and the path as the call wrote it: the same as + * another run's only after the same `cd` from the same folder. Both the + * payload's folder and the path from it are then the checkout's own. + */ +function place(root, cwd, dir) { + const here = pathUnder(root, cwd); + if (!dir) return own(root, here) ? [here, ""] : null; + const there = pathUnder(root, path.resolve(cwd, dir)); + if (!own(root, there)) return null; + if (path.isAbsolute(dir)) return [there, ""]; + return own(root, here) ? [here, dir] : null; +} + +/** Whether `state` is the one a session's start wrote, with nothing noted since. */ +const untouched = (state) => Boolean(state.programs) && !Object.keys(state.programs).length && !state.named?.length; + +/** The session is counted no more: it stores nothing. */ +const close = (sessionId) => removeFile(runsPath(sessionId)); + +/** + * Note the runs and the names (`entry`) of the shell command `command`, run + * in `cwd`, in the state of a session that is counted: the one its start + * wrote (`startFlags`) is there. The launcher calls this where the session's + * commands are counted (`countsRuns` in lib/test-report.mjs). A run is noted + * where its folder is the own one of the checkout of the row the session + * read (`place`): a run in another folder is another repository's, and only + * names its program. A session that runs a shell command before a prompt + * read the row is counted no more (`close`): its first run of a program is + * unknown. So is one that runs a command over `MAX_CALL`, whose names are + * not read. A command adds one line after the ones the state holds and + * rewrites none, so two commands whose hooks run at the same time are both + * noted. The line holds what the state its hook read takes of the command + * (`taken`), and a command it takes nothing of adds none. A later state + * takes no run and no name that an earlier one refused, so what a line + * leaves out would change nothing after the line of a command whose hook + * ran at the same time. + */ +export function noteRuns(sessionId, command, cwd) { + try { + const state = readRuns(sessionId); + if (!state.programs) return; + const held = readSessionState(ROW, sessionId); + const text = String(command || ""); + if (!held.read || text.length > MAX_CALL) { + close(sessionId); + return; + } + const inside = runs(text).flatMap((run) => { + const at = place(held.root, cwd || process.cwd(), run.dir || ""); + return at === null ? [] : [{ ...run, at }]; + }); + const next = folded(state, entry(inside, names(text))); + if (next === state) return; + writePrivateFile(runsPath(sessionId), `${JSON.stringify(taken(state, next))}\n`, { append: true }); + } catch { + /* nothing noted */ + } +} + +/** + * At a session's start, from the payload's `source`: remove what an earlier + * part of the session left, and write the state of a session that is counted + * (`RUNS`). A session is counted where it is new (`startup`, `clear`) and its + * shell commands are (`countsRuns`). One that is resumed knows what its + * earlier part learned, so its first run from here on is no first run. One + * that starts with no credential runs shell commands that are not noted, so + * its first run after a credential comes, from this very start's sign-up or + * later, is no first run either. A start after a compaction is the same + * session's, and changes nothing. A session whose start did not run, or + * named no source, has no state and stores nothing. + */ +export function startFlags(sessionId, source) { + if (source === "compact") return; + endFlags(sessionId); + if (!["startup", "clear"].includes(source) || !countsRuns()) return; + try { + writePrivateFile(runsPath(sessionId), `${JSON.stringify({ programs: {} })}\n`); + } catch { + /* a session with no state stores nothing */ + } +} + +/** + * What the session's runs say of each program it ran, `{ program: { flag: + * "first" | "converged" } }`. A run carries a flag when it holds the flag's + * word, wherever it stands. A flag is `first` when the session's first run + * of the program carries it. It has `converged` when it is not, a run that + * carries it where it is counted as added has an earlier run without it + * whose words are the same but for the flag's word, and from the first run + * that carries it more than half of the session's runs of the program carry + * it. A flag followed by its value converges only where an earlier run held + * that value as a word of its own: the run without the flag's word still + * holds the value. + */ +export function sessionCounts(state) { + const counts = {}; + for (const [program, history] of Object.entries(state.programs || {})) { + const seen = {}; + for (const flag of new Set(history.flatMap((run) => Object.keys(run[1] || {})))) { + const has = history.map((run) => Object.hasOwn(run[1] || {}, flag)); + const from = has.indexOf(true); + const kept = has.slice(from).filter(Boolean).length * 2 > has.length - from; + const added = history.some( + (run, j) => has[j] && history.slice(0, j).some((earlier, i) => !has[i] && earlier[0] === run[1][flag]), + ); + if (from === 0) seen[flag] = "first"; + else if (kept && added) seen[flag] = "converged"; + } + counts[program] = seen; + } + return counts; +} + +/** Whether the counts of `pair` hand it: `MIN_CONVERGED` sessions or more + * converged, and more of them than had the flag on their first run. */ +const enough = (pair) => pair.converged >= MIN_CONVERGED && pair.converged > pair.first; + +/** The pairs of a row a prompt is handed: the row names the flag's word and + * the counts are `enough`. At most `MAX_LINES`, the ones with the most + * converged sessions, in the row's order among equals. */ +export function handed(pairs) { + return pairs + .filter((pair) => countedFlag(pair.flag) && enough(pair)) + .sort((a, b) => b.converged - a.converged) + .slice(0, MAX_LINES); +} + +/** + * The row's pairs after a session, or null for no change. `counts` is + * `sessionCounts` of the session and `pairs` the row as the session read it. + * + * A pair the session was handed (`handed`) keeps its counts: the session + * starts with the flag because it was told to, which would read as a flag on + * the first run and end the line. Any other pair whose program the session + * ran counts one more session that ran it, and one more that converged or had + * the flag on its first run; a pair the row names by a hash is the session's + * flag with that hash. A pair counts no session once `MAX_RAN` ran its + * program: one the row does not hand by then stays as it is, so no later + * session writes the row for it, and while the row holds it it does not + * enter again. A pair the row does not hold enters it with the session that + * converged on it, so its counts start there. A row of `MAX_PAIRS` gives + * such a pair the place of a pair that one session converged on, or that + * counts no more and is not handed: the one whose program the most sessions + * ran. A pair the row names by its hash at `MAX_RAN` is such a one, whatever + * its counts: no session matches its flag to the hash again. A pair that + * lost its place enters again like any other. The row takes no new pair + * where it has no such pair. + */ +export function revised(counts, pairs) { + const told = handed(pairs); + const add = (n, one) => n + (one ? 1 : 0); + let changed = false; + const next = pairs.map((pair) => { + const seen = counts[pair.program]; + if (!seen || told.includes(pair) || pair.ran >= MAX_RAN) return pair; + changed = true; + const flag = Object.keys(seen).find((word) => hidden(pair.program, word) === pair.flag) || pair.flag; + return { + ...pair, + flag, + converged: add(pair.converged, seen[flag] === "converged"), + first: add(pair.first, seen[flag] === "first"), + ran: pair.ran + 1, + }; + }); + const inRow = (program, flag) => + pairs.some((pair) => pair.program === program && [flag, hidden(program, flag)].includes(pair.flag)); + const spent = (pair) => pair.converged === 1 || (pair.ran >= MAX_RAN && !handed(next).includes(pair)); + // The place a full row gives a new pair, -1 for none. + const freeSlot = () => + next.reduce( + (top, pair, at) => + spent(pair) && inRow(pair.program, pair.flag) && (top < 0 || pair.ran > next[top].ran) ? at : top, + -1, + ); + for (const [program, seen] of Object.entries(counts)) { + for (const flag of Object.keys(seen)) { + if (seen[flag] !== "converged" || inRow(program, flag)) continue; + const at = next.length < MAX_PAIRS ? next.length : freeSlot(); + if (at < 0) continue; + next[at] = { program, flag, converged: 1, first: 0, ran: 1 }; + changed = true; + } + } + return changed ? next : null; +} + +/** The row's value for the repository whose id is `repo`: one plain-text + * claim of its pairs' counts. 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. It names a flag by its word only + * for the pairs it hands (`handed`) and by a hash for the others, so recall + * of the row tells no session a flag the line would not. */ +export function claim(repo, pairs) { + const told = handed(pairs); + const each = pairs.map((pair) => { + const { program, converged, first, ran } = pair; + const flag = told.includes(pair) || HIDDEN.test(pair.flag) ? pair.flag : hidden(program, pair.flag); + return `${program} ${flag} in ${converged} of ${ran} sessions that ran ${program}, on the first run in ${first}`; + }); + return `In the repository tagged repo:${repo}, flags that sessions added to a command they had already run: ${each.join("; ")}.`; +} + +const CLAIM = + /^In the repository tagged repo:(\w+), flags that sessions added to a command they had already run: (.+)\.$/; +const PAIR = /^(\S+) (\S+) in (\d{1,2}) of (\d{1,2}) sessions that ran (\S+), on the first run in (\d{1,2})$/; + +/** The pairs a row's value claims of the repository whose id is `repo`, + * `{ program, flag, converged, first, ran }` each, with a hash as the `flag` + * of a pair the row does not hand; null for a value that is not `claim`'s + * text of program names and flags, with counts sessions can give: one that + * converged at least, no more that converged or had the flag on their first + * run than ran the program, and `MAX_RAN` of those at most. A pair whose + * program or flag is not counted is left out: a row written before a word + * joined a list still reads, and its next write is without the pair. */ +export function parseClaim(repo, value) { + const found = typeof value === "string" && value.length <= MAX_VALUE ? CLAIM.exec(value) : null; + if (!found || found[1] !== repo) return null; + const all = found[2].split("; ").map((text) => { + const part = PAIR.exec(text); + if (!part || part[1] !== part[5] || !PROGRAM.test(part[1])) return null; + if (!FLAG.test(part[2]) && !HIDDEN.test(part[2])) return null; + const [converged, ran, first] = [part[3], part[4], part[6]].map(Number); + return converged >= 1 && converged + first <= ran && ran <= MAX_RAN + ? { program: part[1], flag: part[2], converged, first, ran } + : null; + }); + if (all.length > MAX_PAIRS || all.includes(null)) return null; + const pairs = all.filter((pair) => counted(pair.program) && (HIDDEN.test(pair.flag) || countedFlag(pair.flag))); + const told = handed(pairs); + const named = (pair) => (HIDDEN.test(pair.flag) ? pair.flag : hidden(pair.program, pair.flag)); + const distinct = new Set(pairs.map((pair) => `${pair.program} ${named(pair)}`)); + return distinct.size === pairs.length && pairs.every((pair) => HIDDEN.test(pair.flag) || told.includes(pair)) + ? pairs + : null; +} + +/** The line a prompt carries for one pair. It is made of the pair's parts + * and never of the stored text, so a row written by another hand adds no + * sentence. A pair's counts start at the first session that converged on + * it, and the line says so. */ +export function renderFlag({ program, flag, converged, first, ran }) { + const started = + first === 0 + ? `none had the flag on its first ${program} run` + : `${first} had the flag on ${first === 1 ? "its" : "their"} first ${program} run`; + return ( + "Command conventions in this repository (counted in earlier sessions, from the first that added the flag): " + + `of the ${ran} sessions that ran ${program}, ` + + `${converged} first ran it without ${flag} and then added that flag to a ${program} command they had already run; ` + + `${started}.` + ); +} + +/** The key of the row of the repository of `scope` (`resolveScope`), "" for a + * checkout with no remote: `//`. */ +export const flagsKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/command-flags/shell` : ""); + +/** + * The lines for a prompt of a session that is told (`conventionsOn`), in the + * checkout at `root`, or "": one for each pair the repository's row hands + * (`handed`). They go where the test cost line goes, and the row is read and + * kept in the session's state as the test cost row is (`heldRow` in + * lib/repo-row.mjs). A read keeps the session counted only where it has + * noted nothing yet (`untouched`). A session that reads a row after that is + * counted no more: the row is a second checkout's, whose runs the session + * did not note, or the copy of its own was removed. + */ +export async function flagsLine(sessionId, root, scopeOf, options) { + try { + if (!conventionsOn()) return ""; + const parse = (repo, value) => ({ pairs: parseClaim(repo, value) }); + const held = await heldRow(ROW, sessionId, root, scopeOf, flagsKey, parse, options); + if (!held) return ""; + if (held.fresh && !untouched(readRuns(sessionId))) close(sessionId); + return handed(held.row?.pairs || []) + .map(renderFlag) + .join("\n"); + } catch { + return ""; + } +} + +/** + * The flusher's post that stores the row with the session's counts + * (`rowPost` in lib/repo-row.mjs), or null: one `memory.set` where `revised` + * changes the row the session read, a miss included. A row another session + * wrote since refuses it, and the session's counts are dropped. A row whose + * value is not `claim`'s text is left as it is, and one with a pair that is + * not counted is written without that pair. The value is sent only where + * the secret redaction leaves it as it is. + */ +export function flagsPost(sessionId) { + try { + const state = readRuns(sessionId); + const held = readSessionState(ROW, sessionId); + if (!state.programs || !held.read || (held.row && !held.row.pairs)) return null; + const next = revised(sessionCounts(state), held.row?.pairs || []); + const value = next ? claim(held.repo, next) : ""; + return value && redactSecrets(value) === value ? rowPost(held, value, "command-flags") : null; + } catch { + return null; + } +} + +/** Remove the session's state. It goes with the session, whatever the + * session stores. The launcher calls it for a session that ends with no + * credential, whose hand-off does not run. */ +export function endFlags(sessionId) { + for (const file of [runsPath(sessionId), sessionStatePath(ROW, sessionId)]) removeFile(file); +} diff --git a/integrations/claude-code-plugin/lib/repo-row.mjs b/integrations/claude-code-plugin/lib/repo-row.mjs new file mode 100644 index 00000000000..1f296244d83 --- /dev/null +++ b/integrations/claude-code-plugin/lib/repo-row.mjs @@ -0,0 +1,65 @@ +// The one memory row a repository has of a kind, as a session reads it at a +// bug report and revises it at its end: what a test run costs +// (lib/test-cost.mjs) and the command conventions (lib/command-flags.mjs). +// +// The session keeps the row it read, a miss too, in its private state. A +// later prompt in the checkout sends no read, and the session's end knows +// the value it replaces. + +import { hookClient, postBounded } from "./loom-client.mjs"; +import { readSessionState, writeSessionState } from "./tmp-state.mjs"; + +/** + * The repository's row as the session keeps it in its state `kind`, for the + * checkout at `root`: `{ read, root, repo, asked, row }`, with the + * repository's id and the identity the read named, which the session's end + * writes to. `row` is null for a miss, else what `parse(repo, value)` reads + * of the value, with the row's `sha` and the `agent` that wrote it. null + * where the row is not read. + * + * 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. `fresh` is set where this call read the row. The + * read is one `memory.get` by the key `keyOf(scope)` ("" for a checkout that + * has no row), bounded by `options.timeoutMs`. It names the scope's agent and + * finds another agent's row too. `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 keep nothing, and a later prompt asks again. + */ +export async function heldRow(kind, sessionId, root, scopeOf, keyOf, parse, options) { + const kept = readSessionState(kind, sessionId); + if (kept.read && kept.root === root) return kept; + const scope = scopeOf(); + const memory_key = keyOf(scope); + if (!memory_key) return null; + const asked = { org: scope.org, namespace: scope.namespace, agent: scope.agent, memory_key }; + const res = await postBounded("memory.get", { ...asked, fields: ["value", "content_sha256", "agent"] }, options); + if (!res) return null; + const repo = scope.repo.id; + const found = { sha: String(res.content_sha256 || ""), agent: String(res.agent || "") }; + const held = { read: true, root, repo, asked, row: res.found ? { ...parse(repo, res.value), ...found } : null }; + writeSessionState(kind, sessionId, held); + return { ...held, fresh: true }; +} + +/** + * The flusher's post that stores `value` as the row `held` is a copy of + * (`heldRow`): one `memory.set` under the key and the repository of that + * read. It is a revision of the row as read (`if_match_sha256`, under the + * agent that wrote the row), else a first row (`absent`): a row another + * session wrote since refuses it. The value names no file to the server + * (`files: []`), its class says a tool measured it, and `tag` names its kind. + */ +export function rowPost(held, value, tag) { + const body = { + ...held.asked, + agent: held.row?.agent || held.asked.agent, + value, + tags: [`repo:${held.repo}`, `source:${hookClient()}`, tag], + files: [], + source_class: "external", + if_match_sha256: held.row?.sha || "absent", + }; + return { op: "memory.set", body }; +} diff --git a/integrations/claude-code-plugin/lib/shell-command.mjs b/integrations/claude-code-plugin/lib/shell-command.mjs index 764b456ead1..588cb5c1aa4 100644 --- a/integrations/claude-code-plugin/lib/shell-command.mjs +++ b/integrations/claude-code-plugin/lib/shell-command.mjs @@ -380,7 +380,7 @@ export function parseBashBulk(command) { } /** A command's list separators: `;`, `&&`, `||` and newlines. */ -const LIST_SEPARATORS = [";", "&&", "||", "\n"]; +export const LIST_SEPARATORS = [";", "&&", "||", "\n"]; /** True when a command has more than one part: a `;` / `&&` / `||` / newline * list or a pipeline, outside quotes. The shunt never refuses one: a refusal @@ -484,7 +484,7 @@ export function parseBashBulkSegments(command) { // writes one or runs a program are among them only without it (READS_WITH), // and `git` only for the subcommands that read. `awk` is not: its script can // redirect to a file and run a command. -const READ_PROGRAMS = new Set([ +export const READ_PROGRAMS = new Set([ "basename", "cat", "cd", @@ -556,13 +556,13 @@ const READS_WITH = { }; // What a redirect that writes no file looks like: to the null device, or one // stream into another. -const NO_FILE_REDIRECT = /\d*>>?\s*\/dev\/null(?![\w./-])|\d*>&\d+/g; +export const NO_FILE_REDIRECT = /\d*>>?\s*\/dev\/null(?![\w./-])|\d*>&\d+/g; /** `command` without its quoted text, or null where it holds what the shell * runs or what the quote rules here do not read: a substitution or an escape * outside single quotes (an escaped quote inside double ones), and a quote * left open. */ -function unquotedText(command) { +export function unquotedText(command) { let out = ""; let quote = ""; for (let i = 0; i < command.length; i++) { @@ -580,6 +580,13 @@ function unquotedText(command) { return quote ? null : out; } +/** The words of `part`, one simple command or one stage of a pipeline: a word + * is what the shell joins of its quoted and bare pieces. */ +export const shellWords = (part) => + splitOutsideQuotes(part, [" ", "\t"]) + .filter(Boolean) + .map((word) => word.replace(/["']/g, "")); + /** * True when `command` reads as one that wrote no file: every part of it, * across `;`, `&&`, `||`, `|` and newlines, starts one of READ_PROGRAMS with @@ -603,12 +610,8 @@ export function readsOnly(command) { if (bare === null || /[>(){}]|&(?!&)/.test(bare.replace(/&&/g, " "))) return false; return splitOutsideQuotes(c, [...LIST_SEPARATORS, "|"]).every((part) => { if (/^\s*["']/.test(part)) return false; - // A word is what the shell joins of its quoted and bare pieces. A leading - // `VAR=value` sets the environment of the program after it. - const words = splitOutsideQuotes(part, [" ", "\t"]) - .filter(Boolean) - .map((w) => w.replace(/["']/g, "")) - .filter((w, i, all) => !all.slice(0, i + 1).every((x) => /^\w+=/.test(x))); + // A leading `VAR=value` sets the environment of the program after it. + const words = shellWords(part).filter((w, i, all) => !all.slice(0, i + 1).every((x) => /^\w+=/.test(x))); if (!words.length) return !part.trim(); const [program, ...rest] = words; return READ_PROGRAMS.has(program) && (READS_WITH[program]?.(rest) ?? true); diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 4fa734e37fb..4126e9f9439 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -37,7 +37,8 @@ // ignores (`measured`). import path from "node:path"; -import { git, gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; +import { git, gitToplevel, isDirectory, pathUnder, redactSecrets } from "./loom-client.mjs"; +import { heldRow, rowPost } from "./repo-row.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"; @@ -67,7 +68,7 @@ const MAX_SAMPLES = 15; 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 +// the identity the read named (`heldRow`), 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 @@ -309,15 +310,6 @@ export function renderCost({ path: file, tests, seconds, filtered }) { * checkout with no remote: `//`, the runner as the id. */ export const costKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/test-cost/pytest` : ""); -/** The 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, @@ -337,20 +329,8 @@ const identity = (scope) => ({ 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 held = await heldRow(ROW, sessionId, root, scopeOf, costKey, parseClaim, options); + const row = held?.row; const printed = row?.path && row.seconds >= MIN_WHOLE_SECONDS && isFile(path.join(root, row.path)); return printed ? renderCost(row) : ""; } catch { @@ -456,16 +436,7 @@ export function costPost(sessionId, cwd) { 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 }; + return rowPost(held, claim(held.repo, next), "pytest-cost"); } catch { return null; } diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index 42840cc6e21..63f4c41e39a 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -14,7 +14,15 @@ import fs from "node:fs"; import path from "node:path"; -import { envSwitch, gitToplevel, pathUnder } from "./loom-client.mjs"; +import { + agentMode, + envSwitch, + gitToplevel, + hookClient, + pathUnder, + planeEnabled, + resolveToken, +} from "./loom-client.mjs"; import { configuresPytest, pytestAddopts } from "./test-gate.mjs"; import { readSessionState, removeFile, sessionStatePath, writePrivateFile, writeSessionState } from "./tmp-state.mjs"; @@ -40,6 +48,23 @@ export function testReportOn(env = process.env) { return envSwitch("LOOM_TEST_REPORT", envSwitch("CLAUDE_PLUGIN_OPTION_TEST_REPORT", true, env), env); } +/** Whether the session is told its repository's command conventions + * (lib/command-flags.mjs): the test report's switch is on, the client is + * Claude Code, whose launcher reads the shell commands, and the host is not + * Windows, where a `cd` names a folder by a path that library does not + * resolve. */ +export const conventionsOn = () => testReportOn() && hookClient() === "claude-code" && process.platform !== "win32"; + +/** Whether a session's shell commands are counted for them: it is told them, + * its end stores the row (the memory plane runs and session memory is not + * switched off) and it has a credential. The session's start and the + * launcher both ask this. */ +export const countsRuns = () => + conventionsOn() && + planeEnabled("memory") && + envSwitch("LOOM_SESSION_MEMORY", true) && + Boolean(agentMode() || resolveToken()); + /** The result file pytest writes for the session. */ export function reportPath(sessionId, opts = {}) { return sessionStatePath("pytest-report", sessionId, { ...opts, ext: ".xml" }); diff --git a/integrations/claude-code-plugin/tests/command-flags.test.mjs b/integrations/claude-code-plugin/tests/command-flags.test.mjs new file mode 100644 index 00000000000..755ea0fb12d --- /dev/null +++ b/integrations/claude-code-plugin/tests/command-flags.test.mjs @@ -0,0 +1,1600 @@ +// The command conventions line: the runs read from a shell command, what a +// session's runs say of a program and a flag, the repository's row of counts a +// session's end revises, 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 crypto from "node:crypto"; +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 } from "./host-env.mjs"; +import { + KEYWORDS, + OTHER_COMMAND, + OUTSIDE, + REFUSED, + claim, + entry, + flagsKey, + folded, + handed, + names, + parseClaim, + renderFlag, + revised, + runs, + sessionCounts, + stateOf, +} from "../lib/command-flags.mjs"; +import { repoIdentity } from "../lib/loom-client.mjs"; +import { cachePathFor } from "../lib/repo-scope.mjs"; +import { readJsonFile, sessionStatePath } from "../lib/tmp-state.mjs"; + +const root = path.join(path.dirname(fileURLToPath(import.meta.url)), ".."); +const WINDOWS = process.platform === "win32"; +const SESSION = "flags-session-1"; +const ORIGIN = "https://github.com/example/app.git"; +const REPO = repoIdentity(ORIGIN).id; +const KEY = `repo:${REPO}/command-flags/shell`; +const FLAG = "--no-incremental"; + +/** A run as `runs` gives it, after a `cd` to `dir` where one is given. */ +const run = (program, words, flags = [], dir = "") => ({ program, words, flags, ...(dir ? { dir } : {}) }); +/** A pair of a row. */ +const pair = (converged, first, ran, program = "mypy", flag = FLAG) => ({ program, flag, converged, first, ran }); +/** What a row holds in place of a flag's word until it hands the pair. */ +const hash = (program, flag) => + `flag:${crypto.createHash("sha1").update(`${program}\0${flag}`).digest("hex").slice(0, 12)}`; +/** A session's state after a shell call that runs `found` and names `nameCounts`. */ +const noted = (state, found, nameCounts) => folded(state, entry(found, nameCounts)); +/** What a session of `commands`, in order, says of the programs it ran. */ +const session = (...commands) => + sessionCounts(commands.reduce((state, command) => noted(state, runs(command), names(command)), {})); + +// A session that reruns a command with the flag and keeps it, one that starts +// with the flag, and one that never has it. +const ADDS = ["python -m mypy t.py", `python -m mypy ${FLAG} t.py`, `python -m mypy ${FLAG} t.py 2>&1 | tail -5`]; +const STARTS = [`mypy ${FLAG} t.py`, "mypy t.py", `mypy ${FLAG} t.py`]; +const PLAIN = ["mypy t.py", "mypy pkg"]; + +// --- the runs of a shell command ---------------------------------------------- + +test("a run is a simple command that starts a program by its bare name, or a module of the interpreter", () => { + assert.deepEqual(runs("mypy t.py"), [run("mypy", ["t.py"])]); + // A redirect between descriptors or to the null device, and the stages that read its output. + assert.deepEqual(runs(`python -m mypy ${FLAG} /tmp/t.py 2>&1 | tail -5`), [run("mypy", [FLAG, "/tmp/t.py"], [FLAG])]); + assert.deepEqual(runs("mytool --pretty x 2>/dev/null > /dev/null"), [run("mytool", ["--pretty", "x"], ["--pretty"])]); + // Each simple command of a list is a run, variable assignments before the program are left out, + // and a quoted word is the word. + assert.deepEqual(runs(`PYTHONPATH=. python3.12 -m mypy ${FLAG} 't.py'; mypy "t.py" || mytool x\nmytool y`), [ + run("mypy", [FLAG, "t.py"], [FLAG]), + run("mypy", ["t.py"]), + run("mytool", ["x"]), + run("mytool", ["y"]), + ]); + // A list goes on after a `&&` or a `||` at a line's end. + assert.deepEqual(runs("mytool a &&\n mytool b ||\nmytool c"), [ + run("mytool", ["a"]), + run("mytool", ["b"]), + run("mytool", ["c"]), + ]); + // A backslash inside quotes is the word's own, but before a double quote inside double quotes. + assert.deepEqual(runs("mytool 'a\\|b' x"), [run("mytool", ["a\\|b", "x"])]); + assert.deepEqual(runs('mytool "a\\|b" x'), [run("mytool", ["a\\|b", "x"])]); + // A flag is counted once a run, and a comment is not read. + assert.deepEqual(runs("mytool --pretty x --pretty # --slow\n# don't\nmytool y"), [ + run("mytool", ["--pretty", "x", "--pretty"], ["--pretty"]), + run("mytool", ["y"]), + ]); +}); + +test("a run after a cd names the folder it changed to, and no other change of folder is followed", () => { + assert.deepEqual(runs(`cd pkg && mypy ${FLAG} t.py; cd sub; mypy t.py`), [ + run("mypy", [FLAG, "t.py"], [FLAG], "pkg"), + run("mypy", ["t.py"], [], "pkg/sub"), + ]); + assert.deepEqual(runs("mytool a; cd /tmp/scratch && mytool b; cd .. && mytool c"), [ + run("mytool", ["a"]), + run("mytool", ["b"], [], "/tmp/scratch"), + run("mytool", ["c"], [], "/tmp"), + ]); + // The rest of the call is not read after a cd that is not to one plain path, a pushd or a popd. + for (const change of [ + "cd", + "cd -", + "cd ~/work", + "cd $HOME", + "cd a b", + "cd 'my folder'", + "cd pkg > log.txt", + "pushd pkg", + "popd", + ]) { + assert.deepEqual(runs(`mytool a; ${change}; mytool b`), [run("mytool", ["a"])], change); + } +}); + +test("the body of a here-document is not read", () => { + const body = "x: int = 'a' # don't\nmypy --strict | tail\n$(mytool) `mytool`"; + assert.deepEqual(runs(`cat > /tmp/t.py <<'EOF'\n${body}\nEOF\npython -m mypy /tmp/t.py`), [ + run("mypy", ["/tmp/t.py"]), + ]); + assert.deepEqual(runs(`mytool --pretty - <<-EOF\n\t${body}\n\tEOF\nmytool x`), [run("mytool", ["x"])]); + // Its end is the line that is its word: an indented one ends no `<<` body. + assert.deepEqual(runs(`cat < { + for (const command of [ + // A later stage of a pipeline. + "cat log.txt | mytool --pretty", + // A script path, and an interpreter named by its path or given a file. + "./tools/check --pretty x", + "/usr/bin/mytool x", + ".venv/bin/python -m mypy t.py", + "python tools/check.py --pretty", + "python -W ignore -m mypy t.py", + // Inline program text and a script on the standard input. + 'python -c "import mypy"', + "python - <<'E'\nimport mypy\nE", + // A redirect to a file, a job in the background. + "mytool x > out.txt", + "mytool x < in.txt", + "mytool x &", + // A run of more than 24 words. + `mytool ${"x ".repeat(24)}`, + ]) { + assert.deepEqual(runs(command), [], command); + } + // The simple commands of a call around one that is not read are runs. + assert.deepEqual(runs("mytool a; mytool b > out.txt; mytool c &\nmytool d"), [ + run("mytool", ["a"]), + run("mytool", ["d"]), + ]); +}); + +test("a call that holds a shape the reader does not know is not read at all", () => { + for (const rest of [ + // A command substitution or an open quote. + "ls $(cat files.txt)", + "ls `cat files.txt`", + 'ls "$(cat files.txt)"', + "ls 'a", + // A backslash outside quotes, or before a double quote inside double quotes. + "mytool b\\ c", + 'mytool "b\\"; mytool c"', + // A subshell, a group, a function, a variable in braces. + "(cd pkg; mytool b)", + "{ mytool b; }", + "check() {\n mytool --pretty b\n}", + "mytool ${FILE}", + // A pipeline that goes on in the next line: its later stage is no run. + "cat log.txt |\n mytool --pretty x", + "cat log.txt | sort | \n\nmytool --pretty x", + "cat log.txt |&\nmytool --pretty x", + "cat log.txt | # the rest\nmytool --pretty x", + "cat < { + for (const command of [ + // Programs that act outside the checkout, or run what a file of recipes names. + "vercel --prod", + "dropdb --if-exists app", + "psql --quiet app", + "clickhouse-client --multiquery", + "clickhouse local --pretty", + // A release tool: one more flag can turn its trial run into a release. + "semantic-release --no-ci", + "np --any-branch", + "hg push --new-branch", + "shred --zero disk.img", + "make --always-make deploy", + "git status --short", + "git push --force-with-lease", + "rm --recursive build", + // Programs that move or write the files their operands name. + "cp --archive src /tmp/dst", + "ln --symbolic a b", + "tar --extract --file x.tar", + "patch --forward p.diff", + "mkdir --parents a/b", + "touch --no-create x", + "tee --append log.txt", + "ssh host --verbose", + "docker build --pull .", + "kubectl get pods --watch", + "curl --silent https://example.com", + "pip install --upgrade mypy", + "python -m pip install --upgrade mypy", + "npm install --legacy-peer-deps", + "cargo --locked build", + "go --pretty x", + "gem --pretty x", + "dnf --refresh x", + "tox --develop", + "nox --no-venv", + "bazel --batch build", + "gradle --offline build", + "mvn --offline package", + // Words that start another command: its flags are not theirs. + "sudo mytool --pretty x", + "timeout 60 mytool --pretty x", + "env A=1 mytool --pretty x", + "uv run mypy --strict t.py", + "xargs mytool --pretty", + "bash run.sh --pretty", + "pdm run mypy --no-incremental", + "stdbuf -oL mypy --no-incremental x.py", + "strace docker run --privileged img", + "parallel mytool --pretty ::: a b", + "caffeinate ./check.sh --pretty x.py", + "xvfb-run -a ./check.sh --pretty", + "valgrind ./prog --pretty", + "mpiexec -n 4 ./prog --pretty", + "taskset -c 0 ./prog --pretty", + // An interpreter given a script, and a module that runs one. + "node build.js --watch-all", + "ruby x.rb --pretty", + "deno run x.ts --pretty", + "pypy3 run.py --pretty", + "python -m cProfile run.py --pretty", + "dash run.sh --pretty", + "ksh run.ksh --pretty", + "fish x.fish --pretty", + "pwsh x.ps1 --pretty", + "Rscript x.R --pretty", + "julia x.jl --pretty", + "swift x.swift --pretty", + "awk -f x.awk --pretty", + "groovy x.groovy --pretty", + // A module named with a dot is a file inside a package, and a program named with one is a file. + "python -m scripts.codegen.sync --pretty", + "python -m scripts.deploy --pretty", + "pip3.12 install --pre x", + "py.test --pretty", + // A name every object has is no key of the session's state. + "constructor --pretty x", + "__proto__ --pretty x", + // Programs that only read. + "grep --count needle file", + "ls --all", + ]) { + assert.deepEqual(runs(command), [], command); + } +}); + +test("a module with no dot is a program wherever its file lies", () => { + // The command does not say whether `sync` is installed or a `sync.py` at the checkout's root. + assert.deepEqual(runs("python -m sync --pretty x"), [run("sync", ["--pretty", "x"], ["--pretty"])]); +}); + +test("only a long flag written as its word alone is counted", () => { + const none = (command) => + assert.deepEqual( + runs(command).map((found) => found.flags), + [[]], + command, + ); + // A flag written with its value, a short flag, a cluster of them. + none("mypy --cache-dir=/dev/null t.py"); + none("pytest -x -k parse -n4 -rf t.py"); + // A word that is no flag: capitals, an underscore, a digit first, dashes alone. + none("mytool --Fast --no_color --9 -- --- x"); + // A flag of one or two letters is an abbreviation: no refused word can be read in it. + none("pytest --lf --ff --sw --nf --co --x t.py"); + assert.deepEqual(runs("mytool --raw x"), [run("mytool", ["--raw", "x"], ["--raw"])]); + // What follows a lone `--` is the program's operands. + none("mytool -- --pretty x.py"); + // A flag after a bare word is the flag of a subcommand, or of the command a wrapper runs. + none("mytool upgrade --pretty"); + none("mytool db push --pretty x.py"); + none("mytool -v othertool --pretty x.py"); + none("mytool pkg --pretty"); + // After a word that holds a dot or a slash it is the program's own. + assert.deepEqual(runs("mytool -v src/ t.py --pretty"), [ + run("mytool", ["-v", "src/", "t.py", "--pretty"], ["--pretty"]), + ]); + // So is the flag of a script that a wrapper the lists do not hold runs by its path. + assert.deepEqual(runs("mywrap ./check.sh --pretty x.py"), [ + run("mywrap", ["./check.sh", "--pretty", "x.py"], ["--pretty"]), + ]); + // A flag whose word holds a refused word. + for (const flag of [ + "--accept-data-loss", + "--noinput", + "--no-input", + "--non-interactive", + "--auto-approve", + "--noconfirm", + "--clear", + "--cache-clear", + "--clobber", + "--zero", + "--full-refresh", + "--in-place", + "--autocorrect-all", + "--regen-all", + "--add-noqa", + "--apply", + "--exit-zero", + "--fail-never", + "--no-warn-return-any", + "--quiet", + "--fast", + "--notest", + "--no-cov", + "--no-sandbox", + "--privileged", + "--install-types", + "--upgrade", + "--prod", + "--publish", + "--pdb", + "--watch", + "--serve", + "--help", + "--version", + "--verbose", + "--debug", + "--show-traceback", + "--force", + "--force-with-lease", + "--no-verify", + "--yes", + "--assume-yes", + "--hard", + "--delete", + "--remove-orphans", + "--purge", + "--prune", + "--destroy", + "--overwrite", + "--reset", + "--skip-checks", + "--ignore-missing-imports", + "--no-check", + "--no-strict-optional", + "--unsafe-fixes", + "--insecure", + "--allow-empty-bodies", + "--disable-warnings", + "--snapshot-update", + "--fix", + "--write", + "--bypass-hooks", + "--dangerously-skip-permissions", + // A trial run made a real one, or a real one a trial. + "--execute", + "--exec", + "--commit", + "--no-dry-run", + "--run", + "--for-real", + "--live", + "--setup-plan", + // No question asked. + "--no-prompt", + "--no-ask", + "--auto", + "--yolo", + "--no-interaction", + // Files or data rewritten. + "--truncate", + "--recreate", + "--replace", + "--discard-changes", + "--revert", + "--rollback", + "--migrate", + "--format", + "--save", + "--generate", + // A check left out, narrowed or let through. + "--last-failed", + "--failed-first", + "--stepwise", + "--collect-only", + "--setup-only", + "--no-test", + "--no-tests", + "--no-lint", + "--no-validate", + "--continue-on-error", + "--continue", + "--keep-going", + "--no-audit", + "--no-gpg-sign", + "--no-hooks", + "--no-lock", + "--lax", + "--bail", + "--changed", + "--quick", + "--exclude", + "--select", + "--deselect", + "--filter", + // Outside the checkout, or waiting for a person. + "--send", + "--submit", + "--download", + "--fetch", + "--pull", + "--sync", + "--wait", + "--pause", + "--shell", + // The same classes by other words. + "--override", + "--batch", + "--unattended", + "--agree-tos", + "--always", + "--kill", + "--flush", + "--cascade", + "--destructive", + "--reverse", + "--bless", + "--restore", + "--amend", + "--snapshot", + "--record", + "--abort", + "--restart", + "--suppress", + "--lenient", + "--permissive", + "--loose", + "--partial", + "--unverified", + "--downgrade", + "--public", + "--share", + "--expose", + "--tunnel", + "--notify", + "--system", + "--reload", + "--inspect", + "--stdin", + "--list", + "--print-config", + "--dump-config", + ]) { + none(`mytool ${flag} x`); + } + // The word stays one of the run's words: a run with it is not the run without it. + assert.deepEqual(runs("mytool --force x.py"), [run("mytool", ["--force", "x.py"])]); +}); + +// --- what a session's runs say ------------------------------------------------- + +test("a session that reruns a command with a flag and keeps the flag converges on it", () => { + assert.deepEqual(session(...ADDS), { mypy: { [FLAG]: "converged" } }); + // The earlier run may be any run before it, and other runs may stand between them. + assert.deepEqual(session("mypy a.py", "mypy t.py", "pytest t.py", `mypy ${FLAG} t.py`, `mypy ${FLAG} a.py`), { + mypy: { [FLAG]: "converged" }, + pytest: {}, + }); + // More than half of the runs from the first one with the flag on carry it. + assert.deepEqual(session("mypy t.py", `mypy ${FLAG} t.py`, "mypy a.py", `mypy ${FLAG} a.py`), { + mypy: { [FLAG]: "converged" }, + }); +}); + +test("a flag a session tries and drops is no convergence", () => { + assert.deepEqual(session("mypy t.py", `mypy ${FLAG} t.py`, "mypy t.py"), { mypy: {} }); + assert.deepEqual(session("mypy t.py", `mypy ${FLAG} t.py`, "mypy a.py"), { mypy: {} }); + assert.deepEqual(session("mypy t.py", `mypy ${FLAG} t.py`, `mypy ${FLAG} t.py`, "mypy t.py", "mypy t.py"), { + mypy: {}, + }); +}); + +test("a flag on the session's first run of the program is no convergence", () => { + assert.deepEqual(session(...STARTS), { mypy: { [FLAG]: "first" } }); + assert.deepEqual(session(...PLAIN), { mypy: {} }); +}); + +test("a first run that holds the flag where it is not counted as added still had the flag", () => { + const rest = ["mypy t.py", `mypy ${FLAG} t.py`, `mypy ${FLAG} t.py`]; + // After a bare word, and after a lone `--`. + assert.deepEqual(session(`mypy pkg ${FLAG}`, ...rest), { mypy: { [FLAG]: "first" } }); + assert.deepEqual(session(`mypy -- ${FLAG} t.py`, ...rest), { mypy: { [FLAG]: "first" } }); + // Such a run carries the flag, and is no run the flag was added to. + assert.deepEqual(session("mypy pkg", `mypy pkg ${FLAG}`, `mypy pkg ${FLAG}`), { mypy: {} }); + assert.deepEqual(session("mypy t.py", `mypy ${FLAG} t.py`, "mypy pkg", `mypy pkg ${FLAG}`), { + mypy: { [FLAG]: "converged" }, + }); +}); + +test("a flag added to no command the session had run is no convergence", () => { + // No earlier run with the same words but for the flag. + assert.deepEqual(session("mypy t.py", `mypy ${FLAG} other.py`, `mypy ${FLAG} other.py`), { mypy: {} }); + // A flag followed by its value: the run without the flag word is not the earlier run. + assert.deepEqual(session("mypy t.py", "mypy --shadow-file a.py t.py", "mypy --shadow-file a.py t.py"), { + mypy: {}, + }); + // It is, where the earlier run held the value as a word of its own. Only the flag's word is kept. + assert.deepEqual(session("mytool src/", "mytool --root src/", "mytool --root src/"), { + mytool: { "--root": "converged" }, + }); +}); + +test("the same words in another folder are another command", () => { + /** What a session says whose commands ran in the folders given with them. */ + const placed = (...steps) => + sessionCounts( + steps.reduce( + (state, [at, command]) => + noted( + state, + runs(command).map((found) => ({ ...found, at })), + names(command), + ), + {}, + ), + ); + const adds = ["mypy .", `mypy ${FLAG} .`, `mypy ${FLAG} .`]; + const [a, b] = [ + ["a", ""], + ["b", ""], + ]; + assert.deepEqual(placed(...adds.map((command) => [a, command])), { mypy: { [FLAG]: "converged" } }); + // The flag came with a move to another folder: no command the session had run got it. + assert.deepEqual(placed([a, adds[0]], [b, adds[1]], [b, adds[2]]), { mypy: {} }); + // Nor is a run after a relative `cd` from a folder the run in the folder it names. + assert.deepEqual(placed([a, adds[0]], [["", "a"], adds[1]], [["", "a"], adds[2]]), { mypy: {} }); + // The first run of the program is the session's, whatever its folder. + assert.deepEqual(placed([a, adds[1]], [b, adds[0]], [b, adds[1]], [b, adds[2]]), { + mypy: { [FLAG]: "first" }, + }); + // A folder is no word: `mytool b` in `a` is not `mytool` after `cd b` from `a`. + assert.deepEqual(placed([a, "mytool b"], [["a", "b"], "mytool --pretty"], [["a", "b"], "mytool --pretty"]), { + mytool: {}, + }); +}); + +test("a program a command names before its first noted run is not counted", () => { + const rest = ["mypy src", `mypy ${FLAG} src`, `mypy ${FLAG} src`]; + assert.deepEqual(session(...rest), { mypy: { [FLAG]: "converged" } }); + // The first run was in a shape that is not read, and may have had the flag. + for (const first of [ + `timeout 600 mypy ${FLAG} src`, + `uv run mypy ${FLAG} src`, + `.venv/bin/mypy ${FLAG} src`, + `mypy ${FLAG} src > out.txt`, + `ls $(mypy ${FLAG} src)`, + `bash -c "mypy ${FLAG} src"`, + `cat < { + assert.deepEqual( + [...names(`cd /a/b && A=1 .venv/bin/mypy ${FLAG} t.py "$(tool-x)" | grep -c error; git log; x=mypy`)], + [ + ["b", 1], + ["A", 1], + ["mypy", 2], + ["tool-x", 1], + ["error", 1], + ["log", 1], + ["x", 1], + ], + ); + assert.deepEqual([...names("ls -la src/ t.py 123 --pretty")], []); + // A word of one dash and letters names what follows its first `m`. + assert.deepEqual( + [...names("python -mmypy t.py; python3 -Bmpylint t.py; mytool --mypy -m")], + [ + ["python", 1], + ["mypy", 1], + ["python3", 1], + ["pylint", 1], + ["mytool", 1], + ], + ); +}); + +test("a flag with a value, a short flag, a script, a refused flag and a refused program are never counted", () => { + assert.deepEqual(session("mypy t.py", "mypy --cache-dir=/dev/null t.py", "mypy --cache-dir=/dev/null t.py"), { + mypy: {}, + }); + assert.deepEqual(session("pytest t.py", "pytest -x t.py", "pytest -x t.py"), { pytest: {} }); + assert.deepEqual(session("./check.sh t.py", "./check.sh --pretty t.py", "./check.sh --pretty t.py"), {}); + assert.deepEqual( + session("python check.py t.py", "python check.py --pretty t.py", "python check.py --pretty t.py"), + {}, + ); + assert.deepEqual(session("node check.js t.py", "node check.js --pretty t.py", "node check.js --pretty t.py"), {}); + assert.deepEqual(session("pdm run mypy t.py", `pdm run mypy ${FLAG} t.py`, `pdm run mypy ${FLAG} t.py`), {}); + assert.deepEqual(session("mytool x.py", "mytool --force x.py", "mytool --force x.py"), { mytool: {} }); + assert.deepEqual(session("mytool x.py", "mytool --no-verify x.py", "mytool --no-verify x.py"), { mytool: {} }); + // A rerun of the cases that failed, by the flag's word or by its abbreviation. + assert.deepEqual(session("pytest t.py", "pytest --last-failed t.py", "pytest --last-failed t.py"), { pytest: {} }); + assert.deepEqual(session("pytest t.py", "pytest --lf t.py", "pytest --lf t.py"), { pytest: {} }); + // A flag that only prints what the program is, and the flag of a subcommand. + assert.deepEqual(session("mytool x.py", "mytool --help x.py"), { mytool: {} }); + assert.deepEqual(session("mytool upgrade", "mytool upgrade --pretty", "mytool upgrade --pretty"), { mytool: {} }); + assert.deepEqual(session("git status", "git status --short", "git status --short"), {}); + assert.deepEqual(session("rm build", "rm --recursive build", "rm --recursive build"), {}); +}); + +test("the session's state holds a program's name, its flag words and hashes, and no other word of a command", () => { + const state = [ + "API_TOKEN=hunter2 mypy /home/someone/secret-project/t.py", + `mypy ${FLAG} /home/someone/secret-project/t.py`, + "mypy --config-file=/home/someone/mypy.ini --junit-xml /home/someone/out.xml t.py", + ].reduce((held, command) => noted(held, runs(command), names(command)), {}); + const text = JSON.stringify(state); + for (const word of ["hunter2", "API_TOKEN", "someone", "secret-project", "t.py", "mypy.ini", "out.xml"]) { + assert.equal(text.includes(word), false, word); + } + assert.deepEqual(Object.keys(state.programs), ["mypy"]); + assert.equal(state.programs.mypy.length, 3); + assert.deepEqual(Object.keys(state.programs.mypy[1][1]), [FLAG]); + // A name that is no run is kept as a hash, once: the variable and its value, then the folder. + assert.equal(state.named.length, 2); + const named = noted(state, [], names("grep -rn hunter2 secretdir")); + assert.equal(named.named.length, 3); + assert.equal(/hunter2|secretdir/.test(JSON.stringify(named)), false); + // A call that changes nothing gives the state back. + assert.equal(noted(named, [], names("grep -rn hunter2 secretdir; ls t.py")), named); + // A program's first 48 runs and the first 32 programs are kept. + let full = {}; + for (let i = 0; i < 60; i++) + full = noted(full, runs(`mypy t${i}.py; tool${i} x`), names(`mypy t${i}.py; tool${i} x`)); + assert.equal(full.programs.mypy.length, 48); + assert.equal(Object.keys(full.programs).length, 32); + // No program starts once 512 names are kept. + let many = noted({}, runs("mypy t.py"), names("mypy t.py")); + for (let i = 0; i < 520; i++) many = noted(many, [], names(`ls dir${i}`)); + assert.equal(many.named.length, 512); + many = noted(many, runs("mypy a.py; pytest a.py"), names("mypy a.py; pytest a.py")); + assert.deepEqual([Object.keys(many.programs), many.programs.mypy.length], [["mypy"], 2]); +}); + +test("the state is the start's line and the lines of the session's calls, folded in order", () => { + const start = { programs: {} }; + const lines = ["mypy t.py", "grep -rn x pytest", `mypy ${FLAG} t.py`, "pytest t.py"].map((command) => + entry(runs(command), names(command)), + ); + const text = (...all) => all.map((line) => `${JSON.stringify(line)}\n`).join(""); + const state = stateOf(text(start, ...lines)); + assert.deepEqual(state, lines.reduce(folded, start)); + // The call that named pytest before its first run ended its count. + assert.deepEqual(sessionCounts(state), { mypy: { [FLAG]: "converged" } }); + assert.deepEqual(stateOf(text(start)), start); + // A last line with no line end is being written: it is not read. + for (const part of [JSON.stringify(lines[2]), '{"runs":[["my']) { + assert.deepEqual(stateOf(text(start, lines[0]) + part), stateOf(text(start, lines[0])), part); + } + // A text whose first line is not the start's is no state: a call added its line after the state was removed. + for (const none of ["", text(lines[0]), text(lines[0], start)]) assert.deepEqual(stateOf(none), {}, none); + // Nor is one with a line that is no call's. + for (const none of [text(start, "x", lines[0]), `${text(start)}{"runs":\n${text(lines[0])}`]) { + assert.deepEqual(stateOf(none), {}, none); + } +}); + +// --- the repository's row ------------------------------------------------------- + +test("three sessions that converged hand the line, and two do not", () => { + const converged = session(...ADDS); + const one = revised(converged, []); + assert.deepEqual(one, [pair(1, 0, 1)]); + const two = revised(converged, one); + assert.deepEqual(two, [pair(2, 0, 2)]); + assert.deepEqual(handed(two), []); + // A session that ran the program without the flag is one more that ran it. + const ran = revised(session(...PLAIN), two); + assert.deepEqual(ran, [pair(2, 0, 3)]); + const three = revised(converged, ran); + assert.deepEqual(three, [pair(3, 0, 4)]); + assert.deepEqual(handed(three), three); +}); + +test("a pair is handed only where three sessions converged, and more than started with the flag", () => { + // Three of the thirty sessions a pair counts at most are a tenth of them. + assert.deepEqual(handed([pair(3, 2, 30)]), [pair(3, 2, 30)]); + assert.deepEqual(handed([pair(3, 3, 30)]), []); + assert.deepEqual(handed([pair(2, 0, 2)]), []); + // A session that started with the flag counts against a pair the row holds. + assert.deepEqual(revised(session(...STARTS), [pair(2, 2, 20)]), [pair(2, 3, 21)]); +}); + +test("at most two pairs are handed, the ones with the most converged sessions", () => { + const row = [ + pair(3, 0, 9), + pair(7, 0, 9, "pytest", "--no-header"), + pair(5, 0, 9, "tsc", "--pretty"), + pair(2, 0, 9, "ruff", "--quiet"), + ]; + assert.deepEqual(handed(row), [row[1], row[2]]); +}); + +test("a session that was handed the line for a pair changes none of that pair's counts", () => { + const row = [pair(3, 0, 5), pair(1, 0, 2, "mypy", "--pretty")]; + // It starts with the flag because it was told to, converges on it or only runs the program. + assert.equal(revised(session(`mypy ${FLAG} t.py`), [row[0]]), null); + assert.equal(revised(session(...ADDS), [row[0]]), null); + assert.equal(revised(session(...PLAIN), [row[0]]), null); + // A pair of the row it was not handed is counted as in any session. + assert.deepEqual(revised(session(`mypy ${FLAG} t.py`, `mypy ${FLAG} --pretty t.py`), row), [ + row[0], + pair(2, 0, 3, "mypy", "--pretty"), + ]); +}); + +test("a session that ran none of a row's programs and converged on nothing changes nothing", () => { + assert.equal(revised(session("pytest t.py"), [pair(1, 0, 1)]), null); + assert.equal(revised(session(...STARTS), []), null); + assert.equal(revised({}, []), null); +}); + +test("a pair counts no session once thirty ran its program", () => { + // One the row does not hand by then stays as it is: no session writes the row for it. + for (const stays of [pair(2, 0, 30), pair(1, 0, 30), pair(5, 6, 30)]) { + for (const commands of [ADDS, STARTS, PLAIN]) assert.equal(revised(session(...commands), [stays]), null); + } + // The thirtieth session is counted, and can be the one that hands the pair. + assert.deepEqual(revised(session(...ADDS), [pair(2, 0, 29)]), [pair(3, 0, 30)]); + assert.deepEqual(handed([pair(3, 0, 30)]), [pair(3, 0, 30)]); + // While the row holds the pair it does not enter again, and another pair still does. + const other = session("pytest t.py", "pytest --no-header t.py", ...PLAIN); + assert.deepEqual(revised(other, [pair(2, 0, 30)]), [pair(2, 0, 30), pair(1, 0, 1, "pytest", "--no-header")]); +}); + +test("a full row gives a new pair the place of the pair one session converged on that the most sessions ran since", () => { + const eight = Array.from({ length: 8 }, (_, i) => + pair(i === 3 || i === 5 ? 1 : 2, 0, 10 + i, `tool${i}`, "--pretty"), + ); + const next = revised(session(...ADDS), eight); + assert.deepEqual(next, [...eight.slice(0, 5), pair(1, 0, 1), ...eight.slice(6)]); + // No pair of one converged session: the row takes no new pair. + const kept = eight.map((held) => ({ ...held, converged: 2 })); + assert.equal(revised(session(...ADDS), kept), null); + // But the place of a pair that counts no more and is not handed, before one of fewer sessions. + const spent = kept.map((held, i) => + i === 2 ? { ...held, first: 4, ran: 30 } : i === 6 ? { ...held, converged: 1 } : held, + ); + assert.deepEqual(revised(session(...ADDS), spent), [...spent.slice(0, 2), pair(1, 0, 1), ...spent.slice(3)]); + // Not the place of one that counts no more and that the row hands. + const enough = kept.map((held, i) => (i === 2 ? { ...held, converged: 3, ran: 30 } : held)); + assert.equal(revised(session(...ADDS), enough), null); + // But the place of one whose counts would hand it and that the row names by its hash, + // behind two pairs of more converged sessions: no session matches its flag again. + const third = kept.map((held, i) => (i < 2 ? { ...held, converged: 5 - i } : held)); + third[2] = { ...third[2], flag: hash("tool2", "--pretty"), converged: 3, ran: 30 }; + assert.deepEqual(handed(third), third.slice(0, 2)); + assert.deepEqual(revised(session(...ADDS), third), [...third.slice(0, 2), pair(1, 0, 1), ...third.slice(3)]); + // A pair that lost its place is in no later read of the row: it enters again as any other does. + const without = revised(session(...ADDS), spent); + const back = session("tool2 x.py", "tool2 --pretty x.py", "tool2 --pretty x.py"); + assert.deepEqual(revised(back, without), [...without.slice(0, 6), pair(1, 0, 1, "tool2", "--pretty"), without[7]]); +}); + +test("the feature page lists the keywords, the programs and the flag words the reader refuses", () => { + // A Windows clone can hold the page with CRLF line ends. + const page = fs + .readFileSync(new URL("../../../docs/features/integrations/claude-code.md", import.meta.url), "utf8") + .replaceAll("\r\n", "\n"); + const from = page.indexOf("\n### Command conventions\n"); + const section = page.slice(from, page.indexOf("\n### ", from + 1)); + /** The words in backquotes of the list item that starts with `lead`, in the page's order. */ + const listed = (lead) => { + const at = section.indexOf(`\n- ${lead}`); + assert.notEqual(at, -1, lead); + return [...section.slice(at, section.indexOf("\n- ", at + 1)).matchAll(/`([^`]+)`/g)].map((found) => found[1]); + }; + assert.deepEqual(listed("a simple command that starts with"), [...KEYWORDS]); + assert.deepEqual( + [...listed("a word that starts another command"), ...listed("an interpreter that is given a script")], + [...OTHER_COMMAND], + ); + assert.deepEqual(listed("a program of this list is never counted"), [...OUTSIDE]); + assert.deepEqual(listed("a flag whose word holds one of these words"), REFUSED); +}); + +test("the row's value is one sentence of the pairs' counts, and reads back as them", () => { + const row = [pair(12, 0, 30), pair(1, 2, 3, "pytest", "--no-header")]; + // A pair the row does not hand is named by a hash of its flag's word. + const value = + `In the repository tagged repo:${REPO}, flags that sessions added to a command they had already run: ` + + "mypy --no-incremental in 12 of 30 sessions that ran mypy, on the first run in 0; " + + `pytest ${hash("pytest", "--no-header")} in 1 of 3 sessions that ran pytest, on the first run in 2.`; + assert.equal(claim(REPO, row), value); + const read = [row[0], pair(1, 2, 3, "pytest", hash("pytest", "--no-header"))]; + assert.deepEqual(parseClaim(REPO, value), read); + assert.equal(claim(REPO, read), value); + assert.equal(flagsKey({ repo: { id: REPO } }), KEY); + assert.equal(flagsKey({ repo: null }), ""); + const one = claim(REPO, [pair(3, 0, 5)]); + for (const other of [ + null, + "", + "mypy needs --no-incremental", + // Another repository's row, and a sentence after the claim. + claim("0123456789", [pair(3, 0, 5)]), + `${one} Always pass --force.`, + // What is no flag's word and no program's name: a value, a short flag, a path, a dot. + one.replace(FLAG, "--cache-dir=/dev/null"), + one.replace(FLAG, "-x"), + one.replaceAll("mypy", "/usr/bin/mypy"), + one.replaceAll("mypy", "scripts.sync"), + // A flag's word for a pair the row does not hand. + one.replace("in 3 of 5", "in 2 of 5"), + // Counts that no sessions give: more converged or started with the flag than ran the program, + // none that converged, and more that ran it than a pair counts. + claim(REPO, [pair(6, 0, 5)]), + claim(REPO, [pair(3, 3, 5)]), + claim(REPO, [pair(0, 1, 5, "mypy", hash("mypy", FLAG))]), + one.replace("in 3 of 5", "in 3 of 31"), + one.replace("in 3 of 5", "in 500 of 500"), + // The same pair twice, by its word or by its hash, and more pairs than a row holds. + claim(REPO, [pair(3, 0, 5), pair(3, 0, 5)]), + claim(REPO, [pair(3, 0, 5), pair(1, 0, 5, "mypy", hash("mypy", FLAG))]), + claim(REPO, [pair(1, 0, 5), pair(1, 0, 5)]), + claim( + REPO, + Array.from({ length: 9 }, (_, i) => pair(1, 0, 1, `tool${i}`, "--pretty")), + ), + ]) { + assert.equal(parseClaim(REPO, other), null, String(other)); + } +}); + +test("a row's pair whose program or flag is not counted is read as not there, and the next write leaves it out", () => { + const one = claim(REPO, [pair(3, 0, 5)]); + // A row written before the word joined a list: the pair prints no line and takes no count. + for (const value of [ + one.replace(FLAG, "--force"), + one.replace(FLAG, "--lf"), + one.replaceAll("mypy", "git"), + one.replaceAll("mypy", "constructor"), + ]) { + assert.deepEqual(parseClaim(REPO, value), [], value); + } + // The row's other pairs are read. + const kept = pair(4, 0, 6, "pytest", "--no-header"); + const value = claim(REPO, [pair(3, 0, 5), kept]).replace(FLAG, "--force"); + assert.deepEqual(parseClaim(REPO, value), [kept]); + // A session that changes the row writes it without the pair. + const next = revised(session(...ADDS), parseClaim(REPO, value)); + assert.deepEqual(next, [kept, pair(1, 0, 1)]); + assert.equal(claim(REPO, next).includes("--force"), false); + // One that changes nothing leaves the row as it is. + assert.equal(revised(session("tsc x.ts"), parseClaim(REPO, value)), null); +}); + +test("a row names a flag by its word only for a pair it hands", () => { + const converged = session(...ADDS); + const named = (pairs) => parseClaim(REPO, claim(REPO, pairs)); + // Two sessions converged: recall of the row tells no session the flag. + const two = named(revised(converged, named(revised(converged, [])))); + assert.deepEqual(two, [pair(2, 0, 2, "mypy", hash("mypy", FLAG))]); + assert.equal(claim(REPO, two).includes(FLAG), false); + // A session's flag is the pair with its hash: one that started with it, and one that converged. + assert.deepEqual(named(revised(session(...STARTS), two)), [pair(2, 1, 3, "mypy", hash("mypy", FLAG))]); + const three = named(revised(converged, two)); + assert.deepEqual(three, [pair(3, 0, 3)]); + assert.deepEqual(handed(three), three); + // A session that ran the program without the flag counts as one that ran it, and adds no second pair. + assert.deepEqual(named(revised(session(...PLAIN), two)), [pair(2, 0, 3, "mypy", hash("mypy", FLAG))]); + // A pair that is no longer handed is named by its hash again. + const third = pair(9, 0, 9, "tsc", "--pretty"); + const row = [pair(3, 0, 9), pair(7, 0, 9, "pytest", "--no-header"), third]; + assert.deepEqual(named(row), [pair(3, 0, 9, "mypy", hash("mypy", FLAG)), row[1], third]); + // A hash where the row would hand the pair prints no line. + assert.deepEqual(handed([pair(3, 0, 3, "mypy", hash("mypy", FLAG))]), []); +}); + +test("the line is made of the row's counts", () => { + assert.equal( + renderFlag(pair(12, 0, 30)), + "Command conventions in this repository (counted in earlier sessions, from the first that added the flag): " + + "of the 30 sessions that ran mypy, " + + "12 first ran it without --no-incremental and then added that flag to a mypy command they had already run; " + + "none had the flag on its first mypy run.", + ); + assert.match(renderFlag(pair(12, 1, 30)), /; 1 had the flag on its first mypy run\.$/); + assert.match(renderFlag(pair(12, 2, 30)), /; 2 had the flag on their first mypy run\.$/); +}); + +// --- the hooks ---------------------------------------------------------------- + +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"; +// Reads as a bug report: the prompt hook asks for the pick, and for the 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/command-flags-wire.json", import.meta.url), "utf8")); + +/** The repository's row as memory.get answers it. */ +const stored = (pairs) => ({ ...WIRE.responses["memory.get"], value: claim(REPO, pairs) }); + +/** A stub Loom server. `get` is what memory.get answers for the row's key (a + * read of any other key misses), and `refused` has it refuse a memory.set as + * the server does one whose row changed since it was read. A search answers + * after 300 ms, as one that embeds its query does. */ +async function loom(t, { get = { found: false }, refused = false } = {}) { + 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 }); + const row = body.memory_key === KEY ? get : { found: false }; + const answer = + op === "code.search" ? SEARCH : op === "memory.get" ? row : op === "run.begin" ? { run_id: body.run_id } : {}; + res.writeHead(refused && op === "memory.set" ? 409 : 200, { "content-type": "application/json" }); + // Unreferenced: an answer still held back when the test ends does not keep the run open. + setTimeout(() => res.end(JSON.stringify(answer)), op === "code.search" ? 300 : 0).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 && (op !== "memory.get" || r.body.memory_key === KEY)); + return { url: `http://127.0.0.1:${server.address().port}`, requests, sent }; +} + +/** A checkout of ORIGIN, a home and a temp folder; `server` holds the + * checkout's index. */ +function sandbox(t, server) { + const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-command-flags-"))); + const box = { dir, home: path.join(dir, "home"), tmp: path.join(dir, "tmp"), cwd: path.join(dir, "work") }; + for (const d of [box.home, box.tmp, box.cwd]) fs.mkdirSync(d); + const git = (...a) => execFileSync("git", a, { cwd: box.cwd, stdio: "ignore" }); + git("init", "-q", "-b", "main"); + git("remote", "add", "origin", ORIGIN); + fs.writeFileSync( + cachePathFor(box.cwd, box.tmp, { serverUrl: server.url, token: "t" }), + JSON.stringify({ + ts: Date.now(), + indexed: true, + own: true, + matchedVia: "origin", + org: "o", + namespace: "code-app", + repo: "example/app", + prefixes: [], + }), + ); + box.runs = sessionStatePath("command-flags", SESSION, { tmp: box.tmp, ext: ".jsonl" }); + box.row = sessionStatePath("command-flags-row", SESSION, { tmp: box.tmp }); + 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 start(script, event, env, payload, client = "") { + return new Promise((resolve) => { + const argv = [path.join(root, "hooks", script), event, ...(client ? [client] : [])]; + const child = spawn(process.execPath, argv, { 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, one that exited non-zero where `failed`. */ +function afterCommand(box, command, { failed = false, extra, cwd = box.cwd } = {}) { + const result = failed ? { error: "Exit code 1" } : { tool_response: { stdout: "", stderr: "" } }; + return start("loom-record.mjs", failed ? "PostToolUseFailure" : "PostToolUse", box.env(extra), { + cwd, + tool_name: "Bash", + tool_input: { command }, + ...result, + }); +} + +const endSession = (box, extra) => + start("loom-record.mjs", "SessionEnd", box.env(extra), { cwd: box.cwd, reason: "exit" }); + +/** The start of the session, or of the session `id`, with no primer: the hook + * writes the session's state before it. */ +const begin = (box, { source = "startup", extra, id = SESSION } = {}) => + start("loom-session-start.mjs", "SessionStart", box.env({ LOOM_INJECT_CONTEXT: "false", ...extra }), { + cwd: box.cwd, + source, + session_id: id, + }); +// The state a start writes for a session that is counted. +const OPEN = { programs: {} }; +/** The state the session's file holds. */ +const kept = (box) => stateOf(fs.readFileSync(box.runs, "utf8")); + +/** The prompt hook on `prompt`: alone, or in the launcher as Claude Code runs it. */ +const ask = (box, { prompt = BUG, extra, launcher = false, client = "" } = {}) => + start( + launcher ? "loom-record.mjs" : "loom-prompt-pack.mjs", + "UserPromptSubmit", + box.env(extra), + { cwd: box.cwd, prompt }, + client, + ); +const context = (r) => JSON.parse(r.stdout).hookSpecificOutput.additionalContext; + +/** 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); + } +} + +/** 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); +} + +test("a session's runs are noted after its bug report read the row, and its end stores the row", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + const quiet = { code: 0, stdout: "", stderr: "" }; + await begin(box); + assert.deepEqual(kept(box), OPEN); + // The session's bug report finds no row, and prints no line. + assert.equal(context(await ask(box)), BLOCK); + assert.deepEqual( + server.sent("memory.get").map((r) => r.body), + [WIRE.requests["memory.get"]], + ); + const text = () => fs.readFileSync(box.runs, "utf8"); + assert.deepEqual(await afterCommand(box, ADDS[0]), quiet); + const first = text(); + // mypy exits non-zero where it reports an error: a failed call is noted too. + assert.deepEqual(await afterCommand(box, ADDS[1], { failed: true }), quiet); + assert.deepEqual(await afterCommand(box, ADDS[2]), quiet); + // Each command added one line after the ones the state held, and rewrote none. + const noted = text(); + assert.deepEqual([noted.startsWith(first), noted.split("\n").length], [true, 5]); + // A command that holds no run leaves the state as it is. + assert.deepEqual(await afterCommand(box, "cat t.py | head -5"), quiet); + assert.equal(text(), noted); + assert.deepEqual(sessionCounts(kept(box)), { mypy: { [FLAG]: "converged" } }); + assert.equal(noted.includes("t.py"), false); + await settled(box); + // Nothing of it has left the machine before the session ends. + assert.deepEqual(server.sent("memory.set"), []); + + assert.deepEqual(await endSession(box), quiet); + await arrived(server, box, "memory.set"); + // The session's read was a miss: the server writes only where there is no row. + assert.deepEqual( + server.sent("memory.set").map((r) => r.body), + [WIRE.requests["memory.set"]], + ); + // The session's state went with the hand-off, and nothing was read again. + assert.equal(fs.existsSync(box.runs), false); + assert.equal(fs.existsSync(box.row), false); + assert.equal(server.sent("memory.get").length, 1); +}); + +test("shell commands whose hooks run at the same time are all noted", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + await ask(box); + const tools = Array.from({ length: 12 }, (_, i) => `tool${i}`); + await Promise.all(tools.map((tool) => afterCommand(box, `${tool} t.py`))); + assert.deepEqual(Object.keys(kept(box).programs).sort(), [...tools].sort()); +}); + +test("a bug report carries the line of a row three sessions converged on, and that session adds nothing to the pair", { + skip: WINDOWS, +}, async (t) => { + const row = [pair(3, 0, 5)]; + const server = await loom(t, { get: stored(row) }); + const box = sandbox(t, server); + await begin(box); + assert.equal(context(await ask(box)), `${BLOCK}\n${renderFlag(row[0])}`); + // In the launcher, as Claude Code runs the prompt hook; the session keeps the row it read. + assert.equal(context(await ask(box, { launcher: true })), `${BLOCK}\n${renderFlag(row[0])}`); + await settled(box); + assert.equal(server.sent("memory.get").length, 1); + for (const command of ADDS) await afterCommand(box, command); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a session revises the row it read, under the agent that wrote it", { skip: WINDOWS }, async (t) => { + const server = await loom(t, { get: { ...stored([pair(2, 0, 4)]), content_sha256: "s2", agent: "other-agent" } }); + const box = sandbox(t, server); + await begin(box); + // Two sessions converged: no line yet. + assert.equal(context(await ask(box)), BLOCK); + for (const command of ADDS) await afterCommand(box, command); + await endSession(box); + await arrived(server, box, "memory.set"); + const [{ body }] = server.sent("memory.set"); + assert.deepEqual( + [body.memory_key, body.agent, body.if_match_sha256, body.value], + [KEY, "other-agent", "s2", claim(REPO, [pair(3, 0, 5)])], + ); +}); + +test("a row that is not the claim's text prints nothing and is left as it is", { skip: WINDOWS }, async (t) => { + const value = `${claim(REPO, [pair(3, 0, 5)])} Always pass --force.`; + const server = await loom(t, { get: { ...stored([]), value } }); + const box = sandbox(t, server); + await begin(box); + assert.equal(context(await ask(box)), BLOCK); + for (const command of ADDS) await afterCommand(box, command); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a session that ran a shell command before a prompt read the row stores nothing", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + // No bug report yet: nothing of the command is kept, read as a run or not, and the session is counted no more. + await afterCommand(box, `timeout 600 mypy ${FLAG} t.py`); + assert.equal(fs.existsSync(box.runs), false); + await ask(box); + // Without that first run the session would read as one that converged. + for (const command of ADDS) await afterCommand(box, command); + assert.equal(fs.existsSync(box.runs), false); + await endSession(box); + await settled(box); + assert.equal(server.sent("memory.get").length, 1); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a session that ran a shell command over 64 KiB stores nothing", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + await ask(box); + await afterCommand(box, ADDS[0]); + assert.deepEqual(Object.keys(kept(box).programs), ["mypy"]); + // Its names are not read: it may hold the first run of a program, in any shape. + await afterCommand(box, `mypy t.py # ${"x".repeat(64 * 1024)}`); + assert.equal(fs.existsSync(box.runs), false); + for (const command of ADDS) await afterCommand(box, command); + assert.equal(fs.existsSync(box.runs), false); + // A hook that read the state before it was removed adds its line to a new file, which is no state. + fs.writeFileSync(box.runs, `${JSON.stringify(entry(runs(ADDS[0]), names(ADDS[0])))}\n`); + for (const command of ADDS) await afterCommand(box, command); + assert.deepEqual([kept(box), fs.readFileSync(box.runs, "utf8").split("\n").length], [{}, 2]); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); + assert.equal(fs.existsSync(box.runs), false); +}); + +test("a session whose start the hooks did not see stores nothing", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + // The plugin came after the session began, or the start named no source it knows: its first runs are unknown. + for (const source of [null, "", "other"]) { + if (source !== null) await begin(box, { source }); + await ask(box); + for (const command of ADDS) await afterCommand(box, command); + assert.equal(fs.existsSync(box.runs), false, String(source)); + } + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a session whose state the day-old sweep removed stores nothing", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + const old = new Date(Date.now() - 25 * 60 * 60 * 1000); + /** Another session starts: its start removes the state files a day old. */ + const sweep = () => begin(box, { id: "flags-session-2" }); + await begin(box); + await ask(box); + await afterCommand(box, `mypy ${FLAG} t.py`); + // Both files are a day old: the session reads the row again, and its runs from here on are not its first. + for (const file of [box.runs, box.row]) fs.utimesSync(file, old, old); + await sweep(); + assert.deepEqual([fs.existsSync(box.runs), fs.existsSync(box.row)], [false, false]); + await ask(box); + assert.equal(server.sent("memory.get").length, 2); + for (const command of ADDS) await afterCommand(box, command); + assert.equal(fs.existsSync(box.runs), false); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); + + // Only the row's copy is a day old, written at the one read: the runs are kept, the row is read + // again, and the session is counted no more. The first session may have been told a pair by then. + await begin(box); + await ask(box); + for (const command of ADDS) await afterCommand(box, command); + fs.utimesSync(box.row, old, old); + await sweep(); + assert.deepEqual([fs.existsSync(box.runs), fs.existsSync(box.row)], [true, false]); + await ask(box); + assert.equal(fs.existsSync(box.runs), false); + // So is one whose next shell command comes before that read. + await begin(box); + await ask(box); + for (const command of ADDS) await afterCommand(box, command); + fs.utimesSync(box.row, old, old); + await sweep(); + await afterCommand(box, ADDS[2]); + assert.equal(fs.existsSync(box.runs), false); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a session that starts with no credential stores nothing, also where one comes later", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + const none = { LOOM_API_KEY: "" }; + // Its shell commands are not noted, so its start writes no state: the launcher writes nothing either. + await begin(box, { extra: none }); + await afterCommand(box, `mypy ${FLAG} t.py`, { extra: none }); + assert.equal(fs.existsSync(box.runs), false); + // The credential comes, and a bug report reads the row. The runs from here on are not its first. + await ask(box); + assert.equal(readJsonFile(box.row, null).read, true); + for (const command of ADDS) await afterCommand(box, command); + assert.equal(fs.existsSync(box.runs), false); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); + assert.equal(fs.existsSync(box.row), false); +}); + +test("the state of a session that ends with no credential goes with it", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + await ask(box); + await afterCommand(box, ADDS[0]); + assert.deepEqual([fs.existsSync(box.runs), fs.existsSync(box.row)], [true, true]); + // No hand-off runs with no credential: the launcher removes the state. + await endSession(box, { LOOM_API_KEY: "" }); + await settled(box); + assert.deepEqual([fs.existsSync(box.runs), fs.existsSync(box.row)], [false, false]); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("on Windows no run is noted and no row is read", { skip: !WINDOWS }, async (t) => { + const server = await loom(t, { get: stored([pair(3, 0, 5)]) }); + const box = sandbox(t, server); + // A start writes no state. + await begin(box); + assert.equal(fs.existsSync(box.runs), false); + // The bug report's search is sent, and the row's read is not beside it. + const asked = await ask(box); + assert.equal(server.sent("code.search").length, 1); + assert.equal(asked.stdout.includes("Command conventions"), false); + await afterCommand(box, "mypy t.py"); + await settled(box); + assert.deepEqual(server.sent("memory.get"), []); + assert.equal(fs.existsSync(box.runs), false); + assert.equal(fs.existsSync(box.row), false); +}); + +test("a session that is resumed stores nothing, and a start after a compaction is the same session's", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + await ask(box); + await afterCommand(box, ADDS[0]); + // The session goes on after a compaction, with what it noted. + const noted = fs.readFileSync(box.runs, "utf8"); + await begin(box, { source: "compact" }); + assert.equal(fs.readFileSync(box.runs, "utf8"), noted); + assert.equal(readJsonFile(box.row, null).read, true); + // Its end did not run. It knows the flag when it is resumed: what its earlier part left is removed. + await begin(box, { source: "resume" }); + assert.deepEqual([fs.existsSync(box.runs), fs.existsSync(box.row)], [false, false]); + await ask(box); + for (const command of STARTS) await afterCommand(box, command); + assert.equal(fs.existsSync(box.runs), false); + // A compaction opens no session that is not counted. + await begin(box, { source: "compact" }); + assert.equal(fs.existsSync(box.runs), false); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); + // A session that starts after `/clear` is a new one. + await begin(box, { source: "clear" }); + assert.deepEqual(kept(box), OPEN); +}); + +test("a session whose shell commands are not counted has no state from its start", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + // Session memory off, code mode, the test report's switch off, another client's hooks. + for (const extra of [ + { LOOM_SESSION_MEMORY: "off" }, + { LOOM_MODE: "code" }, + { LOOM_TEST_REPORT: "off" }, + { LOOM_CLIENT: "codex" }, + ]) { + await begin(box, { extra }); + assert.equal(fs.existsSync(box.runs), false, JSON.stringify(extra)); + } +}); + +test("a write the server refuses is not sent again", { skip: WINDOWS }, async (t) => { + // Another session wrote the row since this one read it. + const server = await loom(t, { refused: true }); + const box = sandbox(t, server); + await begin(box); + await ask(box); + for (const command of ADDS) await afterCommand(box, command); + await endSession(box); + await arrived(server, box, "memory.set"); + assert.equal(server.sent("memory.set").length, 1); + assert.equal(fs.existsSync(box.runs), false); +}); + +test("a session that reads the row of a second checkout stores nothing", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + await ask(box); + for (const command of ADDS) await afterCommand(box, command); + // A bug report in a checkout of another repository, which this Loom indexes too. + const other = path.join(box.dir, "other"); + fs.mkdirSync(other); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: other, stdio: "ignore" }); + execFileSync("git", ["remote", "add", "origin", "https://github.com/example/lib.git"], { + cwd: other, + stdio: "ignore", + }); + fs.copyFileSync( + cachePathFor(box.cwd, box.tmp, { serverUrl: server.url, token: "t" }), + cachePathFor(other, box.tmp, { serverUrl: server.url, token: "t" }), + ); + await start("loom-prompt-pack.mjs", "UserPromptSubmit", box.env(), { cwd: other, prompt: BUG }); + assert.equal(readJsonFile(box.row, null).root, fs.realpathSync(other)); + // The runs it noted are the first checkout's, and its first run in the second is unknown. + assert.equal(fs.existsSync(box.runs), false); + for (const command of ADDS) await afterCommand(box, command, { cwd: other }); + assert.equal(fs.existsSync(box.runs), false); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + +test("a run in a folder outside the checkout of the row is not noted", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + await ask(box); + // A folder of the checkout is in it, as the command's own or after a cd. + fs.mkdirSync(path.join(box.cwd, "pkg")); + await afterCommand(box, "mypy t.py", { cwd: path.join(box.cwd, "pkg") }); + await afterCommand(box, `cd pkg && mypy t.py; cd ${box.home}; mypy t.py`); + await afterCommand(box, `cd ${box.cwd} && mypy ${FLAG} t.py`, { cwd: box.home }); + assert.equal(kept(box).programs.mypy.length, 3); + // A run in a folder outside it is another repository's: in the command's own folder, or after a cd. + const other = ["pytest t.py", "pytest --no-header t.py", "pytest --no-header t.py"]; + await afterCommand(box, other[0], { cwd: box.home }); + await afterCommand(box, `cd ${box.home} && ${other[1]}`); + await afterCommand(box, `cd ../home; ${other[2]}`); + assert.deepEqual(Object.keys(kept(box).programs), ["mypy"]); + // The program's first run was not noted, so no later run of it in the checkout is. + for (const command of other) await afterCommand(box, command); + assert.deepEqual(Object.keys(kept(box).programs), ["mypy"]); + // A line holds what the state took of its command: no run of a program that is not counted. + await afterCommand(box, `${other[0]}; mypy ${FLAG} z.py`); + assert.equal(kept(box).programs.mypy.length, 4); + assert.equal(fs.readFileSync(box.runs, "utf8").includes("pytest"), false); +}); + +test("a run in another checkout under the row's checkout is not noted", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + await ask(box); + // A submodule or a worktree holds a `.git` file, another clone a `.git` folder. + const nested = path.join(box.cwd, "vendor", "lib"); + const clone = path.join(box.cwd, "clone"); + fs.mkdirSync(path.join(nested, "src"), { recursive: true }); + fs.writeFileSync(path.join(nested, ".git"), "gitdir: ../../.git/modules/lib\n"); + fs.mkdirSync(path.join(clone, ".git"), { recursive: true }); + const other = ["pytest t.py", "pytest --no-header t.py", "pytest --no-header t.py"]; + // In the payload's folder, in a folder under it, and after a cd by a relative or an absolute path. + await afterCommand(box, other[0], { cwd: nested }); + await afterCommand(box, other[1], { cwd: path.join(nested, "src") }); + await afterCommand(box, `cd vendor/lib && ${other[2]}`); + await afterCommand(box, `cd ${clone} && ${other[2]}`); + await afterCommand(box, `cd src && ${other[2]}`, { cwd: nested }); + // Its runs only name the program: no later run of it in the outer checkout is noted. + for (const command of other) await afterCommand(box, command); + assert.deepEqual(kept(box).programs, {}); + // A folder of the outer checkout beside them is its own. + await afterCommand(box, "mypy t.py", { cwd: path.join(box.cwd, "vendor") }); + assert.deepEqual(Object.keys(kept(box).programs), ["mypy"]); +}); + +test("a flag added with a move to another folder is added to no command the session had run", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + for (const folder of ["a", "b"]) fs.mkdirSync(path.join(box.cwd, "services", folder), { recursive: true }); + const counts = () => sessionCounts(kept(box)); + await begin(box); + await ask(box); + await afterCommand(box, "cd services/a && mypy ."); + await afterCommand(box, `cd services/b && mypy ${FLAG} .`); + await afterCommand(box, `cd services/b && mypy ${FLAG} .`); + assert.deepEqual(counts(), { mypy: {} }); + // The same cd from the same folder is the same folder. + await afterCommand(box, `cd services/b && mypy --pretty ${FLAG} .; mypy --pretty ${FLAG} .`); + assert.deepEqual(counts(), { mypy: { "--pretty": "converged" } }); + + // A folder named by the payload and one a cd names by its absolute path are the same folder. + await begin(box); + await ask(box); + const a = path.join(box.cwd, "services", "a"); + await afterCommand(box, "mypy .", { cwd: a }); + await afterCommand(box, `cd ${a} && mypy ${FLAG} .`); + await afterCommand(box, `cd ${a}/../a/ && mypy ${FLAG} .`, { cwd: box.home }); + assert.deepEqual(counts(), { mypy: { [FLAG]: "converged" } }); + + // After a relative cd the payload may hold the folder before the call or after it: the run is + // the same as none in a folder named another way. + await begin(box); + await ask(box); + await afterCommand(box, "cd services/a && mypy ."); + await afterCommand(box, `mypy ${FLAG} .`, { cwd: a }); + await afterCommand(box, `cd ${a} && mypy ${FLAG} .`); + assert.deepEqual(counts(), { mypy: {} }); +}); + +test("a row whose value the secret redaction would change is not sent", { skip: WINDOWS }, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await begin(box); + await ask(box); + // A program named as a token is: the name would leave the machine in the row. + const token = `ghp_${"abcdefghijklmnopqrstuvwxyz0123"}`; + for (const command of [`${token} x.py`, `${token} --pretty x.py`, `${token} --pretty x.py`]) { + await afterCommand(box, command); + } + assert.deepEqual(sessionCounts(kept(box)), { [token]: { "--pretty": "converged" } }); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); + assert.equal( + server.requests.some((r) => JSON.stringify(r.body).includes(token)), + false, + ); +}); + +test("the test report's switch and code mode stop the line and the note, and session memory's the note and the write", { + skip: WINDOWS, +}, async (t) => { + const row = [pair(3, 0, 5)]; + const server = await loom(t, { get: stored(row) }); + const box = sandbox(t, server); + assert.equal(context(await ask(box, { extra: { LOOM_TEST_REPORT: "off" } })), BLOCK); + assert.equal(context(await ask(box, { extra: { LOOM_MODE: "code" } })), BLOCK); + // The launcher that reads the shell commands is Claude Code's: another client reads no row. + assert.equal((await ask(box, { client: "codex" })).stdout.includes("Command conventions"), false); + assert.deepEqual(server.sent("memory.get"), []); + // Session memory's switch stops no line: a session that stores nothing is still told. + const told = `${BLOCK}\n${renderFlag(row[0])}`; + assert.equal(context(await ask(box, { extra: { LOOM_SESSION_MEMORY: "off" } })), told); + // The session needs no test report: the checkout configures no pytest. + await begin(box); + assert.equal(context(await ask(box)), told); + // A session that read the row notes no run with a switch off. + for (const extra of [{ LOOM_TEST_REPORT: "off" }, { LOOM_SESSION_MEMORY: "off" }, { LOOM_MODE: "code" }]) { + await afterCommand(box, "pytest t.py", { extra }); + } + assert.deepEqual(kept(box), OPEN); + // Nor does its end store what an earlier command noted. + await afterCommand(box, "pytest t.py"); + await afterCommand(box, "pytest --no-header t.py"); + assert.deepEqual(sessionCounts(kept(box)), { pytest: { "--no-header": "converged" } }); + await endSession(box, { LOOM_SESSION_MEMORY: "off" }); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); + assert.equal(fs.existsSync(box.runs), false); +}); diff --git a/integrations/claude-code-plugin/tests/fixtures/command-flags-wire.json b/integrations/claude-code-plugin/tests/fixtures/command-flags-wire.json new file mode 100644 index 00000000000..2d730b0f665 --- /dev/null +++ b/integrations/claude-code-plugin/tests/fixtures/command-flags-wire.json @@ -0,0 +1,30 @@ +{ + "requests": { + "memory.get": { + "org": "default", + "namespace": "coding", + "agent": "claude-code", + "memory_key": "repo:315f533aed/command-flags/shell", + "fields": ["value", "content_sha256", "agent"] + }, + "memory.set": { + "org": "default", + "namespace": "coding", + "agent": "claude-code", + "memory_key": "repo:315f533aed/command-flags/shell", + "value": "In the repository tagged repo:315f533aed, flags that sessions added to a command they had already run: mypy flag:e8354afc8ced in 1 of 1 sessions that ran mypy, on the first run in 0.", + "tags": ["repo:315f533aed", "source:claude-code", "command-flags"], + "files": [], + "source_class": "external", + "if_match_sha256": "absent" + } + }, + "responses": { + "memory.get": { + "found": true, + "value": "In the repository tagged repo:315f533aed, flags that sessions added to a command they had already run: mypy flag:e8354afc8ced in 1 of 1 sessions that ran mypy, on the first run in 0.", + "content_sha256": "abc", + "agent": "claude-code" + } + } +} diff --git a/integrations/claude-code-plugin/tests/mode-session.mjs b/integrations/claude-code-plugin/tests/mode-session.mjs index aa11c6ff7dd..5c8a8b40123 100644 --- a/integrations/claude-code-plugin/tests/mode-session.mjs +++ b/integrations/claude-code-plugin/tests/mode-session.mjs @@ -290,7 +290,12 @@ export async function runSession({ } }); return { - ops: [...new Set(server.ops)].filter((op) => op !== "health").sort(), + // A bug report's read of the command conventions row is left out: it is + // sent only where the search has not answered first, and never on + // Windows (command-flags.test.mjs holds it). + ops: [...new Set(server.requests.filter((r) => !/\/command-flags\//.test(r.raw)).map((r) => r.op))] + .filter((op) => op !== "health") + .sort(), requests: server.requests.filter((r) => r.op !== "health"), startText: start.map((d) => d.stdout).join(""), promptContext: context.join(""), diff --git a/integrations/claude-code-plugin/tests/prompt-pack-hook.test.mjs b/integrations/claude-code-plugin/tests/prompt-pack-hook.test.mjs index 085415a5664..68cc1ccee66 100644 --- a/integrations/claude-code-plugin/tests/prompt-pack-hook.test.mjs +++ b/integrations/claude-code-plugin/tests/prompt-pack-hook.test.mjs @@ -814,8 +814,10 @@ test("a bug report asks for the server's pick, with no switch, and is sent by th assert.equal(plain.seen[0].body.rerank, "builtin:pick"); // a question is not a bug report: no pick is asked, the server is given no deadline, and it says no word assert.match(context(await plain.ask(question)), /src\/parser4\.py:10-14 combine4/); - assert.equal(plain.seen[1].body.rerank, "none"); - assert.equal("deadline_ms" in plain.seen[1].body, false); + // (the report read the command conventions row beside its search) + const second = plain.seen.filter((r) => r.op === "code.search")[1].body; + assert.equal(second.rerank, "none"); + assert.equal("deadline_ms" in second, false); // One rule for both words: when the first pick is no place to edit, the picks below it are not sent for it. const migration = { ...results[0], path: "app/migrations/0001_initial.py" }; const misplaced = (pick) => ({ @@ -838,6 +840,9 @@ test("a bug report asks for the server's pick, with no switch, and is sent by th assert.match(context(await served.ask(report)), /^[^\n]+\n- src\/parser2\.py:10-14 combine2\n/); }); +// The command conventions row is asked for beside a bug report's search, on a POSIX host. +const CONVENTIONS = process.platform === "win32" ? [] : ["/v1/memory.get"]; + test("a bug report waits for the pick's bound, a question for its own, and neither past it", async (t) => { const report = "The parser crashes on a nested record prefix that ends with a dot"; // An answer held 900 ms: past a question's bound, inside a report's 6,000 ms. @@ -847,7 +852,8 @@ test("a bug report waits for the pick's bound, a question for its own, and neith // A server that does not answer inside a report's bound: nothing is sent and the hook exits 0. const away = await listening(t, { cached: true, stall: 8000 }); assert.deepEqual(await away.ask({ LOOM_PROMPT_PACK_PICK_TIMEOUT_MS: "500" }, report), SILENT); - assert.deepEqual(away.seen, ["/v1/code.search"]); + // The command conventions row is asked for beside the search, inside the same bound. + assert.deepEqual(away.seen, ["/v1/code.search", ...CONVENTIONS]); const asked = JSON.parse(away.bodies[0]); assert.equal(asked.rerank, "builtin:pick"); // Less than 500 ms is left, and less the 300 ms margin that is under the server's 200 ms @@ -865,7 +871,7 @@ test("a bug report's repository lookup has the pick's bound too, whatever the ot // and past the least a lookup is given. The report's lookup, status and search fit in 6,000 ms. const slow = await listening(t, { repos: [LISTED], stall: 800 }); assert.match(sent(await slow.ask({ LOOM_PROMPT_PACK_TIMEOUT_MS: "300" }, report)), /src\/parser\.py:10-14 combine/); - assert.deepEqual(slow.seen, ["/v1/code.repos", "/v1/code.index_status", "/v1/code.search"]); + assert.deepEqual(slow.seen, ["/v1/code.repos", "/v1/code.index_status", "/v1/code.search", ...CONVENTIONS]); // A question's lookup keeps its own bound: it is given up, and no search follows. const plain = await listening(t, { repos: [LISTED], stall: 800 }); assert.deepEqual(await plain.ask({ LOOM_PROMPT_PACK_TIMEOUT_MS: "300" }), SILENT); diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index ccab6ea4f73..cf86cf17057 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -1256,7 +1256,8 @@ async function loom(t, { get = { found: false }, getStall = 0, mark = () => ({}) server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); }); - const sent = (op) => requests.filter((r) => r.op === op); + // The requests of the command conventions row are another test's (command-flags.test.mjs). + const sent = (op) => requests.filter((r) => r.op === op && !/\/command-flags\//.test(r.body.memory_key)); return { url: `http://127.0.0.1:${server.address().port}`, requests, sent }; } diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index d12cda0ad62..44970942cd3 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.190", + "version": "1.2.191", "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 5033a802771..0b63a62cdbf 100644 --- a/integrations/codex-plugin/hooks/loom-prompt-pack.mjs +++ b/integrations/codex-plugin/hooks/loom-prompt-pack.mjs @@ -63,6 +63,15 @@ // stays until the read has settled or the exit grace has passed. A row whose // file the checkout does not hold prints nothing. // +// Below that go at most two command conventions lines, for a bug report in a +// Claude Code session on a POSIX host, with or without the test report, where +// the memory plane runs (LOOM_TEST_REPORT=off stops them too): for each flag +// that three or more earlier sessions in the repository added to a command of +// a program they had already run, the sessions that did, the ones that had it +// on their first run of the program and the ones that ran the program +// (lib/command-flags.mjs). Its row is a second read by key, sent and waited +// for as the test cost row's is. +// // 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 @@ -151,10 +160,16 @@ 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 +// The test cost line and the command conventions lines are read from memory, +// only where that plane runs: the library of each and its function that reads +// the row. The test report's switch is read with each line, in the library a // bug report loads. -const COST_LINE = planeEnabled("memory"); +const ROW_LINES = planeEnabled("memory") + ? [ + ["../lib/test-cost.mjs", "costLine"], + ["../lib/command-flags.mjs", "flagsLine"], + ] + : []; const CONSUMER = "claude-code-prompt-pack"; // The lookups a session makes as it starts: SessionStart's, and the MCP headers helper's. @@ -228,7 +243,7 @@ function renderLookup(lookup, body, response, repo) { * for the file `checkPointer` reads from them, inside what is left of the * 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. */ + * `rowNote`), 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(); @@ -240,17 +255,17 @@ 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(() => ""); +/** The line of one row of the session's repository, or "": the test cost + * line (`costLine` in lib/test-cost.mjs) or the command conventions lines + * (`flagsLine` in lib/command-flags.mjs). The library is 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`). `scopeOf` resolves the checkout's scope once for both. */ +function rowNote([library, line], payload, root, scopeOf, options) { + return import(library).then((lib) => lib[line](payload.session_id, root, scopeOf, options)).catch(() => ""); } async function main() { @@ -302,17 +317,20 @@ async function main() { const options = { token, serverUrl: resolveServerUrl(), timeoutMs: left }; const asked = requestLookup(lookup.op, body, options); // Started beside the search, once that is sent, and not waited for after it. - const cost = COST_LINE && pick && payload.session_id ? costNote(payload, root, cwd, options) : null; + let scope = null; + const scopeOf = () => (scope ??= resolveScope(cwd)); + const rows = pick && payload.session_id ? ROW_LINES : []; + const lines = rows.map((row) => rowNote(row, payload, root, scopeOf, options)); 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("")]) : ""; + // What each read has answered by now, or nothing: a settled promise wins the race. + const notes = text && sent ? await Promise.all(lines.map((line) => Promise.race([line, Promise.resolve("")]))) : []; scheduleExit(0); - return text ? packPayload([text, check, note].filter(Boolean).join("\n")) : undefined; + return text ? packPayload([text, check, ...notes].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 a98ac53f6db..3be5256f922 100644 --- a/integrations/codex-plugin/hooks/loom-record.mjs +++ b/integrations/codex-plugin/hooks/loom-record.mjs @@ -57,7 +57,8 @@ // launcher reads the planes and switches of the scripts the host waits for // (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. +// at SessionEnd for the cost of a run that outlived its command, and noting +// the runs of a shell command for the repository's command conventions. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -81,7 +82,7 @@ import { keepRunBegin, runLedgerEnabled } from "../lib/run-hook.mjs"; import { readsOnly } from "../lib/shell-command.mjs"; import { useHooksServer } from "../lib/plugin-options.mjs"; import { startsRunner } from "../lib/test-gate.mjs"; -import { endReport, reportPath, showsRefusal, testReportOn, visibleOutput } from "../lib/test-report.mjs"; +import { countsRuns, endReport, reportPath, showsRefusal, testReportOn, visibleOutput } from "../lib/test-report.mjs"; import { readPrivateFile, removeFile } from "../lib/tmp-state.mjs"; /** The scripts each event records with, in the order they start. At @@ -253,11 +254,22 @@ async function hook(script, event, client) { const names = rows.map((row) => row.script); const waits = rows.map((row) => row.waitMs); const waited = names.length ? run(raw, names, payload, waits) : null; + // The runs of a shell command, failed or not, where the session's commands + // are counted for the command conventions (`countsRuns`), asked here to + // leave the library unloaded where they are not. + if (event.startsWith("PostToolUse") && payload.tool_name === "Bash" && countsRuns()) { + const { noteRuns } = await import("../lib/command-flags.mjs"); + noteRuns(payload.session_id, commandText(payload.tool_input), payload.cwd); + } // An agent's token is left to the copy, or at a prompt to what the hook runs // anyway: renewing one is a request. if (records(event, payload) && (agentMode() || resolveToken())) { if (event === "UserPromptSubmit") keepBegin(payload); spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` }); + } else if (event === "SessionEnd") { + // No copy runs with no credential, so loom-session-memory does not remove + // the command conventions state of a session that lost its own. + (await import("../lib/command-flags.mjs")).endFlags(payload.session_id); } const answer = waited ? mergedAnswer(event, await waited) : null; // Exits itself: a host that never closes stdin would hold the process open. diff --git a/integrations/codex-plugin/hooks/loom-session-memory.mjs b/integrations/codex-plugin/hooks/loom-session-memory.mjs index aba50ceb961..5c78f812575 100644 --- a/integrations/codex-plugin/hooks/loom-session-memory.mjs +++ b/integrations/codex-plugin/hooks/loom-session-memory.mjs @@ -27,7 +27,10 @@ // 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 there, whatever is handed off. +// The session's cost state is removed there, whatever is handed off. So it is +// with the repository's command conventions row: one memory.set of the counts +// of the flags the session added to commands it had already run +// (lib/command-flags.mjs), under the same switches. // // Off-switch: LOOM_SESSION_MEMORY=off. LOOM_SESSION_MEMORY_EVERY_TURNS (40) // and LOOM_SESSION_MEMORY_IDLE_MINUTES (30) set when a Stop hands off; 0 turns @@ -46,6 +49,7 @@ import { runHookMain, scheduleExit, } from "../lib/loom-client.mjs"; +import { endFlags, flagsPost } from "../lib/command-flags.mjs"; import { dispatchFlush } from "../lib/flush-job.mjs"; import { changeCommit, @@ -149,11 +153,13 @@ async function main() { const stores = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true) && resolveToken(); // Read for a session that stores, and removed for every session. const cost = ends && stores && testReportOn() ? costPost(sid, payload.cwd) : null; + const flags = ends && stores && testReportOn() ? flagsPost(sid) : null; if (ends) endCost(sid); + if (ends) endFlags(sid); if (stores) { const window = await handOff(event, payload, from, handedOffAt, recalledKeys); if (ends) { - const posts = [window && window.post, cost].filter(Boolean); + const posts = [window && window.post, cost, flags].filter(Boolean); // Spawn failure: nothing is lost that the next session cannot say again. if (posts.length) dispatchFlush({ posts }); } else if (window) { diff --git a/integrations/codex-plugin/hooks/loom-session-start.mjs b/integrations/codex-plugin/hooks/loom-session-start.mjs index bef7865c8ae..7af43611774 100755 --- a/integrations/codex-plugin/hooks/loom-session-start.mjs +++ b/integrations/codex-plugin/hooks/loom-session-start.mjs @@ -86,6 +86,7 @@ import { import { cacheIsFresh, countsBody, renderTaskLine, summarizeCounts } from "../lib/task-inbox.mjs"; import { listBody, listsCollections, renderCollectionsLine } from "../lib/collections-line.mjs"; import { briefPrimerEnabled, primerLine } from "../lib/session-brief.mjs"; +import { startFlags } from "../lib/command-flags.mjs"; import { startReport } from "../lib/test-report.mjs"; import { readJsonFile, sweepStaleStateFiles, tmpStatePath, writeJsonFile } from "../lib/tmp-state.mjs"; @@ -116,6 +117,12 @@ async function main() { // An invalid endpoint has stopped the hook at saveInstall, so neither this // nor loom-record's digest and end runs: nothing is left half set up. startReport(payload); + // A session is counted for the repository's command conventions only from + // the state this writes (lib/command-flags.mjs): for a new session whose + // shell commands are noted, and not for a resumed one, which knows what its + // earlier part learned. Before the sign-up below: a session it signs up + // started with no credential, and its commands so far were not noted. + if (payload.session_id) startFlags(payload.session_id, payload.source); // Default ON; opt out with LOOM_INJECT_CONTEXT=false (see header). if (!envSwitch("LOOM_INJECT_CONTEXT", true)) { scheduleExit(0); diff --git a/integrations/codex-plugin/lib/command-flags.mjs b/integrations/codex-plugin/lib/command-flags.mjs new file mode 100644 index 00000000000..597a3dd7891 --- /dev/null +++ b/integrations/codex-plugin/lib/command-flags.mjs @@ -0,0 +1,763 @@ +// The command conventions of a repository: a flag that sessions add to a +// command of a program after they have run that command without it, told to a +// later session before its first run of the program. A session that does not +// know the convention runs the command, reads a result it cannot use, and +// runs it again with the flag. +// +// It is counted from the session's shell commands, with no model call, in a +// Claude Code session on a POSIX host (`conventionsOn`). A session is counted +// only while it holds the state its start wrote (`startFlags`): one whose +// state is not there, or was removed, stores nothing. The launcher +// (hooks/loom-record.mjs) notes the runs of each shell command in that state +// (`noteRuns`), from the prompt that read the repository's row on. A +// command adds one line to the state and rewrites none, so commands whose +// hooks run at the same time are all noted, in the order their lines were +// written. +// hooks/loom-prompt-pack.mjs reads that one memory row by its key beside a +// bug report's search and prints a line for at most two of its pairs under +// the pointers (`flagsLine`). At the session's end +// hooks/loom-session-memory.mjs hands the row with the session's counts to +// the flusher (`flagsPost`) and removes the session's state (`endFlags`). +// +// The reader refuses a shape it does not know: a missed convention costs +// nothing, and a wrong line is read by every later session. +// +// A call is not read (`runs`) where it holds a backquote, `$(` or `$'` +// outside single quotes, a backslash outside quotes or before a double quote +// inside them, a quote left open, a parenthesis or a brace outside quotes, a +// `|` at a line's end, a simple command that starts with a shell keyword, or +// a here-document whose word is not a plain one or whose body has no end +// line. A here-document's body and a comment are left out. +// +// A run is a simple command of the call, cut at `;`, `&&`, `||`, `|` and line +// ends, that is no later stage of a pipeline, holds no `&`, `<` or `>` +// outside quotes but for a redirect between descriptors or to the null +// device, and has 24 words at most. After a `cd` to one plain path the runs +// are that folder's (`dir`); after any other `cd`, a `pushd` or a `popd` the +// rest of the call is not read. A run is noted where its folder is the +// checkout's own (`place`): in the checkout of the row the session read, and +// in no other checkout under it. +// +// The program is the first word after the variable assignments: a bare name +// with no dot, or the module of `python -m` or `pypy -m`, where the +// interpreter is named by its bare name and `-m` is its first word. A path +// is no program, so a script named by its path never is, and neither is a +// module named with a dot, a file inside a package. A module with no dot is a +// program wherever its file lies, at the checkout's root too: the command +// does not say where. A program of `OTHER_COMMAND`, of `OUTSIDE` or of +// `READ_PROGRAMS` is no run. A wrapper or an interpreter that `OTHER_COMMAND` does not hold is a +// program, and a flag after the script it runs is counted as its own. +// +// A flag is a word of the run that is two dashes and lower-case words joined +// by dashes, 5 to 40 characters. A flag written with its value +// (`--name=value`), a short flag and a flag of one or two letters (`--lf`) +// are not flags: no word of `REFUSED` can be read in an abbreviation. A flag +// whose word holds one of `REFUSED` is never counted. A flag is counted as +// added only before the run's first bare word (one that starts with no dash +// and holds no dot and no slash) and before a lone `--`: a bare word can be +// a subcommand or the command a wrapper runs, and the flags after it are +// that one's. A run that holds the flag's word after that still carries the +// flag. +// +// A program has no first run the session knows where a call names it before +// the first run that is noted (`names`). The run may have been in a shape +// this does not read, with the flag. Such a program is not counted. A name +// is a word of the call's text, the last part of a path there, or what +// follows the first `m` of a word of one dash and letters (`python -mmypy`), +// and no program of a run noted from that call. Every call is read for its +// names, whether or not its runs are. +// +// The state holds, for each program, a hash of each run's folder and words +// and, for each of its flags, a hash of them without the flag, and a hash of +// each name that is not counted: no other text of a command. What leaves the +// machine is the program's name, three counts and the flag's word for a pair +// the row hands, or a hash of the program's name and that word for any other +// pair, under the repository's id. The hash has no secret part: who reads the +// row can try the program's flags against it. + +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +import { pathUnder, redactSecrets } from "./loom-client.mjs"; +import { heldRow, rowPost } from "./repo-row.mjs"; +import { + LIST_SEPARATORS, + NO_FILE_REDIRECT, + READ_PROGRAMS, + shellWords, + splitOutsideQuotes, + unquotedText, +} from "./shell-command.mjs"; +import { conventionsOn, countsRuns } from "./test-report.mjs"; +import { readPrivateFile, readSessionState, removeFile, sessionStatePath, writePrivateFile } from "./tmp-state.mjs"; + +/** The words of `lines`, each a list of words with a space between them. */ +const wordList = (...lines) => lines.join(" ").split(" "); + +// A call that holds a command starting with one of these is not read: the +// commands of a loop, a condition or a function are not the call's own runs. +export const KEYWORDS = new Set(wordList("if then else elif fi for while until do done case esac select function")); +// A word that starts another command, an interpreter given a script, and a +// module that runs one: the flags after it are not its own. +export const OTHER_COMMAND = new Set( + wordList( + "time env exec command nohup nice timeout gtimeout xargs eval watch sudo doas su", + "uv poetry pipx npx pdm hatch pipenv bunx stdbuf strace ltrace parallel", + "caffeinate xvfb-run valgrind unbuffer mpiexec mpirun ionice taskset setsid", + "bash sh zsh dash ksh csh tcsh fish ash busybox pwsh powershell", + "node nodejs deno bun tsx ts-node coffee ruby jruby perl php lua luajit java kotlin scala groovy", + "Rscript R julia swift dart elixir escript erl racket guile clojure clj bb tclsh wish expect", + "awk gawk mawk nawk osascript raku octave runghc runhaskell ipython jython py", + "cProfile profile pdb trace timeit runpy", + ), +); +// A program that acts outside the checkout (a release tool and a database +// client do), moves or writes the files its operands name, or runs what a +// file of recipes names. +export const OUTSIDE = new Set( + wordList( + "git gh hg svn rm rmdir mv cp ln install dd shred truncate chmod chown chgrp touch mkdir mktemp unlink link tee", + "tar unzip zip gzip gunzip bzip2 xz zstd cpio patch kill pkill killall mount umount crontab shutdown reboot", + "ssh scp sftp ftp rsync nc ncat telnet open xdg-open", + "docker docker-compose podman kubectl helm terraform pulumi ansible ansible-playbook aws gcloud az", + "vercel netlify heroku fly flyctl firebase serverless systemctl service launchctl curl wget", + "pip pip3 npm pnpm yarn conda brew apt apt-get twine cargo gem composer go dnf yum", + "semantic-release release-it release-please standard-version np lerna changeset goreleaser", + "bumpversion bump2version cz flit maturin vsce", + "psql mysql sqlite3 mongosh redis-cli clickhouse clickhouse-client clickhouse-local", + "dropdb createdb pg_dump pg_restore prisma dbt alembic django-admin", + "make just rake tox nox invoke ninja gradle mvn bazel", + ), +); +// What the word of a refused flag holds: it forces or confirms, destroys or +// rewrites, turns a trial run into a real one or back, skips, narrows or +// weakens a check, reaches outside the checkout, waits for a person, or only +// prints what the program is. The list is the rule: a word that holds none +// of these can be counted, whatever its flag does. +export const REFUSED = wordList( + "force yes yolo confirm accept approve assume input interact prompt ask auto", + "override batch attend agree consent always", + "hard delete remove purge prune destroy overwrite reset clear clean clobber wipe erase drop zero", + "truncate create replace discard revert rollback migrat", + "kill flush cascade destruct reverse bless nuke undo restore amend rebase squash unlink expunge trash empty", + "modify mutate rename merge init record snapshot baseline abort terminate cancel restart", + "update fix write place correct gen refresh apply noqa format save commit", + "exec dry run real live plan", + "skip only collect stepwise ignore verif check strict unsafe insecure allow disable bypass danger", + "bail changed quick exclude select filter partial subset sample", + "suppress lenient permi loose tolera waive exempt", + "exit fail never warn quiet silent fast test lint valid error continue keep audit sign hook lock lax", + "cov sandbox privileged trust", + "install grade prod deploy publish push upload release remote global send submit download fetch pull sync", + "public share expose tunnel cloud proxy telemetry notify mail sudo admin system", + "pdb watch serve daemon follow open edit wait pause shell reload repl browse gui attach inspect stdin", + "help version verbose debug trace usage list print dump", +); + +const PROGRAM = /^[A-Za-z_][\w+-]{0,39}$/; +const FLAG = /^--[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/; +// A flag of one or two letters is an abbreviation (`--lf`, `--co`): no word +// of `REFUSED`, three letters at least, can be read in it. +const MIN_FLAG = 5; +const MAX_FLAG = 40; +// A `|` that ends a line: the pipeline goes on in the next one. +const OPEN_PIPE = /(?()]*)/g; +// The word of a here-document this reads, without its quotes. +const BODY_WORD = /^[A-Za-z_][\w.-]*$/; +// The option letters a module can follow in one word: `-mmypy`, `-Bmmypy`. +const MODULE_OPTION = /^-[A-Za-z]*?m/; +// The one operand of a `cd` whose folder is read. +const PLAIN_PATH = /^[\w./][\w./+@-]*$/; +const MAX_CALL = 64 * 1024; +const MAX_WORDS = 24; +// The programs a session's state holds, the runs of each, and the names that +// are not counted. +const MAX_PROGRAMS = 32; +const MAX_RUNS = 48; +const MAX_NAMES = 512; +// The pairs a row holds, and the lines a prompt gets. +const MAX_PAIRS = 8; +const MAX_LINES = 2; +// A pair is handed from this many sessions that converged on it. +const MIN_CONVERGED = 3; +// A pair counts sessions until this many ran its program: the most among +// which `MIN_CONVERGED` are a tenth, so the sessions that converged on a pair +// the row hands are a tenth or more of those that ran its program. +const MAX_RAN = 30; +const MAX_VALUE = 4096; + +// The session's runs: `{ programs, named }`, each program's runs in order as +// `[hash of the folder and the words, { flag: hash of them without it }]`, +// with "" for a flag that stands where it is not counted as added. `named` +// holds a hash of each name whose program is not counted (`folded`). The +// state is kept as lines (`stateOf`): the session's start writes the first, +// a state with no program (`startFlags`), and each shell call that changes +// the state adds one, of what the state takes of it (`taken`). A session +// whose first run of a program may not be among its runs has no state: it +// stores nothing. The sweep of day-old state files (`sweepStaleStateFiles`) +// removes the state like any other, and a session that lost it stores +// nothing either. +const RUNS = "command-flags"; +const runsPath = (sessionId) => sessionStatePath(RUNS, sessionId, { ext: ".jsonl" }); +// The repository's row as the session read it (`heldRow` in +// lib/repo-row.mjs). Its `pairs` are null for a value that is not `claim`'s +// text. +const ROW = "command-flags-row"; + +/** Whether runs of `program` are counted. A name every object has + * (`constructor`) is none: programs are the keys of the state's objects. */ +const counted = (program) => + PROGRAM.test(program) && + !(program in Object.prototype) && + !OTHER_COMMAND.has(program) && + !OUTSIDE.has(program) && + !READ_PROGRAMS.has(program); + +/** Whether `word` is a flag that is counted. */ +const countedFlag = (word) => + FLAG.test(word) && word.length >= MIN_FLAG && word.length <= MAX_FLAG && !REFUSED.some((part) => word.includes(part)); + +/** Whether `word` is a bare word: a subcommand, or the command a wrapper runs. */ +const bare = (word) => !word.startsWith("-") && !word.includes(".") && !word.includes("/"); + +/** `text` without the lines of its here-document bodies, up to the line that + * is the body's word (after its leading tabs for `<<-`); null where a word + * is not a plain one, alone or in one pair of quotes, or a body has no such + * line. Quotes around an opener are not read. */ +function withoutBodies(text) { + const lines = text.split("\n"); + const kept = []; + for (let i = 0; i < lines.length; i++) { + kept.push(lines[i]); + for (const found of lines[i].matchAll(OPENER)) { + const raw = found[2]; + const quoted = raw.length > 2 && raw[0] === raw.at(-1) && (raw[0] === "'" || raw[0] === '"'); + const word = quoted ? raw.slice(1, -1) : raw; + if (!BODY_WORD.test(word)) return null; + do i += 1; + while (i < lines.length && (found[1] ? lines[i].replace(/^\t+/, "") : lines[i]) !== word); + if (i === lines.length) return null; + } + } + return kept.join("\n"); +} + +/** `text` without its comments: from a `#` that starts a word outside quotes + * to the line's end. A call whose quotes this misreads holds a backslash, + * and is not read. */ +function withoutComments(text) { + let out = ""; + let quote = ""; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote) quote = ch === quote ? "" : quote; + else if (ch === "'" || ch === '"') quote = ch; + else if (ch === "#" && (!i || " \t\n;&|".includes(text[i - 1]))) { + while (i < text.length && text[i] !== "\n") i += 1; + if (i === text.length) break; + } + out += text[i]; + } + return out; +} + +/** The simple commands of `text`, a shell call without its here-document + * bodies and comments: the words of each one's first stage and whether it is + * `read`; null for a call that is not read. */ +function simpleCommands(text) { + const open = unquotedText(text); + if (open === null || /[(){}]/.test(open) || OPEN_PIPE.test(open)) return null; + return splitOutsideQuotes(text, LIST_SEPARATORS).map((part) => { + const stage = splitOutsideQuotes(part, ["|"])[0]; + return { words: shellWords(stage), read: !/[&<>]/.test(unquotedText(stage)) }; + }); +} + +/** The run of the words of one simple command from its program on, + * `{ program, words, flags }` with the words after the program and its + * distinct flags; null for none. */ +function runOf(all) { + if (!all.length || all.length > MAX_WORDS) return null; + let [program, ...words] = all; + if (INTERPRETER.test(program)) { + if (words[0] !== "-m" || !words[1]) return null; + [program, words] = [words[1], words.slice(2)]; + } + if (!counted(program)) return null; + const end = words.findIndex((word) => word === "--" || bare(word)); + const flags = (end < 0 ? words : words.slice(0, end)).filter(countedFlag); + return { program, words, flags: [...new Set(flags)] }; +} + +/** The runs of the shell call `command`, in order (the rules are above). A + * run after a `cd` names the folder it changed to as `dir`, as the call + * wrote it. */ +export function runs(command) { + const text = withoutBodies(String(command || "").replace(/\\\n/g, "")); + const commands = text === null ? null : simpleCommands(withoutComments(text.replace(NO_FILE_REDIRECT, " "))); + const found = []; + let dir = ""; + for (const { words, read } of commands || []) { + const all = words.slice( + Math.max( + 0, + words.findIndex((word) => !ASSIGNMENT.test(word)), + ), + ); + if (KEYWORDS.has(all[0])) return []; + if (["cd", "pushd", "popd"].includes(all[0])) { + // The folder of what follows is known only after a `cd` to one plain path. + if (all[0] !== "cd" || !read || all.length !== 2 || !PLAIN_PATH.test(all[1])) break; + // The call's paths are a POSIX shell's, whatever the host. + dir = path.posix.isAbsolute(all[1]) ? all[1] : path.posix.join(dir, all[1]); + continue; + } + const run = read ? runOf(all) : null; + if (run) found.push(dir ? { ...run, dir } : run); + } + return found; +} + +/** The names the text of the shell call `command` holds, each with how often: + * a word of letters, digits and `_+-`, alone or as the last part of a path, + * that could be a counted program. The text is cut at every other + * character, so a name in quotes, in a substitution, after a wrapper or in + * a here-document's body is one too. So is the module an interpreter is + * given in the word of its `-m` (`MODULE_OPTION`). */ +export function names(command) { + const found = new Map(); + for (const word of String(command || "").split(/[^\w.+/-]+/)) { + const name = word.slice(word.lastIndexOf("/") + 1).replace(MODULE_OPTION, ""); + if (counted(name)) found.set(name, (found.get(name) || 0) + 1); + } + return found; +} + +/** A short hash of `words`, joined by a character none of them holds. Two + * runs are compared by the hash of their folder and their words. */ +const digest = (words) => crypto.createHash("sha1").update(words.join("\0")).digest("hex").slice(0, 12); + +/** What a row holds in place of the word of `flag` of `program` until it + * hands the pair. */ +const hidden = (program, flag) => `flag:${digest([program, flag])}`; +const HIDDEN = /^flag:[0-9a-f]{12}$/; + +/** The line a shell call adds to the state, `{ runs, names }`: `found` are + * its runs to note (`runs`) and `nameCounts` the names its text holds + * (`names`). A run is `[program, hash, { flag: hash }]` and carries each + * counted flag it holds: one that stands where it is not counted as added + * has no hash. A run's hashes are of its folder (`at`, the two parts + * `place` gives) and its words: the same words in another folder are + * another command. `names` holds a hash of each name the call holds more + * often than `found` runs it. */ +export function entry(found, nameCounts) { + const ran = (name) => found.filter((run) => run.program === name).length; + return { + runs: found.map(({ program, words, flags, at = ["", ""] }) => { + const less = Object.fromEntries([ + ...words.filter(countedFlag).map((flag) => [flag, ""]), + ...flags.map((flag) => [flag, digest([...at, ...words.filter((word) => word !== flag)])]), + ]); + const whole = digest([...at, ...words]); + return Object.keys(less).length ? [program, whole, less] : [program, whole]; + }), + names: [...nameCounts].filter(([name, times]) => times > ran(name)).map(([name]) => digest([name])), + }; +} + +/** `state` after the line of a shell call (`entry`), or `state` itself for + * no change. A program with no run yet that the line names has no first run + * the session knows: its name is kept, and no run of it is noted from then + * on. A program's first `MAX_RUNS` runs and the first `MAX_PROGRAMS` + * programs are kept, and no program starts once `MAX_NAMES` names are. */ +export function folded(state, line) { + const programs = { ...state.programs }; + const named = new Set(state.named); + const before = named.size; + const started = (name) => Object.keys(programs).some((program) => digest([program]) === name); + for (const name of line.names) { + if (!named.has(name) && named.size < MAX_NAMES && !started(name)) named.add(name); + } + let added = false; + for (const [program, ...run] of line.runs) { + const history = programs[program] || []; + const closed = + named.has(digest([program])) || named.size >= MAX_NAMES || Object.keys(programs).length >= MAX_PROGRAMS; + if (history.length >= MAX_RUNS || (!history.length && closed)) continue; + programs[program] = [...history, run]; + added = true; + } + return added || named.size > before ? { ...state, programs, named: [...named] } : state; +} + +/** The state the text of a session's state file holds: its first line, the + * start's, with every later line folded in (`folded`). {} for a text whose + * first line is not the start's, as one a call added to after the state was + * removed, or with a line that does not parse. A last line with no line end + * is being written, and is not read. */ +export function stateOf(text) { + try { + const [first, ...lines] = text + .split("\n") + .slice(0, -1) + .map((line) => JSON.parse(line)); + return first?.programs ? lines.reduce((state, line) => folded(state, line), first) : {}; + } catch { + return {}; + } +} + +/** The line that takes `state` to `next`, the state after a call's line + * (`folded`): the runs and the names of that line that the state took. */ +const taken = (state, next) => ({ + runs: Object.entries(next.programs).flatMap(([program, history]) => + history.slice(state.programs[program]?.length || 0).map((run) => [program, ...run]), + ), + names: next.named.slice(state.named?.length || 0), +}); + +/** The session's state (`stateOf`), {} for none. */ +function readRuns(sessionId) { + try { + return stateOf(readPrivateFile(runsPath(sessionId))); + } catch { + return {}; + } +} + +/** Whether the folder at `rel` under the checkout at `root` is the + * checkout's own: it is in the checkout (`rel` is no null), and no folder + * from below the root down to it holds a `.git`, as the root of a submodule, + * a worktree or another clone does. */ +const own = (root, rel) => + rel !== null && + rel.split("/").every((_, i, parts) => !rel || !fs.existsSync(path.join(root, ...parts.slice(0, i + 1), ".git"))); + +/** + * Where a run of a shell call ran, as its hashes hold it (a folder under the + * root, and a relative `cd` from it or ""), or null for a folder that is not + * the own one (`own`) of the checkout at `root`: a run there is another + * repository's. `cwd` is the payload's folder and `dir` the path the call's + * `cd` changed to, "" for none. + * + * The payload's folder is the session's before the call or after it. With + * no `cd` the two are one, and after a `cd` to an absolute path the run's + * folder is that path: either is named by its path under the root. After a + * `cd` to a relative path the run's folder is that path from the session's + * folder before the call, which the payload may not hold. It is then named + * by the payload's folder and the path as the call wrote it: the same as + * another run's only after the same `cd` from the same folder. Both the + * payload's folder and the path from it are then the checkout's own. + */ +function place(root, cwd, dir) { + const here = pathUnder(root, cwd); + if (!dir) return own(root, here) ? [here, ""] : null; + const there = pathUnder(root, path.resolve(cwd, dir)); + if (!own(root, there)) return null; + if (path.isAbsolute(dir)) return [there, ""]; + return own(root, here) ? [here, dir] : null; +} + +/** Whether `state` is the one a session's start wrote, with nothing noted since. */ +const untouched = (state) => Boolean(state.programs) && !Object.keys(state.programs).length && !state.named?.length; + +/** The session is counted no more: it stores nothing. */ +const close = (sessionId) => removeFile(runsPath(sessionId)); + +/** + * Note the runs and the names (`entry`) of the shell command `command`, run + * in `cwd`, in the state of a session that is counted: the one its start + * wrote (`startFlags`) is there. The launcher calls this where the session's + * commands are counted (`countsRuns` in lib/test-report.mjs). A run is noted + * where its folder is the own one of the checkout of the row the session + * read (`place`): a run in another folder is another repository's, and only + * names its program. A session that runs a shell command before a prompt + * read the row is counted no more (`close`): its first run of a program is + * unknown. So is one that runs a command over `MAX_CALL`, whose names are + * not read. A command adds one line after the ones the state holds and + * rewrites none, so two commands whose hooks run at the same time are both + * noted. The line holds what the state its hook read takes of the command + * (`taken`), and a command it takes nothing of adds none. A later state + * takes no run and no name that an earlier one refused, so what a line + * leaves out would change nothing after the line of a command whose hook + * ran at the same time. + */ +export function noteRuns(sessionId, command, cwd) { + try { + const state = readRuns(sessionId); + if (!state.programs) return; + const held = readSessionState(ROW, sessionId); + const text = String(command || ""); + if (!held.read || text.length > MAX_CALL) { + close(sessionId); + return; + } + const inside = runs(text).flatMap((run) => { + const at = place(held.root, cwd || process.cwd(), run.dir || ""); + return at === null ? [] : [{ ...run, at }]; + }); + const next = folded(state, entry(inside, names(text))); + if (next === state) return; + writePrivateFile(runsPath(sessionId), `${JSON.stringify(taken(state, next))}\n`, { append: true }); + } catch { + /* nothing noted */ + } +} + +/** + * At a session's start, from the payload's `source`: remove what an earlier + * part of the session left, and write the state of a session that is counted + * (`RUNS`). A session is counted where it is new (`startup`, `clear`) and its + * shell commands are (`countsRuns`). One that is resumed knows what its + * earlier part learned, so its first run from here on is no first run. One + * that starts with no credential runs shell commands that are not noted, so + * its first run after a credential comes, from this very start's sign-up or + * later, is no first run either. A start after a compaction is the same + * session's, and changes nothing. A session whose start did not run, or + * named no source, has no state and stores nothing. + */ +export function startFlags(sessionId, source) { + if (source === "compact") return; + endFlags(sessionId); + if (!["startup", "clear"].includes(source) || !countsRuns()) return; + try { + writePrivateFile(runsPath(sessionId), `${JSON.stringify({ programs: {} })}\n`); + } catch { + /* a session with no state stores nothing */ + } +} + +/** + * What the session's runs say of each program it ran, `{ program: { flag: + * "first" | "converged" } }`. A run carries a flag when it holds the flag's + * word, wherever it stands. A flag is `first` when the session's first run + * of the program carries it. It has `converged` when it is not, a run that + * carries it where it is counted as added has an earlier run without it + * whose words are the same but for the flag's word, and from the first run + * that carries it more than half of the session's runs of the program carry + * it. A flag followed by its value converges only where an earlier run held + * that value as a word of its own: the run without the flag's word still + * holds the value. + */ +export function sessionCounts(state) { + const counts = {}; + for (const [program, history] of Object.entries(state.programs || {})) { + const seen = {}; + for (const flag of new Set(history.flatMap((run) => Object.keys(run[1] || {})))) { + const has = history.map((run) => Object.hasOwn(run[1] || {}, flag)); + const from = has.indexOf(true); + const kept = has.slice(from).filter(Boolean).length * 2 > has.length - from; + const added = history.some( + (run, j) => has[j] && history.slice(0, j).some((earlier, i) => !has[i] && earlier[0] === run[1][flag]), + ); + if (from === 0) seen[flag] = "first"; + else if (kept && added) seen[flag] = "converged"; + } + counts[program] = seen; + } + return counts; +} + +/** Whether the counts of `pair` hand it: `MIN_CONVERGED` sessions or more + * converged, and more of them than had the flag on their first run. */ +const enough = (pair) => pair.converged >= MIN_CONVERGED && pair.converged > pair.first; + +/** The pairs of a row a prompt is handed: the row names the flag's word and + * the counts are `enough`. At most `MAX_LINES`, the ones with the most + * converged sessions, in the row's order among equals. */ +export function handed(pairs) { + return pairs + .filter((pair) => countedFlag(pair.flag) && enough(pair)) + .sort((a, b) => b.converged - a.converged) + .slice(0, MAX_LINES); +} + +/** + * The row's pairs after a session, or null for no change. `counts` is + * `sessionCounts` of the session and `pairs` the row as the session read it. + * + * A pair the session was handed (`handed`) keeps its counts: the session + * starts with the flag because it was told to, which would read as a flag on + * the first run and end the line. Any other pair whose program the session + * ran counts one more session that ran it, and one more that converged or had + * the flag on its first run; a pair the row names by a hash is the session's + * flag with that hash. A pair counts no session once `MAX_RAN` ran its + * program: one the row does not hand by then stays as it is, so no later + * session writes the row for it, and while the row holds it it does not + * enter again. A pair the row does not hold enters it with the session that + * converged on it, so its counts start there. A row of `MAX_PAIRS` gives + * such a pair the place of a pair that one session converged on, or that + * counts no more and is not handed: the one whose program the most sessions + * ran. A pair the row names by its hash at `MAX_RAN` is such a one, whatever + * its counts: no session matches its flag to the hash again. A pair that + * lost its place enters again like any other. The row takes no new pair + * where it has no such pair. + */ +export function revised(counts, pairs) { + const told = handed(pairs); + const add = (n, one) => n + (one ? 1 : 0); + let changed = false; + const next = pairs.map((pair) => { + const seen = counts[pair.program]; + if (!seen || told.includes(pair) || pair.ran >= MAX_RAN) return pair; + changed = true; + const flag = Object.keys(seen).find((word) => hidden(pair.program, word) === pair.flag) || pair.flag; + return { + ...pair, + flag, + converged: add(pair.converged, seen[flag] === "converged"), + first: add(pair.first, seen[flag] === "first"), + ran: pair.ran + 1, + }; + }); + const inRow = (program, flag) => + pairs.some((pair) => pair.program === program && [flag, hidden(program, flag)].includes(pair.flag)); + const spent = (pair) => pair.converged === 1 || (pair.ran >= MAX_RAN && !handed(next).includes(pair)); + // The place a full row gives a new pair, -1 for none. + const freeSlot = () => + next.reduce( + (top, pair, at) => + spent(pair) && inRow(pair.program, pair.flag) && (top < 0 || pair.ran > next[top].ran) ? at : top, + -1, + ); + for (const [program, seen] of Object.entries(counts)) { + for (const flag of Object.keys(seen)) { + if (seen[flag] !== "converged" || inRow(program, flag)) continue; + const at = next.length < MAX_PAIRS ? next.length : freeSlot(); + if (at < 0) continue; + next[at] = { program, flag, converged: 1, first: 0, ran: 1 }; + changed = true; + } + } + return changed ? next : null; +} + +/** The row's value for the repository whose id is `repo`: one plain-text + * claim of its pairs' counts. 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. It names a flag by its word only + * for the pairs it hands (`handed`) and by a hash for the others, so recall + * of the row tells no session a flag the line would not. */ +export function claim(repo, pairs) { + const told = handed(pairs); + const each = pairs.map((pair) => { + const { program, converged, first, ran } = pair; + const flag = told.includes(pair) || HIDDEN.test(pair.flag) ? pair.flag : hidden(program, pair.flag); + return `${program} ${flag} in ${converged} of ${ran} sessions that ran ${program}, on the first run in ${first}`; + }); + return `In the repository tagged repo:${repo}, flags that sessions added to a command they had already run: ${each.join("; ")}.`; +} + +const CLAIM = + /^In the repository tagged repo:(\w+), flags that sessions added to a command they had already run: (.+)\.$/; +const PAIR = /^(\S+) (\S+) in (\d{1,2}) of (\d{1,2}) sessions that ran (\S+), on the first run in (\d{1,2})$/; + +/** The pairs a row's value claims of the repository whose id is `repo`, + * `{ program, flag, converged, first, ran }` each, with a hash as the `flag` + * of a pair the row does not hand; null for a value that is not `claim`'s + * text of program names and flags, with counts sessions can give: one that + * converged at least, no more that converged or had the flag on their first + * run than ran the program, and `MAX_RAN` of those at most. A pair whose + * program or flag is not counted is left out: a row written before a word + * joined a list still reads, and its next write is without the pair. */ +export function parseClaim(repo, value) { + const found = typeof value === "string" && value.length <= MAX_VALUE ? CLAIM.exec(value) : null; + if (!found || found[1] !== repo) return null; + const all = found[2].split("; ").map((text) => { + const part = PAIR.exec(text); + if (!part || part[1] !== part[5] || !PROGRAM.test(part[1])) return null; + if (!FLAG.test(part[2]) && !HIDDEN.test(part[2])) return null; + const [converged, ran, first] = [part[3], part[4], part[6]].map(Number); + return converged >= 1 && converged + first <= ran && ran <= MAX_RAN + ? { program: part[1], flag: part[2], converged, first, ran } + : null; + }); + if (all.length > MAX_PAIRS || all.includes(null)) return null; + const pairs = all.filter((pair) => counted(pair.program) && (HIDDEN.test(pair.flag) || countedFlag(pair.flag))); + const told = handed(pairs); + const named = (pair) => (HIDDEN.test(pair.flag) ? pair.flag : hidden(pair.program, pair.flag)); + const distinct = new Set(pairs.map((pair) => `${pair.program} ${named(pair)}`)); + return distinct.size === pairs.length && pairs.every((pair) => HIDDEN.test(pair.flag) || told.includes(pair)) + ? pairs + : null; +} + +/** The line a prompt carries for one pair. It is made of the pair's parts + * and never of the stored text, so a row written by another hand adds no + * sentence. A pair's counts start at the first session that converged on + * it, and the line says so. */ +export function renderFlag({ program, flag, converged, first, ran }) { + const started = + first === 0 + ? `none had the flag on its first ${program} run` + : `${first} had the flag on ${first === 1 ? "its" : "their"} first ${program} run`; + return ( + "Command conventions in this repository (counted in earlier sessions, from the first that added the flag): " + + `of the ${ran} sessions that ran ${program}, ` + + `${converged} first ran it without ${flag} and then added that flag to a ${program} command they had already run; ` + + `${started}.` + ); +} + +/** The key of the row of the repository of `scope` (`resolveScope`), "" for a + * checkout with no remote: `//`. */ +export const flagsKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/command-flags/shell` : ""); + +/** + * The lines for a prompt of a session that is told (`conventionsOn`), in the + * checkout at `root`, or "": one for each pair the repository's row hands + * (`handed`). They go where the test cost line goes, and the row is read and + * kept in the session's state as the test cost row is (`heldRow` in + * lib/repo-row.mjs). A read keeps the session counted only where it has + * noted nothing yet (`untouched`). A session that reads a row after that is + * counted no more: the row is a second checkout's, whose runs the session + * did not note, or the copy of its own was removed. + */ +export async function flagsLine(sessionId, root, scopeOf, options) { + try { + if (!conventionsOn()) return ""; + const parse = (repo, value) => ({ pairs: parseClaim(repo, value) }); + const held = await heldRow(ROW, sessionId, root, scopeOf, flagsKey, parse, options); + if (!held) return ""; + if (held.fresh && !untouched(readRuns(sessionId))) close(sessionId); + return handed(held.row?.pairs || []) + .map(renderFlag) + .join("\n"); + } catch { + return ""; + } +} + +/** + * The flusher's post that stores the row with the session's counts + * (`rowPost` in lib/repo-row.mjs), or null: one `memory.set` where `revised` + * changes the row the session read, a miss included. A row another session + * wrote since refuses it, and the session's counts are dropped. A row whose + * value is not `claim`'s text is left as it is, and one with a pair that is + * not counted is written without that pair. The value is sent only where + * the secret redaction leaves it as it is. + */ +export function flagsPost(sessionId) { + try { + const state = readRuns(sessionId); + const held = readSessionState(ROW, sessionId); + if (!state.programs || !held.read || (held.row && !held.row.pairs)) return null; + const next = revised(sessionCounts(state), held.row?.pairs || []); + const value = next ? claim(held.repo, next) : ""; + return value && redactSecrets(value) === value ? rowPost(held, value, "command-flags") : null; + } catch { + return null; + } +} + +/** Remove the session's state. It goes with the session, whatever the + * session stores. The launcher calls it for a session that ends with no + * credential, whose hand-off does not run. */ +export function endFlags(sessionId) { + for (const file of [runsPath(sessionId), sessionStatePath(ROW, sessionId)]) removeFile(file); +} diff --git a/integrations/codex-plugin/lib/repo-row.mjs b/integrations/codex-plugin/lib/repo-row.mjs new file mode 100644 index 00000000000..1f296244d83 --- /dev/null +++ b/integrations/codex-plugin/lib/repo-row.mjs @@ -0,0 +1,65 @@ +// The one memory row a repository has of a kind, as a session reads it at a +// bug report and revises it at its end: what a test run costs +// (lib/test-cost.mjs) and the command conventions (lib/command-flags.mjs). +// +// The session keeps the row it read, a miss too, in its private state. A +// later prompt in the checkout sends no read, and the session's end knows +// the value it replaces. + +import { hookClient, postBounded } from "./loom-client.mjs"; +import { readSessionState, writeSessionState } from "./tmp-state.mjs"; + +/** + * The repository's row as the session keeps it in its state `kind`, for the + * checkout at `root`: `{ read, root, repo, asked, row }`, with the + * repository's id and the identity the read named, which the session's end + * writes to. `row` is null for a miss, else what `parse(repo, value)` reads + * of the value, with the row's `sha` and the `agent` that wrote it. null + * where the row is not read. + * + * 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. `fresh` is set where this call read the row. The + * read is one `memory.get` by the key `keyOf(scope)` ("" for a checkout that + * has no row), bounded by `options.timeoutMs`. It names the scope's agent and + * finds another agent's row too. `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 keep nothing, and a later prompt asks again. + */ +export async function heldRow(kind, sessionId, root, scopeOf, keyOf, parse, options) { + const kept = readSessionState(kind, sessionId); + if (kept.read && kept.root === root) return kept; + const scope = scopeOf(); + const memory_key = keyOf(scope); + if (!memory_key) return null; + const asked = { org: scope.org, namespace: scope.namespace, agent: scope.agent, memory_key }; + const res = await postBounded("memory.get", { ...asked, fields: ["value", "content_sha256", "agent"] }, options); + if (!res) return null; + const repo = scope.repo.id; + const found = { sha: String(res.content_sha256 || ""), agent: String(res.agent || "") }; + const held = { read: true, root, repo, asked, row: res.found ? { ...parse(repo, res.value), ...found } : null }; + writeSessionState(kind, sessionId, held); + return { ...held, fresh: true }; +} + +/** + * The flusher's post that stores `value` as the row `held` is a copy of + * (`heldRow`): one `memory.set` under the key and the repository of that + * read. It is a revision of the row as read (`if_match_sha256`, under the + * agent that wrote the row), else a first row (`absent`): a row another + * session wrote since refuses it. The value names no file to the server + * (`files: []`), its class says a tool measured it, and `tag` names its kind. + */ +export function rowPost(held, value, tag) { + const body = { + ...held.asked, + agent: held.row?.agent || held.asked.agent, + value, + tags: [`repo:${held.repo}`, `source:${hookClient()}`, tag], + files: [], + source_class: "external", + if_match_sha256: held.row?.sha || "absent", + }; + return { op: "memory.set", body }; +} diff --git a/integrations/codex-plugin/lib/shell-command.mjs b/integrations/codex-plugin/lib/shell-command.mjs index 764b456ead1..588cb5c1aa4 100644 --- a/integrations/codex-plugin/lib/shell-command.mjs +++ b/integrations/codex-plugin/lib/shell-command.mjs @@ -380,7 +380,7 @@ export function parseBashBulk(command) { } /** A command's list separators: `;`, `&&`, `||` and newlines. */ -const LIST_SEPARATORS = [";", "&&", "||", "\n"]; +export const LIST_SEPARATORS = [";", "&&", "||", "\n"]; /** True when a command has more than one part: a `;` / `&&` / `||` / newline * list or a pipeline, outside quotes. The shunt never refuses one: a refusal @@ -484,7 +484,7 @@ export function parseBashBulkSegments(command) { // writes one or runs a program are among them only without it (READS_WITH), // and `git` only for the subcommands that read. `awk` is not: its script can // redirect to a file and run a command. -const READ_PROGRAMS = new Set([ +export const READ_PROGRAMS = new Set([ "basename", "cat", "cd", @@ -556,13 +556,13 @@ const READS_WITH = { }; // What a redirect that writes no file looks like: to the null device, or one // stream into another. -const NO_FILE_REDIRECT = /\d*>>?\s*\/dev\/null(?![\w./-])|\d*>&\d+/g; +export const NO_FILE_REDIRECT = /\d*>>?\s*\/dev\/null(?![\w./-])|\d*>&\d+/g; /** `command` without its quoted text, or null where it holds what the shell * runs or what the quote rules here do not read: a substitution or an escape * outside single quotes (an escaped quote inside double ones), and a quote * left open. */ -function unquotedText(command) { +export function unquotedText(command) { let out = ""; let quote = ""; for (let i = 0; i < command.length; i++) { @@ -580,6 +580,13 @@ function unquotedText(command) { return quote ? null : out; } +/** The words of `part`, one simple command or one stage of a pipeline: a word + * is what the shell joins of its quoted and bare pieces. */ +export const shellWords = (part) => + splitOutsideQuotes(part, [" ", "\t"]) + .filter(Boolean) + .map((word) => word.replace(/["']/g, "")); + /** * True when `command` reads as one that wrote no file: every part of it, * across `;`, `&&`, `||`, `|` and newlines, starts one of READ_PROGRAMS with @@ -603,12 +610,8 @@ export function readsOnly(command) { if (bare === null || /[>(){}]|&(?!&)/.test(bare.replace(/&&/g, " "))) return false; return splitOutsideQuotes(c, [...LIST_SEPARATORS, "|"]).every((part) => { if (/^\s*["']/.test(part)) return false; - // A word is what the shell joins of its quoted and bare pieces. A leading - // `VAR=value` sets the environment of the program after it. - const words = splitOutsideQuotes(part, [" ", "\t"]) - .filter(Boolean) - .map((w) => w.replace(/["']/g, "")) - .filter((w, i, all) => !all.slice(0, i + 1).every((x) => /^\w+=/.test(x))); + // A leading `VAR=value` sets the environment of the program after it. + const words = shellWords(part).filter((w, i, all) => !all.slice(0, i + 1).every((x) => /^\w+=/.test(x))); if (!words.length) return !part.trim(); const [program, ...rest] = words; return READ_PROGRAMS.has(program) && (READS_WITH[program]?.(rest) ?? true); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 4fa734e37fb..4126e9f9439 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -37,7 +37,8 @@ // ignores (`measured`). import path from "node:path"; -import { git, gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; +import { git, gitToplevel, isDirectory, pathUnder, redactSecrets } from "./loom-client.mjs"; +import { heldRow, rowPost } from "./repo-row.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"; @@ -67,7 +68,7 @@ const MAX_SAMPLES = 15; 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 +// the identity the read named (`heldRow`), 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 @@ -309,15 +310,6 @@ export function renderCost({ path: file, tests, seconds, filtered }) { * checkout with no remote: `//`, the runner as the id. */ export const costKey = (scope) => (scope?.repo?.id ? `repo:${scope.repo.id}/test-cost/pytest` : ""); -/** The 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, @@ -337,20 +329,8 @@ const identity = (scope) => ({ 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 held = await heldRow(ROW, sessionId, root, scopeOf, costKey, parseClaim, options); + const row = held?.row; const printed = row?.path && row.seconds >= MIN_WHOLE_SECONDS && isFile(path.join(root, row.path)); return printed ? renderCost(row) : ""; } catch { @@ -456,16 +436,7 @@ export function costPost(sessionId, cwd) { 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 }; + return rowPost(held, claim(held.repo, next), "pytest-cost"); } catch { return null; } diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index 42840cc6e21..63f4c41e39a 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -14,7 +14,15 @@ import fs from "node:fs"; import path from "node:path"; -import { envSwitch, gitToplevel, pathUnder } from "./loom-client.mjs"; +import { + agentMode, + envSwitch, + gitToplevel, + hookClient, + pathUnder, + planeEnabled, + resolveToken, +} from "./loom-client.mjs"; import { configuresPytest, pytestAddopts } from "./test-gate.mjs"; import { readSessionState, removeFile, sessionStatePath, writePrivateFile, writeSessionState } from "./tmp-state.mjs"; @@ -40,6 +48,23 @@ export function testReportOn(env = process.env) { return envSwitch("LOOM_TEST_REPORT", envSwitch("CLAUDE_PLUGIN_OPTION_TEST_REPORT", true, env), env); } +/** Whether the session is told its repository's command conventions + * (lib/command-flags.mjs): the test report's switch is on, the client is + * Claude Code, whose launcher reads the shell commands, and the host is not + * Windows, where a `cd` names a folder by a path that library does not + * resolve. */ +export const conventionsOn = () => testReportOn() && hookClient() === "claude-code" && process.platform !== "win32"; + +/** Whether a session's shell commands are counted for them: it is told them, + * its end stores the row (the memory plane runs and session memory is not + * switched off) and it has a credential. The session's start and the + * launcher both ask this. */ +export const countsRuns = () => + conventionsOn() && + planeEnabled("memory") && + envSwitch("LOOM_SESSION_MEMORY", true) && + Boolean(agentMode() || resolveToken()); + /** The result file pytest writes for the session. */ export function reportPath(sessionId, opts = {}) { return sessionStatePath("pytest-report", sessionId, { ...opts, ext: ".xml" }); diff --git a/server/identity/api/models_namespace_catalog.py b/server/identity/api/models_namespace_catalog.py index 0eb5b0e1c1e..3878c61930e 100644 --- a/server/identity/api/models_namespace_catalog.py +++ b/server/identity/api/models_namespace_catalog.py @@ -348,8 +348,9 @@ class NamespaceAuditSummary(BaseModel): # row still being retried, or whose model call was held or unbilled, is index_backlog). unembedded_rows: int = 0 # 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. + # cost row (key `repo:/test-cost/pytest`) and command conventions row (key + # `repo:/command-flags/shell`), 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 0aa640a9c69..60e36369d56 100644 --- a/server/identity/app/namespace_audit.py +++ b/server/identity/app/namespace_audit.py @@ -128,8 +128,9 @@ # 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}}" +# An exact-key read the object-store gauge counts: not a plugin hook's read of a test cost +# row or a command conventions row. +_GET = f"operation IN {_LEDGER_GETS} AND NOT match({_READ_KEY}, {{hook_keys:String}})" # The reports on a namespace: their own ledger rows say nothing about whether the window's # calls were recorded. _REPORT_OPS = ( @@ -314,13 +315,15 @@ "usage_heuristic", # 2: reads of structured-by-design rows are left out of the gauge. # 3: so is a coding-agent plugin's read of a repository's test cost row. - 3, + # 4: and its read of the repository's command conventions row. + 4, windowed=True, exceptions=( "Reads of rows whose type is structured by design are not counted " "(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." + "(`repo:/test-cost/pytest`) and command conventions row " + "(`repo:/command-flags/shell`), which a coding-agent plugin's prompt hook reads " + "by their keys 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 " @@ -330,11 +333,12 @@ "intentional_exact_key_reads": RuleContract( "usage_heuristic", # 2: a read of a test cost row, which exact_key_store leaves out, is not counted here. - 2, + # 3: nor is a read of a command conventions row. + 3, windowed=True, exceptions=( - "A read of a repository's test cost row is not counted, whatever the row's type " - "(exact_key_store)." + "A read of a repository's test cost row or command conventions row is not " + "counted, whatever the row's type (exact_key_store)." ), uncertainty=( "Only the structured-by-design types are recognised; an agent's other workflows " diff --git a/server/insights/api/models_mentor.py b/server/insights/api/models_mentor.py index c398ac05030..2c8b105a23d 100644 --- a/server/insights/api/models_mentor.py +++ b/server/insights/api/models_mentor.py @@ -103,9 +103,9 @@ 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, 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. + # Calls per operation by this agent in the window, leaving out a coding-agent plugin's + # reads of a repository's test cost and command conventions rows + # (`repo:/test-cost/pytest`, `repo:/command-flags/shell`). usage: dict[str, int] = Field(default_factory=dict) # Every plane the mentor knows, with this agent's calls to it (the sum of its ops' `usage` # counts) and whether it is available. diff --git a/server/insights/store/mentor.py b/server/insights/store/mentor.py index 1ed30108220..7598ad07564 100644 --- a/server/insights/store/mentor.py +++ b/server/insights/store/mentor.py @@ -40,14 +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. +# A coding-agent plugin's prompt hook reads a repository's test cost row and its command +# conventions row by their keys under the session's agent, whatever that agent does +# (`HOOK_READ_KEYS`): counted among the agent's exact-key reads they would grade the agent +# by the plugin it runs. A 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})" + "AND match(if(memory_key != '', memory_key, args['memory_key']), {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. @@ -125,7 +126,7 @@ 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.""" + """The agent's calls by operation, a plugin hook's reads of its two rows left out.""" rows = await self._rows( f"SELECT operation, count() AS n {_LEDGER_AGENT} AND {_NOT_HOOK_READ} " "GROUP BY operation ORDER BY n DESC LIMIT 400" @@ -226,8 +227,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`), a plugin hook's read of a test - cost row left out.""" + `out_found`, `out_found_n` / `out_missing_n`), a plugin hook's read of one of + its two rows left out.""" m = await self._one( f""" SELECT sumIf(if(args['out_found'] != '', 1, diff --git a/server/memory/domain/namespace_shapes.py b/server/memory/domain/namespace_shapes.py index 822dc80c2e7..3324d26366b 100644 --- a/server/memory/domain/namespace_shapes.py +++ b/server/memory/domain/namespace_shapes.py @@ -5,7 +5,7 @@ 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. The -key both know a plugin hook's read by (`HOOK_READ_KEYS`) is here for the same reason. +keys both know a plugin hook's reads by (`HOOK_READ_KEYS`) are here for the same reason. """ from __future__ import annotations @@ -35,9 +35,10 @@ # 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" +# A coding-agent plugin's prompt hook reads a repository's test cost row and its command +# conventions row by their keys in a session, whatever the session's agent does (`costKey` +# in integrations/claude-code-plugin/lib/test-cost.mjs, `flagsKey` in lib/command-flags.mjs): +# counting those reads would grade a namespace, or an agent, by the plugin its sessions run. +# The hook's request names no consumer, so a read is known by its key: a regular expression +# that `match` holds the whole key to. +HOOK_READ_KEYS = r"^repo:[^/]+/(?:test-cost/pytest|command-flags/shell)$" diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 42183a48e6b..3647bc43588 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -65,6 +65,10 @@ "category": "delivery", "reason": "Forwards the operation and body supplied by separately scanned hook call sites." }, + "integrations/claude-code-plugin/lib/repo-row.mjs:memory.get:733c215076d9da7c126b:1": { + "category": "reference", + "reason": "Reads a repository's one row of a kind, the test cost row or the command conventions row, by its key, which the caller builds from the repository's id, with the scoped identity and a fixed field list; no prompt, transcript, command, path or file content is sent." + }, "integrations/claude-code-plugin/lib/repo-scope.mjs:code.index_status:2aa87b1d483d40a0ec91:1": { "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." @@ -77,10 +81,6 @@ "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." @@ -145,6 +145,10 @@ "category": "delivery", "reason": "Forwards the operation and body supplied by separately scanned hook call sites." }, + "integrations/codex-plugin/lib/repo-row.mjs:memory.get:733c215076d9da7c126b:1": { + "category": "reference", + "reason": "Reads a repository's one row of a kind, the test cost row or the command conventions row, by its key, which the caller builds from the repository's id, with the scoped identity and a fixed field list; no prompt, transcript, command, path or file content is sent." + }, "integrations/codex-plugin/lib/repo-scope.mjs:code.index_status:2aa87b1d483d40a0ec91:1": { "category": "scope", "reason": "Sends repository routing, namespace identity or fixed listing limits; no prompt, transcript or changed-file payload." @@ -157,10 +161,6 @@ "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." @@ -402,35 +402,39 @@ "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": "680a09763971ff6d2dfc1f682bf0a0f30839d52af7016e85aca7a7ea07073e40", - "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "4394ac465b4efc5898f03143b38112aaa8015489ac7dc03fa458966bb46b9f16", + "integrations/claude-code-plugin/hooks/loom-prompt-pack.mjs": "caa0ba2ac3b3782da2016e3d7d71d45454d10cee9e29fde4f850285b28a85b01", + "integrations/claude-code-plugin/hooks/loom-session-start.mjs": "553183ac12221dc80e71f0a41e15528c025fde7851813bed0aaa0dc488a53e70", "integrations/claude-code-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", + "integrations/claude-code-plugin/lib/command-flags.mjs": "4cf51f6482c1d5038e5c2ae6fcacc5cde8db4450b512878f115006afc7b8e8f3", "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": "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-row.mjs": "c1dfe40587c2306362060e3c2f308b0a016bad01ae95fd801c79c88fae079fed", "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": "e24a50e1bab07b29f3e107b2e81bf05531af85c7ae700810825eeba5344acf3e", + "integrations/claude-code-plugin/lib/test-cost.mjs": "dd9272022fe667599f2e46c78e3b8e478561258be5b87702157b86e243c08f21", "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": "680a09763971ff6d2dfc1f682bf0a0f30839d52af7016e85aca7a7ea07073e40", - "integrations/codex-plugin/hooks/loom-session-start.mjs": "4394ac465b4efc5898f03143b38112aaa8015489ac7dc03fa458966bb46b9f16", + "integrations/codex-plugin/hooks/loom-prompt-pack.mjs": "caa0ba2ac3b3782da2016e3d7d71d45454d10cee9e29fde4f850285b28a85b01", + "integrations/codex-plugin/hooks/loom-session-start.mjs": "553183ac12221dc80e71f0a41e15528c025fde7851813bed0aaa0dc488a53e70", "integrations/codex-plugin/lib/collections-line.mjs": "4415df00d8af1cbb64f5bc25fa1ba1176433b122c1ae35f809b3981f4439c8c9", + "integrations/codex-plugin/lib/command-flags.mjs": "4cf51f6482c1d5038e5c2ae6fcacc5cde8db4450b512878f115006afc7b8e8f3", "integrations/codex-plugin/lib/first-session.mjs": "ea5c41ac14f173aa81c8fefc894d72a6661be66e242d0b614f502a0de98b8646", "integrations/codex-plugin/lib/flush-job.mjs": "e6c4ae5e42a54cba0e171b727688be621a81245023bf85a8ac093d334bc9bfd5", "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-row.mjs": "c1dfe40587c2306362060e3c2f308b0a016bad01ae95fd801c79c88fae079fed", "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": "e24a50e1bab07b29f3e107b2e81bf05531af85c7ae700810825eeba5344acf3e", + "integrations/codex-plugin/lib/test-cost.mjs": "dd9272022fe667599f2e46c78e3b8e478561258be5b87702157b86e243c08f21", "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 2f501030741..7493aed4e1c 100644 --- a/tests/unit/test_mentor.py +++ b/tests/unit/test_mentor.py @@ -35,11 +35,9 @@ 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" -) +# The requests the plugin's hooks send for their two rows (the plugin's tests hold the hooks +# to them). +_HOOK_WIRE = Path(__file__).resolve().parents[2] / "integrations/claude-code-plugin/tests/fixtures" class _CH: @@ -539,12 +537,15 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> Any @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: +def test_a_hooks_reads_of_its_rows_are_not_among_the_agents_exact_key_reads() -> None: call = _ledger_call cost = "repo:315f533aed/test-cost/pytest" + flags = "repo:315f533aed/command-flags/shell" 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)), + # One read of each row 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(25)), + *(call("memory.get", flags, out_found="false") for _ in range(25)), # 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`. @@ -575,11 +576,12 @@ def profile(hook_keys: str | None = None) -> tuple[dict[str, int], dict[str, int @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 +@pytest.mark.parametrize("name", ["test-cost-wire.json", "command-flags-wire.json"]) +def test_a_hooks_write_of_its_row_is_not_a_write_about_tests(name: str) -> None: + """The session-end hook stores each 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"] + sent = json.loads((_HOOK_WIRE / name).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. @@ -591,7 +593,7 @@ def profile(body: dict[str, Any]) -> tuple[int, set[str]]: 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. + # The same write under a tag that holds the word, as the test cost row's key does. assert profile({**sent, "tags": [*sent["tags"], "test-cost"]}) == (1, {"tracker_unused"}) diff --git a/tests/unit/test_namespace_audit.py b/tests/unit/test_namespace_audit.py index fc95a07e20a..b49e811f4a1 100644 --- a/tests/unit/test_namespace_audit.py +++ b/tests/unit/test_namespace_audit.py @@ -1152,7 +1152,7 @@ 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": ( - 3, + 4, ( na.EXACT_KEY_STORE_RATIO, na.EXACT_KEY_STORE_MIN_GETS, @@ -1160,12 +1160,18 @@ async def test_hot_key_completeness_compares_counts_of_one_statement( tuple(sorted(na.STRUCTURED_TYPES)), na.HOOK_READ_KEYS, ), - (20.0, 200, 20, ("procedural",), "repo:%/test-cost/pytest"), + ( + 20.0, + 200, + 20, + ("procedural",), + r"^repo:[^/]+/(?:test-cost/pytest|command-flags/shell)$", + ), ), "intentional_exact_key_reads": ( - 2, + 3, (tuple(sorted(na.STRUCTURED_TYPES)), na.HOOK_READ_KEYS), - (("procedural",), "repo:%/test-cost/pytest"), + (("procedural",), r"^repo:[^/]+/(?:test-cost/pytest|command-flags/shell)$"), ), "hand_rolled_index_rows": ( 1, @@ -1678,8 +1684,9 @@ async def test_a_procedure_read_over_mcp_is_left_out_of_the_object_store_gauge() @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: +async def test_a_hooks_reads_of_its_rows_are_left_out_of_the_object_store_gauge() -> None: cost = "repo:315f533aed/test-cost/pytest" + flags = "repo:315f533aed/command-flags/shell" 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"), @@ -1688,7 +1695,8 @@ async def test_a_hooks_read_of_a_test_cost_row_is_left_out_of_the_object_store_g 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=cost) for _ in range(100)), + *(_ledger_row("memory.get", key=flags) for _ in range(50)), *(_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)), diff --git a/tests/unit/test_plugin_memory_contract.py b/tests/unit/test_plugin_memory_contract.py index 218c15e034b..173cceafb7c 100644 --- a/tests/unit/test_plugin_memory_contract.py +++ b/tests/unit/test_plugin_memory_contract.py @@ -1,24 +1,25 @@ -"""The test cost hooks send requests, and read a reply, that the memory wire models serve.""" +"""The test cost and command conventions hooks send requests, and read a reply, that the +memory wire models serve.""" import json -from fnmatch import fnmatchcase +import re from pathlib import Path +import pytest + 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" -) +_FIXTURES = Path(__file__).resolve().parents[2] / "integrations/claude-code-plugin/tests/fixtures" -def test_test_cost_requests_and_reply_match_the_memory_wire_models(): +@pytest.mark.parametrize("name", ["test-cost-wire.json", "command-flags-wire.json"]) +def test_a_row_hooks_requests_and_reply_match_the_memory_wire_models(name: str) -> None: """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()) + wire = json.loads((_FIXTURES / name).read_text()) get, put = wire["requests"]["memory.get"], wire["requests"]["memory.set"] reply = wire["responses"]["memory.get"] @@ -40,13 +41,15 @@ def test_test_cost_requests_and_reply_match_the_memory_wire_models(): assert source_class_for(default="asserted", requested=stored.source_class) == "external" -def test_the_audit_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 +@pytest.mark.parametrize("name", ["test-cost-wire.json", "command-flags-wire.json"]) +def test_the_audit_and_the_mentor_know_the_keys_the_prompt_hook_reads(name: str) -> None: + """`namespace.audit` and the mentor leave the hook's reads out of their exact-key counts + by the key each 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()) + wire = json.loads((_FIXTURES / name).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("%", "*")) + # The pattern holds the whole key: a key that only contains one of the two is counted. + assert re.search(HOOK_READ_KEYS, key) + assert not re.search(HOOK_READ_KEYS, f"team/{key}") + assert not re.search(HOOK_READ_KEYS, f"{key}/notes")