From e2a60d4a2827d216d750d4ed4b6945e7780d5d45 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 20:46:27 +0530 Subject: [PATCH 01/52] test(plugin): a pytest run after other commands in its shell call, and a data-driven report, are not noted The cost tests gain the cases the test cost note misses: a run of one test file that follows an inline edit, a git or a sed command in the same shell call, and a result file whose first case names a data file and whose class is under the run's test file. They fail here. Two more hold before and after the change that follows: a command that names a test runner, pytest or || before the run stays no file run, and a result file that an earlier run wrote is not the run's of a later command that printed that run's last line. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- .../tests/test-cost.test.mjs | 193 +++++++++++++++++- 1 file changed, 187 insertions(+), 6 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 21f575ba6c6..934f6f7d165 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -30,12 +30,13 @@ const REPO = repoIdentity(ORIGIN).id; const KEY = `repo:${REPO}/test-cost/pytest`; /** A result file as pytest writes it in the family the option sets, which - * names each case's file: one suite of `tests` cases that took `time`. */ -function report({ tests, time, file = FILE, failures = 0, skipped = 0 }) { + * names each case's file and, in `classname`, the test file's module and what + * holds the case in it: one suite of `tests` cases that took `time`. */ +function report({ tests, time, file = FILE, classname = "tests.test_big", failures = 0, skipped = 0 }) { return ( `` + - `` + + `` + `` ); } @@ -53,7 +54,15 @@ const BOTH = `In the repository tagged repo:${REPO}, a whole run of ${FILE} coll // --- the parts ---------------------------------------------------------------- test("the head of a report gives the run's case count and its seconds", () => { - const whole = { tests: 8000, seconds: 140, time: 140.2, failed: 0, skipped: 0, file: FILE }; + const whole = { + tests: 8000, + seconds: 140, + time: 140.2, + failed: 0, + skipped: 0, + file: FILE, + classname: "tests.test_big", + }; assert.deepEqual(runCost(WHOLE.slice(0, 4096)), whole); assert.deepEqual(runCost(report({ tests: 3, time: "0.4", failures: 2, skipped: 1 })), { tests: 3, @@ -62,10 +71,23 @@ test("the head of a report gives the run's case count and its seconds", () => { failed: 2, skipped: 1, file: FILE, + classname: "tests.test_big", + }); + // A case of a data-driven suite: the data file it was read from, and its class in the test file. + const driven = report({ + tests: 8000, + time: "140.2", + file: "tests/data/parse.test", + classname: "tests.test_big.Suite.parse.test", + }); + assert.deepEqual(runCost(driven), { + ...whole, + file: "tests/data/parse.test", + classname: "tests.test_big.Suite.parse.test", }); // A head cut inside the first case still holds the suite's totals. const cut = WHOLE.slice(0, WHOLE.indexOf(" { + const whole = { + path: FILE, + dir: "", + whole: true, + seconds: null, + cases: null, + failed: null, + skipped: null, + values: [], + }; + // An edit by an inline script, as a session writes one before it checks the edit. + const edit = [ + "python - <<'E'", + "p='src/parser.py'", + "s=open(p).read()", + 's=s.replace(""" return prefix\n""",""" return prefix or ""\n""",1)', + "open(p,'w').write(s)", + "E", + ].join("\n"); + for (const command of [ + `${edit}\ngit diff --stat; sed -n 170,200p src/parser.py; python -m pytest -q -n4 ${FILE} 2>&1 | tail -5`, + `${edit}\npython -m pytest -q -n8 ${FILE} 2>&1 | tail -4`, + `git stash -q; python /tmp/t.py | tail -2; git stash pop -q; python /tmp/t.py | tail -2; python -m pytest -q ${FILE} 2>&1 | tail -4`, + `cat >> src/parser.py <<'E'\nclass Finder:\n found = False\nE\ntimeout 590 python -m pytest -q ${FILE}`, + `git checkout src/parser.py; sed -i 's/a/b/' src/parser.py; echo 'x = 1' >> /tmp/t.py; pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt`, + `rm /tmp/ex.py; pytest ${FILE}`, + ]) { + assert.deepEqual(fileRun(command), whole, command); + } + // The folder of the one `cd`, and a run filtered with -k. + assert.deepEqual(fileRun(`cd pkg && git stash -q; pytest ${FILE} -k parse`), { ...whole, dir: "pkg", whole: false }); + // The last line of the output is the run's where the run ended in the call. + assert.equal(fileRun(`${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -3`, WHOLE_OUTPUT).seconds, 140.21); +}); + test("a command with two pytest runs, two paths, another selection or no run of its own is no file run", () => { for (const command of [ `pytest ${FILE} -q; pytest ${FILE} -k parse`, @@ -245,6 +304,19 @@ test("a command with two pytest runs, two paths, another selection or no run of `make build && pytest ${FILE} -q`, `export OUT=$(make test); pytest ${FILE}`, `export OUT=\`make test\`; pytest ${FILE}`, + // So may one that names a test runner, or pytest, among commands that start none. + `git diff --stat; make test; pytest ${FILE}`, + `tox -e lint; pytest ${FILE}`, + `./run_tests.sh; pytest ${FILE} -q`, + `python -c "import pytest; pytest.main(['tests'])"; python -m pytest ${FILE}`, + `pip install -U pytest; pytest ${FILE}`, + `rm -rf .pytest_cache; pytest ${FILE}`, + // The run may not start after `||`, or where `&&`, `&` or a pipe joins it to a command that is no set-up. + `git stash pop -q || true; pytest ${FILE}`, + `python /tmp/edit.py && pytest ${FILE}`, + `git diff --stat &&\npytest ${FILE}`, + `cat /tmp/names.txt | pytest ${FILE}`, + `sleep 600 & pytest ${FILE}`, // Quotes are not read: a `|` or a parenthesis in one ends the run's part there. `pytest ${FILE} -q 2>&1 | grep -E "passed|failed"`, `pytest ${FILE} -k "parse and (empty or nested)" -q`, @@ -428,6 +500,10 @@ function inTmp(t, fn) { * command returned, and `dropped` is true for a time that is not after now. */ function noted(file) { const state = readJsonFile(file, null); + if (state?.read) { + assert.ok(Math.abs(Date.now() - state.read) < 60000, `the last read was noted at ${state.read}`); + delete state.read; + } if (state?.dropped) state.dropped = state.dropped <= Date.now(); if (!state?.pending) return state; const { at, ...pending } = state.pending; @@ -435,12 +511,15 @@ function noted(file) { return { ...state, pending }; } const runs = () => noted(sessionStatePath("test-cost", SESSION)); -/** Move the times the session's cost state holds `ms` back: its commands returned that long ago. */ +/** Move the times the session's cost state holds `ms` back: its commands + * returned, and its hooks read the report, that long ago. */ function aged(ms) { const file = sessionStatePath("test-cost", SESSION); const state = readJsonFile(file, null); + if (!state) return; if (state.pending) state.pending.at -= ms; if (state.dropped) state.dropped -= ms; + if (state.read) state.read -= ms; writeJsonFile(file, state); } /** What `newReport` reads of a report `xml` that was written `after` ms from now. */ @@ -548,6 +627,108 @@ test("an earlier short run's report is not that of a later short run that wrote }); }); +test("a report whose first case names a data file is the run's when the case's class is under the run's file", { + skip: WINDOWS, +}, (t) => { + inTmp(t, (cwd, file) => { + // The report of a run of 140 s that began after the session's last read. + const note = (classname, source = "tests/data/parse.test") => { + const xml = report({ tests: 8000, time: "140.2", file: source, classname }); + noteCommand(SESSION, { command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(xml, 141000), cwd }); + }; + // A class of another module, of a module that only starts with the file's + // name, of the file's name under another folder, and no class. + for (const classname of [ + "tests.test_other.Suite.parse.test", + "tests.test_bigger.Suite.parse.test", + "tests.test_big_more", + "other.test_big.Suite.parse.test", + "Suite.parse.test", + "", + ]) { + note(classname); + assert.equal(runs()?.files, undefined, classname); + } + // A case in a Python file is that file's, whatever its class: one a class + // of this file's module takes from another file is not counted. + note("tests.test_big.Suite", "tests/test_other.py"); + assert.equal(runs()?.files, undefined); + // The class is named from pytest's root, a folder at or above the file's. + for (const classname of ["tests.test_big.Suite.parse.test", "tests.test_big", "test_big.Suite.parse.test"]) { + note(classname); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, classname); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + } + // A pending run's report, read with a later command, is told the same way. + noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, report: null, cwd }); + const driven = report({ + tests: 8000, + time: "140.2", + file: "tests/data/parse.test", + classname: "tests.test_big.Suite.parse.test", + }); + noteCommand(SESSION, { command: "pgrep -f pytest", output: "", report: read(driven), cwd }); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); + }); +}); + +test("a run after other commands in its shell call is counted with its own report", { skip: WINDOWS }, (t) => { + inTmp(t, (cwd, file) => { + const note = (command, output, xml, after) => + noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); + const edited = `sed -i 's/a/b/' src/parser.py; git diff --stat; python -m pytest -q -n4 ${FILE} 2>&1 | tail -5`; + note(edited, WHOLE_OUTPUT, WHOLE); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); + // The next one's run began 150 s ago, after the read of 200 s ago. + aged(200000); + note(edited, "8000 passed in 150.00s", report({ tests: 8000, time: "150.0" })); + assert.deepEqual(runs().files[file].whole, { tests: 8000, seconds: 150 }); + // A run that outlives its call is the session's pending run. + note(edited, " src/parser.py | 2 +-", null); + assert.deepEqual(runs().pending, { file, whole: true }); + }); +}); + +test("a report of a run that began before the session's last read is not the command's", { skip: WINDOWS }, (t) => { + inTmp(t, (cwd, file) => { + const note = (command, output, xml, after) => + noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); + const stored = () => runs()?.files; + const SMALL = "tests/test_small.py"; + fs.writeFileSync(path.join(cwd, SMALL), ""); + // The command reads the output an earlier run saved, then starts a run of + // the file that outlives the call: its output shows the earlier run's last line. + const again = `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} 2>&1 | tail -5`; + + // A run of two paths went to the background 160 s ago and ended 130 s ago, + // after 152 s: its report, read with the next command, is not that command's. + note(`python -m pytest -q ${FILE} ${SMALL} > /tmp/out.txt 2>&1`, "", null); + aged(160000); + note(again, "8145 passed in 152.44s (0:02:32)", report({ tests: 8145, time: "152.4" }), -130000); + assert.equal(stored(), undefined); + fs.rmSync(sessionStatePath("test-cost", SESSION), { force: true }); + + // The earlier run was a selection of the file, started with workers, whose + // last line counts no deselected case: its report is the pending run's. + note(`python -m pytest -q -n4 ${FILE} -k parse > /tmp/out.txt 2>&1`, "", null); + aged(160000); + note(again, "404 passed in 150.00s (0:02:30)", report({ tests: 404, time: "150.0" }), -130000); + assert.deepEqual(runs(), { files: { [file]: { filtered: [[404, 150]] } } }); + fs.rmSync(sessionStatePath("test-cost", SESSION), { force: true }); + + // The same holds of a command that is the run alone: a hook read the + // report 100 s ago, and the run that wrote this one began 160 s ago. + note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + aged(100000); + note(WHOLE_COMMAND, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" })); + assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 140 } } }); + // A run that began since that read is the command's. + aged(200000); + note(WHOLE_COMMAND, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" })); + assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 160 } } }); + }); +}); + test("a command that is no file run, or names a file that is not there, leaves no state", { skip: WINDOWS, }, (t) => { From 7a7d4b9f6af2921d6740a5a1e8426b2924728c1b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 20:58:59 +0530 Subject: [PATCH 02/52] The plugin notes the cost of a pytest run that follows other commands in its shell call, and of a data-driven file A session that edits and then checks in one shell call (an inline script, git diff --stat, sed, then pytest on one file) had its run refused by fileRun, which allowed only cd, export, source and . before the run. And a suite whose cases come from data files names the data file in each testcase, so the report of its whole run was taken for another file's. Neither run reached the session's state, so no row was stored for the files this note is for. fileRun now also takes a run whose text before it names no test runner, no pytest and no ||, with ; or a line's end before the run's own command. ofFile counts a report whose first case names a file that is no Python file when the case's class is under the run file's module. A command before the run can print an earlier run's last line (tail -5 out.txt; pytest ), and where its own run outlives the call the report read with it is that earlier run's. The state now keeps the time a hook last read the report, and a report is the command's own only when its run began after that time. The text before the run is read once, backwards from the run, and CD reads only spaces and tabs between a separator and cd: a long run of blank lines cost quadratic time. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 43 +++++-- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 34 ++++-- .../claude-code-plugin/lib/test-cost.mjs | 46 ++++++-- .../claude-code-plugin/lib/test-gate.mjs | 43 +++++-- .../claude-code-plugin/lib/test-report.mjs | 13 ++- .../tests/test-cost.test.mjs | 105 ++++++++++++------ 7 files changed, 205 insertions(+), 81 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index ea3bb12c77a..f3a7d996190 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1757,18 +1757,31 @@ session's private state, by the file: parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither; -- a run that anything stands before in its command but `cd`, `export`, `source` and `.` - counts as neither (`make build && pytest tests/test_big.py`): a command before it may - start pytest too, and where the run then does not start, as in - `make test || pytest tests/test_big.py`, the result file and the summary line are that - command's. +- a run counts as neither where a command before it may start pytest too, or where the + run may not start after it (`make test || pytest tests/test_big.py`, + `make build && pytest tests/test_big.py`): the result file and the summary line are + then that command's. What may stand before the run is `cd`, `export`, `source` and `.`, + or the commands of a session that edits and then checks in one shell call, such as + `sed -i 's/a/b/' src/parser.py; git diff --stat; pytest tests/test_big.py`: they name + no test runner, no `pytest` and no `||`, and `;` or a line's end stands before the + run's own command, not `&&`, `&`, a pipe or a parenthesis. The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the -seconds within a second, or a twentieth of them), and the file's first case is in the -test file the command names. The seconds alone do not tell two short runs apart: a run -that wrote no file, such as one that sets its own `PYTEST_ADDOPTS`, is read with the -file an earlier run left. +seconds within a second, or a twentieth of them), the file's first case is in the test +file the command names, and the run that wrote the file began after a hook last read it. +The seconds alone do not tell two short runs apart: a run that wrote no file, such as +one that sets its own `PYTEST_ADDOPTS`, is read with the file an earlier run left. Nor +does the summary line where a command before the run printed it: +`tail -5 out.txt; pytest tests/test_big.py` shows the summary of the run that wrote +`out.txt`, and where its own run outlives the call, the result file read with it is that +earlier run's. That run began before the hook's last read, and the command's own run +after it. + +A case that a data-driven suite reads from a data file names that file in the result +file, not the test file that collected it. Such a case is in the command's test file +when its class is under that file's module (`tests.test_big.Suite` for +`tests/test_big.py`). A run that outlives its shell call writes the file after the hook ran: it is read after the next shell command that names a test runner, or when the session ends. That file is @@ -1860,11 +1873,17 @@ What it does not do: session's start removes the state files untouched for a day. The row is written when a bug report reads it and not again: once it is removed, the session stores nothing unless a later bug report reads the row again. What the session noted of its runs goes - a day after the last run it noted. A session that runs no pytest for a day has no test - report after that: its bug reports read no row and print no line, and its runs are not - noted; + a day after its last shell command that names a test runner. A session that runs no + pytest for a day has no test report after that: its bug reports read no row and print + no line, and its runs are not noted; - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not; +- a command before the run that starts pytest under no runner's name, such as a script + of the repository, is not told apart from an edit: where the run after it does not + start, the script's result file and summary line are counted as the run's. Nor is the + result file of a run put in the background at once, of two paths or another selection + of the test file, told apart from the run of a later command that prints its saved + summary and whose own run outlives the call; - the session keeps one run that outlives its call. A later one of another test file takes its place, and the earlier run is not counted. A later one of the same file and the other kind, whole after `-k` or `-k` after whole, drops both, since the earlier diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 9f69e78fa16..7ce7adb9870 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that anything stands before in its command but `cd`, `export`, `source` and `.` (`make test || pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest` or `||` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after a hook last read the file: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index dba0085e056..a472a206ce9 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1475,11 +1475,17 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that follows in its command but `tail`, `head`, `grep` and `echo`, a redirect of the run to a file aside (`onlyRuns`): a runner started after it (`&& make test`, `; tox`) writes the result file and prints the last - line. So is a run that anything stands before in its command but `cd`, - `export`, `source` and `.` (`onlySetsUp`): a command before it may - start pytest too, and where the run does not start - (`make test || pytest `, an interpreter with no pytest) the - result file and the last line are that command's. Quotes are not read, + line. So is a run that a command stands before which may start pytest + too, or after which the run may not start + (`make test || pytest `, `python edit.py && pytest `): the + result file and the last line are then that command's. What may stand + before the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or + the commands of a session that edits and then checks in one shell call + (an inline script, `git diff --stat`, `sed`): text that names no test + runner (`startsRunner`), no pytest and no `||`, with `;` or a line's + end before the run's own command, not `&&`, `&`, a pipe or a + parenthesis (`startsNoRun`). A script that starts pytest under another + name is not told apart. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with @@ -1503,10 +1509,22 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that The report is the command's when the command's visible output shows pytest's summary line with the cases, the failures and the seconds the report holds, the seconds within a second or a twentieth of them, - and the report's first case is in the file the command names: a run + the report's first case is in the file the command names, and the run + that wrote the report began after a hook last read the report: a run the option did not reach writes no report, and the one read after it is an earlier run's, which the seconds of two short runs do not tell - apart. The summary is pytest's last line, whatever it counts + apart. Nor does the line where a command before the run printed it: + `tail -5 out.txt; pytest ` shows the last line of the run that + wrote `out.txt`, and where its own run outlives the call, the report + read with it is that earlier run's too. That run began before the + hook's last read, which the state keeps for every command the hook + runs after, and the command's own run after it. A run put in the + background at once begins after its own command's hook, and is not + told apart that way. The first case is in the file where its `file` + attribute names it from pytest's root. A case that a data-driven suite + reads from a data file names that file, which is no Python file: it is + in the file where its `classname` is under the file's module (`ofFile` + in lib/test-cost.mjs). The summary is pytest's last line, whatever it counts (`8000 deselected in 1.20s` and `no tests ran in 0.01s` too), read without the colours of a pytest told to colour its output. A run whose output shows no such line may not have ended: one that outlives @@ -1600,7 +1618,7 @@ about s.` The write revises the row the session read (`if_match_sha256`), files, at any session's start a day after their last write. The row is written when a bug report reads it and not again: once it is gone, the session stores nothing unless a later bug report reads the row - again. The runs go a day after the last one was noted. A session + again. The runs go a day after the hook last ran. A session whose report state went that way (**The file's end**, above) reads no row, prints no line and notes no run. - LOOM_TEST_REPORT=off, or the `test_report` option set to false, stops diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index ef209e4c865..94aa8c49e82 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -8,7 +8,10 @@ // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private // state, for a session whose end may store them: for each file, the costliest -// whole run that passed and its latest runs filtered with -k. A run that +// whole run that passed and its latest runs filtered with -k. Other commands +// may stand before the run in its shell call, and may print the last line of +// a run that ended earlier: a report is the command's only when its run began +// after the hook last read the file. A run that // outlives its shell call writes the file after that call's hook ran: a // report read later is its when pytest began the run that wrote it before // that call returned, and the launcher reads the file once more before it @@ -53,9 +56,9 @@ const MAX_PATH = 160; const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, dropped, files }`, by each file's absolute -// path. `dropped` is the time by which a run that lost its place as the -// pending one had begun. +// The session's runs: `{ pending, dropped, read, files }`, by each file's +// absolute path. `dropped` is the time by which a run that lost its place as +// the pending one had begun, and `read` the time a hook last read the report. 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 @@ -92,8 +95,17 @@ function located(run, cwd) { /** Whether the report of `cost` (`runCost`) is one a run of `run`'s file * wrote: its first case is in that file. pytest names the file from its - * root, a folder at or above the file's. */ -const ofFile = (run, cost) => Boolean(cost.file) && run.file.split(path.sep).join("/").endsWith(`/${cost.file}`); + * root, a folder at or above the file's. A case that a data-driven suite + * reads from a data file names that file, which is no Python file: the + * report is then the file's when the case's class is under the file's + * module, which pytest names from its root too. */ +function ofFile(run, cost) { + const file = run.file.split(path.sep).join("/"); + if (!cost.file) return false; + if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); + const folders = file.replace(/\.py$/, "").split("/"); + return folders.some((_, at) => `${cost.classname}.`.startsWith(`${folders.slice(at).join(".")}.`)); +} /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another @@ -126,11 +138,14 @@ function add(state, run, cost) { state.files = Object.fromEntries(held.filter((entry) => entry !== dropped)); } +/** When pytest began the run that wrote `report` (`newReport`), whose head + * gives `cost`: the time the file was written less the suite's seconds. */ +const beganAt = (report, cost) => report.mtimeMs - cost.time * 1000; + /** Count `report` (`newReport`) for the session's pending run, and say * whether it was that run's: its first case is in the run's file (`ofFile`) * and the run that wrote it began before the pending run's command - * returned. pytest began it at the time the file was written less the - * suite's seconds. A command that came later, whatever it is and whether or + * returned (`beganAt`). A command that came later, whatever it is and whether or * not a hook saw it, began its run after that. A run of the file that * something else started while the pending run was in its call began before * it too: its report, read with a command that is not that run, is taken @@ -141,7 +156,7 @@ function settle(state, report) { const cost = report ? runCost(report.head) : null; const pending = state.pending; if (!cost || !pending || !ofFile(pending, cost)) return false; - const began = report.mtimeMs - cost.time * 1000; + const began = beganAt(report, cost); if (began > pending.at || began <= (state.dropped ?? 0)) return false; add(state, pending, cost); state.pending = undefined; @@ -157,7 +172,15 @@ function settle(state, report) { * file (`fileRun`) and its output shows pytest's summary with the cases, the * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The - * seconds alone do not tell two short runs apart. Any other report is the + * seconds alone do not tell two short runs apart. Nor does the summary where + * a command before the run printed it: one that reads the output an earlier + * run saved (`tail -5 out.txt; pytest `) shows that run's last line, + * and where its own run outlives the call, the report read is that run's + * too. So the report's run began after the hook last read the report + * (`read`), as the command did: a run that began before it was started by an + * earlier command. Every call notes that time, a command with no file run + * too. A run put in the background at once begins after its own call's hook, + * and is not told apart from a later command's. Any other report is the * pending run's when it is of that run's file and its run began by the time * the run's command returned (`settle`), and no run's otherwise. So a run * that was put in the background before pytest began is not counted. @@ -181,7 +204,6 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { try { const run = located(fileRun(command, output), cwd); const state = readSessionState(RUNS, sessionId); - if (!run && !state.pending) return; const cost = report ? runCost(report.head) : null; const open = Boolean(run && run.seconds === null); // The summary's seconds and the report's are two clocks on one run. @@ -189,6 +211,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && + beganAt(report, cost) > (state.read ?? 0) && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); @@ -204,6 +227,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { else if (pending && pending.file !== run.file) state.dropped = pending.at; state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } + state.read = Date.now(); writeSessionState(RUNS, sessionId, state); } catch { /* nothing noted */ diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index a99a8e1081b..53170b28e96 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1304,7 +1304,9 @@ const STOPS = /(?:^|\s)(?:-[A-Za-z]*x|--exitfirst|--maxfail)/; // configuration file or in PYTEST_ADDOPTS, which the command does not. const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // The directory a command moves to before it runs something, and any move. -const CD = /(?:^|[;&|(\n])\s*cd\s+([^\s;&|)]+)/g; +// Only spaces and tabs are read between a separator and `cd`: a line's end is +// a separator itself, and a run of blank lines is then read once. +const CD = /(?:^|[;&|(\n])[ \t]*cd\s+([^\s;&|)]+)/g; const MOVE = /\b(?:cd|pushd|popd)\s/g; const unquoted = (word) => word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written @@ -1336,16 +1338,33 @@ const onlyRuns = (tail, runs = Infinity) => .split(/[;&|()\n]/) .every((part, at) => !/[<>`]/.test(part) && (OUTPUT.test(part) || (at < runs && part.match(PYTEST)))); // What a command may hold before the simple command of its pytest run: `cd`, -// `export`, `source` and `.`, with no backquote. Anything else may start -// pytest itself (`make test`, a script), and its last line and result file -// are read as the run's where the run did not start (`make test || pytest -// `, an interpreter with no pytest). +// `export`, `source` and `.`, with no backquote, joined to the run in any +// way (`cd pkg && pytest `). const SETS_UP = /^\s*(?:(?:cd|export|source|\.)\s[^`]*)?$/; const onlySetsUp = (head) => head .split(/[;&|(\n]/) .slice(0, -1) .every((part) => SETS_UP.test(part)); +// Or any other commands, as a session writes them that edits and then checks +// in one shell call (an inline script, `git diff --stat`, `sed`), where none +// can pass for the run: a command that starts pytest itself prints a last +// line and writes the result file, and both are read as the run's where the +// run did not start or wrote none. So the text before the run names no test +// runner (`startsRunner`: `make test`, `tox`, a `run_tests` script), no +// pytest (`pytest.main` in an inline script) and no `||`, and the run does +// not wait on what those commands returned: `;` or a line's end stands +// before its simple command, not `&&`, `&`, a pipe or a parenthesis. A +// script that starts pytest under another name is not told apart. The text +// is read once from the run backwards, so a long one (an inline script of +// blank lines) costs time in proportion to its length. +const startsNoRun = (head) => { + // What ends the command before the run's, and what stands before that. + let end = head.length - head.split(/[;&|(\n]/).pop().length; + if (!/[;\n]/.test(head[end - 1] || "")) return false; + while (end > 0 && /[;\s]/.test(head[end - 1])) end -= 1; + return !/[&|(]/.test(head[end - 1] || "") && !/\|\||py\.?test/.test(head) && !startsRunner(head); +}; /** True when the output holds a whole pytest summary for each of `runs` * and no other summary: `| tail -5; echo exit=$?` hides the exit status, @@ -1423,11 +1442,13 @@ const counted = (line, kinds) => * `PYTEST` does not count) writes the session's result file and prints the * last line. Quotes are not read there or in the run's words (`PYTEST`), so * a run piped into `grep -E "passed|failed"` is none, and neither is one - * with `-k "parse and (empty or nested)"`. Nor is a run that anything stands - * before in the command but `cd`, `export`, `source` and `.` (`onlySetsUp`): - * a command before it may start pytest too (`make test || pytest `), - * and where the run does not start, the last line and the result file are - * that command's. + * with `-k "parse and (empty or nested)"`. Nor is a run that a command stands + * before which may start pytest too, or after which the run may not start + * (`make test; pytest `, `python edit.py && pytest `): the last + * line and the result file are then that command's. What may stand before + * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or commands + * that name no test runner and are followed by `;` or a line's end + * (`startsNoRun`). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1452,7 +1473,7 @@ export function fileRun(command, output = "") { .replace(/\d?>&\d/g, " "); const runs = [...text.matchAll(PYTEST)]; const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; - if (runs.length !== 1 || !ranHere(head) || !onlySetsUp(head)) return null; + if (runs.length !== 1 || !ranHere(head) || !(onlySetsUp(head) || startsNoRun(head))) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index bf6b17197f6..42840cc6e21 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -294,9 +294,12 @@ function scan(xml) { * first testsuite's case count, its seconds to the nearest one and as * written (`time`), how many cases failed or ended in an error, how many * were skipped (pytest counts them as cases, and an expected failure among - * the skipped), and the file of its first testcase, which pytest names in - * the family the option sets ("" where the head holds none). null for a head - * with no whole testsuite tag, no case or no time. */ + * the skipped), and the file and the class of its first testcase ("" where + * the head holds none). pytest names the file in the family the option sets: + * where the case is defined, which for a case a suite reads from a data file + * is that file. The class starts with the module of the test file that + * collected the case. null for a head with no whole testsuite tag, no case or + * no time. */ export function runCost(head) { const first = (text, name) => { try { @@ -313,13 +316,15 @@ export function runCost(head) { const seconds = Number(has.time); if (!Number.isInteger(tests) || tests < 1 || !has.time || !Number.isFinite(seconds) || seconds < 0) return null; const testcase = first(xml.slice(suite.end), "testcase"); + const named = testcase ? attributes(testcase.attrs) : {}; return { tests, seconds: Math.round(seconds), time: seconds, failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), skipped: Number(has.skipped) || 0, - file: testcase ? attributes(testcase.attrs).file || "" : "", + file: named.file || "", + classname: named.classname || "", }; } diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 934f6f7d165..c6ce5118352 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -241,6 +241,12 @@ test("a run that follows commands which name no test runner is a file run", () = assert.deepEqual(fileRun(`cd pkg && git stash -q; pytest ${FILE} -k parse`), { ...whole, dir: "pkg", whole: false }); // The last line of the output is the run's where the run ended in the call. assert.equal(fileRun(`${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -3`, WHOLE_OUTPUT).seconds, 140.21); + // A long text before the run is read in time linear in its length: without + // that, 80,000 blank lines cost seconds of CPU. + const before = process.cpuUsage(); + assert.deepEqual(fileRun(`${"x = 1\n".repeat(20000)}pytest ${FILE}`), whole); + for (const filler of ["\n", " \n", " ", "; ", "&& ", "cd a\n"]) fileRun(`${filler.repeat(80000)}pytest ${FILE}`); + assert.ok(process.cpuUsage(before).user < 2e6); }); test("a command with two pytest runs, two paths, another selection or no run of its own is no file run", () => { @@ -496,14 +502,12 @@ function inTmp(t, fn) { fs.writeFileSync(path.join(cwd, FILE), ""); return withTmpdir(tmp, () => fn(cwd, path.join(cwd, FILE))); } -/** A session's cost state as `file` holds it; a pending run has the time its - * command returned, and `dropped` is true for a time that is not after now. */ +/** A session's cost state as `file` holds it, but for the time of its last + * read; a pending run has the time its command returned, and `dropped` is + * true for a time that is not after now. */ function noted(file) { const state = readJsonFile(file, null); - if (state?.read) { - assert.ok(Math.abs(Date.now() - state.read) < 60000, `the last read was noted at ${state.read}`); - delete state.read; - } + if (state) delete state.read; if (state?.dropped) state.dropped = state.dropped <= Date.now(); if (!state?.pending) return state; const { at, ...pending } = state.pending; @@ -522,6 +526,19 @@ function aged(ms) { if (state.read) state.read -= ms; writeJsonFile(file, state); } +/** Take the session's last read of the report a day back, in the cost state + * at `file`: the run of whatever report the next hook reads began since. */ +function rested(file = sessionStatePath("test-cost", SESSION)) { + const state = readJsonFile(file, null); + if (!state?.read) return; + state.read -= 24 * 60 * 60 * 1000; + writeJsonFile(file, state); +} +/** Note a command of SESSION whose hook comes a day after the session's last one. */ +function noteNext(args) { + rested(); + noteCommand(SESSION, args); +} /** What `newReport` reads of a report `xml` that was written `after` ms from now. */ const read = (xml, after = 0) => (xml === null ? null : { head: xml.slice(0, 4096), mtimeMs: Date.now() + after }); /** Write the report `xml` to `file` as a run that ends `after` ms from now writes it. */ @@ -536,7 +553,7 @@ test("a report is the command's whose output shows the summary with the report's skip: WINDOWS, }, (t) => { inTmp(t, (cwd, file) => { - const note = (command, output, xml) => noteCommand(SESSION, { command, output, report: read(xml), cwd }); + const note = (command, output, xml) => noteNext({ command, output, report: read(xml), cwd }); const whole = (seconds) => ({ tests: 8000, seconds }); // A file of one case has no selection smaller than itself: its whole run is not kept. note(WHOLE_COMMAND, "1 passed in 300.00s", report({ tests: 1, time: "300.0" })); @@ -605,7 +622,7 @@ test("a report is the command's whose output shows the summary with the report's test("an earlier short run's report is not that of a later short run that wrote none", { skip: WINDOWS }, (t) => { inTmp(t, (cwd, file) => { const note = (output, xml) => - noteCommand(SESSION, { command: `PYTEST_ADDOPTS=-q pytest -x ${FILE}`, output, report: read(xml), cwd }); + noteNext({ command: `PYTEST_ADDOPTS=-q pytest -x ${FILE}`, output, report: read(xml), cwd }); // A -k run that no hook read left its report: 12 cases in 1.4 s. The run // after it set its own options and wrote none, and its summary's seconds // are within a second of the report's: it does not count the report's cases. @@ -729,7 +746,7 @@ test("a report of a run that began before the session's last read is not the com }); }); -test("a command that is no file run, or names a file that is not there, leaves no state", { +test("a command that is no file run, or names a file that is not there, notes no run", { skip: WINDOWS, }, (t) => { inTmp(t, (cwd) => { @@ -747,7 +764,8 @@ test("a command that is no file run, or names a file that is not there, leaves n note(`cd elsewhere && pytest ${FILE.replace("big", "gone")} -q`, WHOLE_OUTPUT); // A run in a folder whose name the command quotes is not the session folder's file of that path. note(`cd "/elsewhere/My Projects/app" && pytest ${FILE} -q`, WHOLE_OUTPUT); - assert.equal(runs(), null); + // The state holds the time of the hook's read, and nothing else. + assert.deepEqual(runs(), {}); }); }); @@ -759,7 +777,7 @@ test("a session's state holds eight files, the costliest whole run among them, a fs.writeFileSync(path.join(cwd, name), ""); const xml = report({ tests, time: "2.3", file: name }); const output = `${tests} passed, ${8000 - tests} deselected in 2.31s`; - noteCommand(SESSION, { command: `pytest ${name} -k parse -q`, output, report: read(xml), cwd }); + noteNext({ command: `pytest ${name} -k parse -q`, output, report: read(xml), cwd }); }; note(FILE); for (let i = 0; i < 7; i++) note(`tests/test_${i}.py`); @@ -782,7 +800,7 @@ test("a session's state holds eight files, the costliest whole run among them, a ); // The file with the costliest whole run stays, however long ago it ran: // eight files run after it drop the seven before it and the first of their own. - noteCommand(SESSION, { command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(WHOLE), cwd }); + noteNext({ command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(WHOLE), cwd }); for (let i = 8; i < 16; i++) note(`tests/test_${i}.py`); const last = runs().files; assert.deepEqual(Object.keys(last), [ @@ -1086,6 +1104,7 @@ function run(script, event, env, payload) { /** The launcher after a shell command of the session whose pytest wrote `xml`. */ function afterCommand(box, command, output, xml, extra) { + rested(box.runs); if (xml !== undefined) fs.writeFileSync(box.report, xml); return run("loom-record.mjs", "PostToolUse", box.env(extra), { cwd: box.cwd, @@ -1135,7 +1154,7 @@ test("a slow whole run and a filtered one are noted, and the session's end store assert.equal(context(await ask(box)), BLOCK); assert.deepEqual(await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE), quiet); assert.deepEqual(await afterCommand(box, FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED), quiet); - assert.deepEqual(readJsonFile(box.runs, null), { + assert.deepEqual(noted(box.runs), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 }, filtered: [[12, 2]] } }, }); await settled(box); @@ -1159,12 +1178,33 @@ test("a slow whole run and a filtered one are noted, and the session's end store assert.equal(server.sent("memory.get").length, 1); }); +test("a whole run of a data-driven file that follows an edit in its shell call is stored at the session's end", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await ask(box); + // The first case names the data file it was read from, and its class the test file's module. + const xml = report({ + tests: 8000, + time: "140.2", + file: "tests/data/parse.test", + classname: "tests.test_big.Suite.parse.test", + }); + const command = `sed -i 's/a/b/' src/parser.py; git diff --stat; python -m pytest -q -n4 ${FILE} 2>&1 | tail -5`; + await afterCommand(box, command, ` src/parser.py | 2 +-\n${WHOLE_OUTPUT}`, xml); + assert.deepEqual(noted(box.runs), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); + await endSession(box); + await arrived(server, box, "memory.set"); + assert.equal(server.sent("memory.set")[0].body.value, claim(REPO, { path: FILE, tests: 8000, seconds: 140 })); +}); + test("a session whose prompts read no row stores nothing", { skip: WINDOWS }, async (t) => { const server = await loom(t); const box = sandbox(t, server); await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); // The session measured a run that makes a first row. - assert.deepEqual(readJsonFile(box.runs, null), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); + assert.deepEqual(noted(box.runs), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); // A question is no bug report: it reads no row. assert.equal(context(await ask(box, { prompt: "How are nested record prefixes combined?" })), BLOCK); await endSession(box); @@ -1217,7 +1257,7 @@ test("the launcher at an agent's SessionEnd reads the pending run's report and e skip: WINDOWS, }, async (t) => { const probe = { report: "", runs: "" }; - const mark = () => ({ report: fs.existsSync(probe.report), runs: readJsonFile(probe.runs, null) }); + const mark = () => ({ report: fs.existsSync(probe.report), runs: noted(probe.runs) }); const server = await loom(t, { mark }); const box = sandbox(t, server); Object.assign(probe, { report: box.report, runs: box.runs }); @@ -1241,7 +1281,7 @@ test("the launcher at an agent's SessionEnd reads the pending run's report and e assert.equal(fs.existsSync(box.runs), false); }); -test("nothing is stored for a whole run under 60 s or of one case, a command of two runs, two paths or a command before the run, or with session memory off", { +test("nothing is stored for a whole run under 60 s or of one case, a command of two runs, two paths or a test runner before the run, or with session memory off", { skip: WINDOWS, }, async (t) => { const server = await loom(t); @@ -1251,12 +1291,12 @@ test("nothing is stored for a whole run under 60 s or of one case, a command of [`python -m pytest ${FILE} -q`, "8000 passed in 59.40s", report({ tests: 8000, time: "59.4" }), {}, whole(59)], // One case: no -k selection is smaller than the file, and its whole run is not kept. [`python -m pytest ${FILE} -q`, "1 passed in 300.00s", report({ tests: 1, time: "300.0" }), {}, {}], - // Two runs, two paths, and a selection that is not by name: nothing is noted. - [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}, null], - [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}, null], - [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}, null], + // Two runs, two paths, and a selection that is not by name: no run is noted. + [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}, false], + [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}, false], + [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}, false], // The suite's run passed, so the file's run did not start: the report is the suite's. - [`make test || pytest ${FILE} -q`, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), {}, null], + [`make test || pytest ${FILE} -q`, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), {}, false], // The session hands nothing to memory: nothing is noted for it. [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }, null], ]; @@ -1267,7 +1307,8 @@ test("nothing is stored for a whole run under 60 s or of one case, a command of assert.equal(server.sent("memory.get").length, at + 1, command); await afterCommand(box, command, output, xml, extra); const files = seen?.whole ? { [box.file]: seen } : {}; - assert.deepEqual(readJsonFile(box.runs, null), seen && { files }, command); + // `false`: the state holds the time of the hook's read, and no run. + assert.deepEqual(noted(box.runs), seen === false ? {} : seen && { files }, command); assert.equal(readJsonFile(box.row, {}).row, null, command); await endSession(box, extra); await settled(box); @@ -1296,7 +1337,7 @@ test("a slow whole run of a file whose path is not sent stores nothing", { skip: const xml = report({ tests: 8000, time: "140.2", file: name }); await afterCommand(box, `python -m pytest ${name} -q`, WHOLE_OUTPUT, xml); const seen = { [path.join(box.cwd, name)]: { whole: { tests: 8000, seconds: 140 } } }; - assert.deepEqual(readJsonFile(box.runs, null), { files: seen }, name); + assert.deepEqual(noted(box.runs), { files: seen }, name); await endSession(box); await settled(box); assert.equal(fs.existsSync(box.runs), false, name); @@ -1332,11 +1373,7 @@ test("a slow whole run of a file that git does not list in the checkout stores n await ask(box); assert.equal(server.sent("memory.get").length, at + 1, tree); await afterCommand(box, `cd ${tree} && python -m pytest ${FILE} -q`, WHOLE_OUTPUT, WHOLE); - assert.deepEqual( - readJsonFile(box.runs, null), - { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, - tree, - ); + assert.deepEqual(noted(box.runs), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, tree); await endSession(box); await settled(box); assert.equal(fs.existsSync(box.runs), false, tree); @@ -1399,16 +1436,16 @@ test("a run that pytest ended early, that skipped most of its cases, or that lef // An interrupt ended the run 120 cases in: the line above its last one says so. const early = `!!!!!!!! KeyboardInterrupt !!!!!!!!\n${FILE}:4: KeyboardInterrupt\n120 passed in 30.00s`; await afterCommand(box, `python -m pytest ${FILE} -q`, early, report({ tests: 120, time: "30.0" })); - assert.equal(readJsonFile(box.runs, null), null); + assert.deepEqual(noted(box.runs), {}); // The selection is not among the run's words: its last line says cases were left out. const selected = `export PYTEST_ADDOPTS="$PYTEST_ADDOPTS -k parse"; python -m pytest ${FILE}`; await afterCommand(box, selected, FILTERED_OUTPUT, FILTERED); - assert.equal(readJsonFile(box.runs, null), null); + assert.deepEqual(noted(box.runs), {}); // The cases need a service this machine does not run. const xml = report({ tests: 8000, time: "2.3", skipped: 7988 }); await afterCommand(box, WHOLE_COMMAND, "12 passed, 7988 skipped in 2.31s", xml); // The report was the command's, and counted for nothing. - assert.deepEqual(readJsonFile(box.runs, null), { files: {} }); + assert.deepEqual(noted(box.runs), { files: {} }); await endSession(box); await settled(box); assert.deepEqual(server.sent("memory.set"), []); @@ -1424,7 +1461,7 @@ test("an earlier short run's report, read after a short run that wrote none, doe // its own options, wrote none and stopped at an error half a second in. const earlier = report({ tests: 12, time: "1.4" }); await afterCommand(box, `PYTEST_ADDOPTS=-q pytest -x ${FILE}`, "1 error in 0.52s", earlier); - assert.deepEqual(readJsonFile(box.runs, null), {}); + assert.deepEqual(noted(box.runs), {}); await endSession(box); await settled(box); assert.deepEqual(server.sent("memory.set"), []); @@ -1438,10 +1475,10 @@ test("code-only mode notes nothing, stores nothing and prints no line", { skip: assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); await afterCommand(box, WHOLE_COMMAND, "8000 passed in 200.00s", report({ tests: 8000, time: "200.0" })); const held = { files: { [box.file]: { whole: { tests: 8000, seconds: 200 } } } }; - assert.deepEqual(readJsonFile(box.runs, null), held); + assert.deepEqual(noted(box.runs), held); // In code-only mode a costlier run is not noted, the prompt has no line, and the end stores nothing. await afterCommand(box, WHOLE_COMMAND, "8000 passed in 300.00s", report({ tests: 8000, time: "300.0" }), code); - assert.deepEqual(readJsonFile(box.runs, null), held); + assert.deepEqual(noted(box.runs), held); assert.equal(context(await ask(box, { extra: code })), BLOCK); await endSession(box, code); await settled(box); From c0e90bd05d72cd31da0d372612bc5a6456131788 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 21:06:25 +0530 Subject: [PATCH 03/52] The plugins are 1.2.188, and the Codex plugin has the copy of the changed files Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- .../.claude-plugin/plugin.json | 2 +- .../codex-plugin/.codex-plugin/plugin.json | 2 +- integrations/codex-plugin/lib/test-cost.mjs | 46 ++++++++++++++----- integrations/codex-plugin/lib/test-gate.mjs | 43 ++++++++++++----- integrations/codex-plugin/lib/test-report.mjs | 13 ++++-- 5 files changed, 78 insertions(+), 28 deletions(-) diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 3025c9b0e39..fca406319a7 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.187", + "version": "1.2.188", "description": "Shared long-term memory and code intelligence for Claude Code, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index 58c8777c8af..820e2267033 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.187", + "version": "1.2.188", "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/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index ef209e4c865..94aa8c49e82 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -8,7 +8,10 @@ // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private // state, for a session whose end may store them: for each file, the costliest -// whole run that passed and its latest runs filtered with -k. A run that +// whole run that passed and its latest runs filtered with -k. Other commands +// may stand before the run in its shell call, and may print the last line of +// a run that ended earlier: a report is the command's only when its run began +// after the hook last read the file. A run that // outlives its shell call writes the file after that call's hook ran: a // report read later is its when pytest began the run that wrote it before // that call returned, and the launcher reads the file once more before it @@ -53,9 +56,9 @@ const MAX_PATH = 160; const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, dropped, files }`, by each file's absolute -// path. `dropped` is the time by which a run that lost its place as the -// pending one had begun. +// The session's runs: `{ pending, dropped, read, files }`, by each file's +// absolute path. `dropped` is the time by which a run that lost its place as +// the pending one had begun, and `read` the time a hook last read the report. 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 @@ -92,8 +95,17 @@ function located(run, cwd) { /** Whether the report of `cost` (`runCost`) is one a run of `run`'s file * wrote: its first case is in that file. pytest names the file from its - * root, a folder at or above the file's. */ -const ofFile = (run, cost) => Boolean(cost.file) && run.file.split(path.sep).join("/").endsWith(`/${cost.file}`); + * root, a folder at or above the file's. A case that a data-driven suite + * reads from a data file names that file, which is no Python file: the + * report is then the file's when the case's class is under the file's + * module, which pytest names from its root too. */ +function ofFile(run, cost) { + const file = run.file.split(path.sep).join("/"); + if (!cost.file) return false; + if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); + const folders = file.replace(/\.py$/, "").split("/"); + return folders.some((_, at) => `${cost.classname}.`.startsWith(`${folders.slice(at).join(".")}.`)); +} /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the * report it wrote. A report whose first case is in another file is another @@ -126,11 +138,14 @@ function add(state, run, cost) { state.files = Object.fromEntries(held.filter((entry) => entry !== dropped)); } +/** When pytest began the run that wrote `report` (`newReport`), whose head + * gives `cost`: the time the file was written less the suite's seconds. */ +const beganAt = (report, cost) => report.mtimeMs - cost.time * 1000; + /** Count `report` (`newReport`) for the session's pending run, and say * whether it was that run's: its first case is in the run's file (`ofFile`) * and the run that wrote it began before the pending run's command - * returned. pytest began it at the time the file was written less the - * suite's seconds. A command that came later, whatever it is and whether or + * returned (`beganAt`). A command that came later, whatever it is and whether or * not a hook saw it, began its run after that. A run of the file that * something else started while the pending run was in its call began before * it too: its report, read with a command that is not that run, is taken @@ -141,7 +156,7 @@ function settle(state, report) { const cost = report ? runCost(report.head) : null; const pending = state.pending; if (!cost || !pending || !ofFile(pending, cost)) return false; - const began = report.mtimeMs - cost.time * 1000; + const began = beganAt(report, cost); if (began > pending.at || began <= (state.dropped ?? 0)) return false; add(state, pending, cost); state.pending = undefined; @@ -157,7 +172,15 @@ function settle(state, report) { * file (`fileRun`) and its output shows pytest's summary with the cases, the * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The - * seconds alone do not tell two short runs apart. Any other report is the + * seconds alone do not tell two short runs apart. Nor does the summary where + * a command before the run printed it: one that reads the output an earlier + * run saved (`tail -5 out.txt; pytest `) shows that run's last line, + * and where its own run outlives the call, the report read is that run's + * too. So the report's run began after the hook last read the report + * (`read`), as the command did: a run that began before it was started by an + * earlier command. Every call notes that time, a command with no file run + * too. A run put in the background at once begins after its own call's hook, + * and is not told apart from a later command's. Any other report is the * pending run's when it is of that run's file and its run began by the time * the run's command returned (`settle`), and no run's otherwise. So a run * that was put in the background before pytest began is not counted. @@ -181,7 +204,6 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { try { const run = located(fileRun(command, output), cwd); const state = readSessionState(RUNS, sessionId); - if (!run && !state.pending) return; const cost = report ? runCost(report.head) : null; const open = Boolean(run && run.seconds === null); // The summary's seconds and the report's are two clocks on one run. @@ -189,6 +211,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && + beganAt(report, cost) > (state.read ?? 0) && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); @@ -204,6 +227,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { else if (pending && pending.file !== run.file) state.dropped = pending.at; state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } + state.read = Date.now(); writeSessionState(RUNS, sessionId, state); } catch { /* nothing noted */ diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index a99a8e1081b..53170b28e96 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1304,7 +1304,9 @@ const STOPS = /(?:^|\s)(?:-[A-Za-z]*x|--exitfirst|--maxfail)/; // configuration file or in PYTEST_ADDOPTS, which the command does not. const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // The directory a command moves to before it runs something, and any move. -const CD = /(?:^|[;&|(\n])\s*cd\s+([^\s;&|)]+)/g; +// Only spaces and tabs are read between a separator and `cd`: a line's end is +// a separator itself, and a run of blank lines is then read once. +const CD = /(?:^|[;&|(\n])[ \t]*cd\s+([^\s;&|)]+)/g; const MOVE = /\b(?:cd|pushd|popd)\s/g; const unquoted = (word) => word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written @@ -1336,16 +1338,33 @@ const onlyRuns = (tail, runs = Infinity) => .split(/[;&|()\n]/) .every((part, at) => !/[<>`]/.test(part) && (OUTPUT.test(part) || (at < runs && part.match(PYTEST)))); // What a command may hold before the simple command of its pytest run: `cd`, -// `export`, `source` and `.`, with no backquote. Anything else may start -// pytest itself (`make test`, a script), and its last line and result file -// are read as the run's where the run did not start (`make test || pytest -// `, an interpreter with no pytest). +// `export`, `source` and `.`, with no backquote, joined to the run in any +// way (`cd pkg && pytest `). const SETS_UP = /^\s*(?:(?:cd|export|source|\.)\s[^`]*)?$/; const onlySetsUp = (head) => head .split(/[;&|(\n]/) .slice(0, -1) .every((part) => SETS_UP.test(part)); +// Or any other commands, as a session writes them that edits and then checks +// in one shell call (an inline script, `git diff --stat`, `sed`), where none +// can pass for the run: a command that starts pytest itself prints a last +// line and writes the result file, and both are read as the run's where the +// run did not start or wrote none. So the text before the run names no test +// runner (`startsRunner`: `make test`, `tox`, a `run_tests` script), no +// pytest (`pytest.main` in an inline script) and no `||`, and the run does +// not wait on what those commands returned: `;` or a line's end stands +// before its simple command, not `&&`, `&`, a pipe or a parenthesis. A +// script that starts pytest under another name is not told apart. The text +// is read once from the run backwards, so a long one (an inline script of +// blank lines) costs time in proportion to its length. +const startsNoRun = (head) => { + // What ends the command before the run's, and what stands before that. + let end = head.length - head.split(/[;&|(\n]/).pop().length; + if (!/[;\n]/.test(head[end - 1] || "")) return false; + while (end > 0 && /[;\s]/.test(head[end - 1])) end -= 1; + return !/[&|(]/.test(head[end - 1] || "") && !/\|\||py\.?test/.test(head) && !startsRunner(head); +}; /** True when the output holds a whole pytest summary for each of `runs` * and no other summary: `| tail -5; echo exit=$?` hides the exit status, @@ -1423,11 +1442,13 @@ const counted = (line, kinds) => * `PYTEST` does not count) writes the session's result file and prints the * last line. Quotes are not read there or in the run's words (`PYTEST`), so * a run piped into `grep -E "passed|failed"` is none, and neither is one - * with `-k "parse and (empty or nested)"`. Nor is a run that anything stands - * before in the command but `cd`, `export`, `source` and `.` (`onlySetsUp`): - * a command before it may start pytest too (`make test || pytest `), - * and where the run does not start, the last line and the result file are - * that command's. + * with `-k "parse and (empty or nested)"`. Nor is a run that a command stands + * before which may start pytest too, or after which the run may not start + * (`make test; pytest `, `python edit.py && pytest `): the last + * line and the result file are then that command's. What may stand before + * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or commands + * that name no test runner and are followed by `;` or a line's end + * (`startsNoRun`). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1452,7 +1473,7 @@ export function fileRun(command, output = "") { .replace(/\d?>&\d/g, " "); const runs = [...text.matchAll(PYTEST)]; const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; - if (runs.length !== 1 || !ranHere(head) || !onlySetsUp(head)) return null; + if (runs.length !== 1 || !ranHere(head) || !(onlySetsUp(head) || startsNoRun(head))) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index bf6b17197f6..42840cc6e21 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -294,9 +294,12 @@ function scan(xml) { * first testsuite's case count, its seconds to the nearest one and as * written (`time`), how many cases failed or ended in an error, how many * were skipped (pytest counts them as cases, and an expected failure among - * the skipped), and the file of its first testcase, which pytest names in - * the family the option sets ("" where the head holds none). null for a head - * with no whole testsuite tag, no case or no time. */ + * the skipped), and the file and the class of its first testcase ("" where + * the head holds none). pytest names the file in the family the option sets: + * where the case is defined, which for a case a suite reads from a data file + * is that file. The class starts with the module of the test file that + * collected the case. null for a head with no whole testsuite tag, no case or + * no time. */ export function runCost(head) { const first = (text, name) => { try { @@ -313,13 +316,15 @@ export function runCost(head) { const seconds = Number(has.time); if (!Number.isInteger(tests) || tests < 1 || !has.time || !Number.isFinite(seconds) || seconds < 0) return null; const testcase = first(xml.slice(suite.end), "testcase"); + const named = testcase ? attributes(testcase.attrs) : {}; return { tests, seconds: Math.round(seconds), time: seconds, failed: (Number(has.failures) || 0) + (Number(has.errors) || 0), skipped: Number(has.skipped) || 0, - file: testcase ? attributes(testcase.attrs).file || "" : "", + file: named.file || "", + classname: named.classname || "", }; } From 0507b2ae80db6e30e279cc9e2bf5373a44bd5f1d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 21:48:06 +0530 Subject: [PATCH 04/52] test(plugin): a run in a group, in a shell a failed command ends, or in a quoted argument is no file run Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- .../claude-code-plugin/tests/test-cost.test.mjs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index c6ce5118352..3f43c514b5d 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -234,6 +234,9 @@ test("a run that follows commands which name no test runner is a file run", () = `cat >> src/parser.py <<'E'\nclass Finder:\n found = False\nE\ntimeout 590 python -m pytest -q ${FILE}`, `git checkout src/parser.py; sed -i 's/a/b/' src/parser.py; echo 'x = 1' >> /tmp/t.py; pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt`, `rm /tmp/ex.py; pytest ${FILE}`, + // A quote or a parenthesis left open in a script's own text is not the + // shell's, and the run's own quotes close. + `python - <<'E'\nprint("it's (")\nE\npytest ${FILE} -q | grep "passed"`, ]) { assert.deepEqual(fileRun(command), whole, command); } @@ -323,6 +326,17 @@ test("a command with two pytest runs, two paths, another selection or no run of `git diff --stat &&\npytest ${FILE}`, `cat /tmp/names.txt | pytest ${FILE}`, `sleep 600 & pytest ${FILE}`, + `git stash -q; (pytest ${FILE})`, + `git stash -q; (\npytest ${FILE})`, + // Or in a group that waits on an earlier command, or in a shell that a failed command ends. + `python /tmp/edit.py && (git diff --stat; pytest ${FILE})`, + `set -e\npython /tmp/edit.py\npython -m pytest -q ${FILE} 2>&1 | tail -5`, + `set -o errexit; python /tmp/edit.py; pytest ${FILE}`, + `if ! python /tmp/edit.py; then exit 1; fi; pytest ${FILE}`, + // Text in a quoted argument is no run. + `git commit -qm "parser: keep the prefix; python -m pytest ${FILE}"`, + `echo "source .venv/bin/activate; pytest ${FILE}" > check.sh`, + `echo 'git diff --stat; pytest ${FILE}' >> notes.txt`, // Quotes are not read: a `|` or a parenthesis in one ends the run's part there. `pytest ${FILE} -q 2>&1 | grep -E "passed|failed"`, `pytest ${FILE} -k "parse and (empty or nested)" -q`, From 1c550780ef30f8bd7825ed271a83029678dba299 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 21:48:07 +0530 Subject: [PATCH 05/52] A pytest run in a group, after `set -e` or `exit`, or in a quoted argument is no file run The rule for a run that follows other commands in its shell call read only the separator before the run. A run that never starts was then kept as one that outlives its call: where the shell ends at a failed command, where the run stands in a group that waits on an earlier command, and where the run is the text of a quoted argument. The text before the run now names nothing that ends the shell, and the run with what follows it closes no parenthesis and no quote it did not open. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/integrations/claude-code.md | 11 ++++- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 15 +++++-- .../claude-code-plugin/lib/test-cost.mjs | 4 +- .../claude-code-plugin/lib/test-gate.mjs | 40 ++++++++++++++----- integrations/codex-plugin/lib/test-cost.mjs | 4 +- integrations/codex-plugin/lib/test-gate.mjs | 40 ++++++++++++++----- 7 files changed, 83 insertions(+), 33 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 558d6845120..5bd39c57d6d 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1773,8 +1773,13 @@ session's private state, by the file: then that command's. What may stand before the run is `cd`, `export`, `source` and `.`, or the commands of a session that edits and then checks in one shell call, such as `sed -i 's/a/b/' src/parser.py; git diff --stat; pytest tests/test_big.py`: they name - no test runner, no `pytest` and no `||`, and `;` or a line's end stands before the - run's own command, not `&&`, `&`, a pipe or a parenthesis. + no test runner, no `pytest`, no `||` and nothing that ends the shell where a command + fails (`set -e`, `errexit`, `exit`), and `;` or a line's end stands before the run's + own command, not `&&`, `&`, a pipe or a parenthesis. The run and what follows it close + no parenthesis and no quote opened before them: a run in a group that waits on an + earlier command (`python edit.py && (git diff --stat; pytest tests/test_big.py)`) and + the text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`) count + as neither. The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the @@ -1894,6 +1899,8 @@ What it does not do: result file of a run put in the background at once, of two paths or another selection of the test file, told apart from the run of a later command that prints its saved summary and whose own run outlives the call; +- a run that never starts because the shell ends in a way the command's text does not + name, such as an `exec` before it, is kept as one that outlives its call; - the session keeps one run that outlives its call. A later one of another test file takes its place, and the earlier run is not counted. A later one of the same file and the other kind, whole after `-k` or `-k` after whole, drops both, since the earlier diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index da8a36f643c..a8c7266ff3c 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest` or `||` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after a hook last read the file: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, `||`, `set -e`, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end, or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after a hook last read the file: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 3a9545e4603..5aacda00f02 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1484,10 +1484,17 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that before the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or the commands of a session that edits and then checks in one shell call (an inline script, `git diff --stat`, `sed`): text that names no test - runner (`startsRunner`), no pytest and no `||`, with `;` or a line's - end before the run's own command, not `&&`, `&`, a pipe or a - parenthesis (`startsNoRun`). A script that starts pytest under another - name is not told apart. Quotes are not read, + runner (`startsRunner`), no pytest, no `||` and nothing that ends the + shell where a command fails (`set -e`, `errexit`, `exit`), with `;` or + a line's end before the run's own command, not `&&`, `&`, a pipe or a + parenthesis, and a run that with what follows it closes no parenthesis + and no quote opened before it (`startsNoRun`): a run in a group that + waits on an earlier command (`edit && (git diff; pytest )`) and + the text of a quoted argument (`git commit -m "fix; pytest "`) + are noted as nothing. The text before the run is not read for an open + quote or parenthesis: an inline script holds its own. A script that + starts pytest under another name is not told apart, nor is a shell + that ends another way (`exec`). Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 94aa8c49e82..867aaeb7521 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -103,8 +103,8 @@ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); - const folders = file.replace(/\.py$/, "").split("/"); - return folders.some((_, at) => `${cost.classname}.`.startsWith(`${folders.slice(at).join(".")}.`)); + const parts = file.replace(/\.py$/, "").split("/"); + return parts.some((_, at) => `${cost.classname}.`.startsWith(`${parts.slice(at).join(".")}.`)); } /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 53170b28e96..9934cb9d300 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1354,16 +1354,31 @@ const onlySetsUp = (head) => // runner (`startsRunner`: `make test`, `tox`, a `run_tests` script), no // pytest (`pytest.main` in an inline script) and no `||`, and the run does // not wait on what those commands returned: `;` or a line's end stands -// before its simple command, not `&&`, `&`, a pipe or a parenthesis. A -// script that starts pytest under another name is not told apart. The text -// is read once from the run backwards, so a long one (an inline script of -// blank lines) costs time in proportion to its length. -const startsNoRun = (head) => { +// before its simple command, not `&&`, `&` or a pipe, and the text names +// nothing that ends the shell where a command fails (`set -e`, `errexit`, +// `exit`). Nor does `tail`, the run and what follows it, close a parenthesis +// or a quote it did not open: the run is then in a group that may wait on an +// earlier command (`edit && (git diff; pytest )`), or is the text of a +// quoted argument (`git commit -m "fix; pytest "`). The text before the +// run is not read for either, since an inline script holds quotes and +// parentheses of its own. A script that starts pytest under another name is +// not told apart, nor is a shell that ends another way (`exec`). The text is +// read once from the run backwards, so a long one (an inline script of blank +// lines) costs time in proportion to its length. +const ENDS_SHELL = /\bset\s+-\w*e|errexit|\bexit\b/; +const startsNoRun = (head, tail) => { // What ends the command before the run's, and what stands before that. let end = head.length - head.split(/[;&|(\n]/).pop().length; if (!/[;\n]/.test(head[end - 1] || "")) return false; while (end > 0 && /[;\s]/.test(head[end - 1])) end -= 1; - return !/[&|(]/.test(head[end - 1] || "") && !/\|\||py\.?test/.test(head) && !startsRunner(head); + return ( + !/[&|]/.test(head[end - 1] || "") && + !/\|\||py\.?test/.test(head) && + !ENDS_SHELL.test(head) && + !startsRunner(head) && + !closesParen(tail) && + !['"', "'"].some((quote) => tail.split(quote).length % 2 === 0) + ); }; /** True when the output holds a whole pytest summary for each of `runs` @@ -1447,8 +1462,9 @@ const counted = (line, kinds) => * (`make test; pytest `, `python edit.py && pytest `): the last * line and the result file are then that command's. What may stand before * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or commands - * that name no test runner and are followed by `;` or a line's end - * (`startsNoRun`). + * that name no test runner and nothing that ends the shell, and are followed + * by `;` or a line's end, before a run that closes no parenthesis and no + * quote of theirs (`startsNoRun`). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1472,11 +1488,13 @@ export function fileRun(command, output = "") { .replace(/\\\n/g, "") .replace(/\d?>&\d/g, " "); const runs = [...text.matchAll(PYTEST)]; - const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; - if (runs.length !== 1 || !ranHere(head) || !(onlySetsUp(head) || startsNoRun(head))) return null; + if (runs.length !== 1) return null; + const head = text.slice(0, runs[0].index); + const tail = text.slice(runs[0].index); + if (!ranHere(head) || !(onlySetsUp(head) || startsNoRun(head, tail))) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. - if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; + if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; const cd = [...head.matchAll(CD)]; const followed = cd.length < 2 && diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 94aa8c49e82..867aaeb7521 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -103,8 +103,8 @@ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); - const folders = file.replace(/\.py$/, "").split("/"); - return folders.some((_, at) => `${cost.classname}.`.startsWith(`${folders.slice(at).join(".")}.`)); + const parts = file.replace(/\.py$/, "").split("/"); + return parts.some((_, at) => `${cost.classname}.`.startsWith(`${parts.slice(at).join(".")}.`)); } /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 53170b28e96..9934cb9d300 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1354,16 +1354,31 @@ const onlySetsUp = (head) => // runner (`startsRunner`: `make test`, `tox`, a `run_tests` script), no // pytest (`pytest.main` in an inline script) and no `||`, and the run does // not wait on what those commands returned: `;` or a line's end stands -// before its simple command, not `&&`, `&`, a pipe or a parenthesis. A -// script that starts pytest under another name is not told apart. The text -// is read once from the run backwards, so a long one (an inline script of -// blank lines) costs time in proportion to its length. -const startsNoRun = (head) => { +// before its simple command, not `&&`, `&` or a pipe, and the text names +// nothing that ends the shell where a command fails (`set -e`, `errexit`, +// `exit`). Nor does `tail`, the run and what follows it, close a parenthesis +// or a quote it did not open: the run is then in a group that may wait on an +// earlier command (`edit && (git diff; pytest )`), or is the text of a +// quoted argument (`git commit -m "fix; pytest "`). The text before the +// run is not read for either, since an inline script holds quotes and +// parentheses of its own. A script that starts pytest under another name is +// not told apart, nor is a shell that ends another way (`exec`). The text is +// read once from the run backwards, so a long one (an inline script of blank +// lines) costs time in proportion to its length. +const ENDS_SHELL = /\bset\s+-\w*e|errexit|\bexit\b/; +const startsNoRun = (head, tail) => { // What ends the command before the run's, and what stands before that. let end = head.length - head.split(/[;&|(\n]/).pop().length; if (!/[;\n]/.test(head[end - 1] || "")) return false; while (end > 0 && /[;\s]/.test(head[end - 1])) end -= 1; - return !/[&|(]/.test(head[end - 1] || "") && !/\|\||py\.?test/.test(head) && !startsRunner(head); + return ( + !/[&|]/.test(head[end - 1] || "") && + !/\|\||py\.?test/.test(head) && + !ENDS_SHELL.test(head) && + !startsRunner(head) && + !closesParen(tail) && + !['"', "'"].some((quote) => tail.split(quote).length % 2 === 0) + ); }; /** True when the output holds a whole pytest summary for each of `runs` @@ -1447,8 +1462,9 @@ const counted = (line, kinds) => * (`make test; pytest `, `python edit.py && pytest `): the last * line and the result file are then that command's. What may stand before * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or commands - * that name no test runner and are followed by `;` or a line's end - * (`startsNoRun`). + * that name no test runner and nothing that ends the shell, and are followed + * by `;` or a line's end, before a run that closes no parenthesis and no + * quote of theirs (`startsNoRun`). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1472,11 +1488,13 @@ export function fileRun(command, output = "") { .replace(/\\\n/g, "") .replace(/\d?>&\d/g, " "); const runs = [...text.matchAll(PYTEST)]; - const head = runs.length === 1 ? text.slice(0, runs[0].index) : ""; - if (runs.length !== 1 || !ranHere(head) || !(onlySetsUp(head) || startsNoRun(head))) return null; + if (runs.length !== 1) return null; + const head = text.slice(0, runs[0].index); + const tail = text.slice(runs[0].index); + if (!ranHere(head) || !(onlySetsUp(head) || startsNoRun(head, tail))) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. - if (!onlyRuns(text.slice(runs[0].index).replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; + if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; const cd = [...head.matchAll(CD)]; const followed = cd.length < 2 && From dcf47956ffea827b65b38695fdc37c147a11013d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 22:13:46 +0530 Subject: [PATCH 06/52] test(plugin): a `set` whose `-e` is not its first flag word is no file run `set -u -e` and `set -o pipefail -e` before the run end the shell at a failed command as `set -e` does. A `set` with no `-e`, and the word in a script's text, do not. `aged` drops a branch no test takes: every noted command writes the cost state. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../claude-code-plugin/tests/test-cost.test.mjs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 3f43c514b5d..3a8bcbd13c5 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -237,6 +237,10 @@ test("a run that follows commands which name no test runner is a file run", () = // A quote or a parenthesis left open in a script's own text is not the // shell's, and the run's own quotes close. `python - <<'E'\nprint("it's (")\nE\npytest ${FILE} -q | grep "passed"`, + // A `set` with no `-e` among its flags ends no shell, and neither does + // the word in a script's text. + `set -u; sed -i 's/a/b/' src/parser.py; pytest ${FILE}`, + `python - <<'E'\n# set the per-file limit\nE\npytest ${FILE}`, ]) { assert.deepEqual(fileRun(command), whole, command); } @@ -248,7 +252,8 @@ test("a run that follows commands which name no test runner is a file run", () = // that, 80,000 blank lines cost seconds of CPU. const before = process.cpuUsage(); assert.deepEqual(fileRun(`${"x = 1\n".repeat(20000)}pytest ${FILE}`), whole); - for (const filler of ["\n", " \n", " ", "; ", "&& ", "cd a\n"]) fileRun(`${filler.repeat(80000)}pytest ${FILE}`); + for (const filler of ["\n", " \n", " ", "; ", "&& ", "cd a\n", "set "]) + fileRun(`${filler.repeat(80000)}pytest ${FILE}`); assert.ok(process.cpuUsage(before).user < 2e6); }); @@ -332,6 +337,8 @@ test("a command with two pytest runs, two paths, another selection or no run of `python /tmp/edit.py && (git diff --stat; pytest ${FILE})`, `set -e\npython /tmp/edit.py\npython -m pytest -q ${FILE} 2>&1 | tail -5`, `set -o errexit; python /tmp/edit.py; pytest ${FILE}`, + `set -u -e\npython /tmp/edit.py\npython -m pytest -q ${FILE} 2>&1 | tail -5`, + `set -o pipefail -e; python /tmp/edit.py; pytest ${FILE}`, `if ! python /tmp/edit.py; then exit 1; fi; pytest ${FILE}`, // Text in a quoted argument is no run. `git commit -qm "parser: keep the prefix; python -m pytest ${FILE}"`, @@ -534,7 +541,6 @@ const runs = () => noted(sessionStatePath("test-cost", SESSION)); function aged(ms) { const file = sessionStatePath("test-cost", SESSION); const state = readJsonFile(file, null); - if (!state) return; if (state.pending) state.pending.at -= ms; if (state.dropped) state.dropped -= ms; if (state.read) state.read -= ms; From 51892668333faaf49b0811f499f705c6d3eaf0c0 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 22:18:32 +0530 Subject: [PATCH 07/52] A `set` with `-e` in any of its flag words before a pytest run is no file run `set -u -e` and `set -o pipefail -e` end the shell at a failed command, and the run after them may never start. The flag is read in any word of the `set` command, within 64 characters of it, so a long line is still read in linear time. The limit for a command that starts pytest under no runner's name names the case the rule reaches: the run after it outlives its call. After `;` or a line's end the run always starts. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 9 +++--- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 5 +-- .../claude-code-plugin/lib/test-gate.mjs | 32 ++++++++++--------- integrations/codex-plugin/lib/test-gate.mjs | 32 ++++++++++--------- 5 files changed, 43 insertions(+), 37 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 5bd39c57d6d..d8ca31e8179 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1774,8 +1774,9 @@ session's private state, by the file: or the commands of a session that edits and then checks in one shell call, such as `sed -i 's/a/b/' src/parser.py; git diff --stat; pytest tests/test_big.py`: they name no test runner, no `pytest`, no `||` and nothing that ends the shell where a command - fails (`set -e`, `errexit`, `exit`), and `;` or a line's end stands before the run's - own command, not `&&`, `&`, a pipe or a parenthesis. The run and what follows it close + fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and + `set -u -e`), and `;` or a line's end stands before the run's own command, not `&&`, + `&`, a pipe or a parenthesis. The run and what follows it close no parenthesis and no quote opened before them: a run in a group that waits on an earlier command (`python edit.py && (git diff --stat; pytest tests/test_big.py)`) and the text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`) count @@ -1894,8 +1895,8 @@ What it does not do: - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not; - a command before the run that starts pytest under no runner's name, such as a script - of the repository, is not told apart from an edit: where the run after it does not - start, the script's result file and summary line are counted as the run's. Nor is the + of the repository, is not told apart from an edit: where the run after it outlives its + call, the script's result file and summary line are counted as the run's. Nor is the result file of a run put in the background at once, of two paths or another selection of the test file, told apart from the run of a later command that prints its saved summary and whose own run outlives the call; diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index a8c7266ff3c..2648f4a09b0 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, `||`, `set -e`, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end, or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after a hook last read the file: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, `||`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end, or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after a hook last read the file: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 5aacda00f02..e36a0db2788 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1485,8 +1485,9 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that the commands of a session that edits and then checks in one shell call (an inline script, `git diff --stat`, `sed`): text that names no test runner (`startsRunner`), no pytest, no `||` and nothing that ends the - shell where a command fails (`set -e`, `errexit`, `exit`), with `;` or - a line's end before the run's own command, not `&&`, `&`, a pipe or a + shell where a command fails (`exit`, `errexit`, a `set` with `-e` + among its flags, as `set -e` and `set -u -e`), with `;` or a line's + end before the run's own command, not `&&`, `&`, a pipe or a parenthesis, and a run that with what follows it closes no parenthesis and no quote opened before it (`startsNoRun`): a run in a group that waits on an earlier command (`edit && (git diff; pytest )`) and diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 9934cb9d300..646b9ec332e 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1350,22 +1350,24 @@ const onlySetsUp = (head) => // in one shell call (an inline script, `git diff --stat`, `sed`), where none // can pass for the run: a command that starts pytest itself prints a last // line and writes the result file, and both are read as the run's where the -// run did not start or wrote none. So the text before the run names no test -// runner (`startsRunner`: `make test`, `tox`, a `run_tests` script), no -// pytest (`pytest.main` in an inline script) and no `||`, and the run does -// not wait on what those commands returned: `;` or a line's end stands -// before its simple command, not `&&`, `&` or a pipe, and the text names -// nothing that ends the shell where a command fails (`set -e`, `errexit`, -// `exit`). Nor does `tail`, the run and what follows it, close a parenthesis -// or a quote it did not open: the run is then in a group that may wait on an -// earlier command (`edit && (git diff; pytest )`), or is the text of a -// quoted argument (`git commit -m "fix; pytest "`). The text before the -// run is not read for either, since an inline script holds quotes and -// parentheses of its own. A script that starts pytest under another name is -// not told apart, nor is a shell that ends another way (`exec`). The text is -// read once from the run backwards, so a long one (an inline script of blank +// run outlives its call. So the text before the run names no test runner +// (`startsRunner`: `make test`, `tox`, a `run_tests` script), no pytest +// (`pytest.main` in an inline script) and no `||`, and the run does not wait +// on what those commands returned: `;` or a line's end stands before its +// simple command, not `&&`, `&` or a pipe, and the text names nothing that +// ends the shell where a command fails: `exit`, `errexit`, or a `set` with +// `-e` in any of its flag words (`set -u -e`), read within 64 characters of +// the `set` so that a long line costs time in proportion to its length. Nor +// does `tail`, the run and what follows it, close a parenthesis or a quote it +// did not open: the run is then in a group that may wait on an earlier +// command (`edit && (git diff; pytest )`), or is the text of a quoted +// argument (`git commit -m "fix; pytest "`). The text before the run is +// not read for either, since an inline script holds quotes and parentheses +// of its own. A script that starts pytest under another name is not told +// apart, nor is a shell that ends another way (`exec`). The text is read +// once from the run backwards, so a long one (an inline script of blank // lines) costs time in proportion to its length. -const ENDS_SHELL = /\bset\s+-\w*e|errexit|\bexit\b/; +const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; const startsNoRun = (head, tail) => { // What ends the command before the run's, and what stands before that. let end = head.length - head.split(/[;&|(\n]/).pop().length; diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 9934cb9d300..646b9ec332e 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1350,22 +1350,24 @@ const onlySetsUp = (head) => // in one shell call (an inline script, `git diff --stat`, `sed`), where none // can pass for the run: a command that starts pytest itself prints a last // line and writes the result file, and both are read as the run's where the -// run did not start or wrote none. So the text before the run names no test -// runner (`startsRunner`: `make test`, `tox`, a `run_tests` script), no -// pytest (`pytest.main` in an inline script) and no `||`, and the run does -// not wait on what those commands returned: `;` or a line's end stands -// before its simple command, not `&&`, `&` or a pipe, and the text names -// nothing that ends the shell where a command fails (`set -e`, `errexit`, -// `exit`). Nor does `tail`, the run and what follows it, close a parenthesis -// or a quote it did not open: the run is then in a group that may wait on an -// earlier command (`edit && (git diff; pytest )`), or is the text of a -// quoted argument (`git commit -m "fix; pytest "`). The text before the -// run is not read for either, since an inline script holds quotes and -// parentheses of its own. A script that starts pytest under another name is -// not told apart, nor is a shell that ends another way (`exec`). The text is -// read once from the run backwards, so a long one (an inline script of blank +// run outlives its call. So the text before the run names no test runner +// (`startsRunner`: `make test`, `tox`, a `run_tests` script), no pytest +// (`pytest.main` in an inline script) and no `||`, and the run does not wait +// on what those commands returned: `;` or a line's end stands before its +// simple command, not `&&`, `&` or a pipe, and the text names nothing that +// ends the shell where a command fails: `exit`, `errexit`, or a `set` with +// `-e` in any of its flag words (`set -u -e`), read within 64 characters of +// the `set` so that a long line costs time in proportion to its length. Nor +// does `tail`, the run and what follows it, close a parenthesis or a quote it +// did not open: the run is then in a group that may wait on an earlier +// command (`edit && (git diff; pytest )`), or is the text of a quoted +// argument (`git commit -m "fix; pytest "`). The text before the run is +// not read for either, since an inline script holds quotes and parentheses +// of its own. A script that starts pytest under another name is not told +// apart, nor is a shell that ends another way (`exec`). The text is read +// once from the run backwards, so a long one (an inline script of blank // lines) costs time in proportion to its length. -const ENDS_SHELL = /\bset\s+-\w*e|errexit|\bexit\b/; +const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; const startsNoRun = (head, tail) => { // What ends the command before the run's, and what stands before that. let end = head.length - head.split(/[;&|(\n]/).pop().length; From 9a612877b6300d8e4b530e4e648d0e00215b944c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 22:47:14 +0530 Subject: [PATCH 08/52] test(plugin): an earlier call's run is no later command's, and an `||` list before a run is no refusal Three cases fail here. A command that names no test runner starts the suite and saves its output; the report's hook is not loaded for it. The next command prints the saved last line and starts a run of one file that outlives the call: the suite's report is counted as that file's whole run. `git stash pop -q || true; pytest ` is refused, though the run starts whatever the list returned. `git diff --stat &&` at a line's end, a comment line, then the run is taken for a run that always starts. The linear-time case puts each filler after a command that is no set-up, so the text is read as commands that start no run. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../tests/test-cost.test.mjs | 60 ++++++++++++++++--- 1 file changed, 53 insertions(+), 7 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 3a8bcbd13c5..81c18819778 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -234,6 +234,9 @@ test("a run that follows commands which name no test runner is a file run", () = `cat >> src/parser.py <<'E'\nclass Finder:\n found = False\nE\ntimeout 590 python -m pytest -q ${FILE}`, `git checkout src/parser.py; sed -i 's/a/b/' src/parser.py; echo 'x = 1' >> /tmp/t.py; pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt`, `rm /tmp/ex.py; pytest ${FILE}`, + // The run starts whatever a command before it returned, an `||` list too. + `git stash pop -q || true; pytest ${FILE}`, + `git diff --quiet || git stash -q\npython -m pytest -q ${FILE} 2>&1 | tail -5`, // A quote or a parenthesis left open in a script's own text is not the // shell's, and the run's own quotes close. `python - <<'E'\nprint("it's (")\nE\npytest ${FILE} -q | grep "passed"`, @@ -248,12 +251,21 @@ test("a run that follows commands which name no test runner is a file run", () = assert.deepEqual(fileRun(`cd pkg && git stash -q; pytest ${FILE} -k parse`), { ...whole, dir: "pkg", whole: false }); // The last line of the output is the run's where the run ended in the call. assert.equal(fileRun(`${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -3`, WHOLE_OUTPUT).seconds, 140.21); + // A comment before the run is no command. + assert.deepEqual(fileRun(`git diff --stat\n# check the edit\npytest ${FILE}`), whole); + assert.deepEqual(fileRun(`git diff --stat; # check the edit\npytest ${FILE}`), whole); // A long text before the run is read in time linear in its length: without - // that, 80,000 blank lines cost seconds of CPU. + // that, 80,000 blank lines cost seconds of CPU. Each filler stands after a + // command that is no set-up, so the text is read as commands that start no + // run: back from the run over the separators and the comments, and forward + // for a `set`. const before = process.cpuUsage(); assert.deepEqual(fileRun(`${"x = 1\n".repeat(20000)}pytest ${FILE}`), whole); - for (const filler of ["\n", " \n", " ", "; ", "&& ", "cd a\n", "set "]) - fileRun(`${filler.repeat(80000)}pytest ${FILE}`); + for (const filler of ["\n", " \n", " ", "; ", "set ", "# \n", "#"]) + assert.deepEqual(fileRun(`git status\n${filler.repeat(80000)}\npytest ${FILE}`), whole, JSON.stringify(filler)); + assert.equal(fileRun(`git status\n${"& ".repeat(80000)}\npytest ${FILE}`), null); + // And from the command's start, for the folder of a `cd`. + for (const filler of ["\n", " \n", "cd a\n"]) fileRun(`${filler.repeat(80000)}pytest ${FILE}`); assert.ok(process.cpuUsage(before).user < 2e6); }); @@ -325,10 +337,16 @@ test("a command with two pytest runs, two paths, another selection or no run of `python -c "import pytest; pytest.main(['tests'])"; python -m pytest ${FILE}`, `pip install -U pytest; pytest ${FILE}`, `rm -rf .pytest_cache; pytest ${FILE}`, - // The run may not start after `||`, or where `&&`, `&` or a pipe joins it to a command that is no set-up. - `git stash pop -q || true; pytest ${FILE}`, + // The run may not start where `&&`, `||`, `&` or a pipe joins it to a command that is no set-up, + // on the run's line or at the end of the line before it, with or without a comment between them. `python /tmp/edit.py && pytest ${FILE}`, + `python /tmp/edit.py || pytest ${FILE}`, `git diff --stat &&\npytest ${FILE}`, + `python /tmp/edit.py ||\npytest ${FILE}`, + `git diff --stat &&\n# check the edit\npytest ${FILE}`, + `python /tmp/edit.py ||\n # check the edit\n\npytest ${FILE}`, + `git diff --stat && # check the edit\npytest ${FILE}`, + `cat /tmp/names.txt |\n# the names\npytest ${FILE}`, `cat /tmp/names.txt | pytest ${FILE}`, `sleep 600 & pytest ${FILE}`, `git stash -q; (pytest ${FILE})`, @@ -1123,8 +1141,7 @@ function run(script, event, env, payload) { } /** The launcher after a shell command of the session whose pytest wrote `xml`. */ -function afterCommand(box, command, output, xml, extra) { - rested(box.runs); +function afterCall(box, command, output, xml, extra) { if (xml !== undefined) fs.writeFileSync(box.report, xml); return run("loom-record.mjs", "PostToolUse", box.env(extra), { cwd: box.cwd, @@ -1133,6 +1150,11 @@ function afterCommand(box, command, output, xml, extra) { tool_response: { stdout: output, stderr: "" }, }); } +/** The same, a day after the session's last shell command. */ +function afterCommand(box, command, output, xml, extra) { + rested(box.runs); + return afterCall(box, command, output, xml, extra); +} const endSession = (box, extra) => run("loom-record.mjs", "SessionEnd", box.env(extra), { cwd: box.cwd, reason: "exit" }); @@ -1219,6 +1241,30 @@ test("a whole run of a data-driven file that follows an edit in its shell call i assert.equal(server.sent("memory.set")[0].body.value, claim(REPO, { path: FILE, tests: 8000, seconds: 140 })); }); +test("the report of a run that a command naming no test runner started is not a later command's", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + await ask(box); + // A recipe runs the suite and saves its output: 9,000 cases in 300 s, the + // first of them in the file. Its command names no test runner, so the + // report's hook is not loaded for it and the report stays unread. + const recipe = "just check 2>&1 | tee /tmp/out.txt"; + const suite = report({ tests: 9000, time: "300.1" }); + // A session that hands nothing to memory notes nothing of the call. + await afterCall(box, recipe, "9000 passed in 300.12s", suite, { LOOM_SESSION_MEMORY: "off" }); + assert.equal(fs.existsSync(box.runs), false); + await afterCall(box, recipe, "9000 passed in 300.12s", suite); + // The next command prints the saved last line and starts a run of the file + // that outlives the call: the report read with it is the suite's. + await afterCall(box, `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} 2>&1 | tail -5`, "9000 passed in 300.12s"); + assert.deepEqual(noted(box.runs), {}); + await endSession(box); + await settled(box); + assert.deepEqual(server.sent("memory.set"), []); +}); + test("a session whose prompts read no row stores nothing", { skip: WINDOWS }, async (t) => { const server = await loom(t); const box = sandbox(t, server); From 6dd3146ddd347262f418e0e53b2067c482dc7ded Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 23:07:12 +0530 Subject: [PATCH 09/52] A report is a command's own when its run began after any earlier shell call, and an `||` list before a run is no refusal The cost state kept the time the report's hook last ran, and that hook is loaded only for a command that names a test runner. A recipe that starts the suite under no runner's name left its report unread, with no time noted: a later command that printed the saved last line before a run of one file that outlived the call got the suite's cases and seconds stored as that file's whole run. The launcher notes the time of each shell call the report's hook is not loaded for (`noteCall`), in a session that has the report and hands to memory, so the state holds the return of the session's last shell call (`returned`). `startsNoRun` refused `||` anywhere before the run. What decides whether the run starts is the operator that ends the command before it: `git stash pop -q || true; pytest ` always starts the run. The operator is read at the end of the last line before the run that is no comment, with a comment after it aside, so `git diff --stat &&`, a comment line, then the run is no file run, as the shell reads it. Two comment paragraphs in lib/test-cost.mjs are rewrapped. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 24 +++--- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 31 ++++--- .../claude-code-plugin/hooks/loom-record.mjs | 23 +++++- .../claude-code-plugin/lib/test-cost.mjs | 73 ++++++++++------- .../claude-code-plugin/lib/test-gate.mjs | 53 +++++++----- .../tests/test-cost.test.mjs | 80 +++++++++++++------ .../codex-plugin/hooks/loom-record.mjs | 23 +++++- integrations/codex-plugin/lib/test-cost.mjs | 73 ++++++++++------- integrations/codex-plugin/lib/test-gate.mjs | 53 +++++++----- 10 files changed, 288 insertions(+), 147 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index d8ca31e8179..1efffb38ab0 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1773,11 +1773,14 @@ session's private state, by the file: then that command's. What may stand before the run is `cd`, `export`, `source` and `.`, or the commands of a session that edits and then checks in one shell call, such as `sed -i 's/a/b/' src/parser.py; git diff --stat; pytest tests/test_big.py`: they name - no test runner, no `pytest`, no `||` and nothing that ends the shell where a command - fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and - `set -u -e`), and `;` or a line's end stands before the run's own command, not `&&`, - `&`, a pipe or a parenthesis. The run and what follows it close - no parenthesis and no quote opened before them: a run in a group that waits on an + no test runner, no `pytest` and nothing that ends the shell where a command fails + (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), + and `;` or a line's end stands before the run's own command, not `&&`, `||`, `&`, a + pipe or a parenthesis. A line's end after `&&`, `||`, `&` or a pipe joins the run to + that command too, with or without a comment between them (`git diff --stat &&` on the + line above the run). A list that ended before the run decides nothing: + `git stash pop || true; pytest tests/test_big.py` counts. The run and what follows it + close no parenthesis and no quote opened before them: a run in a group that waits on an earlier command (`python edit.py && (git diff --stat; pytest tests/test_big.py)`) and the text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`) count as neither. @@ -1785,14 +1788,17 @@ session's private state, by the file: The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the seconds within a second, or a twentieth of them), the file's first case is in the test -file the command names, and the run that wrote the file began after a hook last read it. +file the command names, and the run that wrote the file began after the session's +previous shell call returned. The seconds alone do not tell two short runs apart: a run that wrote no file, such as one that sets its own `PYTEST_ADDOPTS`, is read with the file an earlier run left. Nor does the summary line where a command before the run printed it: `tail -5 out.txt; pytest tests/test_big.py` shows the summary of the run that wrote `out.txt`, and where its own run outlives the call, the result file read with it is that -earlier run's. That run began before the hook's last read, and the command's own run -after it. +earlier run's. That run began before the previous shell call returned, and the +command's own run after it. The time is noted after every shell call of a session that +has the test report, one that names no test runner too: a recipe or a script may start +pytest. A case that a data-driven suite reads from a data file names that file in the result file, not the test file that collected it. Such a case is in the command's test file @@ -1889,7 +1895,7 @@ What it does not do: session's start removes the state files untouched for a day. The row is written when a bug report reads it and not again: once it is removed, the session stores nothing unless a later bug report reads the row again. What the session noted of its runs goes - a day after its last shell command that names a test runner. A session that runs no + a day after its last shell command. A session that runs no pytest for a day has no test report after that: its bug reports read no row and print no line, and its runs are not noted; - a run that outlives its shell call is noted when it began before that call returned: a diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 2648f4a09b0..eb5dda665f4 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, `||`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end, or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after a hook last read the file: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too), or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after the session's previous shell call returned: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index e36a0db2788..a5101019f69 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -159,7 +159,7 @@ receives on stdout. | 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, 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 that loads no test report, it notes the call's time in the session's cost state | 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` | @@ -1484,15 +1484,20 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that before the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or the commands of a session that edits and then checks in one shell call (an inline script, `git diff --stat`, `sed`): text that names no test - runner (`startsRunner`), no pytest, no `||` and nothing that ends the + runner (`startsRunner`), no pytest and nothing that ends the shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), with `;` or a line's - end before the run's own command, not `&&`, `&`, a pipe or a - parenthesis, and a run that with what follows it closes no parenthesis + end before the run's own command, not `&&`, `||`, `&`, a pipe or a + parenthesis, no `&&`, `||`, `&` or pipe at the end of the last line + before it that is no comment, a comment after the operator aside + (`edit &&`, then `# check`, then the run), and a run that with what + follows it closes no parenthesis and no quote opened before it (`startsNoRun`): a run in a group that waits on an earlier command (`edit && (git diff; pytest )`) and the text of a quoted argument (`git commit -m "fix; pytest "`) - are noted as nothing. The text before the run is not read for an open + are noted as nothing. A list that ended before the run decides + nothing: `git stash pop || true; pytest ` is a run. The text + before the run is not read for an open quote or parenthesis: an inline script holds its own. A script that starts pytest under another name is not told apart, nor is a shell that ends another way (`exec`). Quotes are not read, @@ -1520,17 +1525,21 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that pytest's summary line with the cases, the failures and the seconds the report holds, the seconds within a second or a twentieth of them, the report's first case is in the file the command names, and the run - that wrote the report began after a hook last read the report: a run + that wrote the report began after the session's previous shell call + returned: a run the option did not reach writes no report, and the one read after it is an earlier run's, which the seconds of two short runs do not tell apart. Nor does the line where a command before the run printed it: `tail -5 out.txt; pytest ` shows the last line of the run that wrote `out.txt`, and where its own run outlives the call, the report read with it is that earlier run's too. That run began before the - hook's last read, which the state keeps for every command the hook - runs after, and the command's own run after it. A run put in the - background at once begins after its own command's hook, and is not - told apart that way. The first case is in the file where its `file` + previous shell call returned, and the command's own run after it. + The state keeps that time for every shell call of a session that has + the report: the hook notes it for a command it runs after, and + `loom-record` for any other (`noteCall`), since a command that names + no test runner may start pytest too (a recipe, a script). A run put + in the background at once begins after its own call returned, and is + not told apart that way. The first case is in the file where its `file` attribute names it from pytest's root. A case that a data-driven suite reads from a data file names that file, which is no Python file: it is in the file where its `classname` is under the file's module (`ofFile` @@ -1628,7 +1637,7 @@ about s.` The write revises the row the session read (`if_match_sha256`), files, at any session's start a day after their last write. The row is written when a bug report reads it and not again: once it is gone, the session stores nothing unless a later bug report reads the row - again. The runs go a day after the hook last ran. A session + again. The runs go a day after the session's last shell command. A session whose report state went that way (**The file's end**, above) reads no row, prints no line and notes no run. - LOOM_TEST_REPORT=off, or the `test_report` option set to false, stops diff --git a/integrations/claude-code-plugin/hooks/loom-record.mjs b/integrations/claude-code-plugin/hooks/loom-record.mjs index a98ac53f6db..f5a93736fb7 100644 --- a/integrations/claude-code-plugin/hooks/loom-record.mjs +++ b/integrations/claude-code-plugin/hooks/loom-record.mjs @@ -56,8 +56,9 @@ // (`planeEnabled`, `promptPointersMode`, `promptRecallMode`, `gateMode`); the // launcher reads the planes and switches of the scripts the host waits for // (WAITED) only to leave one unloaded. What the launcher does itself 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. +// 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, and noting +// the time of a shell call the test report is not read for. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -119,6 +120,23 @@ const TEST_REPORT = { showsRefusal(visibleOutput(payload), reportPath(payload.session_id)), }; +/** Note the time a shell call of `payload` returned for which the test + * report's script is not loaded, where that script would note what a run + * cost (its tool, its planes and switches, and memory's). The script counts + * a report for a command only when the report's run began after the + * session's last shell call returned (lib/test-cost.mjs), and a command that + * names no test runner may start pytest too: a recipe, a script. */ +async function noteShellCall(payload) { + const { tools, planes, on } = TEST_REPORT; + if (!matchesTool(tools, payload.tool_name || "") || !planes.every((plane) => planeEnabled(plane)) || !on()) return; + if (!planeEnabled("memory") || !envSwitch("LOOM_SESSION_MEMORY", true)) return; + try { + (await import("../lib/test-cost.mjs")).noteCall(payload.session_id); + } catch { + /* not noted: the hook still records and answers */ + } +} + /** The scripts whose answer the host waits for, in the order their answers * are joined: they run in the hook. `tools` is the matcher a script has as a * hook of its own, read as Claude Code reads one (names take the whole tool @@ -259,6 +277,7 @@ async function hook(script, event, client) { if (event === "UserPromptSubmit") keepBegin(payload); spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` }); } + if (WAITED[event]?.includes(TEST_REPORT) && !rows.includes(TEST_REPORT)) await noteShellCall(payload); const answer = waited ? mergedAnswer(event, await waited) : null; // Exits itself: a host that never closes stdin would hold the process open. if (answer) printHookAnswer(answer, () => process.exit(0)); diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 867aaeb7521..3604f07b084 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -11,14 +11,16 @@ // whole run that passed and its latest runs filtered with -k. Other commands // may stand before the run in its shell call, and may print the last line of // a run that ended earlier: a report is the command's only when its run began -// after the hook last read the file. A run that -// outlives its shell call writes the file after that call's hook ran: a -// report read later is its when pytest began the run that wrote it before -// that call returned, and the launcher reads the file once more before it -// removes it at the session's end (`settleRun`). The file is one a session: a -// pytest run that ends before a hook read it replaces it, and the session's -// start after a compaction empties it (`startReport`). The run that outlived -// its call is then not counted. +// after the session's previous shell call returned. A command that names no +// test runner may start pytest too, and the report is not read for it: the +// launcher notes the time of such a call (`noteCall`). A run that outlives +// its shell call writes the file after that call's hook ran: a report read +// later is its when pytest began the run that wrote it before that call +// returned, and the launcher reads the file once more before it removes it at +// the session's end (`settleRun`). The file is one a session: a pytest run +// that ends before a hook read it replaces it, and the session's start after +// a compaction empties it (`startReport`). The run that outlived its call is +// then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -56,9 +58,10 @@ const MAX_PATH = 160; const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, dropped, read, files }`, by each file's +// The session's runs: `{ pending, dropped, returned, files }`, by each file's // absolute path. `dropped` is the time by which a run that lost its place as -// the pending one had begun, and `read` the time a hook last read the report. +// the pending one had begun, and `returned` the time the session's last shell +// call returned, as its hook saw it. 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 @@ -145,13 +148,14 @@ const beganAt = (report, cost) => report.mtimeMs - cost.time * 1000; /** Count `report` (`newReport`) for the session's pending run, and say * whether it was that run's: its first case is in the run's file (`ofFile`) * and the run that wrote it began before the pending run's command - * returned (`beganAt`). A command that came later, whatever it is and whether or - * not a hook saw it, began its run after that. A run of the file that - * something else started while the pending run was in its call began before - * it too: its report, read with a command that is not that run, is taken - * for the pending run's. A run that began by the time an earlier pending - * run had (`dropped`) may be that run, whose report is no later run's. The - * pending run is then settled; any other report leaves it pending. */ + * returned (`beganAt`). A command that came later, whatever it is and + * whether or not a hook saw it, began its run after that. A run of the file + * that something else started while the pending run was in its call began + * before it too: its report, read with a command that is not that run, is + * taken for the pending run's. A run that began by the time an earlier + * pending run had (`dropped`) may be that run, whose report is no later + * run's. The pending run is then settled; any other report leaves it + * pending. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; const pending = state.pending; @@ -176,14 +180,16 @@ function settle(state, report) { * a command before the run printed it: one that reads the output an earlier * run saved (`tail -5 out.txt; pytest `) shows that run's last line, * and where its own run outlives the call, the report read is that run's - * too. So the report's run began after the hook last read the report - * (`read`), as the command did: a run that began before it was started by an - * earlier command. Every call notes that time, a command with no file run - * too. A run put in the background at once begins after its own call's hook, - * and is not told apart from a later command's. Any other report is the - * pending run's when it is of that run's file and its run began by the time - * the run's command returned (`settle`), and no run's otherwise. So a run - * that was put in the background before pytest began is not counted. + * too. So the report's run began after the session's previous shell call + * returned (`returned`), as the command did: a run that began before that + * was started by an earlier command. Every shell call notes its time: one + * the report is read for here, a command with no file run too, and any + * other in the launcher (`noteCall`). A run put in the background at once + * begins after its own call returned, and is not told apart from a later + * command's. Any other report is the pending run's when it is of that run's + * file and its run began by the time the run's command returned (`settle`), + * and no run's otherwise. So a run that was put in the background before + * pytest began is not counted. * * A run whose output shows no summary may not have ended: it is kept as the * session's pending run, with the time its command returned. It is taken @@ -211,7 +217,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && - beganAt(report, cost) > (state.read ?? 0) && + beganAt(report, cost) > (state.returned ?? 0) && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); @@ -227,13 +233,26 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { else if (pending && pending.file !== run.file) state.dropped = pending.at; state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } - state.read = Date.now(); + state.returned = Date.now(); writeSessionState(RUNS, sessionId, state); } catch { /* nothing noted */ } } +/** Note the time a shell call of the session returned whose report is not + * read: `noteCommand` notes it for the others, and counts a report for a + * command only when its run began after that. A session with no test + * report has no run to tell from another, and keeps no state. */ +export function noteCall(sessionId) { + try { + if (!sessionId || !seenReport(sessionId)) return; + writeSessionState(RUNS, sessionId, { ...readSessionState(RUNS, sessionId), returned: Date.now() }); + } catch { + /* nothing noted */ + } +} + /** At the session's end, before its report is removed: a report written * since the session's last read is counted for the pending run (`settle`). * One bounded read of the session's own file, and no token is read. */ diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 646b9ec332e..873d3cd6523 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1351,31 +1351,40 @@ const onlySetsUp = (head) => // can pass for the run: a command that starts pytest itself prints a last // line and writes the result file, and both are read as the run's where the // run outlives its call. So the text before the run names no test runner -// (`startsRunner`: `make test`, `tox`, a `run_tests` script), no pytest -// (`pytest.main` in an inline script) and no `||`, and the run does not wait -// on what those commands returned: `;` or a line's end stands before its -// simple command, not `&&`, `&` or a pipe, and the text names nothing that -// ends the shell where a command fails: `exit`, `errexit`, or a `set` with -// `-e` in any of its flag words (`set -u -e`), read within 64 characters of -// the `set` so that a long line costs time in proportion to its length. Nor -// does `tail`, the run and what follows it, close a parenthesis or a quote it -// did not open: the run is then in a group that may wait on an earlier -// command (`edit && (git diff; pytest )`), or is the text of a quoted -// argument (`git commit -m "fix; pytest "`). The text before the run is -// not read for either, since an inline script holds quotes and parentheses -// of its own. A script that starts pytest under another name is not told -// apart, nor is a shell that ends another way (`exec`). The text is read -// once from the run backwards, so a long one (an inline script of blank -// lines) costs time in proportion to its length. +// (`startsRunner`: `make test`, `tox`, a `run_tests` script) and no pytest +// (`pytest.main` in an inline script), and the run does not wait on what +// those commands returned: `;` or a line's end stands before its simple +// command, and the command before that ends in no `&&`, `||`, `&` or pipe, +// on the run's line or at the end of an earlier one. A comment between the +// two is read past, as the shell reads past it: a line that is one, and one +// after the operator (`edit && # then`). A list that ended before the run +// decides nothing, whatever joins it (`git stash pop || true; pytest +// `). The text names nothing that ends the shell where a command +// fails: `exit`, `errexit`, or a `set` with `-e` in any of its flag words +// (`set -u -e`), read within 64 characters of the `set` so that a long line +// costs time in proportion to its length. Nor does `tail`, the run and what +// follows it, close a parenthesis or a quote it did not open: the run is +// then in a group that may wait on an earlier command (`edit && (git diff; +// pytest )`), or is the text of a quoted argument (`git commit -m +// "fix; pytest "`). The text before the run is not read for either, +// since an inline script holds quotes and parentheses of its own. A script +// that starts pytest under another name is not told apart, nor is a shell +// that ends another way (`exec`). The text is read once from the run +// backwards, so a long one (an inline script of blank lines) costs time in +// proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; const startsNoRun = (head, tail) => { - // What ends the command before the run's, and what stands before that. - let end = head.length - head.split(/[;&|(\n]/).pop().length; - if (!/[;\n]/.test(head[end - 1] || "")) return false; - while (end > 0 && /[;\s]/.test(head[end - 1])) end -= 1; + // Where the run's simple command starts, and the last line before it that + // is no comment, up to the end of its last command. + const start = head.length - head.split(/[;&|(\n]/).pop().length; + if (!/[;\n]/.test(head[start - 1] || "")) return false; + const before = head.slice(0, start).replace(/^[ \t]*#[^\n]*$/gm, ""); + let end = before.length; + while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; + const line = before.slice(before.lastIndexOf("\n", end - 1) + 1, end); return ( - !/[&|]/.test(head[end - 1] || "") && - !/\|\||py\.?test/.test(head) && + !/[&|][ \t]*(?:#[^\n]*)?$/.test(line) && + !/py\.?test/.test(head) && !ENDS_SHELL.test(head) && !startsRunner(head) && !closesParen(tail) && diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 81c18819778..f0d33fffd23 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -16,7 +16,16 @@ import { removeSandbox } from "./hook-sandbox.mjs"; import { hostEnv, withTmpdir } from "./host-env.mjs"; import { repoIdentity } from "../lib/loom-client.mjs"; import { cachePathFor } from "../lib/repo-scope.mjs"; -import { claim, costKey, noteCommand, parseClaim, renderCost, revised, settleRun } from "../lib/test-cost.mjs"; +import { + claim, + costKey, + noteCall, + noteCommand, + parseClaim, + renderCost, + revised, + settleRun, +} from "../lib/test-cost.mjs"; import { fileRun } from "../lib/test-gate.mjs"; import { newReport, reportPath, runCost } from "../lib/test-report.mjs"; import { readJsonFile, sessionStatePath, writeJsonFile, writePrivateFile } from "../lib/tmp-state.mjs"; @@ -258,11 +267,16 @@ test("a run that follows commands which name no test runner is a file run", () = // that, 80,000 blank lines cost seconds of CPU. Each filler stands after a // command that is no set-up, so the text is read as commands that start no // run: back from the run over the separators and the comments, and forward - // for a `set`. + // for a `set`. It stands straight before the run, and before a command + // between the two, which a search from each of its characters would reach. const before = process.cpuUsage(); assert.deepEqual(fileRun(`${"x = 1\n".repeat(20000)}pytest ${FILE}`), whole); - for (const filler of ["\n", " \n", " ", "; ", "set ", "# \n", "#"]) - assert.deepEqual(fileRun(`git status\n${filler.repeat(80000)}\npytest ${FILE}`), whole, JSON.stringify(filler)); + for (const filler of ["\n", " \n", " ", "; ", "set ", "# \n", "#"]) { + for (const last of ["", "git diff --stat\n"]) { + const command = `git status\n${filler.repeat(80000)}\n${last}pytest ${FILE}`; + assert.deepEqual(fileRun(command), whole, JSON.stringify([filler, last])); + } + } assert.equal(fileRun(`git status\n${"& ".repeat(80000)}\npytest ${FILE}`), null); // And from the command's start, for the folder of a `cd`. for (const filler of ["\n", " \n", "cd a\n"]) fileRun(`${filler.repeat(80000)}pytest ${FILE}`); @@ -541,12 +555,12 @@ function inTmp(t, fn) { fs.writeFileSync(path.join(cwd, FILE), ""); return withTmpdir(tmp, () => fn(cwd, path.join(cwd, FILE))); } -/** A session's cost state as `file` holds it, but for the time of its last - * read; a pending run has the time its command returned, and `dropped` is - * true for a time that is not after now. */ +/** A session's cost state as `file` holds it, but for the time its last + * shell call returned; a pending run has the time its command returned, and + * `dropped` is true for a time that is not after now. */ function noted(file) { const state = readJsonFile(file, null); - if (state) delete state.read; + if (state) delete state.returned; if (state?.dropped) state.dropped = state.dropped <= Date.now(); if (!state?.pending) return state; const { at, ...pending } = state.pending; @@ -554,25 +568,24 @@ function noted(file) { return { ...state, pending }; } const runs = () => noted(sessionStatePath("test-cost", SESSION)); -/** Move the times the session's cost state holds `ms` back: its commands - * returned, and its hooks read the report, that long ago. */ +/** Move the times the session's cost state holds `ms` back: its commands returned that long ago. */ function aged(ms) { const file = sessionStatePath("test-cost", SESSION); const state = readJsonFile(file, null); if (state.pending) state.pending.at -= ms; if (state.dropped) state.dropped -= ms; - if (state.read) state.read -= ms; + if (state.returned) state.returned -= ms; writeJsonFile(file, state); } -/** Take the session's last read of the report a day back, in the cost state - * at `file`: the run of whatever report the next hook reads began since. */ +/** Take the return of the session's last shell call a day back, in the cost + * state at `file`: the run of whatever report the next hook reads began since. */ function rested(file = sessionStatePath("test-cost", SESSION)) { const state = readJsonFile(file, null); - if (!state?.read) return; - state.read -= 24 * 60 * 60 * 1000; + if (!state?.returned) return; + state.returned -= 24 * 60 * 60 * 1000; writeJsonFile(file, state); } -/** Note a command of SESSION whose hook comes a day after the session's last one. */ +/** Note a command of SESSION that comes a day after the session's last shell call. */ function noteNext(args) { rested(); noteCommand(SESSION, args); @@ -686,7 +699,7 @@ test("a report whose first case names a data file is the run's when the case's c skip: WINDOWS, }, (t) => { inTmp(t, (cwd, file) => { - // The report of a run of 140 s that began after the session's last read. + // The report of a run of 140 s that began after the session's last shell call. const note = (classname, source = "tests/data/parse.test") => { const xml = report({ tests: 8000, time: "140.2", file: source, classname }); noteCommand(SESSION, { command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(xml, 141000), cwd }); @@ -734,7 +747,7 @@ test("a run after other commands in its shell call is counted with its own repor const edited = `sed -i 's/a/b/' src/parser.py; git diff --stat; python -m pytest -q -n4 ${FILE} 2>&1 | tail -5`; note(edited, WHOLE_OUTPUT, WHOLE); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); - // The next one's run began 150 s ago, after the read of 200 s ago. + // The next one's run began 150 s ago, after the call that returned 200 s ago. aged(200000); note(edited, "8000 passed in 150.00s", report({ tests: 8000, time: "150.0" })); assert.deepEqual(runs().files[file].whole, { tests: 8000, seconds: 150 }); @@ -744,7 +757,9 @@ test("a run after other commands in its shell call is counted with its own repor }); }); -test("a report of a run that began before the session's last read is not the command's", { skip: WINDOWS }, (t) => { +test("a report of a run that began before the session's last shell call returned is not the command's", { + skip: WINDOWS, +}, (t) => { inTmp(t, (cwd, file) => { const note = (command, output, xml, after) => noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); @@ -771,16 +786,33 @@ test("a report of a run that began before the session's last read is not the com assert.deepEqual(runs(), { files: { [file]: { filtered: [[404, 150]] } } }); fs.rmSync(sessionStatePath("test-cost", SESSION), { force: true }); - // The same holds of a command that is the run alone: a hook read the - // report 100 s ago, and the run that wrote this one began 160 s ago. + // The same holds of a command that is the run alone: the call before it + // returned 100 s ago, and the run that wrote this report began 160 s ago. note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); aged(100000); note(WHOLE_COMMAND, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" })); assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 140 } } }); - // A run that began since that read is the command's. + // A run that began since that call is the command's. aged(200000); note(WHOLE_COMMAND, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" })); assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 160 } } }); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + + // A call the report is not read for is noted in a session that has the + // report, and its time is the last call's: a suite a recipe ran left its + // report 100 s ago, when that call returned. + noteCall(SESSION); + assert.equal(runs(), null); + writeJsonFile(sessionStatePath("test-report", SESSION), { mtimeMs: 1, size: 0 }); + noteCall(SESSION); + assert.deepEqual(runs(), {}); + aged(100000); + note(again, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), -100100); + assert.deepEqual(runs(), {}); + // The state it holds stays. + note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, 141000); + noteCall(SESSION); + assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 140 } } }); }); }); @@ -802,7 +834,7 @@ test("a command that is no file run, or names a file that is not there, notes no note(`cd elsewhere && pytest ${FILE.replace("big", "gone")} -q`, WHOLE_OUTPUT); // A run in a folder whose name the command quotes is not the session folder's file of that path. note(`cd "/elsewhere/My Projects/app" && pytest ${FILE} -q`, WHOLE_OUTPUT); - // The state holds the time of the hook's read, and nothing else. + // The state holds the time the call returned, and nothing else. assert.deepEqual(runs(), {}); }); }); @@ -1373,7 +1405,7 @@ test("nothing is stored for a whole run under 60 s or of one case, a command of assert.equal(server.sent("memory.get").length, at + 1, command); await afterCommand(box, command, output, xml, extra); const files = seen?.whole ? { [box.file]: seen } : {}; - // `false`: the state holds the time of the hook's read, and no run. + // `false`: the state holds the time the call returned, and no run. assert.deepEqual(noted(box.runs), seen === false ? {} : seen && { files }, command); assert.equal(readJsonFile(box.row, {}).row, null, command); await endSession(box, extra); diff --git a/integrations/codex-plugin/hooks/loom-record.mjs b/integrations/codex-plugin/hooks/loom-record.mjs index a98ac53f6db..f5a93736fb7 100644 --- a/integrations/codex-plugin/hooks/loom-record.mjs +++ b/integrations/codex-plugin/hooks/loom-record.mjs @@ -56,8 +56,9 @@ // (`planeEnabled`, `promptPointersMode`, `promptRecallMode`, `gateMode`); the // launcher reads the planes and switches of the scripts the host waits for // (WAITED) only to leave one unloaded. What the launcher does itself 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. +// 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, and noting +// the time of a shell call the test report is not read for. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -119,6 +120,23 @@ const TEST_REPORT = { showsRefusal(visibleOutput(payload), reportPath(payload.session_id)), }; +/** Note the time a shell call of `payload` returned for which the test + * report's script is not loaded, where that script would note what a run + * cost (its tool, its planes and switches, and memory's). The script counts + * a report for a command only when the report's run began after the + * session's last shell call returned (lib/test-cost.mjs), and a command that + * names no test runner may start pytest too: a recipe, a script. */ +async function noteShellCall(payload) { + const { tools, planes, on } = TEST_REPORT; + if (!matchesTool(tools, payload.tool_name || "") || !planes.every((plane) => planeEnabled(plane)) || !on()) return; + if (!planeEnabled("memory") || !envSwitch("LOOM_SESSION_MEMORY", true)) return; + try { + (await import("../lib/test-cost.mjs")).noteCall(payload.session_id); + } catch { + /* not noted: the hook still records and answers */ + } +} + /** The scripts whose answer the host waits for, in the order their answers * are joined: they run in the hook. `tools` is the matcher a script has as a * hook of its own, read as Claude Code reads one (names take the whole tool @@ -259,6 +277,7 @@ async function hook(script, event, client) { if (event === "UserPromptSubmit") keepBegin(payload); spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` }); } + if (WAITED[event]?.includes(TEST_REPORT) && !rows.includes(TEST_REPORT)) await noteShellCall(payload); const answer = waited ? mergedAnswer(event, await waited) : null; // Exits itself: a host that never closes stdin would hold the process open. if (answer) printHookAnswer(answer, () => process.exit(0)); diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 867aaeb7521..3604f07b084 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -11,14 +11,16 @@ // whole run that passed and its latest runs filtered with -k. Other commands // may stand before the run in its shell call, and may print the last line of // a run that ended earlier: a report is the command's only when its run began -// after the hook last read the file. A run that -// outlives its shell call writes the file after that call's hook ran: a -// report read later is its when pytest began the run that wrote it before -// that call returned, and the launcher reads the file once more before it -// removes it at the session's end (`settleRun`). The file is one a session: a -// pytest run that ends before a hook read it replaces it, and the session's -// start after a compaction empties it (`startReport`). The run that outlived -// its call is then not counted. +// after the session's previous shell call returned. A command that names no +// test runner may start pytest too, and the report is not read for it: the +// launcher notes the time of such a call (`noteCall`). A run that outlives +// its shell call writes the file after that call's hook ran: a report read +// later is its when pytest began the run that wrote it before that call +// returned, and the launcher reads the file once more before it removes it at +// the session's end (`settleRun`). The file is one a session: a pytest run +// that ends before a hook read it replaces it, and the session's start after +// a compaction empties it (`startReport`). The run that outlived its call is +// then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -56,9 +58,10 @@ const MAX_PATH = 160; const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, dropped, read, files }`, by each file's +// The session's runs: `{ pending, dropped, returned, files }`, by each file's // absolute path. `dropped` is the time by which a run that lost its place as -// the pending one had begun, and `read` the time a hook last read the report. +// the pending one had begun, and `returned` the time the session's last shell +// call returned, as its hook saw it. 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 @@ -145,13 +148,14 @@ const beganAt = (report, cost) => report.mtimeMs - cost.time * 1000; /** Count `report` (`newReport`) for the session's pending run, and say * whether it was that run's: its first case is in the run's file (`ofFile`) * and the run that wrote it began before the pending run's command - * returned (`beganAt`). A command that came later, whatever it is and whether or - * not a hook saw it, began its run after that. A run of the file that - * something else started while the pending run was in its call began before - * it too: its report, read with a command that is not that run, is taken - * for the pending run's. A run that began by the time an earlier pending - * run had (`dropped`) may be that run, whose report is no later run's. The - * pending run is then settled; any other report leaves it pending. */ + * returned (`beganAt`). A command that came later, whatever it is and + * whether or not a hook saw it, began its run after that. A run of the file + * that something else started while the pending run was in its call began + * before it too: its report, read with a command that is not that run, is + * taken for the pending run's. A run that began by the time an earlier + * pending run had (`dropped`) may be that run, whose report is no later + * run's. The pending run is then settled; any other report leaves it + * pending. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; const pending = state.pending; @@ -176,14 +180,16 @@ function settle(state, report) { * a command before the run printed it: one that reads the output an earlier * run saved (`tail -5 out.txt; pytest `) shows that run's last line, * and where its own run outlives the call, the report read is that run's - * too. So the report's run began after the hook last read the report - * (`read`), as the command did: a run that began before it was started by an - * earlier command. Every call notes that time, a command with no file run - * too. A run put in the background at once begins after its own call's hook, - * and is not told apart from a later command's. Any other report is the - * pending run's when it is of that run's file and its run began by the time - * the run's command returned (`settle`), and no run's otherwise. So a run - * that was put in the background before pytest began is not counted. + * too. So the report's run began after the session's previous shell call + * returned (`returned`), as the command did: a run that began before that + * was started by an earlier command. Every shell call notes its time: one + * the report is read for here, a command with no file run too, and any + * other in the launcher (`noteCall`). A run put in the background at once + * begins after its own call returned, and is not told apart from a later + * command's. Any other report is the pending run's when it is of that run's + * file and its run began by the time the run's command returned (`settle`), + * and no run's otherwise. So a run that was put in the background before + * pytest began is not counted. * * A run whose output shows no summary may not have ended: it is kept as the * session's pending run, with the time its command returned. It is taken @@ -211,7 +217,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && - beganAt(report, cost) > (state.read ?? 0) && + beganAt(report, cost) > (state.returned ?? 0) && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); @@ -227,13 +233,26 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { else if (pending && pending.file !== run.file) state.dropped = pending.at; state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } - state.read = Date.now(); + state.returned = Date.now(); writeSessionState(RUNS, sessionId, state); } catch { /* nothing noted */ } } +/** Note the time a shell call of the session returned whose report is not + * read: `noteCommand` notes it for the others, and counts a report for a + * command only when its run began after that. A session with no test + * report has no run to tell from another, and keeps no state. */ +export function noteCall(sessionId) { + try { + if (!sessionId || !seenReport(sessionId)) return; + writeSessionState(RUNS, sessionId, { ...readSessionState(RUNS, sessionId), returned: Date.now() }); + } catch { + /* nothing noted */ + } +} + /** At the session's end, before its report is removed: a report written * since the session's last read is counted for the pending run (`settle`). * One bounded read of the session's own file, and no token is read. */ diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 646b9ec332e..873d3cd6523 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1351,31 +1351,40 @@ const onlySetsUp = (head) => // can pass for the run: a command that starts pytest itself prints a last // line and writes the result file, and both are read as the run's where the // run outlives its call. So the text before the run names no test runner -// (`startsRunner`: `make test`, `tox`, a `run_tests` script), no pytest -// (`pytest.main` in an inline script) and no `||`, and the run does not wait -// on what those commands returned: `;` or a line's end stands before its -// simple command, not `&&`, `&` or a pipe, and the text names nothing that -// ends the shell where a command fails: `exit`, `errexit`, or a `set` with -// `-e` in any of its flag words (`set -u -e`), read within 64 characters of -// the `set` so that a long line costs time in proportion to its length. Nor -// does `tail`, the run and what follows it, close a parenthesis or a quote it -// did not open: the run is then in a group that may wait on an earlier -// command (`edit && (git diff; pytest )`), or is the text of a quoted -// argument (`git commit -m "fix; pytest "`). The text before the run is -// not read for either, since an inline script holds quotes and parentheses -// of its own. A script that starts pytest under another name is not told -// apart, nor is a shell that ends another way (`exec`). The text is read -// once from the run backwards, so a long one (an inline script of blank -// lines) costs time in proportion to its length. +// (`startsRunner`: `make test`, `tox`, a `run_tests` script) and no pytest +// (`pytest.main` in an inline script), and the run does not wait on what +// those commands returned: `;` or a line's end stands before its simple +// command, and the command before that ends in no `&&`, `||`, `&` or pipe, +// on the run's line or at the end of an earlier one. A comment between the +// two is read past, as the shell reads past it: a line that is one, and one +// after the operator (`edit && # then`). A list that ended before the run +// decides nothing, whatever joins it (`git stash pop || true; pytest +// `). The text names nothing that ends the shell where a command +// fails: `exit`, `errexit`, or a `set` with `-e` in any of its flag words +// (`set -u -e`), read within 64 characters of the `set` so that a long line +// costs time in proportion to its length. Nor does `tail`, the run and what +// follows it, close a parenthesis or a quote it did not open: the run is +// then in a group that may wait on an earlier command (`edit && (git diff; +// pytest )`), or is the text of a quoted argument (`git commit -m +// "fix; pytest "`). The text before the run is not read for either, +// since an inline script holds quotes and parentheses of its own. A script +// that starts pytest under another name is not told apart, nor is a shell +// that ends another way (`exec`). The text is read once from the run +// backwards, so a long one (an inline script of blank lines) costs time in +// proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; const startsNoRun = (head, tail) => { - // What ends the command before the run's, and what stands before that. - let end = head.length - head.split(/[;&|(\n]/).pop().length; - if (!/[;\n]/.test(head[end - 1] || "")) return false; - while (end > 0 && /[;\s]/.test(head[end - 1])) end -= 1; + // Where the run's simple command starts, and the last line before it that + // is no comment, up to the end of its last command. + const start = head.length - head.split(/[;&|(\n]/).pop().length; + if (!/[;\n]/.test(head[start - 1] || "")) return false; + const before = head.slice(0, start).replace(/^[ \t]*#[^\n]*$/gm, ""); + let end = before.length; + while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; + const line = before.slice(before.lastIndexOf("\n", end - 1) + 1, end); return ( - !/[&|]/.test(head[end - 1] || "") && - !/\|\||py\.?test/.test(head) && + !/[&|][ \t]*(?:#[^\n]*)?$/.test(line) && + !/py\.?test/.test(head) && !ENDS_SHELL.test(head) && !startsRunner(head) && !closesParen(tail) && From 5eb1df56ce12f68a3bb42c2bfa45414a7d5cc9cd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 23:36:51 +0530 Subject: [PATCH 10/52] test(plugin): the time of a session's last shell call is in a file of its own, and the session's end removes it The cost tests read the time a session's last shell call returned from a state file of its own (`shell-return`), not from the runs state, and gain four cases. A launcher call that loads no test report writes that file and leaves the runs state unwritten, so it cannot write back runs another agent's hook noted meanwhile. A session with no credential has the file after a shell call and not after its end. A call of another tool writes nothing. A run during which a shell call of another agent returned is not counted, which pins the limit of a time kept for the whole session. They fail here: the time is still in the runs state, which the launcher writes after every shell call and only a session with a credential removes. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../tests/test-cost.test.mjs | 147 ++++++++++-------- 1 file changed, 84 insertions(+), 63 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index f0d33fffd23..50fe057071b 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -16,16 +16,7 @@ import { removeSandbox } from "./hook-sandbox.mjs"; import { hostEnv, withTmpdir } from "./host-env.mjs"; import { repoIdentity } from "../lib/loom-client.mjs"; import { cachePathFor } from "../lib/repo-scope.mjs"; -import { - claim, - costKey, - noteCall, - noteCommand, - parseClaim, - renderCost, - revised, - settleRun, -} from "../lib/test-cost.mjs"; +import { claim, costKey, noteCommand, parseClaim, renderCost, revised, settleRun } from "../lib/test-cost.mjs"; import { fileRun } from "../lib/test-gate.mjs"; import { newReport, reportPath, runCost } from "../lib/test-report.mjs"; import { readJsonFile, sessionStatePath, writeJsonFile, writePrivateFile } from "../lib/tmp-state.mjs"; @@ -555,12 +546,10 @@ function inTmp(t, fn) { fs.writeFileSync(path.join(cwd, FILE), ""); return withTmpdir(tmp, () => fn(cwd, path.join(cwd, FILE))); } -/** A session's cost state as `file` holds it, but for the time its last - * shell call returned; a pending run has the time its command returned, and - * `dropped` is true for a time that is not after now. */ +/** A session's cost state as `file` holds it; a pending run has the time its + * command returned, and `dropped` is true for a time that is not after now. */ function noted(file) { const state = readJsonFile(file, null); - if (state) delete state.returned; if (state?.dropped) state.dropped = state.dropped <= Date.now(); if (!state?.pending) return state; const { at, ...pending } = state.pending; @@ -568,22 +557,28 @@ function noted(file) { return { ...state, pending }; } const runs = () => noted(sessionStatePath("test-cost", SESSION)); -/** Move the times the session's cost state holds `ms` back: its commands returned that long ago. */ +/** The file that holds the time SESSION's last shell call returned. */ +const returnFile = (tmp) => sessionStatePath("shell-return", SESSION, { tmp }); +/** SESSION's last shell call returned `ms` ago, as its hook noted. */ +const returned = (ms) => writeJsonFile(returnFile(), { at: Date.now() - ms }); +/** Take the return of the session's last shell call `ms` back, a day unless + * given, in `file`: the run of whatever report the next hook reads began since. */ +function rested(file = returnFile(), ms = 24 * 60 * 60 * 1000) { + const at = readJsonFile(file, {}).at; + if (at) writeJsonFile(file, { at: at - ms }); +} +/** Move the times the session's state holds `ms` back: its commands returned that long ago. */ function aged(ms) { const file = sessionStatePath("test-cost", SESSION); const state = readJsonFile(file, null); - if (state.pending) state.pending.at -= ms; - if (state.dropped) state.dropped -= ms; - if (state.returned) state.returned -= ms; - writeJsonFile(file, state); + if (state?.pending) state.pending.at -= ms; + if (state?.dropped) state.dropped -= ms; + if (state) writeJsonFile(file, state); + rested(returnFile(), ms); } -/** Take the return of the session's last shell call a day back, in the cost - * state at `file`: the run of whatever report the next hook reads began since. */ -function rested(file = sessionStatePath("test-cost", SESSION)) { - const state = readJsonFile(file, null); - if (!state?.returned) return; - state.returned -= 24 * 60 * 60 * 1000; - writeJsonFile(file, state); +/** Forget what SESSION noted: its runs, and the time its last shell call returned. */ +function forget() { + for (const file of [sessionStatePath("test-cost", SESSION), returnFile()]) fs.rmSync(file, { force: true }); } /** Note a command of SESSION that comes a day after the session's last shell call. */ function noteNext(args) { @@ -725,7 +720,7 @@ test("a report whose first case names a data file is the run's when the case's c for (const classname of ["tests.test_big.Suite.parse.test", "tests.test_big", "test_big.Suite.parse.test"]) { note(classname); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, classname); - fs.rmSync(sessionStatePath("test-cost", SESSION)); + forget(); } // A pending run's report, read with a later command, is told the same way. noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, report: null, cwd }); @@ -776,7 +771,7 @@ test("a report of a run that began before the session's last shell call returned aged(160000); note(again, "8145 passed in 152.44s (0:02:32)", report({ tests: 8145, time: "152.4" }), -130000); assert.equal(stored(), undefined); - fs.rmSync(sessionStatePath("test-cost", SESSION), { force: true }); + forget(); // The earlier run was a selection of the file, started with workers, whose // last line counts no deselected case: its report is the pending run's. @@ -784,7 +779,7 @@ test("a report of a run that began before the session's last shell call returned aged(160000); note(again, "404 passed in 150.00s (0:02:30)", report({ tests: 404, time: "150.0" }), -130000); assert.deepEqual(runs(), { files: { [file]: { filtered: [[404, 150]] } } }); - fs.rmSync(sessionStatePath("test-cost", SESSION), { force: true }); + forget(); // The same holds of a command that is the run alone: the call before it // returned 100 s ago, and the run that wrote this report began 160 s ago. @@ -796,23 +791,21 @@ test("a report of a run that began before the session's last shell call returned aged(200000); note(WHOLE_COMMAND, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" })); assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 160 } } }); - fs.rmSync(sessionStatePath("test-cost", SESSION)); + forget(); - // A call the report is not read for is noted in a session that has the - // report, and its time is the last call's: a suite a recipe ran left its - // report 100 s ago, when that call returned. - noteCall(SESSION); - assert.equal(runs(), null); - writeJsonFile(sessionStatePath("test-report", SESSION), { mtimeMs: 1, size: 0 }); - noteCall(SESSION); - assert.deepEqual(runs(), {}); - aged(100000); + // The time of a call the report is not read for is the last call's too: a + // suite a recipe ran left its report 100 s ago, when that call returned. + returned(100000); note(again, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), -100100); assert.deepEqual(runs(), {}); - // The state it holds stays. - note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, 141000); - noteCall(SESSION); - assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 140 } } }); + forget(); + + // The time is the session's, whichever of its agents made the call: one + // that returned 100 s ago, while this command's run of 140 s was in its + // call, leaves the run uncounted. + returned(100000); + note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); + assert.deepEqual(runs(), {}); }); }); @@ -834,8 +827,7 @@ test("a command that is no file run, or names a file that is not there, notes no note(`cd elsewhere && pytest ${FILE.replace("big", "gone")} -q`, WHOLE_OUTPUT); // A run in a folder whose name the command quotes is not the session folder's file of that path. note(`cd "/elsewhere/My Projects/app" && pytest ${FILE} -q`, WHOLE_OUTPUT); - // The state holds the time the call returned, and nothing else. - assert.deepEqual(runs(), {}); + assert.equal(runs(), null); }); }); @@ -953,7 +945,7 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS // The whole run's own report, read with a later command, still counts. note("pgrep -f pytest", "", WHOLE, 3000); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); - fs.rmSync(sessionStatePath("test-cost", SESSION)); + forget(); // A selection of the file started while the whole run is open: one of the // two would be counted as the other. @@ -971,7 +963,7 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS // Its own report, of a run that began after that, is. note("pgrep -f pytest", "", WHOLE); assert.deepEqual(runs(), { dropped: true, files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); - fs.rmSync(sessionStatePath("test-cost", SESSION)); + forget(); // A run whose summary is in sight takes its own report, and the open run stays. pending(); @@ -983,7 +975,7 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS written(reportPath(SESSION), report({ tests: 30, time: "70.0" }), 71000); settleRun(SESSION); assert.deepEqual(runs(), { files: { [file]: { filtered: [[12, 2]] } } }); - fs.rmSync(sessionStatePath("test-cost", SESSION)); + forget(); // A selection that a run of another file replaced as the pending run: its // late report is not the whole run's that replaced that one in turn. @@ -1027,7 +1019,7 @@ test("a run that ended in its call with its summary cut is not pending, and the // ended in its call too: the open run stays. note(`pytest ${FILE} -k parse 2>&1 | grep FAILED`, "", FILTERED, 3000); assert.deepEqual(runs(), { ...whole, pending: { file, whole: true } }); - fs.rmSync(sessionStatePath("test-cost", SESSION)); + forget(); // A run of another file that wrote no report stays pending: the next open // run takes its place, and a report of the other file leaves it pending. @@ -1142,6 +1134,7 @@ function sandbox(t, server) { box.report = reportPath(SESSION, { tmp: box.tmp }); box.runs = sessionStatePath("test-cost", SESSION, { tmp: box.tmp }); box.row = sessionStatePath("test-cost-row", SESSION, { tmp: box.tmp }); + box.returned = returnFile(box.tmp); writePrivateFile(box.report, ""); writeJsonFile(sessionStatePath("test-report", SESSION, { tmp: box.tmp }), { mtimeMs: 1, size: 0 }); box.env = (extra = {}) => @@ -1184,7 +1177,7 @@ function afterCall(box, command, output, xml, extra) { } /** The same, a day after the session's last shell command. */ function afterCommand(box, command, output, xml, extra) { - rested(box.runs); + rested(box.returned); return afterCall(box, command, output, xml, extra); } @@ -1286,8 +1279,21 @@ test("the report of a run that a command naming no test runner started is not a const suite = report({ tests: 9000, time: "300.1" }); // A session that hands nothing to memory notes nothing of the call. await afterCall(box, recipe, "9000 passed in 300.12s", suite, { LOOM_SESSION_MEMORY: "off" }); - assert.equal(fs.existsSync(box.runs), false); + assert.equal(fs.existsSync(box.returned), false); + // A call of another tool is no shell call: one that returns while a run is + // in its call leaves the run its command's. + await run("loom-record.mjs", "PostToolUse", box.env(), { + cwd: box.cwd, + tool_name: "Read", + tool_input: { file_path: box.file }, + tool_response: { file: { filePath: box.file, content: "" } }, + }); + assert.equal(fs.existsSync(box.returned), false); await afterCall(box, recipe, "9000 passed in 300.12s", suite); + // The launcher notes the time alone, in a file of its own: the runs are + // the report's hook's to write. + assert.equal(typeof readJsonFile(box.returned, {}).at, "number"); + assert.equal(fs.existsSync(box.runs), false); // The next command prints the saved last line and starts a run of the file // that outlives the call: the report read with it is the suite's. await afterCall(box, `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} 2>&1 | tail -5`, "9000 passed in 300.12s"); @@ -1295,6 +1301,22 @@ test("the report of a run that a command naming no test runner started is not a await endSession(box); await settled(box); assert.deepEqual(server.sent("memory.set"), []); + assert.equal(fs.existsSync(box.returned), false); +}); + +test("a session with no credential notes the time of a shell call, and its end removes it", { + skip: WINDOWS, +}, async (t) => { + const server = await loom(t); + const box = sandbox(t, server); + const bare = { LOOM_API_KEY: "" }; + await afterCall(box, "git status", "nothing to commit", undefined, bare); + assert.equal(typeof readJsonFile(box.returned, {}).at, "number"); + await endSession(box, bare); + await settled(box); + // The launcher removes it with the report: no copy is started to end the session. + assert.deepEqual([box.returned, box.runs, box.report].filter(fs.existsSync), []); + assert.deepEqual(server.requests, []); }); test("a session whose prompts read no row stores nothing", { skip: WINDOWS }, async (t) => { @@ -1389,12 +1411,12 @@ test("nothing is stored for a whole run under 60 s or of one case, a command of [`python -m pytest ${FILE} -q`, "8000 passed in 59.40s", report({ tests: 8000, time: "59.4" }), {}, whole(59)], // One case: no -k selection is smaller than the file, and its whole run is not kept. [`python -m pytest ${FILE} -q`, "1 passed in 300.00s", report({ tests: 1, time: "300.0" }), {}, {}], - // Two runs, two paths, and a selection that is not by name: no run is noted. - [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}, false], - [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}, false], - [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}, false], + // Two runs, two paths, and a selection that is not by name: nothing is noted. + [`pytest ${FILE} -q; pytest ${FILE} -k parse -q`, WHOLE_OUTPUT, WHOLE, {}, null], + [`pytest ${FILE} tests/test_small.py -q`, WHOLE_OUTPUT, WHOLE, {}, null], + [`pytest ${FILE} --lf -q`, WHOLE_OUTPUT, WHOLE, {}, null], // The suite's run passed, so the file's run did not start: the report is the suite's. - [`make test || pytest ${FILE} -q`, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), {}, false], + [`make test || pytest ${FILE} -q`, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), {}, null], // The session hands nothing to memory: nothing is noted for it. [WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, { LOOM_SESSION_MEMORY: "off" }, null], ]; @@ -1405,13 +1427,12 @@ test("nothing is stored for a whole run under 60 s or of one case, a command of assert.equal(server.sent("memory.get").length, at + 1, command); await afterCommand(box, command, output, xml, extra); const files = seen?.whole ? { [box.file]: seen } : {}; - // `false`: the state holds the time the call returned, and no run. - assert.deepEqual(noted(box.runs), seen === false ? {} : seen && { files }, command); + assert.deepEqual(noted(box.runs), seen && { files }, command); assert.equal(readJsonFile(box.row, {}).row, null, command); await endSession(box, extra); await settled(box); // The session's cost state goes with the session, whatever it stores. - assert.deepEqual([box.runs, box.row].filter(fs.existsSync), [], command); + assert.deepEqual([box.runs, box.row, box.returned].filter(fs.existsSync), [], command); } assert.deepEqual(server.sent("memory.set"), []); }); @@ -1499,7 +1520,7 @@ test("a session's end with the test report switched off stores nothing and remov await settled(box); // Nothing was handed to memory, and the state went with the session. assert.deepEqual(server.sent("memory.set"), []); - assert.deepEqual([box.runs, box.row].filter(fs.existsSync), []); + assert.deepEqual([box.runs, box.row, box.returned].filter(fs.existsSync), []); }); test("a pytest run that ends before a hook read the pending run's report replaces it", { @@ -1534,11 +1555,11 @@ test("a run that pytest ended early, that skipped most of its cases, or that lef // An interrupt ended the run 120 cases in: the line above its last one says so. const early = `!!!!!!!! KeyboardInterrupt !!!!!!!!\n${FILE}:4: KeyboardInterrupt\n120 passed in 30.00s`; await afterCommand(box, `python -m pytest ${FILE} -q`, early, report({ tests: 120, time: "30.0" })); - assert.deepEqual(noted(box.runs), {}); + assert.equal(noted(box.runs), null); // The selection is not among the run's words: its last line says cases were left out. const selected = `export PYTEST_ADDOPTS="$PYTEST_ADDOPTS -k parse"; python -m pytest ${FILE}`; await afterCommand(box, selected, FILTERED_OUTPUT, FILTERED); - assert.deepEqual(noted(box.runs), {}); + assert.equal(noted(box.runs), null); // The cases need a service this machine does not run. const xml = report({ tests: 8000, time: "2.3", skipped: 7988 }); await afterCommand(box, WHOLE_COMMAND, "12 passed, 7988 skipped in 2.31s", xml); @@ -1582,7 +1603,7 @@ test("code-only mode notes nothing, stores nothing and prints no line", { skip: await settled(box); assert.equal(server.sent("memory.get").length, 1); assert.deepEqual(server.sent("memory.set"), []); - assert.deepEqual([box.runs, box.row].filter(fs.existsSync), []); + assert.deepEqual([box.runs, box.row, box.returned].filter(fs.existsSync), []); }); test("a bug report carries the repository's cost line under its pointers, from one read while the session stays in the checkout", { From e76bf75de02561a6508fc59dee579b4cb2a7a5cb Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 23:52:53 +0530 Subject: [PATCH 11/52] The time of a session's last shell call has a file of its own, which the launcher removes at the session's end The launcher wrote that time into the runs state after every shell call. The agents of one session run their hooks side by side, so a launcher's write could put back the state it read, without the run another agent's hook noted meanwhile. And only the script a session with a credential starts at its end removed the state, so a session with none kept it until the day-old sweep. The time is now one state file (`noteReturn` in lib/test-report.mjs) that every shell call's hook writes whole and that `endReport` removes with the result file, in every session. The runs state is written as on main: for a file run, or with a run pending. The launcher takes the rows wired for a call's tool, mode and switches once (`wiredRows`) and reads both the scripts to start and the shell call to note from them, in place of a second copy of the test report's filters. The switch of the cost note (`testCostOn`) is shared by the report's hook and the launcher; each still names the memory plane itself, as every hook script does. The time stays the session's, since the result file is: a run is not counted where a shell call of another agent of the session returns while the run is in its call. The docs and HOOKS.md name that limit, and a test pins it. The Codex plugin has the copy of the changed files. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 12 ++-- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 20 +++--- .../claude-code-plugin/hooks/loom-record.mjs | 64 ++++++++++--------- .../hooks/loom-test-report.mjs | 4 +- .../claude-code-plugin/lib/test-cost.mjs | 60 ++++++++--------- .../claude-code-plugin/lib/test-report.mjs | 29 ++++++++- .../codex-plugin/hooks/loom-record.mjs | 64 ++++++++++--------- .../codex-plugin/hooks/loom-test-report.mjs | 4 +- integrations/codex-plugin/lib/test-cost.mjs | 60 ++++++++--------- integrations/codex-plugin/lib/test-report.mjs | 29 ++++++++- 11 files changed, 199 insertions(+), 149 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 1efffb38ab0..ce524f97a16 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1798,7 +1798,8 @@ does the summary line where a command before the run printed it: earlier run's. That run began before the previous shell call returned, and the command's own run after it. The time is noted after every shell call of a session that has the test report, one that names no test runner too: a recipe or a script may start -pytest. +pytest. It is kept in a state file of its own, which goes with the result file when the +session ends. A case that a data-driven suite reads from a data file names that file in the result file, not the test file that collected it. Such a case is in the command's test file @@ -1895,11 +1896,14 @@ What it does not do: session's start removes the state files untouched for a day. The row is written when a bug report reads it and not again: once it is removed, the session stores nothing unless a later bug report reads the row again. What the session noted of its runs goes - a day after its last shell command. A session that runs no - pytest for a day has no test report after that: its bug reports read no row and print - no line, and its runs are not noted; + a day after the last run it noted. A session that runs no pytest for a day has no test + report after that: its bug reports read no row and print no line, and its runs are not + noted; - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not; +- the time of the previous shell call is the session's, whichever of its agents made the + call: a run is not counted where a shell call of another agent of the session, such as + a subagent's, returns while the run is in its call; - a command before the run that starts pytest under no runner's name, such as a script of the repository, is not told apart from an edit: where the run after it outlives its call, the script's result file and summary line are counted as the run's. Nor is the diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index eb5dda665f4..0993a4da535 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too), or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after the session's previous shell call returned: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too), or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after the session's previous shell call returned: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. That time is the session's: a run is not counted where a shell call of another of the session's agents, such as a subagent's, returns while the run is in its call. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index a5101019f69..f192aaf7545 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -159,7 +159,7 @@ receives on stdout. | 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 that loads no test report, it notes the call's time in the session's cost state | each script's own | +| 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 that loads no test report, it notes the call's time in a state file of its own | 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` | @@ -1534,12 +1534,16 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that wrote `out.txt`, and where its own run outlives the call, the report read with it is that earlier run's too. That run began before the previous shell call returned, and the command's own run after it. - The state keeps that time for every shell call of a session that has - the report: the hook notes it for a command it runs after, and - `loom-record` for any other (`noteCall`), since a command that names - no test runner may start pytest too (a recipe, a script). A run put - in the background at once begins after its own call returned, and is - not told apart that way. The first case is in the file where its `file` + A state file of its own keeps that time for every shell call of a + session that has the report (`noteReturn` in lib/test-report.mjs): the + hook notes it for a command it runs after, and `loom-record` for any + other, since a command that names no test runner may start pytest too + (a recipe, a script). The launcher removes the file with the result + file at SessionEnd. The time is the session's, whichever of its + agents made the call: a run is not counted where a shell call of + another agent of the session, such as a subagent's, returns while the + run is in its call. A run put in the background at once begins after + its own call returned, and is not told apart that way. The first case is in the file where its `file` attribute names it from pytest's root. A case that a data-driven suite reads from a data file names that file, which is no Python file: it is in the file where its `classname` is under the file's module (`ofFile` @@ -1637,7 +1641,7 @@ about s.` The write revises the row the session read (`if_match_sha256`), files, at any session's start a day after their last write. The row is written when a bug report reads it and not again: once it is gone, the session stores nothing unless a later bug report reads the row - again. The runs go a day after the session's last shell command. A session + again. The runs go a day after the last one was noted. A session whose report state went that way (**The file's end**, above) reads no row, prints no line and notes no run. - LOOM_TEST_REPORT=off, or the `test_report` option set to false, stops diff --git a/integrations/claude-code-plugin/hooks/loom-record.mjs b/integrations/claude-code-plugin/hooks/loom-record.mjs index f5a93736fb7..650a7709c19 100644 --- a/integrations/claude-code-plugin/hooks/loom-record.mjs +++ b/integrations/claude-code-plugin/hooks/loom-record.mjs @@ -58,7 +58,7 @@ // (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, and noting -// the time of a shell call the test report is not read for. +// the time of a shell call the test report's script is not loaded for. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -82,7 +82,16 @@ 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 { + endReport, + noteReturn, + reportPath, + seenReport, + showsRefusal, + testCostOn, + 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 @@ -120,23 +129,6 @@ const TEST_REPORT = { showsRefusal(visibleOutput(payload), reportPath(payload.session_id)), }; -/** Note the time a shell call of `payload` returned for which the test - * report's script is not loaded, where that script would note what a run - * cost (its tool, its planes and switches, and memory's). The script counts - * a report for a command only when the report's run began after the - * session's last shell call returned (lib/test-cost.mjs), and a command that - * names no test runner may start pytest too: a recipe, a script. */ -async function noteShellCall(payload) { - const { tools, planes, on } = TEST_REPORT; - if (!matchesTool(tools, payload.tool_name || "") || !planes.every((plane) => planeEnabled(plane)) || !on()) return; - if (!planeEnabled("memory") || !envSwitch("LOOM_SESSION_MEMORY", true)) return; - try { - (await import("../lib/test-cost.mjs")).noteCall(payload.session_id); - } catch { - /* not noted: the hook still records and answers */ - } -} - /** The scripts whose answer the host waits for, in the order their answers * are joined: they run in the hook. `tools` is the matcher a script has as a * hook of its own, read as Claude Code reads one (names take the whole tool @@ -185,20 +177,25 @@ export function matchesTool(tools, toolName) { return new RegExp(tools).test(toolName); } -/** The rows of `event` the host waits for on `payload`, in this mode and - * with these switches. A payload that names no tool starts no script wired - * for one. */ -function waitedRows(event, payload, env = process.env) { +/** The rows of `event` wired for the tool of `payload`, in this mode and + * with these switches. A payload that names no tool has no row wired for + * one. */ +function wiredRows(event, payload, env = process.env) { return (WAITED[event] || []) .filter((row) => row.planes.every((plane) => planeEnabled(plane, env))) .filter((row) => !row.on || row.on(env)) - .filter((row) => !row.tools || matchesTool(row.tools, payload.tool_name || "")) - .filter((row) => !row.when || row.when(payload)); + .filter((row) => !row.tools || matchesTool(row.tools, payload.tool_name || "")); +} + +/** Of the rows `wired`, the ones the host waits for on `payload`: a row + * with nothing to say about the call starts no script. */ +function waitedRows(wired, payload) { + return wired.filter((row) => !row.when || row.when(payload)); } -/** The scripts of those rows. */ +/** The scripts the host waits for at `event` on `payload`. */ export function waitedScripts(event, payload, env = process.env) { - return waitedRows(event, payload, env).map((row) => row.script); + return waitedRows(wiredRows(event, payload, env), payload).map((row) => row.script); } function run(raw, names, payload, waits) { @@ -267,7 +264,8 @@ async function hook(script, event, client) { // and the scripts it runs read it too. const payload = parsePayload(raw); // Started first: they share what the hook looks up about the checkout below. - const rows = waitedRows(event, payload); + const wired = wiredRows(event, payload); + const rows = waitedRows(wired, payload); const names = rows.map((row) => row.script); const waits = rows.map((row) => row.waitMs); const waited = names.length ? run(raw, names, payload, waits) : null; @@ -277,7 +275,15 @@ async function hook(script, event, client) { if (event === "UserPromptSubmit") keepBegin(payload); spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` }); } - if (WAITED[event]?.includes(TEST_REPORT) && !rows.includes(TEST_REPORT)) await noteShellCall(payload); + // A shell call the test report's script is wired for and not loaded on + // returned: that script counts a report for a command only when the + // report's run began after the session's last shell call returned + // (lib/test-cost.mjs), and a command that names no test runner may start + // pytest too: a recipe, a script. Noted where the script would note what a + // run cost, in a session that has the report. + if (wired.includes(TEST_REPORT) && !rows.includes(TEST_REPORT) && planeEnabled("memory") && testCostOn()) { + if (payload.session_id && seenReport(payload.session_id)) noteReturn(payload.session_id); + } const answer = waited ? mergedAnswer(event, await waited) : null; // Exits itself: a host that never closes stdin would hold the process open. if (answer) printHookAnswer(answer, () => process.exit(0)); diff --git a/integrations/claude-code-plugin/hooks/loom-test-report.mjs b/integrations/claude-code-plugin/hooks/loom-test-report.mjs index cef2dddd018..13f85103b14 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-report.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-report.mjs @@ -35,7 +35,6 @@ import { commandText, - envSwitch, gitToplevel, planeEnabled, readStdinJson, @@ -53,13 +52,14 @@ import { reportPath, seenReport, shownAlready, + testCostOn, testReportOn, visibleOutput, } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); // What a run cost is memory's: noted only where the session's end may store it. -const COST = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true); +const COST = planeEnabled("memory") && testCostOn(); // True of a command the option did not reach too (one run in the sandbox). const REFUSED = "Loom: this command's pytest does not accept the report option Loom added (`--junitxml`), and a run that got it ended with `unrecognized arguments`. The option is removed for the rest of this session: run the command again if it ended that way."; diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 3604f07b084..ea44c310586 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -13,14 +13,16 @@ // a run that ended earlier: a report is the command's only when its run began // after the session's previous shell call returned. A command that names no // test runner may start pytest too, and the report is not read for it: the -// launcher notes the time of such a call (`noteCall`). A run that outlives -// its shell call writes the file after that call's hook ran: a report read -// later is its when pytest began the run that wrote it before that call -// returned, and the launcher reads the file once more before it removes it at -// the session's end (`settleRun`). The file is one a session: a pytest run -// that ends before a hook read it replaces it, and the session's start after -// a compaction empties it (`startReport`). The run that outlived its call is -// then not counted. +// launcher notes the time of such a call (`noteReturn`, lib/test-report.mjs). +// The time is one for the session: a run is not counted as its command's +// where a shell call of another agent of the session returned while the run +// was in its call. A run that outlives its shell call writes the file after +// that call's hook ran: a report read later is its when pytest began the run +// that wrote it before that call returned, and the launcher reads the file +// once more before it removes it at the session's end (`settleRun`). The file +// is one a session: a pytest run that ends before a hook read it replaces it, +// and the session's start after a compaction empties it (`startReport`). The +// run that outlived its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -40,7 +42,7 @@ import path from "node:path"; import { git, gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; import { fileRun, isFile } from "./test-gate.mjs"; -import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; +import { newReport, noteReturn, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; // A whole run shorter than this is not worth a line in a prompt. @@ -58,10 +60,9 @@ const MAX_PATH = 160; const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, dropped, returned, files }`, by each file's -// absolute path. `dropped` is the time by which a run that lost its place as -// the pending one had begun, and `returned` the time the session's last shell -// call returned, as its hook saw it. +// The session's runs: `{ pending, dropped, files }`, by each file's absolute +// path. `dropped` is the time by which a run that lost its place as the +// pending one had begun. const RUNS = "test-cost"; // The repository's row as the session read it last, in the checkout at // `root`: `{ read, root, repo, asked, row }`, with the repository's id and @@ -181,15 +182,16 @@ function settle(state, report) { * run saved (`tail -5 out.txt; pytest `) shows that run's last line, * and where its own run outlives the call, the report read is that run's * too. So the report's run began after the session's previous shell call - * returned (`returned`), as the command did: a run that began before that + * returned (`noteReturn`), as the command did: a run that began before that * was started by an earlier command. Every shell call notes its time: one * the report is read for here, a command with no file run too, and any - * other in the launcher (`noteCall`). A run put in the background at once - * begins after its own call returned, and is not told apart from a later - * command's. Any other report is the pending run's when it is of that run's - * file and its run began by the time the run's command returned (`settle`), - * and no run's otherwise. So a run that was put in the background before - * pytest began is not counted. + * other in the launcher. The call may be another agent's of the session: + * one that returned while this command's run was in its call leaves the run + * uncounted. A run put in the background at once begins after its own call + * returned, and is not told apart from a later command's. Any other report + * is the pending run's when it is of that run's file and its run began by + * the time the run's command returned (`settle`), and no run's otherwise. So + * a run that was put in the background before pytest began is not counted. * * A run whose output shows no summary may not have ended: it is kept as the * session's pending run, with the time its command returned. It is taken @@ -208,8 +210,10 @@ function settle(state, report) { */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { + const returned = noteReturn(sessionId); const run = located(fileRun(command, output), cwd); const state = readSessionState(RUNS, sessionId); + if (!run && !state.pending) return; const cost = report ? runCost(report.head) : null; const open = Boolean(run && run.seconds === null); // The summary's seconds and the report's are two clocks on one run. @@ -217,7 +221,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && - beganAt(report, cost) > (state.returned ?? 0) && + beganAt(report, cost) > returned && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); @@ -233,26 +237,12 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { else if (pending && pending.file !== run.file) state.dropped = pending.at; state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } - state.returned = Date.now(); writeSessionState(RUNS, sessionId, state); } catch { /* nothing noted */ } } -/** Note the time a shell call of the session returned whose report is not - * read: `noteCommand` notes it for the others, and counts a report for a - * command only when its run began after that. A session with no test - * report has no run to tell from another, and keeps no state. */ -export function noteCall(sessionId) { - try { - if (!sessionId || !seenReport(sessionId)) return; - writeSessionState(RUNS, sessionId, { ...readSessionState(RUNS, sessionId), returned: Date.now() }); - } catch { - /* nothing noted */ - } -} - /** At the session's end, before its report is removed: a report written * since the session's last read is counted for the pending run (`settle`). * One bounded read of the session's own file, and no token is read. */ diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index 42840cc6e21..2c02ebb96b7 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -33,6 +33,12 @@ const MESSAGE_HEAD = 4000; // them are looked up in the checkout. const TEXT_TAIL = 64 * 1024; const MAX_FRAMES = 24; +// The time the session's last shell call returned, as its hook saw it: +// `{ at }`. A file of its own, written whole after every shell call: the +// agents of one session run their hooks side by side, and a hook that kept +// the time in state another hook reads and writes back would undo that +// hook's write. +const RETURNED = "shell-return"; /** Whether the session gets the test report: LOOM_TEST_REPORT, else the * `test_report` option, else on. */ @@ -40,6 +46,13 @@ export function testReportOn(env = process.env) { return envSwitch("LOOM_TEST_REPORT", envSwitch("CLAUDE_PLUGIN_OPTION_TEST_REPORT", true, env), env); } +/** Whether a session that runs the memory plane notes what its pytest runs + * cost (lib/test-cost.mjs): session memory is not switched off, so the + * session's end may store it. */ +export function testCostOn(env = process.env) { + return envSwitch("LOOM_SESSION_MEMORY", true, env); +} + /** The result file pytest writes for the session. */ export function reportPath(sessionId, opts = {}) { return sessionStatePath("pytest-report", sessionId, { ...opts, ext: ".xml" }); @@ -143,13 +156,25 @@ export function newReport(sessionId, seen) { } } +/** Note that a shell call of the session returned now, and give the time + * the call before it did, 0 for none: a report is a command's own only when + * its run began after that (`noteCommand` in lib/test-cost.mjs). The time + * is the session's, whichever of its agents made the call. A read that + * lands inside another hook's write finds none. */ +export function noteReturn(sessionId) { + const before = readSessionState(RETURNED, sessionId).at; + writeSessionState(RETURNED, sessionId, { at: Date.now() }); + return typeof before === "number" ? before : 0; +} + /** End the session's report: the line adds the option only where the result * file can be written, so with the file gone no later command gets it. The - * note of a refusal stays for a resume of the session, until the stale - * sweep. */ + * time of the session's last shell call goes with it. The note of a refusal + * stays for a resume of the session, until the stale sweep. */ export function endReport(sessionId) { if (!sessionId) return; removeFile(reportPath(sessionId)); + removeFile(sessionStatePath(RETURNED, sessionId)); if (!readSessionState("test-report", sessionId).refused) removeFile(sessionStatePath("test-report", sessionId)); } diff --git a/integrations/codex-plugin/hooks/loom-record.mjs b/integrations/codex-plugin/hooks/loom-record.mjs index f5a93736fb7..650a7709c19 100644 --- a/integrations/codex-plugin/hooks/loom-record.mjs +++ b/integrations/codex-plugin/hooks/loom-record.mjs @@ -58,7 +58,7 @@ // (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, and noting -// the time of a shell call the test report is not read for. +// the time of a shell call the test report's script is not loaded for. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -82,7 +82,16 @@ 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 { + endReport, + noteReturn, + reportPath, + seenReport, + showsRefusal, + testCostOn, + 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 @@ -120,23 +129,6 @@ const TEST_REPORT = { showsRefusal(visibleOutput(payload), reportPath(payload.session_id)), }; -/** Note the time a shell call of `payload` returned for which the test - * report's script is not loaded, where that script would note what a run - * cost (its tool, its planes and switches, and memory's). The script counts - * a report for a command only when the report's run began after the - * session's last shell call returned (lib/test-cost.mjs), and a command that - * names no test runner may start pytest too: a recipe, a script. */ -async function noteShellCall(payload) { - const { tools, planes, on } = TEST_REPORT; - if (!matchesTool(tools, payload.tool_name || "") || !planes.every((plane) => planeEnabled(plane)) || !on()) return; - if (!planeEnabled("memory") || !envSwitch("LOOM_SESSION_MEMORY", true)) return; - try { - (await import("../lib/test-cost.mjs")).noteCall(payload.session_id); - } catch { - /* not noted: the hook still records and answers */ - } -} - /** The scripts whose answer the host waits for, in the order their answers * are joined: they run in the hook. `tools` is the matcher a script has as a * hook of its own, read as Claude Code reads one (names take the whole tool @@ -185,20 +177,25 @@ export function matchesTool(tools, toolName) { return new RegExp(tools).test(toolName); } -/** The rows of `event` the host waits for on `payload`, in this mode and - * with these switches. A payload that names no tool starts no script wired - * for one. */ -function waitedRows(event, payload, env = process.env) { +/** The rows of `event` wired for the tool of `payload`, in this mode and + * with these switches. A payload that names no tool has no row wired for + * one. */ +function wiredRows(event, payload, env = process.env) { return (WAITED[event] || []) .filter((row) => row.planes.every((plane) => planeEnabled(plane, env))) .filter((row) => !row.on || row.on(env)) - .filter((row) => !row.tools || matchesTool(row.tools, payload.tool_name || "")) - .filter((row) => !row.when || row.when(payload)); + .filter((row) => !row.tools || matchesTool(row.tools, payload.tool_name || "")); +} + +/** Of the rows `wired`, the ones the host waits for on `payload`: a row + * with nothing to say about the call starts no script. */ +function waitedRows(wired, payload) { + return wired.filter((row) => !row.when || row.when(payload)); } -/** The scripts of those rows. */ +/** The scripts the host waits for at `event` on `payload`. */ export function waitedScripts(event, payload, env = process.env) { - return waitedRows(event, payload, env).map((row) => row.script); + return waitedRows(wiredRows(event, payload, env), payload).map((row) => row.script); } function run(raw, names, payload, waits) { @@ -267,7 +264,8 @@ async function hook(script, event, client) { // and the scripts it runs read it too. const payload = parsePayload(raw); // Started first: they share what the hook looks up about the checkout below. - const rows = waitedRows(event, payload); + const wired = wiredRows(event, payload); + const rows = waitedRows(wired, payload); const names = rows.map((row) => row.script); const waits = rows.map((row) => row.waitMs); const waited = names.length ? run(raw, names, payload, waits) : null; @@ -277,7 +275,15 @@ async function hook(script, event, client) { if (event === "UserPromptSubmit") keepBegin(payload); spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` }); } - if (WAITED[event]?.includes(TEST_REPORT) && !rows.includes(TEST_REPORT)) await noteShellCall(payload); + // A shell call the test report's script is wired for and not loaded on + // returned: that script counts a report for a command only when the + // report's run began after the session's last shell call returned + // (lib/test-cost.mjs), and a command that names no test runner may start + // pytest too: a recipe, a script. Noted where the script would note what a + // run cost, in a session that has the report. + if (wired.includes(TEST_REPORT) && !rows.includes(TEST_REPORT) && planeEnabled("memory") && testCostOn()) { + if (payload.session_id && seenReport(payload.session_id)) noteReturn(payload.session_id); + } const answer = waited ? mergedAnswer(event, await waited) : null; // Exits itself: a host that never closes stdin would hold the process open. if (answer) printHookAnswer(answer, () => process.exit(0)); diff --git a/integrations/codex-plugin/hooks/loom-test-report.mjs b/integrations/codex-plugin/hooks/loom-test-report.mjs index cef2dddd018..13f85103b14 100644 --- a/integrations/codex-plugin/hooks/loom-test-report.mjs +++ b/integrations/codex-plugin/hooks/loom-test-report.mjs @@ -35,7 +35,6 @@ import { commandText, - envSwitch, gitToplevel, planeEnabled, readStdinJson, @@ -53,13 +52,14 @@ import { reportPath, seenReport, shownAlready, + testCostOn, testReportOn, visibleOutput, } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); // What a run cost is memory's: noted only where the session's end may store it. -const COST = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true); +const COST = planeEnabled("memory") && testCostOn(); // True of a command the option did not reach too (one run in the sandbox). const REFUSED = "Loom: this command's pytest does not accept the report option Loom added (`--junitxml`), and a run that got it ended with `unrecognized arguments`. The option is removed for the rest of this session: run the command again if it ended that way."; diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 3604f07b084..ea44c310586 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -13,14 +13,16 @@ // a run that ended earlier: a report is the command's only when its run began // after the session's previous shell call returned. A command that names no // test runner may start pytest too, and the report is not read for it: the -// launcher notes the time of such a call (`noteCall`). A run that outlives -// its shell call writes the file after that call's hook ran: a report read -// later is its when pytest began the run that wrote it before that call -// returned, and the launcher reads the file once more before it removes it at -// the session's end (`settleRun`). The file is one a session: a pytest run -// that ends before a hook read it replaces it, and the session's start after -// a compaction empties it (`startReport`). The run that outlived its call is -// then not counted. +// launcher notes the time of such a call (`noteReturn`, lib/test-report.mjs). +// The time is one for the session: a run is not counted as its command's +// where a shell call of another agent of the session returned while the run +// was in its call. A run that outlives its shell call writes the file after +// that call's hook ran: a report read later is its when pytest began the run +// that wrote it before that call returned, and the launcher reads the file +// once more before it removes it at the session's end (`settleRun`). The file +// is one a session: a pytest run that ends before a hook read it replaces it, +// and the session's start after a compaction empties it (`startReport`). The +// run that outlived its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -40,7 +42,7 @@ import path from "node:path"; import { git, gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; import { fileRun, isFile } from "./test-gate.mjs"; -import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; +import { newReport, noteReturn, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; // A whole run shorter than this is not worth a line in a prompt. @@ -58,10 +60,9 @@ const MAX_PATH = 160; const MAX_FILES = 8; const MAX_SAMPLES = 15; -// The session's runs: `{ pending, dropped, returned, files }`, by each file's -// absolute path. `dropped` is the time by which a run that lost its place as -// the pending one had begun, and `returned` the time the session's last shell -// call returned, as its hook saw it. +// The session's runs: `{ pending, dropped, files }`, by each file's absolute +// path. `dropped` is the time by which a run that lost its place as the +// pending one had begun. const RUNS = "test-cost"; // The repository's row as the session read it last, in the checkout at // `root`: `{ read, root, repo, asked, row }`, with the repository's id and @@ -181,15 +182,16 @@ function settle(state, report) { * run saved (`tail -5 out.txt; pytest `) shows that run's last line, * and where its own run outlives the call, the report read is that run's * too. So the report's run began after the session's previous shell call - * returned (`returned`), as the command did: a run that began before that + * returned (`noteReturn`), as the command did: a run that began before that * was started by an earlier command. Every shell call notes its time: one * the report is read for here, a command with no file run too, and any - * other in the launcher (`noteCall`). A run put in the background at once - * begins after its own call returned, and is not told apart from a later - * command's. Any other report is the pending run's when it is of that run's - * file and its run began by the time the run's command returned (`settle`), - * and no run's otherwise. So a run that was put in the background before - * pytest began is not counted. + * other in the launcher. The call may be another agent's of the session: + * one that returned while this command's run was in its call leaves the run + * uncounted. A run put in the background at once begins after its own call + * returned, and is not told apart from a later command's. Any other report + * is the pending run's when it is of that run's file and its run began by + * the time the run's command returned (`settle`), and no run's otherwise. So + * a run that was put in the background before pytest began is not counted. * * A run whose output shows no summary may not have ended: it is kept as the * session's pending run, with the time its command returned. It is taken @@ -208,8 +210,10 @@ function settle(state, report) { */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { + const returned = noteReturn(sessionId); const run = located(fileRun(command, output), cwd); const state = readSessionState(RUNS, sessionId); + if (!run && !state.pending) return; const cost = report ? runCost(report.head) : null; const open = Boolean(run && run.seconds === null); // The summary's seconds and the report's are two clocks on one run. @@ -217,7 +221,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && - beganAt(report, cost) > (state.returned ?? 0) && + beganAt(report, cost) > returned && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); @@ -233,26 +237,12 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { else if (pending && pending.file !== run.file) state.dropped = pending.at; state.pending = other ? undefined : { file: run.file, whole: run.whole, at: Date.now() }; } - state.returned = Date.now(); writeSessionState(RUNS, sessionId, state); } catch { /* nothing noted */ } } -/** Note the time a shell call of the session returned whose report is not - * read: `noteCommand` notes it for the others, and counts a report for a - * command only when its run began after that. A session with no test - * report has no run to tell from another, and keeps no state. */ -export function noteCall(sessionId) { - try { - if (!sessionId || !seenReport(sessionId)) return; - writeSessionState(RUNS, sessionId, { ...readSessionState(RUNS, sessionId), returned: Date.now() }); - } catch { - /* nothing noted */ - } -} - /** At the session's end, before its report is removed: a report written * since the session's last read is counted for the pending run (`settle`). * One bounded read of the session's own file, and no token is read. */ diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index 42840cc6e21..2c02ebb96b7 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -33,6 +33,12 @@ const MESSAGE_HEAD = 4000; // them are looked up in the checkout. const TEXT_TAIL = 64 * 1024; const MAX_FRAMES = 24; +// The time the session's last shell call returned, as its hook saw it: +// `{ at }`. A file of its own, written whole after every shell call: the +// agents of one session run their hooks side by side, and a hook that kept +// the time in state another hook reads and writes back would undo that +// hook's write. +const RETURNED = "shell-return"; /** Whether the session gets the test report: LOOM_TEST_REPORT, else the * `test_report` option, else on. */ @@ -40,6 +46,13 @@ export function testReportOn(env = process.env) { return envSwitch("LOOM_TEST_REPORT", envSwitch("CLAUDE_PLUGIN_OPTION_TEST_REPORT", true, env), env); } +/** Whether a session that runs the memory plane notes what its pytest runs + * cost (lib/test-cost.mjs): session memory is not switched off, so the + * session's end may store it. */ +export function testCostOn(env = process.env) { + return envSwitch("LOOM_SESSION_MEMORY", true, env); +} + /** The result file pytest writes for the session. */ export function reportPath(sessionId, opts = {}) { return sessionStatePath("pytest-report", sessionId, { ...opts, ext: ".xml" }); @@ -143,13 +156,25 @@ export function newReport(sessionId, seen) { } } +/** Note that a shell call of the session returned now, and give the time + * the call before it did, 0 for none: a report is a command's own only when + * its run began after that (`noteCommand` in lib/test-cost.mjs). The time + * is the session's, whichever of its agents made the call. A read that + * lands inside another hook's write finds none. */ +export function noteReturn(sessionId) { + const before = readSessionState(RETURNED, sessionId).at; + writeSessionState(RETURNED, sessionId, { at: Date.now() }); + return typeof before === "number" ? before : 0; +} + /** End the session's report: the line adds the option only where the result * file can be written, so with the file gone no later command gets it. The - * note of a refusal stays for a resume of the session, until the stale - * sweep. */ + * time of the session's last shell call goes with it. The note of a refusal + * stays for a resume of the session, until the stale sweep. */ export function endReport(sessionId) { if (!sessionId) return; removeFile(reportPath(sessionId)); + removeFile(sessionStatePath(RETURNED, sessionId)); if (!readSessionState("test-report", sessionId).refused) removeFile(sessionStatePath("test-report", sessionId)); } From 54339e69a80995d70993b2f1f4e879c386f8e979 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 00:23:51 +0530 Subject: [PATCH 12/52] test(plugin): a stale report is told by when it was written, and an operator on a heredoc's opening line joins the run The cost tests no longer read or set a time of the session's last shell call. They state four things the code does not do yet. A run of two paths that is put in the background begins after its call returned. The next command prints its saved last line and starts a run of one file that outlives the call: the report read with it was written 127 s before the hook, and it is stored as a whole run of the file. A command that is the run alone is counted whatever shell call of the session returned while the run was in its call, and however long before the hook its report was written. `fileRun` says which runs those are (`first`). `git apply <<'P' &&`, the patch, `P`, then the run on the next line waits on `git apply`: the operator is on the line that opens the heredoc, and the last line before the run is the heredoc's end. A run after other commands is counted with a report written up to 10 s before the hook. They fail here, 12 of 46: the tests that note two commands in a row also fail, since each has the other's hook between its run's begin and its own hook. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../tests/test-cost.test.mjs | 238 ++++++++---------- 1 file changed, 102 insertions(+), 136 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 50fe057071b..e2e96f4f6d3 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -132,6 +132,7 @@ test("a command's one pytest run of one test file is whole or filtered with -k", failed: null, skipped: null, values: [], + first: true, }; for (const command of [ `pytest ${FILE}`, @@ -217,6 +218,7 @@ test("a run that follows commands which name no test runner is a file run", () = failed: null, skipped: null, values: [], + first: false, }; // An edit by an inline script, as a session writes one before it checks the edit. const edit = [ @@ -244,6 +246,8 @@ test("a run that follows commands which name no test runner is a file run", () = // the word in a script's text. `set -u; sed -i 's/a/b/' src/parser.py; pytest ${FILE}`, `python - <<'E'\n# set the per-file limit\nE\npytest ${FILE}`, + // An inline script piped into a reader: the pipe ends on the script's own line. + `python - <<'E' 2>&1 | tail -2\nprint(1 << 4 | 1)\nE\npytest ${FILE}`, ]) { assert.deepEqual(fileRun(command), whole, command); } @@ -262,7 +266,7 @@ test("a run that follows commands which name no test runner is a file run", () = // between the two, which a search from each of its characters would reach. const before = process.cpuUsage(); assert.deepEqual(fileRun(`${"x = 1\n".repeat(20000)}pytest ${FILE}`), whole); - for (const filler of ["\n", " \n", " ", "; ", "set ", "# \n", "#"]) { + for (const filler of ["\n", " \n", " ", "; ", "set ", "# \n", "#", "<< "]) { for (const last of ["", "git diff --stat\n"]) { const command = `git status\n${filler.repeat(80000)}\n${last}pytest ${FILE}`; assert.deepEqual(fileRun(command), whole, JSON.stringify([filler, last])); @@ -356,6 +360,12 @@ test("a command with two pytest runs, two paths, another selection or no run of `sleep 600 & pytest ${FILE}`, `git stash -q; (pytest ${FILE})`, `git stash -q; (\npytest ${FILE})`, + // An operator on the line that opens a heredoc joins the run to that command: the last line + // before the run is the heredoc's end. + `git apply <<'P' &&\n--- a/src/parser.py\n+++ b/src/parser.py\n@@ -1 +1 @@\n-a\n+b\nP\npytest ${FILE}`, + `python - <&1 | tail -5`, // Or in a group that waits on an earlier command, or in a shell that a failed command ends. `python /tmp/edit.py && (git diff --stat; pytest ${FILE})`, `set -e\npython /tmp/edit.py\npython -m pytest -q ${FILE} 2>&1 | tail -5`, @@ -557,33 +567,13 @@ function noted(file) { return { ...state, pending }; } const runs = () => noted(sessionStatePath("test-cost", SESSION)); -/** The file that holds the time SESSION's last shell call returned. */ -const returnFile = (tmp) => sessionStatePath("shell-return", SESSION, { tmp }); -/** SESSION's last shell call returned `ms` ago, as its hook noted. */ -const returned = (ms) => writeJsonFile(returnFile(), { at: Date.now() - ms }); -/** Take the return of the session's last shell call `ms` back, a day unless - * given, in `file`: the run of whatever report the next hook reads began since. */ -function rested(file = returnFile(), ms = 24 * 60 * 60 * 1000) { - const at = readJsonFile(file, {}).at; - if (at) writeJsonFile(file, { at: at - ms }); -} -/** Move the times the session's state holds `ms` back: its commands returned that long ago. */ +/** Move the times the session's cost state holds `ms` back: its commands returned that long ago. */ function aged(ms) { const file = sessionStatePath("test-cost", SESSION); const state = readJsonFile(file, null); - if (state?.pending) state.pending.at -= ms; - if (state?.dropped) state.dropped -= ms; - if (state) writeJsonFile(file, state); - rested(returnFile(), ms); -} -/** Forget what SESSION noted: its runs, and the time its last shell call returned. */ -function forget() { - for (const file of [sessionStatePath("test-cost", SESSION), returnFile()]) fs.rmSync(file, { force: true }); -} -/** Note a command of SESSION that comes a day after the session's last shell call. */ -function noteNext(args) { - rested(); - noteCommand(SESSION, args); + if (state.pending) state.pending.at -= ms; + if (state.dropped) state.dropped -= ms; + writeJsonFile(file, state); } /** What `newReport` reads of a report `xml` that was written `after` ms from now. */ const read = (xml, after = 0) => (xml === null ? null : { head: xml.slice(0, 4096), mtimeMs: Date.now() + after }); @@ -599,7 +589,7 @@ test("a report is the command's whose output shows the summary with the report's skip: WINDOWS, }, (t) => { inTmp(t, (cwd, file) => { - const note = (command, output, xml) => noteNext({ command, output, report: read(xml), cwd }); + const note = (command, output, xml) => noteCommand(SESSION, { command, output, report: read(xml), cwd }); const whole = (seconds) => ({ tests: 8000, seconds }); // A file of one case has no selection smaller than itself: its whole run is not kept. note(WHOLE_COMMAND, "1 passed in 300.00s", report({ tests: 1, time: "300.0" })); @@ -668,7 +658,7 @@ test("a report is the command's whose output shows the summary with the report's test("an earlier short run's report is not that of a later short run that wrote none", { skip: WINDOWS }, (t) => { inTmp(t, (cwd, file) => { const note = (output, xml) => - noteNext({ command: `PYTEST_ADDOPTS=-q pytest -x ${FILE}`, output, report: read(xml), cwd }); + noteCommand(SESSION, { command: `PYTEST_ADDOPTS=-q pytest -x ${FILE}`, output, report: read(xml), cwd }); // A -k run that no hook read left its report: 12 cases in 1.4 s. The run // after it set its own options and wrote none, and its summary's seconds // are within a second of the report's: it does not count the report's cases. @@ -694,10 +684,9 @@ test("a report whose first case names a data file is the run's when the case's c skip: WINDOWS, }, (t) => { inTmp(t, (cwd, file) => { - // The report of a run of 140 s that began after the session's last shell call. const note = (classname, source = "tests/data/parse.test") => { const xml = report({ tests: 8000, time: "140.2", file: source, classname }); - noteCommand(SESSION, { command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(xml, 141000), cwd }); + noteCommand(SESSION, { command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(xml), cwd }); }; // A class of another module, of a module that only starts with the file's // name, of the file's name under another folder, and no class. @@ -720,7 +709,7 @@ test("a report whose first case names a data file is the run's when the case's c for (const classname of ["tests.test_big.Suite.parse.test", "tests.test_big", "test_big.Suite.parse.test"]) { note(classname); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, classname); - forget(); + fs.rmSync(sessionStatePath("test-cost", SESSION)); } // A pending run's report, read with a later command, is told the same way. noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, report: null, cwd }); @@ -735,16 +724,22 @@ test("a report whose first case names a data file is the run's when the case's c }); }); -test("a run after other commands in its shell call is counted with its own report", { skip: WINDOWS }, (t) => { +test("a run after other commands in its shell call is counted with the report it wrote in that call", { + skip: WINDOWS, +}, (t) => { + // The clock stands still, so a report is as old at the hook as the test writes it. + t.mock.timers.enable({ apis: ["Date"], now: Date.now() }); inTmp(t, (cwd, file) => { const note = (command, output, xml, after) => noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); const edited = `sed -i 's/a/b/' src/parser.py; git diff --stat; python -m pytest -q -n4 ${FILE} 2>&1 | tail -5`; - note(edited, WHOLE_OUTPUT, WHOLE); + // The run ended in its call: it wrote the report a moment before the call's hook read it. + note(edited, WHOLE_OUTPUT, WHOLE, -300); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); - // The next one's run began 150 s ago, after the call that returned 200 s ago. - aged(200000); - note(edited, "8000 passed in 150.00s", report({ tests: 8000, time: "150.0" })); + // 10 s before the hook is still that moment, and a millisecond more is not. + note(edited, "8000 passed in 150.00s", report({ tests: 8000, time: "150.0" }), -10000); + assert.deepEqual(runs().files[file].whole, { tests: 8000, seconds: 150 }); + note(edited, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" }), -10001); assert.deepEqual(runs().files[file].whole, { tests: 8000, seconds: 150 }); // A run that outlives its call is the session's pending run. note(edited, " src/parser.py | 2 +-", null); @@ -752,9 +747,11 @@ test("a run after other commands in its shell call is counted with its own repor }); }); -test("a report of a run that began before the session's last shell call returned is not the command's", { +test("a report written before a command's own run could end is not the command's, where a command before the run may have printed its summary", { skip: WINDOWS, }, (t) => { + t.mock.timers.enable({ apis: ["Date"], now: Date.now() }); + const later = (seconds) => t.mock.timers.tick(seconds * 1000); inTmp(t, (cwd, file) => { const note = (command, output, xml, after) => noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); @@ -765,51 +762,48 @@ test("a report of a run that began before the session's last shell call returned // the file that outlives the call: its output shows the earlier run's last line. const again = `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} 2>&1 | tail -5`; - // A run of two paths went to the background 160 s ago and ended 130 s ago, - // after 152 s: its report, read with the next command, is not that command's. - note(`python -m pytest -q ${FILE} ${SMALL} > /tmp/out.txt 2>&1`, "", null); - aged(160000); - note(again, "8145 passed in 152.44s (0:02:32)", report({ tests: 8145, time: "152.4" }), -130000); + // A run of two paths is put in the background: pytest begins it after its + // call returned, and it ends 153 s later. The next command returns at its + // timeout, 280 s after that call: the report was written 127 s before. + note(`python -m pytest -q ${FILE} ${SMALL} > /tmp/out.txt 2>&1`, STARTED, null); + later(280); + note(again, "8145 passed in 152.44s (0:02:32)", report({ tests: 8145, time: "152.4" }), -127000); assert.equal(stored(), undefined); - forget(); + fs.rmSync(sessionStatePath("test-cost", SESSION)); // The earlier run was a selection of the file, started with workers, whose - // last line counts no deselected case: its report is the pending run's. + // last line counts no deselected case. Its call returned at the timeout + // with pytest 118 s into the run, which ended 32 s later: the report is + // the pending run's. note(`python -m pytest -q -n4 ${FILE} -k parse > /tmp/out.txt 2>&1`, "", null); - aged(160000); - note(again, "404 passed in 150.00s (0:02:30)", report({ tests: 404, time: "150.0" }), -130000); + later(160); + note(again, "404 passed in 150.00s (0:02:30)", report({ tests: 404, time: "150.0" }), -128000); assert.deepEqual(runs(), { files: { [file]: { filtered: [[404, 150]] } } }); - forget(); + fs.rmSync(sessionStatePath("test-cost", SESSION)); - // The same holds of a command that is the run alone: the call before it - // returned 100 s ago, and the run that wrote this report began 160 s ago. - note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); - aged(100000); - note(WHOLE_COMMAND, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" })); + // A suite that a recipe ran left its report unread: no hook is loaded for + // a command that names no test runner. + note(again, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), -125000); + assert.deepEqual(runs(), {}); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + + // A command that is the run alone prints no line but its own: its report + // counts however long before the hook it was written, and whatever shell + // call of the session returned while the run was in its call. + note("git status --short", "", null); + later(100); + note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, -130000); assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 140 } } }); - // A run that began since that call is the command's. - aged(200000); - note(WHOLE_COMMAND, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" })); + note( + `cd tests && source ../env.sh; pytest test_big.py -q`, + "8000 passed in 160.00s", + report({ tests: 8000, time: "160.0" }), + ); assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 160 } } }); - forget(); - - // The time of a call the report is not read for is the last call's too: a - // suite a recipe ran left its report 100 s ago, when that call returned. - returned(100000); - note(again, "9000 passed in 300.12s", report({ tests: 9000, time: "300.1" }), -100100); - assert.deepEqual(runs(), {}); - forget(); - - // The time is the session's, whichever of its agents made the call: one - // that returned 100 s ago, while this command's run of 140 s was in its - // call, leaves the run uncounted. - returned(100000); - note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); - assert.deepEqual(runs(), {}); }); }); -test("a command that is no file run, or names a file that is not there, notes no run", { +test("a command that is no file run, or names a file that is not there, leaves no state", { skip: WINDOWS, }, (t) => { inTmp(t, (cwd) => { @@ -839,7 +833,7 @@ test("a session's state holds eight files, the costliest whole run among them, a fs.writeFileSync(path.join(cwd, name), ""); const xml = report({ tests, time: "2.3", file: name }); const output = `${tests} passed, ${8000 - tests} deselected in 2.31s`; - noteNext({ command: `pytest ${name} -k parse -q`, output, report: read(xml), cwd }); + noteCommand(SESSION, { command: `pytest ${name} -k parse -q`, output, report: read(xml), cwd }); }; note(FILE); for (let i = 0; i < 7; i++) note(`tests/test_${i}.py`); @@ -862,7 +856,7 @@ test("a session's state holds eight files, the costliest whole run among them, a ); // The file with the costliest whole run stays, however long ago it ran: // eight files run after it drop the seven before it and the first of their own. - noteNext({ command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(WHOLE), cwd }); + noteCommand(SESSION, { command: WHOLE_COMMAND, output: WHOLE_OUTPUT, report: read(WHOLE), cwd }); for (let i = 8; i < 16; i++) note(`tests/test_${i}.py`); const last = runs().files; assert.deepEqual(Object.keys(last), [ @@ -945,7 +939,7 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS // The whole run's own report, read with a later command, still counts. note("pgrep -f pytest", "", WHOLE, 3000); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); - forget(); + fs.rmSync(sessionStatePath("test-cost", SESSION)); // A selection of the file started while the whole run is open: one of the // two would be counted as the other. @@ -963,7 +957,7 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS // Its own report, of a run that began after that, is. note("pgrep -f pytest", "", WHOLE); assert.deepEqual(runs(), { dropped: true, files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); - forget(); + fs.rmSync(sessionStatePath("test-cost", SESSION)); // A run whose summary is in sight takes its own report, and the open run stays. pending(); @@ -975,7 +969,7 @@ test("a report that could be another run's is counted for none", { skip: WINDOWS written(reportPath(SESSION), report({ tests: 30, time: "70.0" }), 71000); settleRun(SESSION); assert.deepEqual(runs(), { files: { [file]: { filtered: [[12, 2]] } } }); - forget(); + fs.rmSync(sessionStatePath("test-cost", SESSION)); // A selection that a run of another file replaced as the pending run: its // late report is not the whole run's that replaced that one in turn. @@ -1019,7 +1013,7 @@ test("a run that ended in its call with its summary cut is not pending, and the // ended in its call too: the open run stays. note(`pytest ${FILE} -k parse 2>&1 | grep FAILED`, "", FILTERED, 3000); assert.deepEqual(runs(), { ...whole, pending: { file, whole: true } }); - forget(); + fs.rmSync(sessionStatePath("test-cost", SESSION)); // A run of another file that wrote no report stays pending: the next open // run takes its place, and a report of the other file leaves it pending. @@ -1134,7 +1128,6 @@ function sandbox(t, server) { box.report = reportPath(SESSION, { tmp: box.tmp }); box.runs = sessionStatePath("test-cost", SESSION, { tmp: box.tmp }); box.row = sessionStatePath("test-cost-row", SESSION, { tmp: box.tmp }); - box.returned = returnFile(box.tmp); writePrivateFile(box.report, ""); writeJsonFile(sessionStatePath("test-report", SESSION, { tmp: box.tmp }), { mtimeMs: 1, size: 0 }); box.env = (extra = {}) => @@ -1166,7 +1159,7 @@ function run(script, event, env, payload) { } /** The launcher after a shell command of the session whose pytest wrote `xml`. */ -function afterCall(box, command, output, xml, extra) { +function afterCommand(box, command, output, xml, extra) { if (xml !== undefined) fs.writeFileSync(box.report, xml); return run("loom-record.mjs", "PostToolUse", box.env(extra), { cwd: box.cwd, @@ -1175,11 +1168,6 @@ function afterCall(box, command, output, xml, extra) { tool_response: { stdout: output, stderr: "" }, }); } -/** The same, a day after the session's last shell command. */ -function afterCommand(box, command, output, xml, extra) { - rested(box.returned); - return afterCall(box, command, output, xml, extra); -} const endSession = (box, extra) => run("loom-record.mjs", "SessionEnd", box.env(extra), { cwd: box.cwd, reason: "exit" }); @@ -1221,7 +1209,7 @@ test("a slow whole run and a filtered one are noted, and the session's end store assert.equal(context(await ask(box)), BLOCK); assert.deepEqual(await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE), quiet); assert.deepEqual(await afterCommand(box, FILTERED_COMMAND, FILTERED_OUTPUT, FILTERED), quiet); - assert.deepEqual(noted(box.runs), { + assert.deepEqual(readJsonFile(box.runs, null), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 }, filtered: [[12, 2]] } }, }); await settled(box); @@ -1259,8 +1247,11 @@ test("a whole run of a data-driven file that follows an edit in its shell call i classname: "tests.test_big.Suite.parse.test", }); const command = `sed -i 's/a/b/' src/parser.py; git diff --stat; python -m pytest -q -n4 ${FILE} 2>&1 | tail -5`; - await afterCommand(box, command, ` src/parser.py | 2 +-\n${WHOLE_OUTPUT}`, xml); - assert.deepEqual(noted(box.runs), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); + // The run wrote the report as its call returned. The file's time is set a + // minute ahead: on a loaded machine this test's hook starts seconds later. + written(box.report, xml, 60000); + await afterCommand(box, command, ` src/parser.py | 2 +-\n${WHOLE_OUTPUT}`); + assert.deepEqual(readJsonFile(box.runs, null), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); await endSession(box); await arrived(server, box, "memory.set"); assert.equal(server.sent("memory.set")[0].body.value, claim(REPO, { path: FILE, tests: 8000, seconds: 140 })); @@ -1275,48 +1266,19 @@ test("the report of a run that a command naming no test runner started is not a // A recipe runs the suite and saves its output: 9,000 cases in 300 s, the // first of them in the file. Its command names no test runner, so the // report's hook is not loaded for it and the report stays unread. - const recipe = "just check 2>&1 | tee /tmp/out.txt"; const suite = report({ tests: 9000, time: "300.1" }); - // A session that hands nothing to memory notes nothing of the call. - await afterCall(box, recipe, "9000 passed in 300.12s", suite, { LOOM_SESSION_MEMORY: "off" }); - assert.equal(fs.existsSync(box.returned), false); - // A call of another tool is no shell call: one that returns while a run is - // in its call leaves the run its command's. - await run("loom-record.mjs", "PostToolUse", box.env(), { - cwd: box.cwd, - tool_name: "Read", - tool_input: { file_path: box.file }, - tool_response: { file: { filePath: box.file, content: "" } }, - }); - assert.equal(fs.existsSync(box.returned), false); - await afterCall(box, recipe, "9000 passed in 300.12s", suite); - // The launcher notes the time alone, in a file of its own: the runs are - // the report's hook's to write. - assert.equal(typeof readJsonFile(box.returned, {}).at, "number"); + await afterCommand(box, "just check 2>&1 | tee /tmp/out.txt", "9000 passed in 300.12s", suite); assert.equal(fs.existsSync(box.runs), false); // The next command prints the saved last line and starts a run of the file - // that outlives the call: the report read with it is the suite's. - await afterCall(box, `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} 2>&1 | tail -5`, "9000 passed in 300.12s"); - assert.deepEqual(noted(box.runs), {}); + // that outlives the call: the report read with it is the suite's, written + // 130 s before. + written(box.report, suite, -130000); + const again = `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} 2>&1 | tail -5`; + await afterCommand(box, again, "9000 passed in 300.12s"); + assert.deepEqual(readJsonFile(box.runs, null), {}); await endSession(box); await settled(box); assert.deepEqual(server.sent("memory.set"), []); - assert.equal(fs.existsSync(box.returned), false); -}); - -test("a session with no credential notes the time of a shell call, and its end removes it", { - skip: WINDOWS, -}, async (t) => { - const server = await loom(t); - const box = sandbox(t, server); - const bare = { LOOM_API_KEY: "" }; - await afterCall(box, "git status", "nothing to commit", undefined, bare); - assert.equal(typeof readJsonFile(box.returned, {}).at, "number"); - await endSession(box, bare); - await settled(box); - // The launcher removes it with the report: no copy is started to end the session. - assert.deepEqual([box.returned, box.runs, box.report].filter(fs.existsSync), []); - assert.deepEqual(server.requests, []); }); test("a session whose prompts read no row stores nothing", { skip: WINDOWS }, async (t) => { @@ -1324,7 +1286,7 @@ test("a session whose prompts read no row stores nothing", { skip: WINDOWS }, as const box = sandbox(t, server); await afterCommand(box, WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE); // The session measured a run that makes a first row. - assert.deepEqual(noted(box.runs), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); + assert.deepEqual(readJsonFile(box.runs, null), { files: { [box.file]: { whole: { tests: 8000, seconds: 140 } } } }); // A question is no bug report: it reads no row. assert.equal(context(await ask(box, { prompt: "How are nested record prefixes combined?" })), BLOCK); await endSession(box); @@ -1377,7 +1339,7 @@ test("the launcher at an agent's SessionEnd reads the pending run's report and e skip: WINDOWS, }, async (t) => { const probe = { report: "", runs: "" }; - const mark = () => ({ report: fs.existsSync(probe.report), runs: noted(probe.runs) }); + const mark = () => ({ report: fs.existsSync(probe.report), runs: readJsonFile(probe.runs, null) }); const server = await loom(t, { mark }); const box = sandbox(t, server); Object.assign(probe, { report: box.report, runs: box.runs }); @@ -1427,12 +1389,12 @@ test("nothing is stored for a whole run under 60 s or of one case, a command of assert.equal(server.sent("memory.get").length, at + 1, command); await afterCommand(box, command, output, xml, extra); const files = seen?.whole ? { [box.file]: seen } : {}; - assert.deepEqual(noted(box.runs), seen && { files }, command); + assert.deepEqual(readJsonFile(box.runs, null), seen && { files }, command); assert.equal(readJsonFile(box.row, {}).row, null, command); await endSession(box, extra); await settled(box); // The session's cost state goes with the session, whatever it stores. - assert.deepEqual([box.runs, box.row, box.returned].filter(fs.existsSync), [], command); + assert.deepEqual([box.runs, box.row].filter(fs.existsSync), [], command); } assert.deepEqual(server.sent("memory.set"), []); }); @@ -1456,7 +1418,7 @@ test("a slow whole run of a file whose path is not sent stores nothing", { skip: const xml = report({ tests: 8000, time: "140.2", file: name }); await afterCommand(box, `python -m pytest ${name} -q`, WHOLE_OUTPUT, xml); const seen = { [path.join(box.cwd, name)]: { whole: { tests: 8000, seconds: 140 } } }; - assert.deepEqual(noted(box.runs), { files: seen }, name); + assert.deepEqual(readJsonFile(box.runs, null), { files: seen }, name); await endSession(box); await settled(box); assert.equal(fs.existsSync(box.runs), false, name); @@ -1492,7 +1454,11 @@ test("a slow whole run of a file that git does not list in the checkout stores n await ask(box); assert.equal(server.sent("memory.get").length, at + 1, tree); await afterCommand(box, `cd ${tree} && python -m pytest ${FILE} -q`, WHOLE_OUTPUT, WHOLE); - assert.deepEqual(noted(box.runs), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, tree); + assert.deepEqual( + readJsonFile(box.runs, null), + { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, + tree, + ); await endSession(box); await settled(box); assert.equal(fs.existsSync(box.runs), false, tree); @@ -1520,7 +1486,7 @@ test("a session's end with the test report switched off stores nothing and remov await settled(box); // Nothing was handed to memory, and the state went with the session. assert.deepEqual(server.sent("memory.set"), []); - assert.deepEqual([box.runs, box.row, box.returned].filter(fs.existsSync), []); + assert.deepEqual([box.runs, box.row].filter(fs.existsSync), []); }); test("a pytest run that ends before a hook read the pending run's report replaces it", { @@ -1555,16 +1521,16 @@ test("a run that pytest ended early, that skipped most of its cases, or that lef // An interrupt ended the run 120 cases in: the line above its last one says so. const early = `!!!!!!!! KeyboardInterrupt !!!!!!!!\n${FILE}:4: KeyboardInterrupt\n120 passed in 30.00s`; await afterCommand(box, `python -m pytest ${FILE} -q`, early, report({ tests: 120, time: "30.0" })); - assert.equal(noted(box.runs), null); + assert.equal(readJsonFile(box.runs, null), null); // The selection is not among the run's words: its last line says cases were left out. const selected = `export PYTEST_ADDOPTS="$PYTEST_ADDOPTS -k parse"; python -m pytest ${FILE}`; await afterCommand(box, selected, FILTERED_OUTPUT, FILTERED); - assert.equal(noted(box.runs), null); + assert.equal(readJsonFile(box.runs, null), null); // The cases need a service this machine does not run. const xml = report({ tests: 8000, time: "2.3", skipped: 7988 }); await afterCommand(box, WHOLE_COMMAND, "12 passed, 7988 skipped in 2.31s", xml); // The report was the command's, and counted for nothing. - assert.deepEqual(noted(box.runs), { files: {} }); + assert.deepEqual(readJsonFile(box.runs, null), { files: {} }); await endSession(box); await settled(box); assert.deepEqual(server.sent("memory.set"), []); @@ -1580,7 +1546,7 @@ test("an earlier short run's report, read after a short run that wrote none, doe // its own options, wrote none and stopped at an error half a second in. const earlier = report({ tests: 12, time: "1.4" }); await afterCommand(box, `PYTEST_ADDOPTS=-q pytest -x ${FILE}`, "1 error in 0.52s", earlier); - assert.deepEqual(noted(box.runs), {}); + assert.deepEqual(readJsonFile(box.runs, null), {}); await endSession(box); await settled(box); assert.deepEqual(server.sent("memory.set"), []); @@ -1594,16 +1560,16 @@ test("code-only mode notes nothing, stores nothing and prints no line", { skip: assert.equal(context(await ask(box)), `${BLOCK}\n${LINE}`); await afterCommand(box, WHOLE_COMMAND, "8000 passed in 200.00s", report({ tests: 8000, time: "200.0" })); const held = { files: { [box.file]: { whole: { tests: 8000, seconds: 200 } } } }; - assert.deepEqual(noted(box.runs), held); + assert.deepEqual(readJsonFile(box.runs, null), held); // In code-only mode a costlier run is not noted, the prompt has no line, and the end stores nothing. await afterCommand(box, WHOLE_COMMAND, "8000 passed in 300.00s", report({ tests: 8000, time: "300.0" }), code); - assert.deepEqual(noted(box.runs), held); + assert.deepEqual(readJsonFile(box.runs, null), held); assert.equal(context(await ask(box, { extra: code })), BLOCK); await endSession(box, code); await settled(box); assert.equal(server.sent("memory.get").length, 1); assert.deepEqual(server.sent("memory.set"), []); - assert.deepEqual([box.runs, box.row, box.returned].filter(fs.existsSync), []); + assert.deepEqual([box.runs, box.row].filter(fs.existsSync), []); }); test("a bug report carries the repository's cost line under its pointers, from one read while the session stays in the checkout", { From d8843b0691d0d45395af82d4771d45e9aad21526 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 00:37:08 +0530 Subject: [PATCH 13/52] A run after other commands counts with a report written within 10 s of its hook, and an operator on a heredoc's opening line joins the run A command before the run can print the last line of an earlier run (`tail -5 out.txt; pytest `), and where its own run outlives the call, the report read with it is that earlier run's. The guard against it compared the begin of the report's run with the return of the session's previous shell call. A run put in the background begins after its own call returned, so its report passed as a later command's: a run of two paths was stored as a whole run of one file. The time was also the session's, so a command that is the run alone was not counted where a shell call of another agent returned during it, which main counts. The bound is now on the report itself. A run that ended in its call writes the report as the call returns, and a stale one was written before the command's own run began. For a run that a command which is no set-up stands before (`first` is false in `fileRun`), the report is the command's only when it was written no more than 10 s before the hook read it (`OWN_REPORT_MS`). A command that is the run alone prints no line but its own and keeps main's rule. No time of a shell call is kept: `noteReturn`, its state file, the launcher's note after every shell call and `testCostOn` are gone, and `hooks/loom-record.mjs`, `hooks/loom-test-report.mjs` and `endReport` are as on main. `startsNoRun` refuses a head in which a line that holds `<<` ends in `&&`, `||`, `&` or a pipe, with or without a comment after it: `git apply <<'P' &&` joins the run after the patch to `git apply`, and the last line before the run is the heredoc's end. Where a heredoc ends is not read, so such a line in an inline script's text is refused too. The Codex plugin has the copy of the changed files. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 47 ++++++----- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 32 ++++---- .../claude-code-plugin/hooks/loom-record.mjs | 49 +++-------- .../hooks/loom-test-report.mjs | 4 +- .../claude-code-plugin/lib/test-cost.mjs | 81 +++++++++---------- .../claude-code-plugin/lib/test-gate.mjs | 30 ++++--- .../claude-code-plugin/lib/test-report.mjs | 29 +------ .../codex-plugin/hooks/loom-record.mjs | 49 +++-------- .../codex-plugin/hooks/loom-test-report.mjs | 4 +- integrations/codex-plugin/lib/test-cost.mjs | 81 +++++++++---------- integrations/codex-plugin/lib/test-gate.mjs | 30 ++++--- integrations/codex-plugin/lib/test-report.mjs | 29 +------ 13 files changed, 191 insertions(+), 276 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index ce524f97a16..2d3e8460248 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1778,7 +1778,10 @@ session's private state, by the file: and `;` or a line's end stands before the run's own command, not `&&`, `||`, `&`, a pipe or a parenthesis. A line's end after `&&`, `||`, `&` or a pipe joins the run to that command too, with or without a comment between them (`git diff --stat &&` on the - line above the run). A list that ended before the run decides nothing: + line above the run), and so does one at the end of a line that holds `<<`: + `git apply <<'P' &&` joins the run after the patch to `git apply`. Where a heredoc ends + is not read, so a line of an inline script's text that holds `<<` and ends in one of + them counts too. A list that ended before the run decides nothing: `git stash pop || true; pytest tests/test_big.py` counts. The run and what follows it close no parenthesis and no quote opened before them: a run in a group that waits on an earlier command (`python edit.py && (git diff --stat; pytest tests/test_big.py)`) and @@ -1787,19 +1790,18 @@ session's private state, by the file: The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the -seconds within a second, or a twentieth of them), the file's first case is in the test -file the command names, and the run that wrote the file began after the session's -previous shell call returned. -The seconds alone do not tell two short runs apart: a run that wrote no file, such as -one that sets its own `PYTEST_ADDOPTS`, is read with the file an earlier run left. Nor -does the summary line where a command before the run printed it: -`tail -5 out.txt; pytest tests/test_big.py` shows the summary of the run that wrote -`out.txt`, and where its own run outlives the call, the result file read with it is that -earlier run's. That run began before the previous shell call returned, and the -command's own run after it. The time is noted after every shell call of a session that -has the test report, one that names no test runner too: a recipe or a script may start -pytest. It is kept in a state file of its own, which goes with the result file when the -session ends. +seconds within a second, or a twentieth of them), and the file's first case is in the +test file the command names. The seconds alone do not tell two short runs apart: a run +that wrote no file, such as one that sets its own `PYTEST_ADDOPTS`, is read with the +file an earlier run left. Nor does the summary line where a command before the run +printed it: `tail -5 out.txt; pytest tests/test_big.py` shows the summary of the run +that wrote `out.txt`, and where its own run outlives the call, the result file read with +it is that earlier run's. That file was written before the command's own run began, +and a run that ended in its call writes the file as the call returns. So where other +commands than `cd`, `export`, `source` and `.` stand before the run, the result file is +the command's only when it was written no more than 10 s before the hook read it. A +command that is the run alone prints no summary line but its own, and its result file +has no such bound. A case that a data-driven suite reads from a data file names that file in the result file, not the test file that collected it. Such a case is in the command's test file @@ -1901,15 +1903,16 @@ What it does not do: noted; - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not; -- the time of the previous shell call is the session's, whichever of its agents made the - call: a run is not counted where a shell call of another agent of the session, such as - a subagent's, returns while the run is in its call; +- a run that other commands stand before is not counted where its result file was + written more than 10 s before the hook read it, as by a pytest whose process ends that + long after it wrote the file; - a command before the run that starts pytest under no runner's name, such as a script - of the repository, is not told apart from an edit: where the run after it outlives its - call, the script's result file and summary line are counted as the run's. Nor is the - result file of a run put in the background at once, of two paths or another selection - of the test file, told apart from the run of a later command that prints its saved - summary and whose own run outlives the call; + of the repository, is not told apart from an edit. Its result file and summary line + are counted as the run's where the script ended within 10 s of the call's return and + the run after it shows no summary line of its own: it outlives the call, or ends + before pytest prints one. The same holds of the result file an earlier run left + unread, where a command prints that run's saved summary and its call returns within + 10 s of the time the file was written; - a run that never starts because the shell ends in a way the command's text does not name, such as an `exec` before it, is kept as one that outlives its call; - the session keeps one run that outlives its call. A later one of another test file diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 0993a4da535..150b3ad4f38 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too), or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, its first case is in the test file the command names (for a case read from a data file, its class is under that file's module), and the run that wrote it began after the session's previous shell call returned: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's. That time is the session's: a run is not counted where a shell call of another of the session's agents, such as a subagent's, returns while the run is in its call. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch), or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run, the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index f192aaf7545..aba853bcb2b 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -159,7 +159,7 @@ receives on stdout. | 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 that loads no test report, it notes the call's time in a state file of its own | each script's own | +| 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` | @@ -1490,7 +1490,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that end before the run's own command, not `&&`, `||`, `&`, a pipe or a parenthesis, no `&&`, `||`, `&` or pipe at the end of the last line before it that is no comment, a comment after the operator aside - (`edit &&`, then `# check`, then the run), and a run that with what + (`edit &&`, then `# check`, then the run), no line that holds `<<` + and ends in one of those operators (`git apply <<'P' &&` joins the run + after the patch to `git apply`; where a heredoc ends is not read, so a + line of an inline script's text counts too), and a run that with what follows it closes no parenthesis and no quote opened before it (`startsNoRun`): a run in a group that waits on an earlier command (`edit && (git diff; pytest )`) and @@ -1524,26 +1527,21 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that The report is the command's when the command's visible output shows pytest's summary line with the cases, the failures and the seconds the report holds, the seconds within a second or a twentieth of them, - the report's first case is in the file the command names, and the run - that wrote the report began after the session's previous shell call - returned: a run + and the report's first case is in the file the command names: a run the option did not reach writes no report, and the one read after it is an earlier run's, which the seconds of two short runs do not tell apart. Nor does the line where a command before the run printed it: `tail -5 out.txt; pytest ` shows the last line of the run that wrote `out.txt`, and where its own run outlives the call, the report - read with it is that earlier run's too. That run began before the - previous shell call returned, and the command's own run after it. - A state file of its own keeps that time for every shell call of a - session that has the report (`noteReturn` in lib/test-report.mjs): the - hook notes it for a command it runs after, and `loom-record` for any - other, since a command that names no test runner may start pytest too - (a recipe, a script). The launcher removes the file with the result - file at SessionEnd. The time is the session's, whichever of its - agents made the call: a run is not counted where a shell call of - another agent of the session, such as a subagent's, returns while the - run is in its call. A run put in the background at once begins after - its own call returned, and is not told apart that way. The first case is in the file where its `file` + read with it is that earlier run's too. That report was written + before the command's own run began, and a run that ended in its call + writes the report as the call returns. So for a run that a command + which is no set-up stands before, the report is the command's only + when it was written no more than 10 s before the hook read it + (`OWN_REPORT_MS` in lib/test-cost.mjs). A command that is the run + alone, or has only `cd`, `export`, `source` and `.` before it, prints + no line but its own, and its report has no such bound. The first case + is in the file where its `file` attribute names it from pytest's root. A case that a data-driven suite reads from a data file names that file, which is no Python file: it is in the file where its `classname` is under the file's module (`ofFile` diff --git a/integrations/claude-code-plugin/hooks/loom-record.mjs b/integrations/claude-code-plugin/hooks/loom-record.mjs index 650a7709c19..a98ac53f6db 100644 --- a/integrations/claude-code-plugin/hooks/loom-record.mjs +++ b/integrations/claude-code-plugin/hooks/loom-record.mjs @@ -56,9 +56,8 @@ // (`planeEnabled`, `promptPointersMode`, `promptRecallMode`, `gateMode`); the // launcher reads the planes and switches of the scripts the host waits for // (WAITED) only to leave one unloaded. What the launcher does itself 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, and noting -// the time of a shell call the test report's script is not loaded for. +// ledger's, keeping the run's begin, and memory's, reading the test report +// at SessionEnd for the cost of a run that outlived its command. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -82,16 +81,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, - noteReturn, - reportPath, - seenReport, - showsRefusal, - testCostOn, - testReportOn, - visibleOutput, -} from "../lib/test-report.mjs"; +import { 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 @@ -177,25 +167,20 @@ export function matchesTool(tools, toolName) { return new RegExp(tools).test(toolName); } -/** The rows of `event` wired for the tool of `payload`, in this mode and - * with these switches. A payload that names no tool has no row wired for - * one. */ -function wiredRows(event, payload, env = process.env) { +/** The rows of `event` the host waits for on `payload`, in this mode and + * with these switches. A payload that names no tool starts no script wired + * for one. */ +function waitedRows(event, payload, env = process.env) { return (WAITED[event] || []) .filter((row) => row.planes.every((plane) => planeEnabled(plane, env))) .filter((row) => !row.on || row.on(env)) - .filter((row) => !row.tools || matchesTool(row.tools, payload.tool_name || "")); -} - -/** Of the rows `wired`, the ones the host waits for on `payload`: a row - * with nothing to say about the call starts no script. */ -function waitedRows(wired, payload) { - return wired.filter((row) => !row.when || row.when(payload)); + .filter((row) => !row.tools || matchesTool(row.tools, payload.tool_name || "")) + .filter((row) => !row.when || row.when(payload)); } -/** The scripts the host waits for at `event` on `payload`. */ +/** The scripts of those rows. */ export function waitedScripts(event, payload, env = process.env) { - return waitedRows(wiredRows(event, payload, env), payload).map((row) => row.script); + return waitedRows(event, payload, env).map((row) => row.script); } function run(raw, names, payload, waits) { @@ -264,8 +249,7 @@ async function hook(script, event, client) { // and the scripts it runs read it too. const payload = parsePayload(raw); // Started first: they share what the hook looks up about the checkout below. - const wired = wiredRows(event, payload); - const rows = waitedRows(wired, payload); + const rows = waitedRows(event, payload); const names = rows.map((row) => row.script); const waits = rows.map((row) => row.waitMs); const waited = names.length ? run(raw, names, payload, waits) : null; @@ -275,15 +259,6 @@ async function hook(script, event, client) { if (event === "UserPromptSubmit") keepBegin(payload); spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` }); } - // A shell call the test report's script is wired for and not loaded on - // returned: that script counts a report for a command only when the - // report's run began after the session's last shell call returned - // (lib/test-cost.mjs), and a command that names no test runner may start - // pytest too: a recipe, a script. Noted where the script would note what a - // run cost, in a session that has the report. - if (wired.includes(TEST_REPORT) && !rows.includes(TEST_REPORT) && planeEnabled("memory") && testCostOn()) { - if (payload.session_id && seenReport(payload.session_id)) noteReturn(payload.session_id); - } const answer = waited ? mergedAnswer(event, await waited) : null; // Exits itself: a host that never closes stdin would hold the process open. if (answer) printHookAnswer(answer, () => process.exit(0)); diff --git a/integrations/claude-code-plugin/hooks/loom-test-report.mjs b/integrations/claude-code-plugin/hooks/loom-test-report.mjs index 13f85103b14..cef2dddd018 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-report.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-report.mjs @@ -35,6 +35,7 @@ import { commandText, + envSwitch, gitToplevel, planeEnabled, readStdinJson, @@ -52,14 +53,13 @@ import { reportPath, seenReport, shownAlready, - testCostOn, testReportOn, visibleOutput, } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); // What a run cost is memory's: noted only where the session's end may store it. -const COST = planeEnabled("memory") && testCostOn(); +const COST = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true); // True of a command the option did not reach too (one run in the sandbox). const REFUSED = "Loom: this command's pytest does not accept the report option Loom added (`--junitxml`), and a run that got it ended with `unrecognized arguments`. The option is removed for the rest of this session: run the command again if it ended that way."; diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index ea44c310586..047183f040a 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -10,19 +10,16 @@ // state, for a session whose end may store them: for each file, the costliest // whole run that passed and its latest runs filtered with -k. Other commands // may stand before the run in its shell call, and may print the last line of -// a run that ended earlier: a report is the command's only when its run began -// after the session's previous shell call returned. A command that names no -// test runner may start pytest too, and the report is not read for it: the -// launcher notes the time of such a call (`noteReturn`, lib/test-report.mjs). -// The time is one for the session: a run is not counted as its command's -// where a shell call of another agent of the session returned while the run -// was in its call. A run that outlives its shell call writes the file after -// that call's hook ran: a report read later is its when pytest began the run -// that wrote it before that call returned, and the launcher reads the file -// once more before it removes it at the session's end (`settleRun`). The file -// is one a session: a pytest run that ends before a hook read it replaces it, -// and the session's start after a compaction empties it (`startReport`). The -// run that outlived its call is then not counted. +// a run that ended earlier: the report is then the command's only when it was +// written moments before the hook read it (`OWN_REPORT_MS`), as a run that +// ended in the call writes it. A run that +// outlives its shell call writes the file after that call's hook ran: a +// report read later is its when pytest began the run that wrote it before +// that call returned, and the launcher reads the file once more before it +// removes it at the session's end (`settleRun`). The file is one a session: a +// pytest run that ends before a hook read it replaces it, and the session's +// start after a compaction empties it (`startReport`). The run that outlived +// its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -42,7 +39,7 @@ import path from "node:path"; import { git, gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; import { fileRun, isFile } from "./test-gate.mjs"; -import { newReport, noteReturn, runCost, seenReport, testReportOn } from "./test-report.mjs"; +import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; // A whole run shorter than this is not worth a line in a prompt. @@ -55,6 +52,10 @@ const CALL_TIMEOUT_SECONDS = 120; // The report counts an expected failure (xfail) as skipped, the summary line // does not: a run that outlived its call has the report's count only. const MAX_SKIPPED_SHARE = 0.1; +// How long before its shell call's hook a run that ended in the call wrote +// its report: pytest writes it as its last step, and the hook starts when +// the call returns. +const OWN_REPORT_MS = 10_000; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. const MAX_FILES = 8; @@ -142,26 +143,22 @@ function add(state, run, cost) { state.files = Object.fromEntries(held.filter((entry) => entry !== dropped)); } -/** When pytest began the run that wrote `report` (`newReport`), whose head - * gives `cost`: the time the file was written less the suite's seconds. */ -const beganAt = (report, cost) => report.mtimeMs - cost.time * 1000; - /** Count `report` (`newReport`) for the session's pending run, and say * whether it was that run's: its first case is in the run's file (`ofFile`) * and the run that wrote it began before the pending run's command - * returned (`beganAt`). A command that came later, whatever it is and - * whether or not a hook saw it, began its run after that. A run of the file - * that something else started while the pending run was in its call began - * before it too: its report, read with a command that is not that run, is - * taken for the pending run's. A run that began by the time an earlier - * pending run had (`dropped`) may be that run, whose report is no later - * run's. The pending run is then settled; any other report leaves it - * pending. */ + * returned. pytest began it at the time the file was written less the + * suite's seconds. A command that came later, whatever it is and whether or + * not a hook saw it, began its run after that. A run of the file that + * something else started while the pending run was in its call began before + * it too: its report, read with a command that is not that run, is taken + * for the pending run's. A run that began by the time an earlier pending + * run had (`dropped`) may be that run, whose report is no later run's. The + * pending run is then settled; any other report leaves it pending. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; const pending = state.pending; if (!cost || !pending || !ofFile(pending, cost)) return false; - const began = beganAt(report, cost); + const began = report.mtimeMs - cost.time * 1000; if (began > pending.at || began <= (state.dropped ?? 0)) return false; add(state, pending, cost); state.pending = undefined; @@ -178,20 +175,19 @@ function settle(state, report) { * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The * seconds alone do not tell two short runs apart. Nor does the summary where - * a command before the run printed it: one that reads the output an earlier - * run saved (`tail -5 out.txt; pytest `) shows that run's last line, - * and where its own run outlives the call, the report read is that run's - * too. So the report's run began after the session's previous shell call - * returned (`noteReturn`), as the command did: a run that began before that - * was started by an earlier command. Every shell call notes its time: one - * the report is read for here, a command with no file run too, and any - * other in the launcher. The call may be another agent's of the session: - * one that returned while this command's run was in its call leaves the run - * uncounted. A run put in the background at once begins after its own call - * returned, and is not told apart from a later command's. Any other report - * is the pending run's when it is of that run's file and its run began by - * the time the run's command returned (`settle`), and no run's otherwise. So - * a run that was put in the background before pytest began is not counted. + * a command before the run printed it (`run.first` is false): one that reads + * the output an earlier run saved (`tail -5 out.txt; pytest `) shows + * that run's last line, and where its own run outlives the call, the report + * read is that run's too. That report was written before the command's own + * run began, and a run that ended in the call writes its report as the call + * returns: the report of such a command is its own only when it was written + * no more than `OWN_REPORT_MS` before this read. A report that a command + * before the run wrote within that time is not told apart from the run's, + * nor is one an earlier run wrote that shortly before the call returned. Any + * other report is the pending run's when it is of that run's file and its + * run began by the time the run's command returned (`settle`), and no run's + * otherwise. So a run that was put in the background before pytest began is + * not counted. * * A run whose output shows no summary may not have ended: it is kept as the * session's pending run, with the time its command returned. It is taken @@ -210,7 +206,6 @@ function settle(state, report) { */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { - const returned = noteReturn(sessionId); const run = located(fileRun(command, output), cwd); const state = readSessionState(RUNS, sessionId); if (!run && !state.pending) return; @@ -221,7 +216,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && - beganAt(report, cost) > returned && + (run.first || Date.now() - report.mtimeMs <= OWN_REPORT_MS) && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 873d3cd6523..14ce1550187 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1357,7 +1357,11 @@ const onlySetsUp = (head) => // command, and the command before that ends in no `&&`, `||`, `&` or pipe, // on the run's line or at the end of an earlier one. A comment between the // two is read past, as the shell reads past it: a line that is one, and one -// after the operator (`edit && # then`). A list that ended before the run +// after the operator (`edit && # then`). So is a heredoc's text: an operator +// at the end of the line that opens one joins the run to that line's command +// (`git apply <<'P' &&`, the patch, `P`, then the run). Where a heredoc ends +// is not read, so no line that holds `<<` ends in one of those operators, a +// line of an inline script's text included. A list that ended before the run // decides nothing, whatever joins it (`git stash pop || true; pytest // `). The text names nothing that ends the shell where a command // fails: `exit`, `errexit`, or a `set` with `-e` in any of its flag words @@ -1370,9 +1374,12 @@ const onlySetsUp = (head) => // since an inline script holds quotes and parentheses of its own. A script // that starts pytest under another name is not told apart, nor is a shell // that ends another way (`exec`). The text is read once from the run -// backwards, so a long one (an inline script of blank lines) costs time in -// proportion to its length. +// backwards and once line by line, so a long one (an inline script of blank +// lines) costs time in proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; +// A line that ends in `&&`, `||`, `&` or a pipe, with or without a comment +// after it: the command it holds goes on with the next one. +const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; const startsNoRun = (head, tail) => { // Where the run's simple command starts, and the last line before it that // is no comment, up to the end of its last command. @@ -1383,7 +1390,8 @@ const startsNoRun = (head, tail) => { while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; const line = before.slice(before.lastIndexOf("\n", end - 1) + 1, end); return ( - !/[&|][ \t]*(?:#[^\n]*)?$/.test(line) && + !JOINS.test(line) && + !before.split("\n").some((opens) => opens.includes("<<") && JOINS.test(opens)) && !/py\.?test/.test(head) && !ENDS_SHELL.test(head) && !startsRunner(head) && @@ -1446,10 +1454,12 @@ const counted = (line, kinds) => /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values }`, - * else null. `path` is the file as the command spells it and `dir` the folder - * of the one `cd` before the run, "" for none. `whole` is false for a run - * filtered with `-k`. `seconds` is what pytest's last line in the visible + * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values, + * first }`, else null. `path` is the file as the command spells it and `dir` + * the folder of the one `cd` before the run, "" for none. `whole` is false for + * a run filtered with `-k`. `first` is false where a command that is no set-up + * stands before the run (`startsNoRun`): it may have printed a line the output + * shows. `seconds` is what pytest's last line in the visible * `output` shows (`LAST_LINE`), read without its colours. `cases` is the * cases that line counts, all but the deselected: the result file's `tests`, * but for a case whose teardown raised an error, which the line counts twice @@ -1502,7 +1512,8 @@ export function fileRun(command, output = "") { if (runs.length !== 1) return null; const head = text.slice(0, runs[0].index); const tail = text.slice(runs[0].index); - if (!ranHere(head) || !(onlySetsUp(head) || startsNoRun(head, tail))) return null; + const first = onlySetsUp(head); + if (!ranHere(head) || !(first || startsNoRun(head, tail))) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; @@ -1544,6 +1555,7 @@ export function fileRun(command, output = "") { failed: summary ? counted(summary, "failed|errors?") : null, skipped: summary ? counted(summary, "skipped") : null, values, + first, }; } diff --git a/integrations/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index 2c02ebb96b7..42840cc6e21 100644 --- a/integrations/claude-code-plugin/lib/test-report.mjs +++ b/integrations/claude-code-plugin/lib/test-report.mjs @@ -33,12 +33,6 @@ const MESSAGE_HEAD = 4000; // them are looked up in the checkout. const TEXT_TAIL = 64 * 1024; const MAX_FRAMES = 24; -// The time the session's last shell call returned, as its hook saw it: -// `{ at }`. A file of its own, written whole after every shell call: the -// agents of one session run their hooks side by side, and a hook that kept -// the time in state another hook reads and writes back would undo that -// hook's write. -const RETURNED = "shell-return"; /** Whether the session gets the test report: LOOM_TEST_REPORT, else the * `test_report` option, else on. */ @@ -46,13 +40,6 @@ export function testReportOn(env = process.env) { return envSwitch("LOOM_TEST_REPORT", envSwitch("CLAUDE_PLUGIN_OPTION_TEST_REPORT", true, env), env); } -/** Whether a session that runs the memory plane notes what its pytest runs - * cost (lib/test-cost.mjs): session memory is not switched off, so the - * session's end may store it. */ -export function testCostOn(env = process.env) { - return envSwitch("LOOM_SESSION_MEMORY", true, env); -} - /** The result file pytest writes for the session. */ export function reportPath(sessionId, opts = {}) { return sessionStatePath("pytest-report", sessionId, { ...opts, ext: ".xml" }); @@ -156,25 +143,13 @@ export function newReport(sessionId, seen) { } } -/** Note that a shell call of the session returned now, and give the time - * the call before it did, 0 for none: a report is a command's own only when - * its run began after that (`noteCommand` in lib/test-cost.mjs). The time - * is the session's, whichever of its agents made the call. A read that - * lands inside another hook's write finds none. */ -export function noteReturn(sessionId) { - const before = readSessionState(RETURNED, sessionId).at; - writeSessionState(RETURNED, sessionId, { at: Date.now() }); - return typeof before === "number" ? before : 0; -} - /** End the session's report: the line adds the option only where the result * file can be written, so with the file gone no later command gets it. The - * time of the session's last shell call goes with it. The note of a refusal - * stays for a resume of the session, until the stale sweep. */ + * note of a refusal stays for a resume of the session, until the stale + * sweep. */ export function endReport(sessionId) { if (!sessionId) return; removeFile(reportPath(sessionId)); - removeFile(sessionStatePath(RETURNED, sessionId)); if (!readSessionState("test-report", sessionId).refused) removeFile(sessionStatePath("test-report", sessionId)); } diff --git a/integrations/codex-plugin/hooks/loom-record.mjs b/integrations/codex-plugin/hooks/loom-record.mjs index 650a7709c19..a98ac53f6db 100644 --- a/integrations/codex-plugin/hooks/loom-record.mjs +++ b/integrations/codex-plugin/hooks/loom-record.mjs @@ -56,9 +56,8 @@ // (`planeEnabled`, `promptPointersMode`, `promptRecallMode`, `gateMode`); the // launcher reads the planes and switches of the scripts the host waits for // (WAITED) only to leave one unloaded. What the launcher does itself 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, and noting -// the time of a shell call the test report's script is not loaded for. +// ledger's, keeping the run's begin, and memory's, reading the test report +// at SessionEnd for the cost of a run that outlived its command. import { recordsToolCall } from "../lib/after-tool.mjs"; import { spawnDetached } from "../lib/flush-job.mjs"; @@ -82,16 +81,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, - noteReturn, - reportPath, - seenReport, - showsRefusal, - testCostOn, - testReportOn, - visibleOutput, -} from "../lib/test-report.mjs"; +import { 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 @@ -177,25 +167,20 @@ export function matchesTool(tools, toolName) { return new RegExp(tools).test(toolName); } -/** The rows of `event` wired for the tool of `payload`, in this mode and - * with these switches. A payload that names no tool has no row wired for - * one. */ -function wiredRows(event, payload, env = process.env) { +/** The rows of `event` the host waits for on `payload`, in this mode and + * with these switches. A payload that names no tool starts no script wired + * for one. */ +function waitedRows(event, payload, env = process.env) { return (WAITED[event] || []) .filter((row) => row.planes.every((plane) => planeEnabled(plane, env))) .filter((row) => !row.on || row.on(env)) - .filter((row) => !row.tools || matchesTool(row.tools, payload.tool_name || "")); -} - -/** Of the rows `wired`, the ones the host waits for on `payload`: a row - * with nothing to say about the call starts no script. */ -function waitedRows(wired, payload) { - return wired.filter((row) => !row.when || row.when(payload)); + .filter((row) => !row.tools || matchesTool(row.tools, payload.tool_name || "")) + .filter((row) => !row.when || row.when(payload)); } -/** The scripts the host waits for at `event` on `payload`. */ +/** The scripts of those rows. */ export function waitedScripts(event, payload, env = process.env) { - return waitedRows(wiredRows(event, payload, env), payload).map((row) => row.script); + return waitedRows(event, payload, env).map((row) => row.script); } function run(raw, names, payload, waits) { @@ -264,8 +249,7 @@ async function hook(script, event, client) { // and the scripts it runs read it too. const payload = parsePayload(raw); // Started first: they share what the hook looks up about the checkout below. - const wired = wiredRows(event, payload); - const rows = waitedRows(wired, payload); + const rows = waitedRows(event, payload); const names = rows.map((row) => row.script); const waits = rows.map((row) => row.waitMs); const waited = names.length ? run(raw, names, payload, waits) : null; @@ -275,15 +259,6 @@ async function hook(script, event, client) { if (event === "UserPromptSubmit") keepBegin(payload); spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` }); } - // A shell call the test report's script is wired for and not loaded on - // returned: that script counts a report for a command only when the - // report's run began after the session's last shell call returned - // (lib/test-cost.mjs), and a command that names no test runner may start - // pytest too: a recipe, a script. Noted where the script would note what a - // run cost, in a session that has the report. - if (wired.includes(TEST_REPORT) && !rows.includes(TEST_REPORT) && planeEnabled("memory") && testCostOn()) { - if (payload.session_id && seenReport(payload.session_id)) noteReturn(payload.session_id); - } const answer = waited ? mergedAnswer(event, await waited) : null; // Exits itself: a host that never closes stdin would hold the process open. if (answer) printHookAnswer(answer, () => process.exit(0)); diff --git a/integrations/codex-plugin/hooks/loom-test-report.mjs b/integrations/codex-plugin/hooks/loom-test-report.mjs index 13f85103b14..cef2dddd018 100644 --- a/integrations/codex-plugin/hooks/loom-test-report.mjs +++ b/integrations/codex-plugin/hooks/loom-test-report.mjs @@ -35,6 +35,7 @@ import { commandText, + envSwitch, gitToplevel, planeEnabled, readStdinJson, @@ -52,14 +53,13 @@ import { reportPath, seenReport, shownAlready, - testCostOn, testReportOn, visibleOutput, } from "../lib/test-report.mjs"; const ENABLED = planeEnabled("ledger") && testReportOn(); // What a run cost is memory's: noted only where the session's end may store it. -const COST = planeEnabled("memory") && testCostOn(); +const COST = planeEnabled("memory") && envSwitch("LOOM_SESSION_MEMORY", true); // True of a command the option did not reach too (one run in the sandbox). const REFUSED = "Loom: this command's pytest does not accept the report option Loom added (`--junitxml`), and a run that got it ended with `unrecognized arguments`. The option is removed for the rest of this session: run the command again if it ended that way."; diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index ea44c310586..047183f040a 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -10,19 +10,16 @@ // state, for a session whose end may store them: for each file, the costliest // whole run that passed and its latest runs filtered with -k. Other commands // may stand before the run in its shell call, and may print the last line of -// a run that ended earlier: a report is the command's only when its run began -// after the session's previous shell call returned. A command that names no -// test runner may start pytest too, and the report is not read for it: the -// launcher notes the time of such a call (`noteReturn`, lib/test-report.mjs). -// The time is one for the session: a run is not counted as its command's -// where a shell call of another agent of the session returned while the run -// was in its call. A run that outlives its shell call writes the file after -// that call's hook ran: a report read later is its when pytest began the run -// that wrote it before that call returned, and the launcher reads the file -// once more before it removes it at the session's end (`settleRun`). The file -// is one a session: a pytest run that ends before a hook read it replaces it, -// and the session's start after a compaction empties it (`startReport`). The -// run that outlived its call is then not counted. +// a run that ended earlier: the report is then the command's only when it was +// written moments before the hook read it (`OWN_REPORT_MS`), as a run that +// ended in the call writes it. A run that +// outlives its shell call writes the file after that call's hook ran: a +// report read later is its when pytest began the run that wrote it before +// that call returned, and the launcher reads the file once more before it +// removes it at the session's end (`settleRun`). The file is one a session: a +// pytest run that ends before a hook read it replaces it, and the session's +// start after a compaction empties it (`startReport`). The run that outlived +// its call is then not counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -42,7 +39,7 @@ import path from "node:path"; import { git, gitToplevel, hookClient, isDirectory, pathUnder, postBounded, redactSecrets } from "./loom-client.mjs"; import { fileRun, isFile } from "./test-gate.mjs"; -import { newReport, noteReturn, runCost, seenReport, testReportOn } from "./test-report.mjs"; +import { newReport, runCost, seenReport, testReportOn } from "./test-report.mjs"; import { readSessionState, removeFile, sessionStatePath, writeSessionState } from "./tmp-state.mjs"; // A whole run shorter than this is not worth a line in a prompt. @@ -55,6 +52,10 @@ const CALL_TIMEOUT_SECONDS = 120; // The report counts an expected failure (xfail) as skipped, the summary line // does not: a run that outlived its call has the report's count only. const MAX_SKIPPED_SHARE = 0.1; +// How long before its shell call's hook a run that ended in the call wrote +// its report: pytest writes it as its last step, and the hook starts when +// the call returns. +const OWN_REPORT_MS = 10_000; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. const MAX_FILES = 8; @@ -142,26 +143,22 @@ function add(state, run, cost) { state.files = Object.fromEntries(held.filter((entry) => entry !== dropped)); } -/** When pytest began the run that wrote `report` (`newReport`), whose head - * gives `cost`: the time the file was written less the suite's seconds. */ -const beganAt = (report, cost) => report.mtimeMs - cost.time * 1000; - /** Count `report` (`newReport`) for the session's pending run, and say * whether it was that run's: its first case is in the run's file (`ofFile`) * and the run that wrote it began before the pending run's command - * returned (`beganAt`). A command that came later, whatever it is and - * whether or not a hook saw it, began its run after that. A run of the file - * that something else started while the pending run was in its call began - * before it too: its report, read with a command that is not that run, is - * taken for the pending run's. A run that began by the time an earlier - * pending run had (`dropped`) may be that run, whose report is no later - * run's. The pending run is then settled; any other report leaves it - * pending. */ + * returned. pytest began it at the time the file was written less the + * suite's seconds. A command that came later, whatever it is and whether or + * not a hook saw it, began its run after that. A run of the file that + * something else started while the pending run was in its call began before + * it too: its report, read with a command that is not that run, is taken + * for the pending run's. A run that began by the time an earlier pending + * run had (`dropped`) may be that run, whose report is no later run's. The + * pending run is then settled; any other report leaves it pending. */ function settle(state, report) { const cost = report ? runCost(report.head) : null; const pending = state.pending; if (!cost || !pending || !ofFile(pending, cost)) return false; - const began = beganAt(report, cost); + const began = report.mtimeMs - cost.time * 1000; if (began > pending.at || began <= (state.dropped ?? 0)) return false; add(state, pending, cost); state.pending = undefined; @@ -178,20 +175,19 @@ function settle(state, report) { * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The * seconds alone do not tell two short runs apart. Nor does the summary where - * a command before the run printed it: one that reads the output an earlier - * run saved (`tail -5 out.txt; pytest `) shows that run's last line, - * and where its own run outlives the call, the report read is that run's - * too. So the report's run began after the session's previous shell call - * returned (`noteReturn`), as the command did: a run that began before that - * was started by an earlier command. Every shell call notes its time: one - * the report is read for here, a command with no file run too, and any - * other in the launcher. The call may be another agent's of the session: - * one that returned while this command's run was in its call leaves the run - * uncounted. A run put in the background at once begins after its own call - * returned, and is not told apart from a later command's. Any other report - * is the pending run's when it is of that run's file and its run began by - * the time the run's command returned (`settle`), and no run's otherwise. So - * a run that was put in the background before pytest began is not counted. + * a command before the run printed it (`run.first` is false): one that reads + * the output an earlier run saved (`tail -5 out.txt; pytest `) shows + * that run's last line, and where its own run outlives the call, the report + * read is that run's too. That report was written before the command's own + * run began, and a run that ended in the call writes its report as the call + * returns: the report of such a command is its own only when it was written + * no more than `OWN_REPORT_MS` before this read. A report that a command + * before the run wrote within that time is not told apart from the run's, + * nor is one an earlier run wrote that shortly before the call returned. Any + * other report is the pending run's when it is of that run's file and its + * run began by the time the run's command returned (`settle`), and no run's + * otherwise. So a run that was put in the background before pytest began is + * not counted. * * A run whose output shows no summary may not have ended: it is kept as the * session's pending run, with the time its command returned. It is taken @@ -210,7 +206,6 @@ function settle(state, report) { */ export function noteCommand(sessionId, { command, output, report, cwd }) { try { - const returned = noteReturn(sessionId); const run = located(fileRun(command, output), cwd); const state = readSessionState(RUNS, sessionId); if (!run && !state.pending) return; @@ -221,7 +216,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && - beganAt(report, cost) > returned && + (run.first || Date.now() - report.mtimeMs <= OWN_REPORT_MS) && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 873d3cd6523..14ce1550187 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1357,7 +1357,11 @@ const onlySetsUp = (head) => // command, and the command before that ends in no `&&`, `||`, `&` or pipe, // on the run's line or at the end of an earlier one. A comment between the // two is read past, as the shell reads past it: a line that is one, and one -// after the operator (`edit && # then`). A list that ended before the run +// after the operator (`edit && # then`). So is a heredoc's text: an operator +// at the end of the line that opens one joins the run to that line's command +// (`git apply <<'P' &&`, the patch, `P`, then the run). Where a heredoc ends +// is not read, so no line that holds `<<` ends in one of those operators, a +// line of an inline script's text included. A list that ended before the run // decides nothing, whatever joins it (`git stash pop || true; pytest // `). The text names nothing that ends the shell where a command // fails: `exit`, `errexit`, or a `set` with `-e` in any of its flag words @@ -1370,9 +1374,12 @@ const onlySetsUp = (head) => // since an inline script holds quotes and parentheses of its own. A script // that starts pytest under another name is not told apart, nor is a shell // that ends another way (`exec`). The text is read once from the run -// backwards, so a long one (an inline script of blank lines) costs time in -// proportion to its length. +// backwards and once line by line, so a long one (an inline script of blank +// lines) costs time in proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; +// A line that ends in `&&`, `||`, `&` or a pipe, with or without a comment +// after it: the command it holds goes on with the next one. +const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; const startsNoRun = (head, tail) => { // Where the run's simple command starts, and the last line before it that // is no comment, up to the end of its last command. @@ -1383,7 +1390,8 @@ const startsNoRun = (head, tail) => { while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; const line = before.slice(before.lastIndexOf("\n", end - 1) + 1, end); return ( - !/[&|][ \t]*(?:#[^\n]*)?$/.test(line) && + !JOINS.test(line) && + !before.split("\n").some((opens) => opens.includes("<<") && JOINS.test(opens)) && !/py\.?test/.test(head) && !ENDS_SHELL.test(head) && !startsRunner(head) && @@ -1446,10 +1454,12 @@ const counted = (line, kinds) => /** * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing - * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values }`, - * else null. `path` is the file as the command spells it and `dir` the folder - * of the one `cd` before the run, "" for none. `whole` is false for a run - * filtered with `-k`. `seconds` is what pytest's last line in the visible + * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values, + * first }`, else null. `path` is the file as the command spells it and `dir` + * the folder of the one `cd` before the run, "" for none. `whole` is false for + * a run filtered with `-k`. `first` is false where a command that is no set-up + * stands before the run (`startsNoRun`): it may have printed a line the output + * shows. `seconds` is what pytest's last line in the visible * `output` shows (`LAST_LINE`), read without its colours. `cases` is the * cases that line counts, all but the deselected: the result file's `tests`, * but for a case whose teardown raised an error, which the line counts twice @@ -1502,7 +1512,8 @@ export function fileRun(command, output = "") { if (runs.length !== 1) return null; const head = text.slice(0, runs[0].index); const tail = text.slice(runs[0].index); - if (!ranHere(head) || !(onlySetsUp(head) || startsNoRun(head, tail))) return null; + const first = onlySetsUp(head); + if (!ranHere(head) || !(first || startsNoRun(head, tail))) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; @@ -1544,6 +1555,7 @@ export function fileRun(command, output = "") { failed: summary ? counted(summary, "failed|errors?") : null, skipped: summary ? counted(summary, "skipped") : null, values, + first, }; } diff --git a/integrations/codex-plugin/lib/test-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index 2c02ebb96b7..42840cc6e21 100644 --- a/integrations/codex-plugin/lib/test-report.mjs +++ b/integrations/codex-plugin/lib/test-report.mjs @@ -33,12 +33,6 @@ const MESSAGE_HEAD = 4000; // them are looked up in the checkout. const TEXT_TAIL = 64 * 1024; const MAX_FRAMES = 24; -// The time the session's last shell call returned, as its hook saw it: -// `{ at }`. A file of its own, written whole after every shell call: the -// agents of one session run their hooks side by side, and a hook that kept -// the time in state another hook reads and writes back would undo that -// hook's write. -const RETURNED = "shell-return"; /** Whether the session gets the test report: LOOM_TEST_REPORT, else the * `test_report` option, else on. */ @@ -46,13 +40,6 @@ export function testReportOn(env = process.env) { return envSwitch("LOOM_TEST_REPORT", envSwitch("CLAUDE_PLUGIN_OPTION_TEST_REPORT", true, env), env); } -/** Whether a session that runs the memory plane notes what its pytest runs - * cost (lib/test-cost.mjs): session memory is not switched off, so the - * session's end may store it. */ -export function testCostOn(env = process.env) { - return envSwitch("LOOM_SESSION_MEMORY", true, env); -} - /** The result file pytest writes for the session. */ export function reportPath(sessionId, opts = {}) { return sessionStatePath("pytest-report", sessionId, { ...opts, ext: ".xml" }); @@ -156,25 +143,13 @@ export function newReport(sessionId, seen) { } } -/** Note that a shell call of the session returned now, and give the time - * the call before it did, 0 for none: a report is a command's own only when - * its run began after that (`noteCommand` in lib/test-cost.mjs). The time - * is the session's, whichever of its agents made the call. A read that - * lands inside another hook's write finds none. */ -export function noteReturn(sessionId) { - const before = readSessionState(RETURNED, sessionId).at; - writeSessionState(RETURNED, sessionId, { at: Date.now() }); - return typeof before === "number" ? before : 0; -} - /** End the session's report: the line adds the option only where the result * file can be written, so with the file gone no later command gets it. The - * time of the session's last shell call goes with it. The note of a refusal - * stays for a resume of the session, until the stale sweep. */ + * note of a refusal stays for a resume of the session, until the stale + * sweep. */ export function endReport(sessionId) { if (!sessionId) return; removeFile(reportPath(sessionId)); - removeFile(sessionStatePath(RETURNED, sessionId)); if (!readSessionState("test-report", sessionId).refused) removeFile(sessionStatePath("test-report", sessionId)); } From a7c0de63cbb2c39cadda6032fe8b9f4eaa1a908b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 01:08:53 +0530 Subject: [PATCH 14/52] test(plugin): a run in a comment or after an escaped semicolon is no file run, and the last of two summary lines is the run's The shell starts no run where the `;` before it is in a comment on the run's line or follows a backslash: `fileRun` gives a run for both, so the two new refusals fail. The other assertions pin what the code already does: the run's own summary is the last one where a command before the run printed an earlier run's, a run after set-up alone counts with a report of any age, and a comment line alone above the run is read as a command that is no set-up. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../tests/test-cost.test.mjs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index e2e96f4f6d3..b2943b5520b 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -253,11 +253,18 @@ test("a run that follows commands which name no test runner is a file run", () = } // The folder of the one `cd`, and a run filtered with -k. assert.deepEqual(fileRun(`cd pkg && git stash -q; pytest ${FILE} -k parse`), { ...whole, dir: "pkg", whole: false }); - // The last line of the output is the run's where the run ended in the call. + // The last line of the output is the run's where the run ended in the call, + // under one that a command before the run printed. assert.equal(fileRun(`${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -3`, WHOLE_OUTPUT).seconds, 140.21); + const shown = fileRun(`tail -5 /tmp/out.txt; pytest ${FILE} -q`, `8145 passed in 152.44s (0:02:32)\n${WHOLE_OUTPUT}`); + assert.deepEqual([shown.seconds, shown.cases], [140.21, 8000]); // A comment before the run is no command. assert.deepEqual(fileRun(`git diff --stat\n# check the edit\npytest ${FILE}`), whole); assert.deepEqual(fileRun(`git diff --stat; # check the edit\npytest ${FILE}`), whole); + // A comment line alone above the run is read as a command that is no set-up. + assert.deepEqual(fileRun(`# check the parser\npytest ${FILE}`), whole); + // A `#` inside a word starts no comment. + assert.deepEqual(fileRun(`grep -c '^#' src/parser.py; echo $#; pytest ${FILE}`), whole); // A long text before the run is read in time linear in its length: without // that, 80,000 blank lines cost seconds of CPU. Each filler stands after a // command that is no set-up, so the text is read as commands that start no @@ -375,6 +382,12 @@ test("a command with two pytest runs, two paths, another selection or no run of `if ! python /tmp/edit.py; then exit 1; fi; pytest ${FILE}`, // Text in a quoted argument is no run. `git commit -qm "parser: keep the prefix; python -m pytest ${FILE}"`, + // Nor is the text of a comment, or of a word that holds an escaped `;`. + `git diff --stat # then; pytest ${FILE}`, + `git diff --stat;# then; pytest ${FILE}`, + `# then; pytest ${FILE}`, + `git diff --stat\n # then; pytest ${FILE}`, + `echo done\\; pytest ${FILE}`, `echo "source .venv/bin/activate; pytest ${FILE}" > check.sh`, `echo 'git diff --stat; pytest ${FILE}' >> notes.txt`, // Quotes are not read: a `|` or a parenthesis in one ends the run's part there. @@ -741,6 +754,15 @@ test("a run after other commands in its shell call is counted with the report it assert.deepEqual(runs().files[file].whole, { tests: 8000, seconds: 150 }); note(edited, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" }), -10001); assert.deepEqual(runs().files[file].whole, { tests: 8000, seconds: 150 }); + // A command before the run printed the last line of an earlier run: the + // run's own line is the one under it, and its report holds that line's numbers. + note( + `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} 2>&1 | tail -5`, + "8145 passed in 152.44s (0:02:32)\n8000 passed in 170.00s (0:02:50)", + report({ tests: 8000, time: "170.0" }), + -300, + ); + assert.deepEqual(runs().files[file].whole, { tests: 8000, seconds: 170 }); // A run that outlives its call is the session's pending run. note(edited, " src/parser.py | 2 +-", null); assert.deepEqual(runs().pending, { file, whole: true }); @@ -789,7 +811,8 @@ test("a report written before a command's own run could end is not the command's // A command that is the run alone prints no line but its own: its report // counts however long before the hook it was written, and whatever shell - // call of the session returned while the run was in its call. + // call of the session returned while the run was in its call. So does the + // report of a run after set-up alone, which is taken as the command's own. note("git status --short", "", null); later(100); note(WHOLE_COMMAND, WHOLE_OUTPUT, WHOLE, -130000); @@ -798,6 +821,7 @@ test("a report written before a command's own run could end is not the command's `cd tests && source ../env.sh; pytest test_big.py -q`, "8000 passed in 160.00s", report({ tests: 8000, time: "160.0" }), + -130000, ); assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 160 } } }); }); @@ -821,6 +845,9 @@ test("a command that is no file run, or names a file that is not there, leaves n note(`cd elsewhere && pytest ${FILE.replace("big", "gone")} -q`, WHOLE_OUTPUT); // A run in a folder whose name the command quotes is not the session folder's file of that path. note(`cd "/elsewhere/My Projects/app" && pytest ${FILE} -q`, WHOLE_OUTPUT); + // A run the shell never starts is no pending run: its `;` is in a comment, or escaped. + note(`git diff --stat # then; pytest ${FILE}`, " src/parser.py | 2 +-"); + note(`echo done\\; pytest ${FILE}`, `done; pytest ${FILE}`); assert.equal(runs(), null); }); }); From a9febd2b1fcdcfa58f451f56997a623e370c0397 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 01:16:32 +0530 Subject: [PATCH 15/52] A run in a comment or after an escaped semicolon is no file run `startsNoRun` took `git diff --stat # then; pytest ` and `echo done\; pytest ` as runs: the split on `;` reads a separator where the shell reads a comment's text or a word. Such a run never starts, shows no summary and was kept as the session's pending run. It is refused now: no backslash stands before the run's `;`, and no `#` that starts a word stands before the run on its line. Quotes are not read, so the line is read up to its first one: a `#` after a quote may be an argument's, as in an edit that inserts a comment (`sed -i '5a\ # note' ; pytest `), and a comment that starts there is named among the limits. The pages say what the code does for the bound on a report's age: a comment line above the run is read as a command that is no set-up, and the report of a run after `cd`, `export`, `source` and `.` alone is taken as the command's own, whatever a sourced file printed. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 20 +++++++--- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 21 +++++++--- .../claude-code-plugin/lib/test-gate.mjs | 38 ++++++++++++------- .../tests/test-cost.test.mjs | 8 +++- integrations/codex-plugin/lib/test-gate.mjs | 38 ++++++++++++------- 6 files changed, 87 insertions(+), 40 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 2d3e8460248..b59c1fb3a70 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1776,7 +1776,11 @@ session's private state, by the file: no test runner, no `pytest` and nothing that ends the shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), and `;` or a line's end stands before the run's own command, not `&&`, `||`, `&`, a - pipe or a parenthesis. A line's end after `&&`, `||`, `&` or a pipe joins the run to + pipe or a parenthesis. The `;` is one the shell reads: a run after `\;`, or after a + `#` that starts a word on its line ahead of the line's first quote, counts as neither + (`git diff --stat # then; pytest tests/test_big.py` holds a comment and no run). A + `#` after a quote may be an argument's, as in `sed -i '5a\ # note' src/parser.py`, + and decides nothing. A line's end after `&&`, `||`, `&` or a pipe joins the run to that command too, with or without a comment between them (`git diff --stat &&` on the line above the run), and so does one at the end of a line that holds `<<`: `git apply <<'P' &&` joins the run after the patch to `git apply`. Where a heredoc ends @@ -1798,10 +1802,12 @@ printed it: `tail -5 out.txt; pytest tests/test_big.py` shows the summary of the that wrote `out.txt`, and where its own run outlives the call, the result file read with it is that earlier run's. That file was written before the command's own run began, and a run that ended in its call writes the file as the call returns. So where other -commands than `cd`, `export`, `source` and `.` stand before the run, the result file is -the command's only when it was written no more than 10 s before the hook read it. A -command that is the run alone prints no summary line but its own, and its result file -has no such bound. +commands than `cd`, `export`, `source` and `.` stand before the run (a comment line +counts as one), the result file is the command's only when it was written no more than +10 s before the hook read it. A command that is the run alone prints no summary line but +its own, and its result file has no such bound. Neither has the result file of a run +with only `cd`, `export`, `source` and `.` before it, which is taken as the command's +own. A case that a data-driven suite reads from a data file names that file in the result file, not the test file that collected it. Such a case is in the command's test file @@ -1914,7 +1920,9 @@ What it does not do: unread, where a command prints that run's saved summary and its call returns within 10 s of the time the file was written; - a run that never starts because the shell ends in a way the command's text does not - name, such as an `exec` before it, is kept as one that outlives its call; + name, such as an `exec` before it, is kept as one that outlives its call. So is a run + in a comment that starts after a quote on its line + (`echo 'done' # then; pytest tests/test_big.py`); - the session keeps one run that outlives its call. A later one of another test file takes its place, and the earlier run is not counted. A later one of the same file and the other kind, whole after `-k` or `-k` after whole, drops both, since the earlier diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 150b3ad4f38..b97defb10f0 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch), or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run, the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch), or one after `\;` or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run), or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index aba853bcb2b..6367bb4c040 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1488,7 +1488,13 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), with `;` or a line's end before the run's own command, not `&&`, `||`, `&`, a pipe or a - parenthesis, no `&&`, `||`, `&` or pipe at the end of the last line + parenthesis, that `;` one the shell reads (none after a backslash, + and no `#` that starts a word before the run on its line, ahead of + the line's first quote: `git diff --stat # then; pytest ` holds + a comment and no run; quotes are not read, so a `#` after one may be + an argument's, as in `sed -i '5a\ # note' src/parser.py`, and a + comment that starts there is not told apart), no `&&`, `||`, `&` or + pipe at the end of the last line before it that is no comment, a comment after the operator aside (`edit &&`, then `# check`, then the run), no line that holds `<<` and ends in one of those operators (`git apply <<'P' &&` joins the run @@ -1536,11 +1542,14 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that read with it is that earlier run's too. That report was written before the command's own run began, and a run that ended in its call writes the report as the call returns. So for a run that a command - which is no set-up stands before, the report is the command's only - when it was written no more than 10 s before the hook read it - (`OWN_REPORT_MS` in lib/test-cost.mjs). A command that is the run - alone, or has only `cd`, `export`, `source` and `.` before it, prints - no line but its own, and its report has no such bound. The first case + which is no set-up stands before, or a comment line, which is read + as one, the report is the command's only when it was written no more + than 10 s before the hook read it (`OWN_REPORT_MS` in + lib/test-cost.mjs). A command that is the run alone prints no line + but its own, and its report has no such bound. Neither has the + report of a run with only `cd`, `export`, `source` and `.` before it: + it is taken as the command's own, whatever a file that `source` or + `.` read printed. The first case is in the file where its `file` attribute names it from pytest's root. A case that a data-driven suite reads from a data file names that file, which is no Python file: it is diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 14ce1550187..e1749106a33 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1366,25 +1366,35 @@ const onlySetsUp = (head) => // `). The text names nothing that ends the shell where a command // fails: `exit`, `errexit`, or a `set` with `-e` in any of its flag words // (`set -u -e`), read within 64 characters of the `set` so that a long line -// costs time in proportion to its length. Nor does `tail`, the run and what -// follows it, close a parenthesis or a quote it did not open: the run is -// then in a group that may wait on an earlier command (`edit && (git diff; -// pytest )`), or is the text of a quoted argument (`git commit -m -// "fix; pytest "`). The text before the run is not read for either, -// since an inline script holds quotes and parentheses of its own. A script -// that starts pytest under another name is not told apart, nor is a shell -// that ends another way (`exec`). The text is read once from the run -// backwards and once line by line, so a long one (an inline script of blank -// lines) costs time in proportion to its length. +// costs time in proportion to its length. The shell reads the `;` before +// the run: no backslash stands before it, and no `#` that starts a word +// stands before the run on its line, where the run would be a comment's text +// (`git diff --stat # then; pytest `). Quotes are not read, so the +// line is read up to its first one: a `#` after it may be an argument's +// (`sed -i '5a\ # note' src/parser.py; pytest `), and a comment that +// starts there is not told apart. Nor does `tail`, the run and what follows +// it, close a parenthesis or a quote it did not open: the run is then in a +// group that may wait on an earlier command (`edit && (git diff; pytest +// )`), or is the text of a quoted argument (`git commit -m "fix; +// pytest "`). The text before the run is not read for an open +// parenthesis or quote, since an inline script holds quotes and parentheses +// of its own. A script that starts pytest under another name is not told +// apart, nor is a shell that ends another way (`exec`). The text is read +// once from the run backwards and once line by line, so a long one (an +// inline script of blank lines) costs time in proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; // A line that ends in `&&`, `||`, `&` or a pipe, with or without a comment // after it: the command it holds goes on with the next one. const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; +// A `#` that starts a word, and with it a comment to the line's end. +const COMMENT = /(?:^|[\s;&|()])#/; const startsNoRun = (head, tail) => { // Where the run's simple command starts, and the last line before it that // is no comment, up to the end of its last command. const start = head.length - head.split(/[;&|(\n]/).pop().length; if (!/[;\n]/.test(head[start - 1] || "")) return false; + if (head[start - 2] === "\\" || COMMENT.test(head.slice(head.lastIndexOf("\n") + 1).split(/['"]/, 1)[0])) + return false; const before = head.slice(0, start).replace(/^[ \t]*#[^\n]*$/gm, ""); let end = before.length; while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; @@ -1459,7 +1469,8 @@ const counted = (line, kinds) => * the folder of the one `cd` before the run, "" for none. `whole` is false for * a run filtered with `-k`. `first` is false where a command that is no set-up * stands before the run (`startsNoRun`): it may have printed a line the output - * shows. `seconds` is what pytest's last line in the visible + * shows. A comment line above the run is read as such a command + * (`onlySetsUp`). `seconds` is what pytest's last line in the visible * `output` shows (`LAST_LINE`), read without its colours. `cases` is the * cases that line counts, all but the deselected: the result file's `tests`, * but for a case whose teardown raised an error, which the line counts twice @@ -1484,8 +1495,9 @@ const counted = (line, kinds) => * line and the result file are then that command's. What may stand before * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or commands * that name no test runner and nothing that ends the shell, and are followed - * by `;` or a line's end, before a run that closes no parenthesis and no - * quote of theirs (`startsNoRun`). + * by `;` or a line's end that the shell reads (no `;` after a backslash, or + * in a comment that starts before any quote of its line), before a run that + * closes no parenthesis and no quote of theirs (`startsNoRun`). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index b2943b5520b..28ebc956700 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -263,8 +263,14 @@ test("a run that follows commands which name no test runner is a file run", () = assert.deepEqual(fileRun(`git diff --stat; # check the edit\npytest ${FILE}`), whole); // A comment line alone above the run is read as a command that is no set-up. assert.deepEqual(fileRun(`# check the parser\npytest ${FILE}`), whole); - // A `#` inside a word starts no comment. + // A `#` inside a word starts no comment, and one after a quote of the + // run's line may be an argument's: an edit that inserts a comment. assert.deepEqual(fileRun(`grep -c '^#' src/parser.py; echo $#; pytest ${FILE}`), whole); + const inserts = "sed -i '5a\\ # Keep the prefix.\\n self.count = 0' src/parser.py"; + assert.deepEqual(fileRun(`cd pkg; ${inserts}; git diff --stat; python -m pytest -q -n4 ${FILE} 2>&1 | tail -5`), { + ...whole, + dir: "pkg", + }); // A long text before the run is read in time linear in its length: without // that, 80,000 blank lines cost seconds of CPU. Each filler stands after a // command that is no set-up, so the text is read as commands that start no diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 14ce1550187..e1749106a33 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1366,25 +1366,35 @@ const onlySetsUp = (head) => // `). The text names nothing that ends the shell where a command // fails: `exit`, `errexit`, or a `set` with `-e` in any of its flag words // (`set -u -e`), read within 64 characters of the `set` so that a long line -// costs time in proportion to its length. Nor does `tail`, the run and what -// follows it, close a parenthesis or a quote it did not open: the run is -// then in a group that may wait on an earlier command (`edit && (git diff; -// pytest )`), or is the text of a quoted argument (`git commit -m -// "fix; pytest "`). The text before the run is not read for either, -// since an inline script holds quotes and parentheses of its own. A script -// that starts pytest under another name is not told apart, nor is a shell -// that ends another way (`exec`). The text is read once from the run -// backwards and once line by line, so a long one (an inline script of blank -// lines) costs time in proportion to its length. +// costs time in proportion to its length. The shell reads the `;` before +// the run: no backslash stands before it, and no `#` that starts a word +// stands before the run on its line, where the run would be a comment's text +// (`git diff --stat # then; pytest `). Quotes are not read, so the +// line is read up to its first one: a `#` after it may be an argument's +// (`sed -i '5a\ # note' src/parser.py; pytest `), and a comment that +// starts there is not told apart. Nor does `tail`, the run and what follows +// it, close a parenthesis or a quote it did not open: the run is then in a +// group that may wait on an earlier command (`edit && (git diff; pytest +// )`), or is the text of a quoted argument (`git commit -m "fix; +// pytest "`). The text before the run is not read for an open +// parenthesis or quote, since an inline script holds quotes and parentheses +// of its own. A script that starts pytest under another name is not told +// apart, nor is a shell that ends another way (`exec`). The text is read +// once from the run backwards and once line by line, so a long one (an +// inline script of blank lines) costs time in proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; // A line that ends in `&&`, `||`, `&` or a pipe, with or without a comment // after it: the command it holds goes on with the next one. const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; +// A `#` that starts a word, and with it a comment to the line's end. +const COMMENT = /(?:^|[\s;&|()])#/; const startsNoRun = (head, tail) => { // Where the run's simple command starts, and the last line before it that // is no comment, up to the end of its last command. const start = head.length - head.split(/[;&|(\n]/).pop().length; if (!/[;\n]/.test(head[start - 1] || "")) return false; + if (head[start - 2] === "\\" || COMMENT.test(head.slice(head.lastIndexOf("\n") + 1).split(/['"]/, 1)[0])) + return false; const before = head.slice(0, start).replace(/^[ \t]*#[^\n]*$/gm, ""); let end = before.length; while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; @@ -1459,7 +1469,8 @@ const counted = (line, kinds) => * the folder of the one `cd` before the run, "" for none. `whole` is false for * a run filtered with `-k`. `first` is false where a command that is no set-up * stands before the run (`startsNoRun`): it may have printed a line the output - * shows. `seconds` is what pytest's last line in the visible + * shows. A comment line above the run is read as such a command + * (`onlySetsUp`). `seconds` is what pytest's last line in the visible * `output` shows (`LAST_LINE`), read without its colours. `cases` is the * cases that line counts, all but the deselected: the result file's `tests`, * but for a case whose teardown raised an error, which the line counts twice @@ -1484,8 +1495,9 @@ const counted = (line, kinds) => * line and the result file are then that command's. What may stand before * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or commands * that name no test runner and nothing that ends the shell, and are followed - * by `;` or a line's end, before a run that closes no parenthesis and no - * quote of theirs (`startsNoRun`). + * by `;` or a line's end that the shell reads (no `;` after a backslash, or + * in a comment that starts before any quote of its line), before a run that + * closes no parenthesis and no quote of theirs (`startsNoRun`). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run From 123a45efd2cc9747a43b45aca97234ed536a8672 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 01:59:43 +0530 Subject: [PATCH 16/52] The README says a set-up command after another command joins the run like any other, and each clause of startsNoRun carries its reason `sed -i 's/a/b/' src/parser.py; cd pkg && pytest ` is no file run: where `cd` fails the run does not start, and a command before it may have printed a summary. The README read as if `cd`, `export`, `source` and `.` were aside from the join rule anywhere. They are for a run with nothing else before it, and two commands of that shape join the refusal test. The rule of `startsNoRun` stood in one paragraph above three constants. Each clause has its reason beside it, the doc comment of `fileRun` names the function in place of repeating its rule, and the expression for a shell comment is `SHELL_COMMENT`, apart from `COMMENTED`, which reads a repository's files. No behaviour changes. Signed-off-by: Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/lib/test-gate.mjs | 94 ++++++++++--------- .../tests/test-cost.test.mjs | 3 + integrations/codex-plugin/lib/test-gate.mjs | 94 ++++++++++--------- 4 files changed, 100 insertions(+), 93 deletions(-) diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index b97defb10f0..5ca0dc5ed04 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch), or one after `\;` or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run), or one that closes a parenthesis or a quote opened before it, `cd`, `export`, `source` and `.` aside (`make test || pytest `, `python edit.py && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch), or one after `\;` or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run), or one that closes a parenthesis or a quote opened before it, a run with nothing but `cd`, `export`, `source` and `.` before it aside (`make test || pytest `, `python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index e1749106a33..f6aa9587857 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1346,66 +1346,71 @@ const onlySetsUp = (head) => .split(/[;&|(\n]/) .slice(0, -1) .every((part) => SETS_UP.test(part)); -// Or any other commands, as a session writes them that edits and then checks -// in one shell call (an inline script, `git diff --stat`, `sed`), where none -// can pass for the run: a command that starts pytest itself prints a last -// line and writes the result file, and both are read as the run's where the -// run outlives its call. So the text before the run names no test runner -// (`startsRunner`: `make test`, `tox`, a `run_tests` script) and no pytest -// (`pytest.main` in an inline script), and the run does not wait on what -// those commands returned: `;` or a line's end stands before its simple -// command, and the command before that ends in no `&&`, `||`, `&` or pipe, -// on the run's line or at the end of an earlier one. A comment between the -// two is read past, as the shell reads past it: a line that is one, and one -// after the operator (`edit && # then`). So is a heredoc's text: an operator -// at the end of the line that opens one joins the run to that line's command -// (`git apply <<'P' &&`, the patch, `P`, then the run). Where a heredoc ends -// is not read, so no line that holds `<<` ends in one of those operators, a -// line of an inline script's text included. A list that ended before the run -// decides nothing, whatever joins it (`git stash pop || true; pytest -// `). The text names nothing that ends the shell where a command -// fails: `exit`, `errexit`, or a `set` with `-e` in any of its flag words -// (`set -u -e`), read within 64 characters of the `set` so that a long line -// costs time in proportion to its length. The shell reads the `;` before -// the run: no backslash stands before it, and no `#` that starts a word -// stands before the run on its line, where the run would be a comment's text -// (`git diff --stat # then; pytest `). Quotes are not read, so the -// line is read up to its first one: a `#` after it may be an argument's -// (`sed -i '5a\ # note' src/parser.py; pytest `), and a comment that -// starts there is not told apart. Nor does `tail`, the run and what follows -// it, close a parenthesis or a quote it did not open: the run is then in a -// group that may wait on an earlier command (`edit && (git diff; pytest -// )`), or is the text of a quoted argument (`git commit -m "fix; -// pytest "`). The text before the run is not read for an open -// parenthesis or quote, since an inline script holds quotes and parentheses -// of its own. A script that starts pytest under another name is not told -// apart, nor is a shell that ends another way (`exec`). The text is read -// once from the run backwards and once line by line, so a long one (an -// inline script of blank lines) costs time in proportion to its length. +// What ends the shell where a command fails: `exit`, `errexit`, or a `set` +// with `-e` in any of its flag words (`set -u -e`), read within 64 characters +// of the `set` so that a long line costs time in proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; // A line that ends in `&&`, `||`, `&` or a pipe, with or without a comment // after it: the command it holds goes on with the next one. const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; -// A `#` that starts a word, and with it a comment to the line's end. -const COMMENT = /(?:^|[\s;&|()])#/; +// A `#` that starts a word of a shell command, and with it a comment to the +// line's end. +const SHELL_COMMENT = /(?:^|[\s;&|()])#/; +// True where the commands of `head` that are no set-up cannot pass for the +// run `tail` starts with, as a session writes them that edits and then checks +// in one shell call (an inline script, `git diff --stat`, `sed`): none starts +// pytest itself, and the run starts whatever they returned. Quotes are not +// read. `head` is read once from the run backwards and once line by line, so +// a long one costs time in proportion to its length. const startsNoRun = (head, tail) => { - // Where the run's simple command starts, and the last line before it that - // is no comment, up to the end of its last command. + // `;` or a line's end stands before the run's simple command, not `&&`, + // `||`, `&`, a pipe or `(`: the run starts whatever the command before it + // returned. const start = head.length - head.split(/[;&|(\n]/).pop().length; if (!/[;\n]/.test(head[start - 1] || "")) return false; - if (head[start - 2] === "\\" || COMMENT.test(head.slice(head.lastIndexOf("\n") + 1).split(/['"]/, 1)[0])) + // The shell reads that `;`: no backslash stands before it, and no `#` that + // starts a word stands before the run on its line, where the run is a + // comment's text (`git diff --stat # then; pytest `). The line is + // read up to its first quote: a `#` after one may be an argument's (`sed -i + // '5a\ # note' src/parser.py; pytest `), and a comment that starts + // there is not told apart. + if (head[start - 2] === "\\" || SHELL_COMMENT.test(head.slice(head.lastIndexOf("\n") + 1).split(/['"]/, 1)[0])) return false; + // The last line before the run that is no comment, up to the end of its + // last command: the shell reads past a comment line. const before = head.slice(0, start).replace(/^[ \t]*#[^\n]*$/gm, ""); let end = before.length; while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; const line = before.slice(before.lastIndexOf("\n", end - 1) + 1, end); return ( + // The command before the run ends in no operator, on the run's line or at + // the end of an earlier one (`edit && # then` above the run). A list that + // ended before the run decides nothing (`git stash pop || true; pytest + // `). !JOINS.test(line) && + // Nor does a line that opens a heredoc: the run under the heredoc's text + // waits on that line's command (`git apply <<'P' &&`, the patch, `P`, the + // run). Where a heredoc ends is not read, so a line of an inline script's + // text that holds `<<` counts too. !before.split("\n").some((opens) => opens.includes("<<") && JOINS.test(opens)) && + // `head` names no pytest (`pytest.main` in an inline script): a command + // that starts pytest prints a last line and writes the result file, and + // both are read as the run's where the run outlives its call. !/py\.?test/.test(head) && + // Nor anything that ends the shell before the run starts. A shell that + // ends another way (`exec`) is not told apart. !ENDS_SHELL.test(head) && + // Nor a test runner, which starts pytest too (`make test`, `tox`, a + // `run_tests` script). A script that starts it under another name is not + // told apart. !startsRunner(head) && + // `tail`, the run and what follows it, closes no parenthesis it did not + // open: the run is then in a group that may wait on an earlier command + // (`edit && (git diff; pytest )`). !closesParen(tail) && + // Nor a quote: the run is then the text of a quoted argument (`git commit + // -m "fix; pytest "`). `head` is not read for an open parenthesis + // or quote, since an inline script holds its own. !['"', "'"].some((quote) => tail.split(quote).length % 2 === 0) ); }; @@ -1493,11 +1498,8 @@ const counted = (line, kinds) => * before which may start pytest too, or after which the run may not start * (`make test; pytest `, `python edit.py && pytest `): the last * line and the result file are then that command's. What may stand before - * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or commands - * that name no test runner and nothing that ends the shell, and are followed - * by `;` or a line's end that the shell reads (no `;` after a backslash, or - * in a comment that starts before any quote of its line), before a run that - * closes no parenthesis and no quote of theirs (`startsNoRun`). + * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or other + * commands that cannot pass for it (`startsNoRun`). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 28ebc956700..12be4ad999a 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -373,6 +373,9 @@ test("a command with two pytest runs, two paths, another selection or no run of `sleep 600 & pytest ${FILE}`, `git stash -q; (pytest ${FILE})`, `git stash -q; (\npytest ${FILE})`, + // A set-up command after another command joins the run like any other: the run may not start. + `sed -i 's/a/b/' src/parser.py; cd pkg && pytest ${FILE}`, + `tail -5 /tmp/out.txt; source .venv/bin/activate && pytest ${FILE}`, // An operator on the line that opens a heredoc joins the run to that command: the last line // before the run is the heredoc's end. `git apply <<'P' &&\n--- a/src/parser.py\n+++ b/src/parser.py\n@@ -1 +1 @@\n-a\n+b\nP\npytest ${FILE}`, diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index e1749106a33..f6aa9587857 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1346,66 +1346,71 @@ const onlySetsUp = (head) => .split(/[;&|(\n]/) .slice(0, -1) .every((part) => SETS_UP.test(part)); -// Or any other commands, as a session writes them that edits and then checks -// in one shell call (an inline script, `git diff --stat`, `sed`), where none -// can pass for the run: a command that starts pytest itself prints a last -// line and writes the result file, and both are read as the run's where the -// run outlives its call. So the text before the run names no test runner -// (`startsRunner`: `make test`, `tox`, a `run_tests` script) and no pytest -// (`pytest.main` in an inline script), and the run does not wait on what -// those commands returned: `;` or a line's end stands before its simple -// command, and the command before that ends in no `&&`, `||`, `&` or pipe, -// on the run's line or at the end of an earlier one. A comment between the -// two is read past, as the shell reads past it: a line that is one, and one -// after the operator (`edit && # then`). So is a heredoc's text: an operator -// at the end of the line that opens one joins the run to that line's command -// (`git apply <<'P' &&`, the patch, `P`, then the run). Where a heredoc ends -// is not read, so no line that holds `<<` ends in one of those operators, a -// line of an inline script's text included. A list that ended before the run -// decides nothing, whatever joins it (`git stash pop || true; pytest -// `). The text names nothing that ends the shell where a command -// fails: `exit`, `errexit`, or a `set` with `-e` in any of its flag words -// (`set -u -e`), read within 64 characters of the `set` so that a long line -// costs time in proportion to its length. The shell reads the `;` before -// the run: no backslash stands before it, and no `#` that starts a word -// stands before the run on its line, where the run would be a comment's text -// (`git diff --stat # then; pytest `). Quotes are not read, so the -// line is read up to its first one: a `#` after it may be an argument's -// (`sed -i '5a\ # note' src/parser.py; pytest `), and a comment that -// starts there is not told apart. Nor does `tail`, the run and what follows -// it, close a parenthesis or a quote it did not open: the run is then in a -// group that may wait on an earlier command (`edit && (git diff; pytest -// )`), or is the text of a quoted argument (`git commit -m "fix; -// pytest "`). The text before the run is not read for an open -// parenthesis or quote, since an inline script holds quotes and parentheses -// of its own. A script that starts pytest under another name is not told -// apart, nor is a shell that ends another way (`exec`). The text is read -// once from the run backwards and once line by line, so a long one (an -// inline script of blank lines) costs time in proportion to its length. +// What ends the shell where a command fails: `exit`, `errexit`, or a `set` +// with `-e` in any of its flag words (`set -u -e`), read within 64 characters +// of the `set` so that a long line costs time in proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; // A line that ends in `&&`, `||`, `&` or a pipe, with or without a comment // after it: the command it holds goes on with the next one. const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; -// A `#` that starts a word, and with it a comment to the line's end. -const COMMENT = /(?:^|[\s;&|()])#/; +// A `#` that starts a word of a shell command, and with it a comment to the +// line's end. +const SHELL_COMMENT = /(?:^|[\s;&|()])#/; +// True where the commands of `head` that are no set-up cannot pass for the +// run `tail` starts with, as a session writes them that edits and then checks +// in one shell call (an inline script, `git diff --stat`, `sed`): none starts +// pytest itself, and the run starts whatever they returned. Quotes are not +// read. `head` is read once from the run backwards and once line by line, so +// a long one costs time in proportion to its length. const startsNoRun = (head, tail) => { - // Where the run's simple command starts, and the last line before it that - // is no comment, up to the end of its last command. + // `;` or a line's end stands before the run's simple command, not `&&`, + // `||`, `&`, a pipe or `(`: the run starts whatever the command before it + // returned. const start = head.length - head.split(/[;&|(\n]/).pop().length; if (!/[;\n]/.test(head[start - 1] || "")) return false; - if (head[start - 2] === "\\" || COMMENT.test(head.slice(head.lastIndexOf("\n") + 1).split(/['"]/, 1)[0])) + // The shell reads that `;`: no backslash stands before it, and no `#` that + // starts a word stands before the run on its line, where the run is a + // comment's text (`git diff --stat # then; pytest `). The line is + // read up to its first quote: a `#` after one may be an argument's (`sed -i + // '5a\ # note' src/parser.py; pytest `), and a comment that starts + // there is not told apart. + if (head[start - 2] === "\\" || SHELL_COMMENT.test(head.slice(head.lastIndexOf("\n") + 1).split(/['"]/, 1)[0])) return false; + // The last line before the run that is no comment, up to the end of its + // last command: the shell reads past a comment line. const before = head.slice(0, start).replace(/^[ \t]*#[^\n]*$/gm, ""); let end = before.length; while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; const line = before.slice(before.lastIndexOf("\n", end - 1) + 1, end); return ( + // The command before the run ends in no operator, on the run's line or at + // the end of an earlier one (`edit && # then` above the run). A list that + // ended before the run decides nothing (`git stash pop || true; pytest + // `). !JOINS.test(line) && + // Nor does a line that opens a heredoc: the run under the heredoc's text + // waits on that line's command (`git apply <<'P' &&`, the patch, `P`, the + // run). Where a heredoc ends is not read, so a line of an inline script's + // text that holds `<<` counts too. !before.split("\n").some((opens) => opens.includes("<<") && JOINS.test(opens)) && + // `head` names no pytest (`pytest.main` in an inline script): a command + // that starts pytest prints a last line and writes the result file, and + // both are read as the run's where the run outlives its call. !/py\.?test/.test(head) && + // Nor anything that ends the shell before the run starts. A shell that + // ends another way (`exec`) is not told apart. !ENDS_SHELL.test(head) && + // Nor a test runner, which starts pytest too (`make test`, `tox`, a + // `run_tests` script). A script that starts it under another name is not + // told apart. !startsRunner(head) && + // `tail`, the run and what follows it, closes no parenthesis it did not + // open: the run is then in a group that may wait on an earlier command + // (`edit && (git diff; pytest )`). !closesParen(tail) && + // Nor a quote: the run is then the text of a quoted argument (`git commit + // -m "fix; pytest "`). `head` is not read for an open parenthesis + // or quote, since an inline script holds its own. !['"', "'"].some((quote) => tail.split(quote).length % 2 === 0) ); }; @@ -1493,11 +1498,8 @@ const counted = (line, kinds) => * before which may start pytest too, or after which the run may not start * (`make test; pytest `, `python edit.py && pytest `): the last * line and the result file are then that command's. What may stand before - * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or commands - * that name no test runner and nothing that ends the shell, and are followed - * by `;` or a line's end that the shell reads (no `;` after a backslash, or - * in a comment that starts before any quote of its line), before a run that - * closes no parenthesis and no quote of theirs (`startsNoRun`). + * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or other + * commands that cannot pass for it (`startsNoRun`). * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run From c4800d66ef1db2042695dd537882c608d327856a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 02:28:25 +0530 Subject: [PATCH 17/52] test(plugin): a build tool's test target after a target of a verb's name is no file run's head `make install test; pytest `, `make install testall; pytest ` and `gradle install test; pytest ` are no file runs: the command before the run starts a test runner. `make install; pytest ` is one. Fails 1 of 46 here: the three are taken for file runs. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-cost.test.mjs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 12be4ad999a..ef8f2a80106 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -236,6 +236,8 @@ test("a run that follows commands which name no test runner is a file run", () = `cat >> src/parser.py <<'E'\nclass Finder:\n found = False\nE\ntimeout 590 python -m pytest -q ${FILE}`, `git checkout src/parser.py; sed -i 's/a/b/' src/parser.py; echo 'x = 1' >> /tmp/t.py; pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt`, `rm /tmp/ex.py; pytest ${FILE}`, + // A build tool with no test target among its words. + `make install; pytest ${FILE}`, // The run starts whatever a command before it returned, an `||` list too. `git stash pop -q || true; pytest ${FILE}`, `git diff --quiet || git stash -q\npython -m pytest -q ${FILE} 2>&1 | tail -5`, @@ -359,6 +361,10 @@ test("a command with two pytest runs, two paths, another selection or no run of `python -c "import pytest; pytest.main(['tests'])"; python -m pytest ${FILE}`, `pip install -U pytest; pytest ${FILE}`, `rm -rf .pytest_cache; pytest ${FILE}`, + // A build tool's test target after a target of a verb's name is a runner here too. + `make install test; pytest ${FILE}`, + `make install testall; pytest ${FILE}`, + `gradle install test; pytest ${FILE}`, // The run may not start where `&&`, `||`, `&` or a pipe joins it to a command that is no set-up, // on the run's line or at the end of the line before it, with or without a comment between them. `python /tmp/edit.py && pytest ${FILE}`, From 5c7994ceb79b0f662f71b3b77ce523f142b25259 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 02:36:58 +0530 Subject: [PATCH 18/52] A build tool's test target after a verb-named target is a runner before a file run, and the pages name what `&`, a pipe and a late report do `make install test; pytest ` was a file run: `startsRunner` reads a test target after a target of a verb's name as a package's, so the head passed for commands that start no run. `startsNoRun` refuses a head in which a build tool is followed by a word that starts with `test`, whatever stands before the word. A package of such a name is refused with it (`npm install test-utils; pytest `). A run after `&` or a pipe always starts. It is refused because the command before it runs beside it, and may print and write after it; the comments and the pages gave "the run may not start" as the reason, which holds of `&&` and `||` alone. A command put in the background earlier in the call is not read, and the limits list says so. The limits list also names the report of a pytest that a command before the run started and that ended after the call returned (`./check.sh; pytest `, where the call times out in the script). The run is pending, that pytest began before the call returned too, and the 10 s bound is on a report read with its command: read later, the report is counted as the run's. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 46 +++++++++++++------ integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 28 ++++++++--- .../claude-code-plugin/lib/test-cost.mjs | 6 ++- .../claude-code-plugin/lib/test-gate.mjs | 40 +++++++++++----- .../tests/test-cost.test.mjs | 5 +- integrations/codex-plugin/lib/test-cost.mjs | 6 ++- integrations/codex-plugin/lib/test-gate.mjs | 40 +++++++++++----- 8 files changed, 123 insertions(+), 50 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index b59c1fb3a70..b32fa420880 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1767,26 +1767,33 @@ session's private state, by the file: parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither; -- a run counts as neither where a command before it may start pytest too, or where the - run may not start after it (`make test || pytest tests/test_big.py`, - `make build && pytest tests/test_big.py`): the result file and the summary line are - then that command's. What may stand before the run is `cd`, `export`, `source` and `.`, - or the commands of a session that edits and then checks in one shell call, such as +- a run counts as neither where a command before it may start pytest too, where the + run may not start after it, or where that command runs beside it + (`make test || pytest tests/test_big.py`, `make build && pytest tests/test_big.py`, + `sleep 600 & pytest tests/test_big.py`): the result file and the summary line may + then be that command's. What may stand before the run is `cd`, `export`, `source` and + `.`, or the commands of a session that edits and then checks in one shell call, such as `sed -i 's/a/b/' src/parser.py; git diff --stat; pytest tests/test_big.py`: they name no test runner, no `pytest` and nothing that ends the shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), and `;` or a line's end stands before the run's own command, not `&&`, `||`, `&`, a - pipe or a parenthesis. The `;` is one the shell reads: a run after `\;`, or after a - `#` that starts a word on its line ahead of the line's first quote, counts as neither + pipe or a parenthesis. A build tool with a word that starts with `test` after it + counts as a test runner there whatever stands before the word: `make install test` + runs the tests, and a package of such a name counts too (`npm install test-utils`). + After `&&` or `||` the run waits on what the command before it returned. After `&` or + a pipe the run always starts, and that command runs beside it: what it prints and + writes may come after the run's. The `;` is one the shell reads: a run after `\;`, or + after a `#` that starts a word on its line ahead of the line's first quote, counts as + neither (`git diff --stat # then; pytest tests/test_big.py` holds a comment and no run). A `#` after a quote may be an argument's, as in `sed -i '5a\ # note' src/parser.py`, - and decides nothing. A line's end after `&&`, `||`, `&` or a pipe joins the run to - that command too, with or without a comment between them (`git diff --stat &&` on the - line above the run), and so does one at the end of a line that holds `<<`: - `git apply <<'P' &&` joins the run after the patch to `git apply`. Where a heredoc ends - is not read, so a line of an inline script's text that holds `<<` and ends in one of - them counts too. A list that ended before the run decides nothing: - `git stash pop || true; pytest tests/test_big.py` counts. The run and what follows it + and decides nothing. One of `&&`, `||`, `&` or a pipe at the end of the line above the + run counts as one before the run on its line, with or without a comment between them + (`git diff --stat &&` on the line above the run), and so does one at the end of a line + that holds `<<`: under `git apply <<'P' &&`, the run after the patch waits on + `git apply`. Where a heredoc ends is not read, so a line of an inline script's text + that holds `<<` and ends in one of them counts too. A list that ended before the run + decides nothing: `git stash pop || true; pytest tests/test_big.py` counts. The run and what follows it close no parenthesis and no quote opened before them: a run in a group that waits on an earlier command (`python edit.py && (git diff --stat; pytest tests/test_big.py)`) and the text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`) count @@ -1919,6 +1926,17 @@ What it does not do: before pytest prints one. The same holds of the result file an earlier run left unread, where a command prints that run's saved summary and its call returns within 10 s of the time the file was written; +- the 10 s bound does not hold where that script's pytest ends after the call returned, + as when the call times out while the script runs + (`./check.sh; pytest tests/test_big.py`). The run after it shows no summary line and is + kept as one that outlives its call, the script's pytest began before the call returned + too, and its result file is counted as the run's when a hook reads it before the run's + own, where its first case is in the run's test file; +- a command put in the background earlier in the call is not read + (`./check.sh & sleep 1; pytest tests/test_big.py`), nor is a script that leaves its + pytest in the background. That pytest runs beside the run: where it ends after the + run, its summary line and its result file are the last ones, and are counted as the + run's where its first case is in the run's test file; - a run that never starts because the shell ends in a way the command's text does not name, such as an `exec` before it, is kept as one that outlives its call. So is a run in a comment that starts after a quote on its line diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 5ca0dc5ed04..9ebf745651a 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch), or one after `\;` or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run), or one that closes a parenthesis or a quote opened before it, a run with nothing but `cd`, `export`, `source` and `.` before it aside (`make test || pytest `, `python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `: where the run does not start, the result file and the summary are the earlier command's) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, a build tool with a word that starts with `test` after it (`make install test`), the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch), or one after `\;` or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run), or one that closes a parenthesis or a quote opened before it, a run with nothing but `cd`, `export`, `source` and `.` before it aside (`make test || pytest `, `python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `: where the run does not start, the result file and the summary are the earlier command's, and after `&` or a pipe that command runs beside the run and may print and write after it) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 6367bb4c040..f76634c835a 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1478,17 +1478,24 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that redirect of the run to a file aside (`onlyRuns`): a runner started after it (`&& make test`, `; tox`) writes the result file and prints the last line. So is a run that a command stands before which may start pytest - too, or after which the run may not start - (`make test || pytest `, `python edit.py && pytest `): the - result file and the last line are then that command's. What may stand + too, after which the run may not start, or beside which it runs + (`make test || pytest `, `python edit.py && pytest `, + `sleep 600 & pytest `): the result file and the last line may + then be that command's. What may stand before the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or the commands of a session that edits and then checks in one shell call (an inline script, `git diff --stat`, `sed`): text that names no test - runner (`startsRunner`), no pytest and nothing that ends the + runner (`startsRunner`), no build tool with a word that starts with + `test` after it, whatever stands before the word (`make install test` + runs the tests, and `npm install test-utils` counts too: + `BUILDS_TEST`), no pytest and nothing that ends the shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), with `;` or a line's end before the run's own command, not `&&`, `||`, `&`, a pipe or a - parenthesis, that `;` one the shell reads (none after a backslash, + parenthesis (after `&&` or `||` the run waits on what the command + before it returned; after `&` or a pipe it always starts, and that + command runs beside it: what it prints and writes may come after + the run's), that `;` one the shell reads (none after a backslash, and no `#` that starts a word before the run on its line, ahead of the line's first quote: `git diff --stat # then; pytest ` holds a comment and no run; quotes are not read, so a `#` after one may be @@ -1508,7 +1515,9 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that nothing: `git stash pop || true; pytest ` is a run. The text before the run is not read for an open quote or parenthesis: an inline script holds its own. A script that - starts pytest under another name is not told apart, nor is a shell + starts pytest under another name is not told apart, nor is a command + put in the background earlier in the call + (`./check.sh & sleep 1; pytest `), nor a shell that ends another way (`exec`). Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into @@ -1568,7 +1577,12 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that command, began after it. A run of the file that something else started while the pending run was in its call, such as a script in the background, began before that time too: its report, read with a command - that is not that run, is counted as the pending run's. The launcher + that is not that run, is counted as the pending run's. So is the + report of a pytest that a command before the pending run started in + the same call and that ended after the call returned + (`./check.sh; pytest `, where the call times out while the + script runs): the 10 s bound is on a report read with its command, and + this one is read later. The launcher reads the report once more at SessionEnd, before it removes the file, without reading a token. A run put in the background at once returns before pytest began, and is not counted. diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 047183f040a..be3bd5bead0 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -151,7 +151,11 @@ function add(state, run, cost) { * not a hook saw it, began its run after that. A run of the file that * something else started while the pending run was in its call began before * it too: its report, read with a command that is not that run, is taken - * for the pending run's. A run that began by the time an earlier pending + * for the pending run's. So did the pytest of a command that stands before + * the pending run in its call and ended after the call returned + * (`./check.sh; pytest `, where the call times out in the script): + * `OWN_REPORT_MS` bounds a report read with its command, not this one. A + * run that began by the time an earlier pending * run had (`dropped`) may be that run, whose report is no later run's. The * pending run is then settled; any other report leaves it pending. */ function settle(state, report) { diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index f6aa9587857..36349371ef4 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1169,9 +1169,12 @@ const FETCHED = String.raw`\s(?:(?:un)?install|add|i|ci|get|remove|rm|update|upg // build -x test`), and `test.skip`, Maven's property (`mvn package // -Dmaven.test.skip=true`). const LEFT_OUT = String.raw`\s-x\s+\S*`; +// A build tool and what stands between it and an argument of its simple +// command. +const BUILDS = String.raw`(?:go|cargo|npm|pnpm|yarn|bun|deno|make|mvn|gradle|gradlew|dotnet|swift|bazel|mix|rake|node)\s${SPAN}`; const RUNNER = new RegExp( String.raw`(? // of the `set` so that a long line costs time in proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; // A line that ends in `&&`, `||`, `&` or a pipe, with or without a comment -// after it: the command it holds goes on with the next one. +// after it: the next line's command waits on what the line's command returns +// (`&&`, `||`), or starts while it runs (`&`, a pipe). const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; // A `#` that starts a word of a shell command, and with it a comment to the // line's end. const SHELL_COMMENT = /(?:^|[\s;&|()])#/; +// A build tool with a word that starts with `test`, whatever stands before +// the word: `RUNNER` reads a test target after a target of a verb's name as a +// package's, and the tool runs it (`make install test`). +const BUILDS_TEST = new RegExp(String.raw`(? { - // `;` or a line's end stands before the run's simple command, not `&&`, - // `||`, `&`, a pipe or `(`: the run starts whatever the command before it - // returned. + // `;` or a line's end stands before the run's simple command: the command + // before it has ended, and the run starts whatever it returned. After `&&` + // or `||` the run may not start. After `&` or a pipe it always starts, and + // that command runs beside it: what it prints and writes may come after + // the run's. A `(` opens a group, which is not read. const start = head.length - head.split(/[;&|(\n]/).pop().length; if (!/[;\n]/.test(head[start - 1] || "")) return false; // The shell reads that `;`: no backslash stands before it, and no `#` that @@ -1386,7 +1397,8 @@ const startsNoRun = (head, tail) => { // The command before the run ends in no operator, on the run's line or at // the end of an earlier one (`edit && # then` above the run). A list that // ended before the run decides nothing (`git stash pop || true; pytest - // `). + // `), and a command put in the background earlier is not read + // (`redis-server & sleep 1; pytest `). !JOINS.test(line) && // Nor does a line that opens a heredoc: the run under the heredoc's text // waits on that line's command (`git apply <<'P' &&`, the patch, `P`, the @@ -1404,6 +1416,9 @@ const startsNoRun = (head, tail) => { // `run_tests` script). A script that starts it under another name is not // told apart. !startsRunner(head) && + // Nor a build tool's test target that `startsRunner` reads as a package's + // name (`make install test`). + !BUILDS_TEST.test(head) && // `tail`, the run and what follows it, closes no parenthesis it did not // open: the run is then in a group that may wait on an earlier command // (`edit && (git diff; pytest )`). @@ -1495,9 +1510,10 @@ const counted = (line, kinds) => * last line. Quotes are not read there or in the run's words (`PYTEST`), so * a run piped into `grep -E "passed|failed"` is none, and neither is one * with `-k "parse and (empty or nested)"`. Nor is a run that a command stands - * before which may start pytest too, or after which the run may not start - * (`make test; pytest `, `python edit.py && pytest `): the last - * line and the result file are then that command's. What may stand before + * before which may start pytest too, after which the run may not start, or + * beside which it runs (`make test; pytest `, `python edit.py && pytest + * `, `sleep 600 & pytest `): the last line and the result file + * may then be that command's. What may stand before * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or other * commands that cannot pass for it (`startsNoRun`). * diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index ef8f2a80106..dda48926674 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -365,8 +365,9 @@ test("a command with two pytest runs, two paths, another selection or no run of `make install test; pytest ${FILE}`, `make install testall; pytest ${FILE}`, `gradle install test; pytest ${FILE}`, - // The run may not start where `&&`, `||`, `&` or a pipe joins it to a command that is no set-up, - // on the run's line or at the end of the line before it, with or without a comment between them. + // The run may not start where `&&` or `||` joins it to a command that is no set-up, and after `&` + // or a pipe that command runs beside it: on the run's line or at the end of the line before it, + // with or without a comment between them. `python /tmp/edit.py && pytest ${FILE}`, `python /tmp/edit.py || pytest ${FILE}`, `git diff --stat &&\npytest ${FILE}`, diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 047183f040a..be3bd5bead0 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -151,7 +151,11 @@ function add(state, run, cost) { * not a hook saw it, began its run after that. A run of the file that * something else started while the pending run was in its call began before * it too: its report, read with a command that is not that run, is taken - * for the pending run's. A run that began by the time an earlier pending + * for the pending run's. So did the pytest of a command that stands before + * the pending run in its call and ended after the call returned + * (`./check.sh; pytest `, where the call times out in the script): + * `OWN_REPORT_MS` bounds a report read with its command, not this one. A + * run that began by the time an earlier pending * run had (`dropped`) may be that run, whose report is no later run's. The * pending run is then settled; any other report leaves it pending. */ function settle(state, report) { diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index f6aa9587857..36349371ef4 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1169,9 +1169,12 @@ const FETCHED = String.raw`\s(?:(?:un)?install|add|i|ci|get|remove|rm|update|upg // build -x test`), and `test.skip`, Maven's property (`mvn package // -Dmaven.test.skip=true`). const LEFT_OUT = String.raw`\s-x\s+\S*`; +// A build tool and what stands between it and an argument of its simple +// command. +const BUILDS = String.raw`(?:go|cargo|npm|pnpm|yarn|bun|deno|make|mvn|gradle|gradlew|dotnet|swift|bazel|mix|rake|node)\s${SPAN}`; const RUNNER = new RegExp( String.raw`(? // of the `set` so that a long line costs time in proportion to its length. const ENDS_SHELL = /\bset[ \t](?:[^;&|\n]{0,64}?[ \t])?-\w*e|errexit|\bexit\b/; // A line that ends in `&&`, `||`, `&` or a pipe, with or without a comment -// after it: the command it holds goes on with the next one. +// after it: the next line's command waits on what the line's command returns +// (`&&`, `||`), or starts while it runs (`&`, a pipe). const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; // A `#` that starts a word of a shell command, and with it a comment to the // line's end. const SHELL_COMMENT = /(?:^|[\s;&|()])#/; +// A build tool with a word that starts with `test`, whatever stands before +// the word: `RUNNER` reads a test target after a target of a verb's name as a +// package's, and the tool runs it (`make install test`). +const BUILDS_TEST = new RegExp(String.raw`(? { - // `;` or a line's end stands before the run's simple command, not `&&`, - // `||`, `&`, a pipe or `(`: the run starts whatever the command before it - // returned. + // `;` or a line's end stands before the run's simple command: the command + // before it has ended, and the run starts whatever it returned. After `&&` + // or `||` the run may not start. After `&` or a pipe it always starts, and + // that command runs beside it: what it prints and writes may come after + // the run's. A `(` opens a group, which is not read. const start = head.length - head.split(/[;&|(\n]/).pop().length; if (!/[;\n]/.test(head[start - 1] || "")) return false; // The shell reads that `;`: no backslash stands before it, and no `#` that @@ -1386,7 +1397,8 @@ const startsNoRun = (head, tail) => { // The command before the run ends in no operator, on the run's line or at // the end of an earlier one (`edit && # then` above the run). A list that // ended before the run decides nothing (`git stash pop || true; pytest - // `). + // `), and a command put in the background earlier is not read + // (`redis-server & sleep 1; pytest `). !JOINS.test(line) && // Nor does a line that opens a heredoc: the run under the heredoc's text // waits on that line's command (`git apply <<'P' &&`, the patch, `P`, the @@ -1404,6 +1416,9 @@ const startsNoRun = (head, tail) => { // `run_tests` script). A script that starts it under another name is not // told apart. !startsRunner(head) && + // Nor a build tool's test target that `startsRunner` reads as a package's + // name (`make install test`). + !BUILDS_TEST.test(head) && // `tail`, the run and what follows it, closes no parenthesis it did not // open: the run is then in a group that may wait on an earlier command // (`edit && (git diff; pytest )`). @@ -1495,9 +1510,10 @@ const counted = (line, kinds) => * last line. Quotes are not read there or in the run's words (`PYTEST`), so * a run piped into `grep -E "passed|failed"` is none, and neither is one * with `-k "parse and (empty or nested)"`. Nor is a run that a command stands - * before which may start pytest too, or after which the run may not start - * (`make test; pytest `, `python edit.py && pytest `): the last - * line and the result file are then that command's. What may stand before + * before which may start pytest too, after which the run may not start, or + * beside which it runs (`make test; pytest `, `python edit.py && pytest + * `, `sleep 600 & pytest `): the last line and the result file + * may then be that command's. What may stand before * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or other * commands that cannot pass for it (`startsNoRun`). * From 3e8c2e5bf19af360f830c4c5b3671e3e40b76218 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 03:11:42 +0530 Subject: [PATCH 19/52] test(plugin): a cd that does not start the command is a move the reader cannot follow after a command that is no set-up The text before a run may hold a heredoc or a quoted argument, and a `cd` in one is not the shell's. Fails on the head before it: `cat > run.sh <<'E'`, `cd pkg`, `E`, then the run is read as a run in `pkg`, and so is a run after `bash -c 'make build; cd pkg; ls'` and one after `export NOTE="built; cd pkg; ran"`. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../claude-code-plugin/tests/test-cost.test.mjs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index dda48926674..385489b323a 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -255,6 +255,10 @@ test("a run that follows commands which name no test runner is a file run", () = } // The folder of the one `cd`, and a run filtered with -k. assert.deepEqual(fileRun(`cd pkg && git stash -q; pytest ${FILE} -k parse`), { ...whole, dir: "pkg", whole: false }); + // A `cd` that starts the command is the shell's own, whatever stands between it and the run, and + // so is one among set-up alone. + assert.deepEqual(fileRun(`cd pkg && ${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -5`), { ...whole, dir: "pkg" }); + assert.deepEqual(fileRun(`export A=1; cd pkg && pytest ${FILE}`), { ...whole, dir: "pkg", first: true }); // The last line of the output is the run's where the run ended in the call, // under one that a command before the run printed. assert.equal(fileRun(`${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -3`, WHOLE_OUTPUT).seconds, 140.21); @@ -340,6 +344,12 @@ test("a command with two pytest runs, two paths, another selection or no run of `cd /work/My\\ Projects/app && pytest ${FILE}`, `cd 'My Projects' && pytest ${FILE}`, `cd -P pkg && pytest ${FILE}`, + // Nor is a `cd` that does not start the command, where a command that is no set-up stands before + // the run: it may be the text of a heredoc or of a quoted argument, which the shell does not run. + `cat > run.sh <<'E'\ncd pkg\nE\npytest ${FILE}`, + `bash -c 'make build; cd pkg; ls'; pytest ${FILE}`, + `export NOTE="built; cd pkg; ran"; pytest ${FILE}`, + `sed -i 's/a/b/' src/parser.py; cd pkg; pytest ${FILE}`, // A runner started after the run writes the result file and prints the last line. `pytest ${FILE} -q && make test`, `pytest ${FILE} -q 2>&1 | tail -3; tox`, From fea208dfdca16df01cf5c0817ec05e5fdde0766e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 03:18:08 +0530 Subject: [PATCH 20/52] After a command that is no set-up, a cd is followed only where it starts the command The text before a run may hold a heredoc or a quoted argument, which `fileRun` does not read: a `cd pkg` line under `cat > run.sh <<'E'` was followed as the shell's own, and the run's cost could be noted for `pkg/` where the checkout holds that path too. A `cd` that starts the command is the shell's own. One further on is a move the reader cannot follow, and the run is no file run. A run with only set-up before it reads its `cd` as before. The comment in `startsNoRun` gives the background case with the example the pages use, `./check.sh & sleep 1; pytest `. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 5 ++++- integrations/claude-code-plugin/hooks/HOOKS.md | 4 ++++ .../claude-code-plugin/lib/test-gate.mjs | 18 ++++++++++++++---- integrations/codex-plugin/lib/test-gate.mjs | 18 ++++++++++++++---- 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index b32fa420880..74f53b06a89 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1797,7 +1797,10 @@ session's private state, by the file: close no parenthesis and no quote opened before them: a run in a group that waits on an earlier command (`python edit.py && (git diff --stat; pytest tests/test_big.py)`) and the text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`) count - as neither. + as neither. After such commands a `cd` is followed only where it starts the command + (`cd pkg && sed -i 's/a/b/' src/parser.py; pytest tests/test_big.py`): further on it + may be the text of a heredoc or of a quoted argument, as a `cd pkg` line under + `cat > run.sh <<'E'`, and the run counts as neither. The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index f76634c835a..3843f345a6f 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1539,6 +1539,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that noted as nothing: a second `cd`, `pushd`, a `cd` in a subshell that closed, or a `cd` to a folder written with anything but letters, digits and `._/-` (a quoted or escaped name, an option, `$`, `~`). + So is a run after a `cd` that does not start the command, where a + command that is no set-up stands before the run: such a `cd` may be + the text of a heredoc or of a quoted argument, which is not read + (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run). The report is the command's when the command's visible output shows pytest's summary line with the cases, the failures and the seconds the report holds, the seconds within a second or a twentieth of them, diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 36349371ef4..18e171b77a1 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1398,7 +1398,7 @@ const startsNoRun = (head, tail) => { // the end of an earlier one (`edit && # then` above the run). A list that // ended before the run decides nothing (`git stash pop || true; pytest // `), and a command put in the background earlier is not read - // (`redis-server & sleep 1; pytest `). + // (`./check.sh & sleep 1; pytest `). !JOINS.test(line) && // Nor does a line that opens a heredoc: the run under the heredoc's text // waits on that line's command (`git apply <<'P' &&`, the patch, `P`, the @@ -1522,8 +1522,9 @@ const counted = (line, kinds) => * every case; the rest run none), or a cluster of short flags that may hold * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second - * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder that is - * not written plainly, `PLAIN_FOLDER`). The word after a flag that may take + * `cd`, `pushd`, a `cd` in a subshell that closed, one to a folder that is + * not written plainly, `PLAIN_FOLDER`, or one that does not start the + * command where `first` is false). The word after a flag that may take * a value is that value and no path (`BARE`); a short flag written with its * value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag may take * none (`--no-header`), and @@ -1548,10 +1549,19 @@ export function fileRun(command, output = "") { // the run's own, and is left out of that reading. if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; const cd = [...head.matchAll(CD)]; + // After a command that is no set-up, a `cd` is the shell's own where it + // starts the command. Further on it may be the text of a heredoc or of a + // quoted argument (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run), + // which is not read. const followed = cd.length < 2 && (head.match(MOVE) || []).length === cd.length && - cd.every((m) => PLAIN_FOLDER.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); + cd.every( + (m) => + PLAIN_FOLDER.test(m[1]) && + (first || !head.slice(0, m.index).trim()) && + !closesParen(head.slice(m.index + m[0].length)), + ); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; const values = []; diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 36349371ef4..18e171b77a1 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1398,7 +1398,7 @@ const startsNoRun = (head, tail) => { // the end of an earlier one (`edit && # then` above the run). A list that // ended before the run decides nothing (`git stash pop || true; pytest // `), and a command put in the background earlier is not read - // (`redis-server & sleep 1; pytest `). + // (`./check.sh & sleep 1; pytest `). !JOINS.test(line) && // Nor does a line that opens a heredoc: the run under the heredoc's text // waits on that line's command (`git apply <<'P' &&`, the patch, `P`, the @@ -1522,8 +1522,9 @@ const counted = (line, kinds) => * every case; the rest run none), or a cluster of short flags that may hold * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second - * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder that is - * not written plainly, `PLAIN_FOLDER`). The word after a flag that may take + * `cd`, `pushd`, a `cd` in a subshell that closed, one to a folder that is + * not written plainly, `PLAIN_FOLDER`, or one that does not start the + * command where `first` is false). The word after a flag that may take * a value is that value and no path (`BARE`); a short flag written with its * value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag may take * none (`--no-header`), and @@ -1548,10 +1549,19 @@ export function fileRun(command, output = "") { // the run's own, and is left out of that reading. if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; const cd = [...head.matchAll(CD)]; + // After a command that is no set-up, a `cd` is the shell's own where it + // starts the command. Further on it may be the text of a heredoc or of a + // quoted argument (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run), + // which is not read. const followed = cd.length < 2 && (head.match(MOVE) || []).length === cd.length && - cd.every((m) => PLAIN_FOLDER.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); + cd.every( + (m) => + PLAIN_FOLDER.test(m[1]) && + (first || !head.slice(0, m.index).trim()) && + !closesParen(head.slice(m.index + m[0].length)), + ); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; const values = []; From b680fe7fb59d12b5349e7646940d2f5f00e926d9 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 03:44:41 +0530 Subject: [PATCH 21/52] test(plugin): a cd with no folder is a move, and the text after a followed cd is not read for a parenthesis Three cases fail: `cd; pytest ` and `cd` on a line above the run are read as runs in the session's folder, though the shell ran them in the home folder, by the cost reader and by the test gate; and a run after `cd pkg &&` and an edit whose own text closes a parenthesis is no file run, while the same command without the `cd` is one. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-cost.test.mjs | 7 +++++++ integrations/claude-code-plugin/tests/test-gate.test.mjs | 2 ++ 2 files changed, 9 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 385489b323a..38db0345ec5 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -259,6 +259,8 @@ test("a run that follows commands which name no test runner is a file run", () = // so is one among set-up alone. assert.deepEqual(fileRun(`cd pkg && ${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -5`), { ...whole, dir: "pkg" }); assert.deepEqual(fileRun(`export A=1; cd pkg && pytest ${FILE}`), { ...whole, dir: "pkg", first: true }); + // The text between that `cd` and the run is not read for a parenthesis: an edit holds its own. + assert.deepEqual(fileRun(`cd pkg && sed -i 's/)$/, None)/' src/parser.py; pytest ${FILE}`), { ...whole, dir: "pkg" }); // The last line of the output is the run's where the run ended in the call, // under one that a command before the run printed. assert.equal(fileRun(`${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -3`, WHOLE_OUTPUT).seconds, 140.21); @@ -338,7 +340,12 @@ test("a command with two pytest runs, two paths, another selection or no run of `cd a && cd b && pytest ${FILE}`, `pushd pkg && pytest ${FILE}`, `(cd pkg && make build); pytest ${FILE}`, + ` (cd pkg; git stash -q)\npytest ${FILE}`, `cd "$PKG" && pytest ${FILE}`, + // A `cd` with no folder goes to the home folder, and the word on the next line is no folder. + `cd; pytest ${FILE}`, + `sed -i 's/a/b/' src/parser.py; cd; pytest ${FILE}`, + `cd\npython -m pytest ${FILE}`, // A folder that is not written plainly: its name is cut at a space, or is an option. `cd "/work/My Projects/app" && pytest ${FILE}`, `cd /work/My\\ Projects/app && pytest ${FILE}`, diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index d78b0905b27..e9c572f6b16 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1270,6 +1270,8 @@ test("a run's paths are read from the directory its command moved to", () => { "pushd sub && pytest tests -q", "(cd sub && make build); pytest tests -q", "cd a && cd sub && pytest tests -q", + // A `cd` with no folder goes to the home folder. + "cd; pytest tests -q", "docker exec app pytest tests -q", "kubectl exec pod -- pytest tests -q", "ssh host 'cd repo; pytest tests -q'", From 1e454e825c8b29d52a9969b018de10bb2af08a31 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 03:52:03 +0530 Subject: [PATCH 22/52] A cd with no folder is a move, and the text after a followed cd is not read for a parenthesis A `cd` with no folder goes to the home folder. Both readers of a command's moves wanted a blank after `cd`, so `cd; pytest ` held no move, and a line's end counted as that blank, so the first word of the next line was read as the folder. The move now ends at a separator or the command's end, and the folder stands on the line of its `cd`: such a run is no file run, and the test gate does not take it for a run in the session's folder. After a command that is no set-up, a `cd` that starts the command is refused where it stands in a group, and the text after it is no longer read for a closing parenthesis: that text is the edit's own (`sed -i 's/)$/, None)/'`), and a group that holds the run is already refused. The README names what text before a run is refused (any text that holds `pytest`, as `.pytest_cache`) in sentences of its own. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 8 +++-- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 13 ++++--- .../claude-code-plugin/lib/test-gate.mjs | 36 ++++++++++--------- integrations/codex-plugin/lib/test-gate.mjs | 36 ++++++++++--------- 5 files changed, 56 insertions(+), 39 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 74f53b06a89..4acf4e44efd 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1774,7 +1774,8 @@ session's private state, by the file: then be that command's. What may stand before the run is `cd`, `export`, `source` and `.`, or the commands of a session that edits and then checks in one shell call, such as `sed -i 's/a/b/' src/parser.py; git diff --stat; pytest tests/test_big.py`: they name - no test runner, no `pytest` and nothing that ends the shell where a command fails + no test runner, their text holds no `pytest` or `py.test` (`.pytest_cache` and + `pytest.ini` hold it) and nothing that ends the shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), and `;` or a line's end stands before the run's own command, not `&&`, `||`, `&`, a pipe or a parenthesis. A build tool with a word that starts with `test` after it @@ -1800,7 +1801,10 @@ session's private state, by the file: as neither. After such commands a `cd` is followed only where it starts the command (`cd pkg && sed -i 's/a/b/' src/parser.py; pytest tests/test_big.py`): further on it may be the text of a heredoc or of a quoted argument, as a `cd pkg` line under - `cat > run.sh <<'E'`, and the run counts as neither. + `cat > run.sh <<'E'`, and the run counts as neither. So does a run after a `cd` that + starts the command in a group (`(cd pkg && git stash -q); pytest tests/test_big.py`); +- a run after a `cd` with no folder counts as neither: `cd; pytest tests/test_big.py` + runs in the home folder. The result file is the command's when the command's output shows pytest's summary line, whatever it counts, with the cases, the failures and the seconds the file holds (the diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 9ebf745651a..95103599ca0 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary), a run that a test runner, a build tool with a word that starts with `test` after it (`make install test`), the word `pytest`, a `set` with `-e` among its flags, `errexit` or `exit` stands before in its command, or one joined to an earlier command by anything but `;` or a line's end (`&&` or `||` at the end of the line before it joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch), or one after `\;` or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run), or one that closes a parenthesis or a quote opened before it, a run with nothing but `cd`, `export`, `source` and `.` before it aside (`make test || pytest `, `python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `: where the run does not start, the result file and the summary are the earlier command's, and after `&` or a pipe that command runs beside the run and may print and write after it) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in four cases. First, the text before the run names a test runner, a build tool with a word that starts with `test` after it (`make install test`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 3843f345a6f..843bc407e85 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1488,7 +1488,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that runner (`startsRunner`), no build tool with a word that starts with `test` after it, whatever stands before the word (`make install test` runs the tests, and `npm install test-utils` counts too: - `BUILDS_TEST`), no pytest and nothing that ends the + `BUILDS_TEST`), no `pytest` or `py.test` in any word + (`.pytest_cache`, `pytest.ini`) and nothing that ends the shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), with `;` or a line's end before the run's own command, not `&&`, `||`, `&`, a pipe or a @@ -1536,13 +1537,17 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that file or a folder is noted as nothing too. The file is the one the command names, from the payload's folder and the command's one `cd`, where it is there. A run after a move the hook does not follow is - noted as nothing: a second `cd`, `pushd`, a `cd` in a subshell that - closed, or a `cd` to a folder written with anything but letters, + noted as nothing: a second `cd`, `pushd`, a `cd` with no folder + (`cd; pytest ` runs in the home folder), a `cd` in a subshell + that closed, or a `cd` to a folder written with anything but letters, digits and `._/-` (a quoted or escaped name, an option, `$`, `~`). So is a run after a `cd` that does not start the command, where a command that is no set-up stands before the run: such a `cd` may be the text of a heredoc or of a quoted argument, which is not read - (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run). + (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run). A `cd` that + starts such a command in a group is not followed either + (`(cd pkg && git stash -q); pytest `), and the text after one + that is followed is not read for a parenthesis. The report is the command's when the command's visible output shows pytest's summary line with the cases, the failures and the seconds the report holds, the seconds within a second or a twentieth of them, diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 18e171b77a1..3044fbced14 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1308,9 +1308,11 @@ const STOPS = /(?:^|\s)(?:-[A-Za-z]*x|--exitfirst|--maxfail)/; const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // The directory a command moves to before it runs something, and any move. // Only spaces and tabs are read between a separator and `cd`: a line's end is -// a separator itself, and a run of blank lines is then read once. -const CD = /(?:^|[;&|(\n])[ \t]*cd\s+([^\s;&|)]+)/g; -const MOVE = /\b(?:cd|pushd|popd)\s/g; +// a separator itself, and a run of blank lines is then read once. Nor is a +// line's end read between `cd` and its folder: a `cd` with no folder goes to +// the home folder, and is a move with no directory. +const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; +const MOVE = /\b(?:cd|pushd|popd)(?=[\s;&|)]|$)/g; const unquoted = (word) => word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path @@ -1522,12 +1524,12 @@ const counted = (line, kinds) => * every case; the rest run none), or a cluster of short flags that may hold * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second - * `cd`, `pushd`, a `cd` in a subshell that closed, one to a folder that is - * not written plainly, `PLAIN_FOLDER`, or one that does not start the - * command where `first` is false). The word after a flag that may take - * a value is that value and no path (`BARE`); a short flag written with its - * value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag may take - * none (`--no-header`), and + * `cd`, `pushd`, a `cd` with no folder, one in a subshell that closed, one + * to a folder that is not written plainly, `PLAIN_FOLDER`, or one that does + * not start the command where `first` is false). The word after a flag that + * may take a value is that value and no path (`BARE`); a short flag written + * with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag + * may take none (`--no-header`), and * the word after it is then a second path: a run with such a word that names * a Python file is none, and the others are `values`. The caller drops a run * where one of them names a folder (`--no-header tests`, and `--cov src` @@ -1550,17 +1552,19 @@ export function fileRun(command, output = "") { if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; const cd = [...head.matchAll(CD)]; // After a command that is no set-up, a `cd` is the shell's own where it - // starts the command. Further on it may be the text of a heredoc or of a - // quoted argument (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run), - // which is not read. + // starts the command, outside a group. Further on it may be the text of a + // heredoc or of a quoted argument (`cat > run.sh <<'E'`, `cd pkg`, `E`, + // then the run), which is not read, and neither is the text after the `cd` + // for the end of a group: an edit holds its own parentheses. const followed = cd.length < 2 && (head.match(MOVE) || []).length === cd.length && cd.every( (m) => PLAIN_FOLDER.test(m[1]) && - (first || !head.slice(0, m.index).trim()) && - !closesParen(head.slice(m.index + m[0].length)), + (first + ? !closesParen(head.slice(m.index + m[0].length)) + : !m[0].startsWith("(") && !head.slice(0, m.index).trim()), ); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; @@ -1652,8 +1656,8 @@ function wholeRuns(objs, { root, cwd, since } = {}) { // that failed to import as one error among the tests that ran; a // quoted argument may be a flag's value in several words; a move the // reader cannot follow (a second `cd`, one between two runs, one in a - // subshell that closed before the run, `pushd`) leaves the paths - // unknown. + // subshell that closed before the run, one with no folder, `pushd`) + // leaves the paths unknown. const ran = from >= 0 && allRan(result.output, runs) && diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 18e171b77a1..3044fbced14 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1308,9 +1308,11 @@ const STOPS = /(?:^|\s)(?:-[A-Za-z]*x|--exitfirst|--maxfail)/; const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // The directory a command moves to before it runs something, and any move. // Only spaces and tabs are read between a separator and `cd`: a line's end is -// a separator itself, and a run of blank lines is then read once. -const CD = /(?:^|[;&|(\n])[ \t]*cd\s+([^\s;&|)]+)/g; -const MOVE = /\b(?:cd|pushd|popd)\s/g; +// a separator itself, and a run of blank lines is then read once. Nor is a +// line's end read between `cd` and its folder: a `cd` with no folder goes to +// the home folder, and is a move with no directory. +const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; +const MOVE = /\b(?:cd|pushd|popd)(?=[\s;&|)]|$)/g; const unquoted = (word) => word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path @@ -1522,12 +1524,12 @@ const counted = (line, kinds) => * every case; the rest run none), or a cluster of short flags that may hold * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second - * `cd`, `pushd`, a `cd` in a subshell that closed, one to a folder that is - * not written plainly, `PLAIN_FOLDER`, or one that does not start the - * command where `first` is false). The word after a flag that may take - * a value is that value and no path (`BARE`); a short flag written with its - * value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag may take - * none (`--no-header`), and + * `cd`, `pushd`, a `cd` with no folder, one in a subshell that closed, one + * to a folder that is not written plainly, `PLAIN_FOLDER`, or one that does + * not start the command where `first` is false). The word after a flag that + * may take a value is that value and no path (`BARE`); a short flag written + * with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag + * may take none (`--no-header`), and * the word after it is then a second path: a run with such a word that names * a Python file is none, and the others are `values`. The caller drops a run * where one of them names a folder (`--no-header tests`, and `--cov src` @@ -1550,17 +1552,19 @@ export function fileRun(command, output = "") { if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; const cd = [...head.matchAll(CD)]; // After a command that is no set-up, a `cd` is the shell's own where it - // starts the command. Further on it may be the text of a heredoc or of a - // quoted argument (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run), - // which is not read. + // starts the command, outside a group. Further on it may be the text of a + // heredoc or of a quoted argument (`cat > run.sh <<'E'`, `cd pkg`, `E`, + // then the run), which is not read, and neither is the text after the `cd` + // for the end of a group: an edit holds its own parentheses. const followed = cd.length < 2 && (head.match(MOVE) || []).length === cd.length && cd.every( (m) => PLAIN_FOLDER.test(m[1]) && - (first || !head.slice(0, m.index).trim()) && - !closesParen(head.slice(m.index + m[0].length)), + (first + ? !closesParen(head.slice(m.index + m[0].length)) + : !m[0].startsWith("(") && !head.slice(0, m.index).trim()), ); const words = (runs[0][1].replace(/\d?>>?\s*\S*/g, " ").match(/"[^"]*"|'[^']*'|\S+/g) || []).map(unquoted); const named = []; @@ -1652,8 +1656,8 @@ function wholeRuns(objs, { root, cwd, since } = {}) { // that failed to import as one error among the tests that ran; a // quoted argument may be a flag's value in several words; a move the // reader cannot follow (a second `cd`, one between two runs, one in a - // subshell that closed before the run, `pushd`) leaves the paths - // unknown. + // subshell that closed before the run, one with no folder, `pushd`) + // leaves the paths unknown. const ran = from >= 0 && allRan(result.output, runs) && From 71fc7d96ca480a365db1d8f65ad830367d6c1982 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 04:18:51 +0530 Subject: [PATCH 23/52] test(plugin): a remote or container tool's name before a run, and test after no letter inside a word, make no file run Both refusals hold already; no test named a command for either. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-cost.test.mjs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 38db0345ec5..38da7e54f3c 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -382,6 +382,10 @@ test("a command with two pytest runs, two paths, another selection or no run of `make install test; pytest ${FILE}`, `make install testall; pytest ${FILE}`, `gradle install test; pytest ${FILE}`, + // So is `test` after no letter inside a word, which no other rule reads as a run. + `make run-testsuite; pytest ${FILE}`, + `go build ./internal/testutil/...; pytest ${FILE}`, + `npm run build:testdata; pytest ${FILE}`, // The run may not start where `&&` or `||` joins it to a command that is no set-up, and after `&` // or a pipe that command runs beside it: on the run's line or at the end of the line before it, // with or without a comment between them. @@ -428,6 +432,10 @@ test("a command with two pytest runs, two paths, another selection or no run of `pytest ${FILE} -k "parse and (empty or nested)" -q`, // Run elsewhere, or not run. `docker exec app pytest ${FILE}`, + // What follows `ssh`, `docker`, `podman` or `kubectl` anywhere before the run may run elsewhere. + `docker compose up -d db; pytest ${FILE}`, + `ssh build 'make assets'; pytest ${FILE}`, + `export NOTE="see kubectl logs"; pytest ${FILE}`, `echo "pytest ${FILE}"`, `grep -rn pytest ${FILE}`, "make test", From 34aa01028912058626ee693cfe43d687ac70f8e0 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 04:23:28 +0530 Subject: [PATCH 24/52] The pages name every refusal of a run after other commands, and say what a build tool's test word is The README counted four cases where a run after other commands is no file run, and the code has two more: a cd that does not start the command, and the word ssh, docker, podman or kubectl anywhere before the run. The second was in no page. The comment and three pages said a build tool is refused with a word that starts with test, and the expression takes test after no letter, inside a word too. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 11 ++++++++--- integrations/claude-code-plugin/README.md | 2 +- integrations/claude-code-plugin/hooks/HOOKS.md | 13 +++++++++---- integrations/claude-code-plugin/lib/test-gate.mjs | 8 +++++--- .../claude-code-plugin/tests/test-cost.test.mjs | 2 +- integrations/codex-plugin/lib/test-gate.mjs | 8 +++++--- 6 files changed, 29 insertions(+), 15 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 4acf4e44efd..72af089b033 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1778,9 +1778,14 @@ session's private state, by the file: `pytest.ini` hold it) and nothing that ends the shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), and `;` or a line's end stands before the run's own command, not `&&`, `||`, `&`, a - pipe or a parenthesis. A build tool with a word that starts with `test` after it - counts as a test runner there whatever stands before the word: `make install test` - runs the tests, and a package of such a name counts too (`npm install test-utils`). + pipe or a parenthesis. A build tool with `test` after no letter further on in its + command counts as a test runner there, inside a word too and whatever stands before + it: `make install test` runs the tests, and a package, a target or a path of such a + name counts too (`npm install test-utils`, `make run-testsuite`, + `go build ./internal/testutil/...`). Nor does the text before the run hold the word + `ssh`, `docker`, `podman` or `kubectl`, in a set-up command's value too: what follows + one may run elsewhere, so `docker compose up -d db; pytest tests/test_big.py` counts + as neither. After `&&` or `||` the run waits on what the command before it returned. After `&` or a pipe the run always starts, and that command runs beside it: what it prints and writes may come after the run's. The `;` is one the shell reads: a run after `\;`, or diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 95103599ca0..3f0f636afee 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in four cases. First, the text before the run names a test runner, a build tool with a word that starts with `test` after it (`make install test`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `cd` stands before the run that does not start the command, or that starts it in a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `): further on it may be the text of a heredoc or of a quoted argument. Sixth, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 843bc407e85..5f14e4b2f3e 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1485,10 +1485,15 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that before the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or the commands of a session that edits and then checks in one shell call (an inline script, `git diff --stat`, `sed`): text that names no test - runner (`startsRunner`), no build tool with a word that starts with - `test` after it, whatever stands before the word (`make install test` - runs the tests, and `npm install test-utils` counts too: - `BUILDS_TEST`), no `pytest` or `py.test` in any word + runner (`startsRunner`), no build tool with `test` after no letter + further on in its command, inside a word too and whatever stands + before it (`make install test` runs the tests, and + `npm install test-utils`, `make run-testsuite` and + `go build ./internal/testutil/...` count too: `BUILDS_TEST`), no word + `ssh`, `docker`, `podman` or `kubectl`, in a set-up command's value + too (`ranHere`: what follows one may run elsewhere, so + `docker compose up -d db; pytest ` is noted as nothing), no + `pytest` or `py.test` in any word (`.pytest_cache`, `pytest.ini`) and nothing that ends the shell where a command fails (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), with `;` or a line's diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 3044fbced14..efad7783b6f 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1362,9 +1362,11 @@ const JOINS = /[&|][ \t]*(?:#[^\n]*)?$/; // A `#` that starts a word of a shell command, and with it a comment to the // line's end. const SHELL_COMMENT = /(?:^|[\s;&|()])#/; -// A build tool with a word that starts with `test`, whatever stands before -// the word: `RUNNER` reads a test target after a target of a verb's name as a -// package's, and the tool runs it (`make install test`). +// A build tool with `test` after no letter further on in its simple command, +// inside a word too and whatever stands before it: `RUNNER` reads a test +// target after a target of a verb's name as a package's, and the tool runs it +// (`make install test`), and it reads no `test` before a lower-case letter +// but at a word's start (`make run-testsuite`). const BUILDS_TEST = new RegExp(String.raw`(? Date: Sun, 6 Dec 2026 04:56:11 +0530 Subject: [PATCH 25/52] test(plugin): the gate reads no folder for a cd on a line of its own, and the hooks page numbers the refusals of a run after other commands The Stop gate's reader shares `CD` and `MOVE` with `fileRun`. Where `CD` reads the first word of the next line as the folder, `cd` on a line above `python -m pytest tests -q` answers a gate whose test is under `python/tests/`. The gate test holds that command against such a gate. HOOKS.md held every condition of `startsNoRun` in one sentence. It lists them as the six cases the README numbers, the `cd` case among them. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../claude-code-plugin/hooks/HOOKS.md | 87 ++++++++++--------- .../tests/test-gate.test.mjs | 9 +- 2 files changed, 54 insertions(+), 42 deletions(-) diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 5f14e4b2f3e..00dbc0f2167 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1484,40 +1484,52 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that then be that command's. What may stand before the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or the commands of a session that edits and then checks in one shell call - (an inline script, `git diff --stat`, `sed`): text that names no test - runner (`startsRunner`), no build tool with `test` after no letter - further on in its command, inside a word too and whatever stands - before it (`make install test` runs the tests, and - `npm install test-utils`, `make run-testsuite` and - `go build ./internal/testutil/...` count too: `BUILDS_TEST`), no word - `ssh`, `docker`, `podman` or `kubectl`, in a set-up command's value - too (`ranHere`: what follows one may run elsewhere, so - `docker compose up -d db; pytest ` is noted as nothing), no - `pytest` or `py.test` in any word - (`.pytest_cache`, `pytest.ini`) and nothing that ends the - shell where a command fails (`exit`, `errexit`, a `set` with `-e` - among its flags, as `set -e` and `set -u -e`), with `;` or a line's - end before the run's own command, not `&&`, `||`, `&`, a pipe or a - parenthesis (after `&&` or `||` the run waits on what the command - before it returned; after `&` or a pipe it always starts, and that - command runs beside it: what it prints and writes may come after - the run's), that `;` one the shell reads (none after a backslash, - and no `#` that starts a word before the run on its line, ahead of - the line's first quote: `git diff --stat # then; pytest ` holds - a comment and no run; quotes are not read, so a `#` after one may be - an argument's, as in `sed -i '5a\ # note' src/parser.py`, and a - comment that starts there is not told apart), no `&&`, `||`, `&` or - pipe at the end of the last line - before it that is no comment, a comment after the operator aside - (`edit &&`, then `# check`, then the run), no line that holds `<<` - and ends in one of those operators (`git apply <<'P' &&` joins the run - after the patch to `git apply`; where a heredoc ends is not read, so a - line of an inline script's text counts too), and a run that with what - follows it closes no parenthesis - and no quote opened before it (`startsNoRun`): a run in a group that - waits on an earlier command (`edit && (git diff; pytest )`) and - the text of a quoted argument (`git commit -m "fix; pytest "`) - are noted as nothing. A list that ended before the run decides + (an inline script, `git diff --stat`, `sed`). After such commands the + run is noted as nothing in the six cases that follow; `startsNoRun` + reads the first four. + First, the text before the run names a test runner (`startsRunner`), + holds `pytest` or `py.test` in any word (`.pytest_cache`, + `pytest.ini`), or holds something that ends the shell where a command + fails: `exit`, `errexit`, or a `set` with `-e` among its flags, as + `set -e` and `set -u -e`. A build tool with `test` after no letter + further on in its command counts as a test runner there, inside a + word too and whatever stands before it (`BUILDS_TEST`): + `make install test` runs the tests, and `npm install test-utils`, + `make run-testsuite` and `go build ./internal/testutil/...` count too. + Second, `&&`, `||`, `&`, a pipe or a parenthesis stands before the + run's own command, not `;` or a line's end. After `&&` or `||` the run + waits on what the command before it returned. After `&` or a pipe it + always starts, and that command runs beside it: what it prints and + writes may come after the run's. One of `&&`, `||`, `&` or a pipe at + the end of the last line before the run that is no comment joins the + run to that line's command too, a comment after the operator aside + (`edit &&`, then `# check`, then the run). So does one at the end of + a line that holds `<<`: `git apply <<'P' &&` joins the run after the + patch to `git apply`. Where a heredoc ends is not read, so a line of + an inline script's text counts too. + Third, the shell does not read the `;` before the run: a backslash + stands before it, or a `#` that starts a word stands before the run + on its line, ahead of the line's first quote + (`git diff --stat # then; pytest ` holds a comment and no run). + Quotes are not read, so a `#` after one may be an argument's, as in + `sed -i '5a\ # note' src/parser.py`, and a comment that starts there + is not told apart. + Fourth, the run and what follows it close a parenthesis or a quote + opened before them: the run is in a group that waits on an earlier + command (`edit && (git diff; pytest )`), or it is the text of a + quoted argument (`git commit -m "fix; pytest "`). + Fifth, a `cd` stands before the run that does not start the command, + or that starts it in a group. Further on, a `cd` may be the text of a + heredoc or of a quoted argument, which is not read + (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run). A group ends + before the run (`(cd pkg && git stash -q); pytest `). The text + after a `cd` that starts the command outside a group is not read for + a parenthesis. + Sixth, the text before the run holds the word `ssh`, `docker`, + `podman` or `kubectl`, in a set-up command's value too (`ranHere`): + what follows one may run elsewhere, so + `docker compose up -d db; pytest ` is noted as nothing. + A list that ended before the run decides nothing: `git stash pop || true; pytest ` is a run. The text before the run is not read for an open quote or parenthesis: an inline script holds its own. A script that @@ -1546,13 +1558,6 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that (`cd; pytest ` runs in the home folder), a `cd` in a subshell that closed, or a `cd` to a folder written with anything but letters, digits and `._/-` (a quoted or escaped name, an option, `$`, `~`). - So is a run after a `cd` that does not start the command, where a - command that is no set-up stands before the run: such a `cd` may be - the text of a heredoc or of a quoted argument, which is not read - (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run). A `cd` that - starts such a command in a group is not followed either - (`(cd pkg && git stash -q); pytest `), and the text after one - that is followed is not read for a parenthesis. The report is the command's when the command's visible output shows pytest's summary line with the cases, the failures and the seconds the report holds, the seconds within a second or a twentieth of them, diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index e9c572f6b16..de2ad41e65d 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1266,12 +1266,18 @@ test("a run's paths are read from the directory its command moved to", () => { true, ); // A move this reader does not follow, and a run outside the checkout. + const inPython = { + ...RUN_GATE, + tests: [{ test_path: "python/tests/test_a.py", run: "pytest python/tests/test_a.py" }], + }; for (const elsewhere of [ "pushd sub && pytest tests -q", "(cd sub && make build); pytest tests -q", "cd a && cd sub && pytest tests -q", - // A `cd` with no folder goes to the home folder. + // A `cd` with no folder goes to the home folder: the word on the line + // under it is the next command, not its folder. "cd; pytest tests -q", + "cd\npython -m pytest tests -q", "docker exec app pytest tests -q", "kubectl exec pod -- pytest tests -q", "ssh host 'cd repo; pytest tests -q'", @@ -1279,6 +1285,7 @@ test("a run's paths are read from the directory its command moved to", () => { ]) { assert.equal(answered([edit(), bash(elsewhere, "3 passed in 0.10s")]), false, elsewhere); assert.equal(answered([edit(), bash(elsewhere, "3 passed in 0.10s")], nested), false, elsewhere); + assert.equal(answered([edit(), bash(elsewhere, "3 passed in 0.10s")], inPython), false, elsewhere); } // A PowerShell run is not read: its moves are not ones the reader knows. for (const command of ["pytest tests -q", "Set-Location sub; pytest tests -q"]) { From 9c817ec0baee920f31861d9cb7f2976af5fb421d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 05:20:13 +0530 Subject: [PATCH 26/52] test(plugin): the case of a run in a group on one line reaches the parenthesis rule `PYTEST` reads no run written straight after `(`, so `fileRun` returned nothing for `git stash -q; (pytest )` before it read the text before the run, and the case passed with the parenthesis rule taken out. With a space after the `(` the run is read and the parenthesis is what refuses it. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-cost.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index a8b89e10159..dae379346dc 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -399,7 +399,7 @@ test("a command with two pytest runs, two paths, another selection or no run of `cat /tmp/names.txt |\n# the names\npytest ${FILE}`, `cat /tmp/names.txt | pytest ${FILE}`, `sleep 600 & pytest ${FILE}`, - `git stash -q; (pytest ${FILE})`, + `git stash -q; ( pytest ${FILE})`, `git stash -q; (\npytest ${FILE})`, // A set-up command after another command joins the run like any other: the run may not start. `sed -i 's/a/b/' src/parser.py; cd pkg && pytest ${FILE}`, From a6d90204c8118047bc55d52db58b022e7fdfde1c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 05:44:39 +0530 Subject: [PATCH 27/52] test(plugin): the word cd at the end of an argument is no move `MOVE` counts `cd`, `pushd` and `popd` before `;`, `&`, `|`, `)` or the text's end wherever the word stands, so an argument that ends in `cd` is read as a move with no folder. `export OUT=/media/cd; pytest ` is then no file run, and `ls /media/cd; pytest tests -q` does not answer the Stop gate. Three tests fail: the two lists of file runs and the gate's. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-cost.test.mjs | 4 ++++ integrations/claude-code-plugin/tests/test-gate.test.mjs | 2 ++ 2 files changed, 6 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index dae379346dc..a03bf3fa045 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -144,6 +144,8 @@ test("a command's one pytest run of one test file is whole or filtered with -k", // What sets the shell up may stand before it. `source .venv/bin/activate && export PYTHONPATH=src; pytest ${FILE}`, `. .venv/bin/activate; pytest ${FILE} -q`, + // The word `cd` at the end of a value is no move. + `export OUT=/media/cd; pytest ${FILE}`, // What reads the run's output may follow it. `pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt; echo exit=$?`, ]) { @@ -236,6 +238,8 @@ test("a run that follows commands which name no test runner is a file run", () = `cat >> src/parser.py <<'E'\nclass Finder:\n found = False\nE\ntimeout 590 python -m pytest -q ${FILE}`, `git checkout src/parser.py; sed -i 's/a/b/' src/parser.py; echo 'x = 1' >> /tmp/t.py; pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt`, `rm /tmp/ex.py; pytest ${FILE}`, + // The word `cd` at the end of an argument is no move. + `ls /media/cd; pytest ${FILE}`, // A build tool with no test target among its words. `make install; pytest ${FILE}`, // The run starts whatever a command before it returned, an `||` list too. diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index de2ad41e65d..4afad9c04fe 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1265,6 +1265,8 @@ test("a run's paths are read from the directory its command moved to", () => { answered([edit(), bash("pytest tests -q", "3 passed in 0.10s", { cwd: ROOT })], RUN_GATE, "/r/sub"), true, ); + // The word `cd` at the end of an argument is no move. + assert.equal(answered([edit(), bash("ls /media/cd; pytest tests -q", "3 passed in 0.10s")]), true); // A move this reader does not follow, and a run outside the checkout. const inPython = { ...RUN_GATE, From c581a07e005e94c7d1a51b22be0ee853841d5922 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 05:45:55 +0530 Subject: [PATCH 28/52] A cd with no folder is a move only where it starts a command `MOVE` reads `cd`, `pushd` and `popd` before a blank wherever the word stands, as on `main`, and a `cd` straight before `;`, `&`, `|` or `)` only after the text's start or a separator. The word at the end of an argument (`export OUT=/media/cd; pytest `, `ls /media/cd; pytest tests -q`) is no move again, and `cd; pytest ` still is one. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/lib/test-gate.mjs | 6 ++++-- integrations/codex-plugin/lib/test-gate.mjs | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index efad7783b6f..88709c2c988 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1310,9 +1310,11 @@ const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // Only spaces and tabs are read between a separator and `cd`: a line's end is // a separator itself, and a run of blank lines is then read once. Nor is a // line's end read between `cd` and its folder: a `cd` with no folder goes to -// the home folder, and is a move with no directory. +// the home folder, and is a move with no directory. A `cd` straight before a +// separator is that move where it starts a command: the word at the end of +// an argument is none (`ls /media/cd; pytest `). const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; -const MOVE = /\b(?:cd|pushd|popd)(?=[\s;&|)]|$)/g; +const MOVE = /\b(?:cd|pushd|popd)\s|(?:^|[;&|(\n])[ \t]*cd(?=[;&|)])/g; const unquoted = (word) => word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index efad7783b6f..88709c2c988 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1310,9 +1310,11 @@ const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // Only spaces and tabs are read between a separator and `cd`: a line's end is // a separator itself, and a run of blank lines is then read once. Nor is a // line's end read between `cd` and its folder: a `cd` with no folder goes to -// the home folder, and is a move with no directory. +// the home folder, and is a move with no directory. A `cd` straight before a +// separator is that move where it starts a command: the word at the end of +// an argument is none (`ls /media/cd; pytest `). const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; -const MOVE = /\b(?:cd|pushd|popd)(?=[\s;&|)]|$)/g; +const MOVE = /\b(?:cd|pushd|popd)\s|(?:^|[;&|(\n])[ \t]*cd(?=[;&|)])/g; const unquoted = (word) => word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path From 583987445b6e55d1883297aaca556c001a1e1b16 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 05:47:38 +0530 Subject: [PATCH 29/52] fileRun names the field for what it says: only set-up stands before the run `first` read as the first run of the command at its one use in `noteCommand`. It is true where nothing but `cd`, `export`, `source` and `.` stands before the run, so it is `afterSetUpOnly`. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../claude-code-plugin/lib/test-cost.mjs | 6 ++-- .../claude-code-plugin/lib/test-gate.mjs | 36 +++++++++---------- .../tests/test-cost.test.mjs | 6 ++-- integrations/codex-plugin/lib/test-cost.mjs | 6 ++-- integrations/codex-plugin/lib/test-gate.mjs | 36 +++++++++---------- 5 files changed, 45 insertions(+), 45 deletions(-) diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index be3bd5bead0..38855e72c3a 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -179,8 +179,8 @@ function settle(state, report) { * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The * seconds alone do not tell two short runs apart. Nor does the summary where - * a command before the run printed it (`run.first` is false): one that reads - * the output an earlier run saved (`tail -5 out.txt; pytest `) shows + * a command before the run printed it (`run.afterSetUpOnly` is false): one + * that reads the output an earlier run saved (`tail -5 out.txt; pytest `) shows * that run's last line, and where its own run outlives the call, the report * read is that run's too. That report was written before the command's own * run began, and a run that ended in the call writes its report as the call @@ -220,7 +220,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && - (run.first || Date.now() - report.mtimeMs <= OWN_REPORT_MS) && + (run.afterSetUpOnly || Date.now() - report.mtimeMs <= OWN_REPORT_MS) && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 88709c2c988..40fdecc6204 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1491,16 +1491,16 @@ const counted = (line, kinds) => * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values, - * first }`, else null. `path` is the file as the command spells it and `dir` - * the folder of the one `cd` before the run, "" for none. `whole` is false for - * a run filtered with `-k`. `first` is false where a command that is no set-up - * stands before the run (`startsNoRun`): it may have printed a line the output - * shows. A comment line above the run is read as such a command - * (`onlySetsUp`). `seconds` is what pytest's last line in the visible - * `output` shows (`LAST_LINE`), read without its colours. `cases` is the - * cases that line counts, all but the deselected: the result file's `tests`, - * but for a case whose teardown raised an error, which the line counts twice - * and the file once. + * afterSetUpOnly }`, else null. `path` is the file as the command spells it + * and `dir` the folder of the one `cd` before the run, "" for none. `whole` is + * false for a run filtered with `-k`. `afterSetUpOnly` is false where a + * command that is no set-up stands before the run (`startsNoRun`): it may + * have printed a line the output shows. A comment line above the run is read + * as such a command (`onlySetsUp`). `seconds` is what pytest's last line in + * the visible `output` shows (`LAST_LINE`), read without its colours. `cases` + * is the cases that line counts, all but the deselected: the result file's + * `tests`, but for a case whose teardown raised an error, which the line + * counts twice and the file once. * `failed` is the failures and errors among them and `skipped` the skipped * ones, apart from the expected failures. All four are null where the output * holds no such line: the run did not finish inside the call. A run with no @@ -1530,10 +1530,10 @@ const counted = (line, kinds) => * (`OWN_REPORT`), or one after a move the reader cannot follow (a second * `cd`, `pushd`, a `cd` with no folder, one in a subshell that closed, one * to a folder that is not written plainly, `PLAIN_FOLDER`, or one that does - * not start the command where `first` is false). The word after a flag that - * may take a value is that value and no path (`BARE`); a short flag written - * with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag - * may take none (`--no-header`), and + * not start the command where `afterSetUpOnly` is false). The word after a + * flag that may take a value is that value and no path (`BARE`); a short flag + * written with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A + * long flag may take none (`--no-header`), and * the word after it is then a second path: a run with such a word that names * a Python file is none, and the others are `values`. The caller drops a run * where one of them names a folder (`--no-header tests`, and `--cov src` @@ -1549,8 +1549,8 @@ export function fileRun(command, output = "") { if (runs.length !== 1) return null; const head = text.slice(0, runs[0].index); const tail = text.slice(runs[0].index); - const first = onlySetsUp(head); - if (!ranHere(head) || !(first || startsNoRun(head, tail))) return null; + const afterSetUpOnly = onlySetsUp(head); + if (!ranHere(head) || !(afterSetUpOnly || startsNoRun(head, tail))) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; @@ -1566,7 +1566,7 @@ export function fileRun(command, output = "") { cd.every( (m) => PLAIN_FOLDER.test(m[1]) && - (first + (afterSetUpOnly ? !closesParen(head.slice(m.index + m[0].length)) : !m[0].startsWith("(") && !head.slice(0, m.index).trim()), ); @@ -1603,7 +1603,7 @@ export function fileRun(command, output = "") { failed: summary ? counted(summary, "failed|errors?") : null, skipped: summary ? counted(summary, "skipped") : null, values, - first, + afterSetUpOnly, }; } diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index a03bf3fa045..2a518457c66 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -132,7 +132,7 @@ test("a command's one pytest run of one test file is whole or filtered with -k", failed: null, skipped: null, values: [], - first: true, + afterSetUpOnly: true, }; for (const command of [ `pytest ${FILE}`, @@ -220,7 +220,7 @@ test("a run that follows commands which name no test runner is a file run", () = failed: null, skipped: null, values: [], - first: false, + afterSetUpOnly: false, }; // An edit by an inline script, as a session writes one before it checks the edit. const edit = [ @@ -262,7 +262,7 @@ test("a run that follows commands which name no test runner is a file run", () = // A `cd` that starts the command is the shell's own, whatever stands between it and the run, and // so is one among set-up alone. assert.deepEqual(fileRun(`cd pkg && ${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -5`), { ...whole, dir: "pkg" }); - assert.deepEqual(fileRun(`export A=1; cd pkg && pytest ${FILE}`), { ...whole, dir: "pkg", first: true }); + assert.deepEqual(fileRun(`export A=1; cd pkg && pytest ${FILE}`), { ...whole, dir: "pkg", afterSetUpOnly: true }); // The text between that `cd` and the run is not read for a parenthesis: an edit holds its own. assert.deepEqual(fileRun(`cd pkg && sed -i 's/)$/, None)/' src/parser.py; pytest ${FILE}`), { ...whole, dir: "pkg" }); // The last line of the output is the run's where the run ended in the call, diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index be3bd5bead0..38855e72c3a 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -179,8 +179,8 @@ function settle(state, report) { * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The * seconds alone do not tell two short runs apart. Nor does the summary where - * a command before the run printed it (`run.first` is false): one that reads - * the output an earlier run saved (`tail -5 out.txt; pytest `) shows + * a command before the run printed it (`run.afterSetUpOnly` is false): one + * that reads the output an earlier run saved (`tail -5 out.txt; pytest `) shows * that run's last line, and where its own run outlives the call, the report * read is that run's too. That report was written before the command's own * run began, and a run that ended in the call writes its report as the call @@ -220,7 +220,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && - (run.first || Date.now() - report.mtimeMs <= OWN_REPORT_MS) && + (run.afterSetUpOnly || Date.now() - report.mtimeMs <= OWN_REPORT_MS) && run.cases === cost.tests && run.failed === cost.failed && Math.abs(run.seconds - cost.time) <= Math.max(1, run.seconds / 20); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 88709c2c988..40fdecc6204 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1491,16 +1491,16 @@ const counted = (line, kinds) => * The pytest run of `command` when it is the command's one pytest run, * started in this checkout (`ranHere`), and names one test file and nothing * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values, - * first }`, else null. `path` is the file as the command spells it and `dir` - * the folder of the one `cd` before the run, "" for none. `whole` is false for - * a run filtered with `-k`. `first` is false where a command that is no set-up - * stands before the run (`startsNoRun`): it may have printed a line the output - * shows. A comment line above the run is read as such a command - * (`onlySetsUp`). `seconds` is what pytest's last line in the visible - * `output` shows (`LAST_LINE`), read without its colours. `cases` is the - * cases that line counts, all but the deselected: the result file's `tests`, - * but for a case whose teardown raised an error, which the line counts twice - * and the file once. + * afterSetUpOnly }`, else null. `path` is the file as the command spells it + * and `dir` the folder of the one `cd` before the run, "" for none. `whole` is + * false for a run filtered with `-k`. `afterSetUpOnly` is false where a + * command that is no set-up stands before the run (`startsNoRun`): it may + * have printed a line the output shows. A comment line above the run is read + * as such a command (`onlySetsUp`). `seconds` is what pytest's last line in + * the visible `output` shows (`LAST_LINE`), read without its colours. `cases` + * is the cases that line counts, all but the deselected: the result file's + * `tests`, but for a case whose teardown raised an error, which the line + * counts twice and the file once. * `failed` is the failures and errors among them and `skipped` the skipped * ones, apart from the expected failures. All four are null where the output * holds no such line: the run did not finish inside the call. A run with no @@ -1530,10 +1530,10 @@ const counted = (line, kinds) => * (`OWN_REPORT`), or one after a move the reader cannot follow (a second * `cd`, `pushd`, a `cd` with no folder, one in a subshell that closed, one * to a folder that is not written plainly, `PLAIN_FOLDER`, or one that does - * not start the command where `first` is false). The word after a flag that - * may take a value is that value and no path (`BARE`); a short flag written - * with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag - * may take none (`--no-header`), and + * not start the command where `afterSetUpOnly` is false). The word after a + * flag that may take a value is that value and no path (`BARE`); a short flag + * written with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A + * long flag may take none (`--no-header`), and * the word after it is then a second path: a run with such a word that names * a Python file is none, and the others are `values`. The caller drops a run * where one of them names a folder (`--no-header tests`, and `--cov src` @@ -1549,8 +1549,8 @@ export function fileRun(command, output = "") { if (runs.length !== 1) return null; const head = text.slice(0, runs[0].index); const tail = text.slice(runs[0].index); - const first = onlySetsUp(head); - if (!ranHere(head) || !(first || startsNoRun(head, tail))) return null; + const afterSetUpOnly = onlySetsUp(head); + if (!ranHere(head) || !(afterSetUpOnly || startsNoRun(head, tail))) return null; // Only what reads the run's output may follow it. A redirect to a file is // the run's own, and is left out of that reading. if (!onlyRuns(tail.replace(/\d?>>?\s*[^\s;&|()]+/g, " "), 1)) return null; @@ -1566,7 +1566,7 @@ export function fileRun(command, output = "") { cd.every( (m) => PLAIN_FOLDER.test(m[1]) && - (first + (afterSetUpOnly ? !closesParen(head.slice(m.index + m[0].length)) : !m[0].startsWith("(") && !head.slice(0, m.index).trim()), ); @@ -1603,7 +1603,7 @@ export function fileRun(command, output = "") { failed: summary ? counted(summary, "failed|errors?") : null, skipped: summary ? counted(summary, "skipped") : null, values, - first, + afterSetUpOnly, }; } From a3228ef90a3c44aaa20b23fa9533fff784fb0602 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 05:50:00 +0530 Subject: [PATCH 30/52] The pages say when pytest writes the result file: at the session's end, before the summary pytest writes the report in its session-finish hook and prints the summary after it, so a run that ended in its call wrote the file before it printed the last line, not as the call returned. The comment on `OWN_REPORT_MS`, the hooks page and the feature page say so, and the feature page's limit names what takes the time after the file is written: printing the summary and ending. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 7 ++++--- integrations/claude-code-plugin/hooks/HOOKS.md | 3 ++- .../claude-code-plugin/lib/test-cost.mjs | 17 +++++++++-------- integrations/codex-plugin/lib/test-cost.mjs | 17 +++++++++-------- 4 files changed, 24 insertions(+), 20 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 72af089b033..85c876ab41f 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1820,7 +1820,8 @@ file an earlier run left. Nor does the summary line where a command before the r printed it: `tail -5 out.txt; pytest tests/test_big.py` shows the summary of the run that wrote `out.txt`, and where its own run outlives the call, the result file read with it is that earlier run's. That file was written before the command's own run began, -and a run that ended in its call writes the file as the call returns. So where other +and a run that ended in its call wrote the file at its session's end, before pytest +printed the summary. So where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the result file is the command's only when it was written no more than 10 s before the hook read it. A command that is the run alone prints no summary line but @@ -1929,8 +1930,8 @@ What it does not do: - a run that outlives its shell call is noted when it began before that call returned: a run put in the background at once, before pytest began, is not; - a run that other commands stand before is not counted where its result file was - written more than 10 s before the hook read it, as by a pytest whose process ends that - long after it wrote the file; + written more than 10 s before the hook read it, as by a pytest that takes that long + to print its summary and end after it wrote the file; - a command before the run that starts pytest under no runner's name, such as a script of the repository, is not told apart from an edit. Its result file and summary line are counted as the run's where the script ended within 10 s of the call's return and diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 00dbc0f2167..a6f2486c233 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1569,7 +1569,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that wrote `out.txt`, and where its own run outlives the call, the report read with it is that earlier run's too. That report was written before the command's own run began, and a run that ended in its call - writes the report as the call returns. So for a run that a command + wrote the report at its session's end, before pytest printed the + summary. So for a run that a command which is no set-up stands before, or a comment line, which is read as one, the report is the command's only when it was written no more than 10 s before the hook read it (`OWN_REPORT_MS` in diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 38855e72c3a..2a82047d863 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -53,8 +53,8 @@ const CALL_TIMEOUT_SECONDS = 120; // does not: a run that outlived its call has the report's count only. const MAX_SKIPPED_SHARE = 0.1; // How long before its shell call's hook a run that ended in the call wrote -// its report: pytest writes it as its last step, and the hook starts when -// the call returns. +// its report: pytest writes it at the session's end, before it prints its +// summary, and the hook starts when the call returns. const OWN_REPORT_MS = 10_000; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. @@ -180,12 +180,13 @@ function settle(state, report) { * writes no report, and the one read after it is an earlier run's. The * seconds alone do not tell two short runs apart. Nor does the summary where * a command before the run printed it (`run.afterSetUpOnly` is false): one - * that reads the output an earlier run saved (`tail -5 out.txt; pytest `) shows - * that run's last line, and where its own run outlives the call, the report - * read is that run's too. That report was written before the command's own - * run began, and a run that ended in the call writes its report as the call - * returns: the report of such a command is its own only when it was written - * no more than `OWN_REPORT_MS` before this read. A report that a command + * that reads the output an earlier run saved (`tail -5 out.txt; pytest + * `) shows that run's last line, and where its own run outlives the + * call, the report read is that run's too. That report was written before + * the command's own run began, and a run that ended in the call wrote its + * report at its session's end, before it printed the summary: the report of + * such a command is its own only when it was written no more than + * `OWN_REPORT_MS` before this read. A report that a command * before the run wrote within that time is not told apart from the run's, * nor is one an earlier run wrote that shortly before the call returned. Any * other report is the pending run's when it is of that run's file and its diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 38855e72c3a..2a82047d863 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -53,8 +53,8 @@ const CALL_TIMEOUT_SECONDS = 120; // does not: a run that outlived its call has the report's count only. const MAX_SKIPPED_SHARE = 0.1; // How long before its shell call's hook a run that ended in the call wrote -// its report: pytest writes it as its last step, and the hook starts when -// the call returns. +// its report: pytest writes it at the session's end, before it prints its +// summary, and the hook starts when the call returns. const OWN_REPORT_MS = 10_000; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. @@ -180,12 +180,13 @@ function settle(state, report) { * writes no report, and the one read after it is an earlier run's. The * seconds alone do not tell two short runs apart. Nor does the summary where * a command before the run printed it (`run.afterSetUpOnly` is false): one - * that reads the output an earlier run saved (`tail -5 out.txt; pytest `) shows - * that run's last line, and where its own run outlives the call, the report - * read is that run's too. That report was written before the command's own - * run began, and a run that ended in the call writes its report as the call - * returns: the report of such a command is its own only when it was written - * no more than `OWN_REPORT_MS` before this read. A report that a command + * that reads the output an earlier run saved (`tail -5 out.txt; pytest + * `) shows that run's last line, and where its own run outlives the + * call, the report read is that run's too. That report was written before + * the command's own run began, and a run that ended in the call wrote its + * report at its session's end, before it printed the summary: the report of + * such a command is its own only when it was written no more than + * `OWN_REPORT_MS` before this read. A report that a command * before the run wrote within that time is not told apart from the run's, * nor is one an earlier run wrote that shortly before the call returned. Any * other report is the pending run's when it is of that run's file and its From 030b2a336f7555885d20c84400f1e0615d68e59a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 06:06:29 +0530 Subject: [PATCH 31/52] test(plugin): the gate holds each separator after a cd with no folder `cd&& pytest tests -q`, `cd|| pytest tests -q` and `(make build; cd); pytest tests -q` answer no gate. Taking `&`, `|` or `)` out of the separators `MOVE` reads after such a `cd` fails the test. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-gate.test.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index 4afad9c04fe..36ce92c2203 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1279,6 +1279,9 @@ test("a run's paths are read from the directory its command moved to", () => { // A `cd` with no folder goes to the home folder: the word on the line // under it is the next command, not its folder. "cd; pytest tests -q", + "cd&& pytest tests -q", + "cd|| pytest tests -q", + "(make build; cd); pytest tests -q", "cd\npython -m pytest tests -q", "docker exec app pytest tests -q", "kubectl exec pod -- pytest tests -q", From c1c6876b9d3fd94d4ed89a8e4746eda42e2f6bc4 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 06:35:02 +0530 Subject: [PATCH 32/52] test(plugin): the comment says what a comment between a command and the run does The comment above the two assertions said a comment before the run is no command, and the next one says a comment line alone above the run is read as a command that is no set-up, which is what `onlySetsUp` does. The two assertions check that a comment between a command and the run joins the two in no way, so the comment says that. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-cost.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 2a518457c66..be956cda7da 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -270,7 +270,7 @@ test("a run that follows commands which name no test runner is a file run", () = assert.equal(fileRun(`${edit}\npython -m pytest -q ${FILE} 2>&1 | tail -3`, WHOLE_OUTPUT).seconds, 140.21); const shown = fileRun(`tail -5 /tmp/out.txt; pytest ${FILE} -q`, `8145 passed in 152.44s (0:02:32)\n${WHOLE_OUTPUT}`); assert.deepEqual([shown.seconds, shown.cases], [140.21, 8000]); - // A comment before the run is no command. + // A comment between a command and the run joins the two in no way: the shell reads past it. assert.deepEqual(fileRun(`git diff --stat\n# check the edit\npytest ${FILE}`), whole); assert.deepEqual(fileRun(`git diff --stat; # check the edit\npytest ${FILE}`), whole); // A comment line alone above the run is read as a command that is no set-up. From d4285ce1fcfbbcc99b430b70799e91628c6a2c8d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 07:09:19 +0530 Subject: [PATCH 33/52] test(plugin): the word cd at the end of an argument is no move before a line's end `ls /media/cd` and `export OUT=/media/cd` on the line above the run are no move, as the same commands joined to the run by `;` are none. The two tests of `fileRun` and the gate test fail: `MOVE` counts the word before a line's end wherever it stands. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-cost.test.mjs | 6 ++++-- integrations/claude-code-plugin/tests/test-gate.test.mjs | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index be956cda7da..3eec08fd02b 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -144,8 +144,9 @@ test("a command's one pytest run of one test file is whole or filtered with -k", // What sets the shell up may stand before it. `source .venv/bin/activate && export PYTHONPATH=src; pytest ${FILE}`, `. .venv/bin/activate; pytest ${FILE} -q`, - // The word `cd` at the end of a value is no move. + // The word `cd` at the end of a value is no move, before a line's end too. `export OUT=/media/cd; pytest ${FILE}`, + `export OUT=/media/cd\npytest ${FILE}`, // What reads the run's output may follow it. `pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt; echo exit=$?`, ]) { @@ -238,8 +239,9 @@ test("a run that follows commands which name no test runner is a file run", () = `cat >> src/parser.py <<'E'\nclass Finder:\n found = False\nE\ntimeout 590 python -m pytest -q ${FILE}`, `git checkout src/parser.py; sed -i 's/a/b/' src/parser.py; echo 'x = 1' >> /tmp/t.py; pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt`, `rm /tmp/ex.py; pytest ${FILE}`, - // The word `cd` at the end of an argument is no move. + // The word `cd` at the end of an argument is no move, before a line's end too. `ls /media/cd; pytest ${FILE}`, + `ls /media/cd\npytest ${FILE}`, // A build tool with no test target among its words. `make install; pytest ${FILE}`, // The run starts whatever a command before it returned, an `||` list too. diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index 36ce92c2203..9ad2fa01037 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1265,8 +1265,10 @@ test("a run's paths are read from the directory its command moved to", () => { answered([edit(), bash("pytest tests -q", "3 passed in 0.10s", { cwd: ROOT })], RUN_GATE, "/r/sub"), true, ); - // The word `cd` at the end of an argument is no move. - assert.equal(answered([edit(), bash("ls /media/cd; pytest tests -q", "3 passed in 0.10s")]), true); + // The word `cd` at the end of an argument is no move, before a line's end too. + for (const command of ["ls /media/cd; pytest tests -q", "ls /media/cd\npytest tests -q"]) { + assert.equal(answered([edit(), bash(command, "3 passed in 0.10s")]), true, command); + } // A move this reader does not follow, and a run outside the checkout. const inPython = { ...RUN_GATE, From 9b75691d10d4386ee0c6a522d16f646424401cd3 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 07:09:19 +0530 Subject: [PATCH 34/52] The word cd at the end of an argument is no move before a line's end `MOVE` counted `cd` before any blank wherever the word stood, a line's end included, so `ls /media/cd` on the line above the run held a move with no folder: the run was no file run and did not answer the gate, and the same commands joined by `;` did both. `MOVE` now reads `cd` before a line's end as it reads it before `;`, `&`, `|` and `)`: a move only where it starts a command. Before a space or a tab the word counts as a move wherever it stands, as before, and `pushd` and `popd` are read as before. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/lib/test-gate.mjs | 7 ++++--- integrations/codex-plugin/lib/test-gate.mjs | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 40fdecc6204..cf9000e0388 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1311,10 +1311,11 @@ const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // a separator itself, and a run of blank lines is then read once. Nor is a // line's end read between `cd` and its folder: a `cd` with no folder goes to // the home folder, and is a move with no directory. A `cd` straight before a -// separator is that move where it starts a command: the word at the end of -// an argument is none (`ls /media/cd; pytest `). +// separator or a line's end is that move where it starts a command: the word +// at the end of an argument is none (`ls /media/cd; pytest `). Before a +// space or a tab it counts as a move wherever it stands. const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; -const MOVE = /\b(?:cd|pushd|popd)\s|(?:^|[;&|(\n])[ \t]*cd(?=[;&|)])/g; +const MOVE = /\bcd[ \t]|\b(?:pushd|popd)\s|(?:^|[;&|(\n])[ \t]*cd(?=[\s;&|)])/g; const unquoted = (word) => word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 40fdecc6204..cf9000e0388 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1311,10 +1311,11 @@ const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // a separator itself, and a run of blank lines is then read once. Nor is a // line's end read between `cd` and its folder: a `cd` with no folder goes to // the home folder, and is a move with no directory. A `cd` straight before a -// separator is that move where it starts a command: the word at the end of -// an argument is none (`ls /media/cd; pytest `). +// separator or a line's end is that move where it starts a command: the word +// at the end of an argument is none (`ls /media/cd; pytest `). Before a +// space or a tab it counts as a move wherever it stands. const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; -const MOVE = /\b(?:cd|pushd|popd)\s|(?:^|[;&|(\n])[ \t]*cd(?=[;&|)])/g; +const MOVE = /\bcd[ \t]|\b(?:pushd|popd)\s|(?:^|[;&|(\n])[ \t]*cd(?=[\s;&|)])/g; const unquoted = (word) => word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path From 99e760ca511e533dd2874963aa121c4e3f117662 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 07:38:23 +0530 Subject: [PATCH 35/52] test(plugin): a cd with no folder after a keyword or a prefix word is a move `if [ -d pkg ]; then cd` above `fi` and the run, `{ cd` at a line's end, `builtin cd; pytest ` and `command cd` on the line above the run go to the home folder. `MOVE` reads a `cd` before a separator or a line's end only after the text's start or a separator, so each is taken for a run in the session's folder: one test of `fileRun` and the gate test fail. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-cost.test.mjs | 5 +++++ integrations/claude-code-plugin/tests/test-gate.test.mjs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 3eec08fd02b..88ed732483d 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -352,6 +352,11 @@ test("a command with two pytest runs, two paths, another selection or no run of `cd; pytest ${FILE}`, `sed -i 's/a/b/' src/parser.py; cd; pytest ${FILE}`, `cd\npython -m pytest ${FILE}`, + // So does one after a shell keyword or a word the shell runs `cd` under. + `if [ -d pkg ]; then cd\nfi\npytest ${FILE}`, + `[ -d pkg ] || { cd\n}\npytest ${FILE}`, + `builtin cd; pytest ${FILE}`, + `command cd\npytest ${FILE}`, // A folder that is not written plainly: its name is cut at a space, or is an option. `cd "/work/My Projects/app" && pytest ${FILE}`, `cd /work/My\\ Projects/app && pytest ${FILE}`, diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index 9ad2fa01037..c8c29740cff 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1285,6 +1285,11 @@ test("a run's paths are read from the directory its command moved to", () => { "cd|| pytest tests -q", "(make build; cd); pytest tests -q", "cd\npython -m pytest tests -q", + // So does one after a shell keyword or a word the shell runs `cd` under. + "if [ -d sub ]; then cd\nfi\npytest tests -q", + "[ -d sub ] || { cd\n}\npytest tests -q", + "builtin cd; pytest tests -q", + "command cd\npytest tests -q", "docker exec app pytest tests -q", "kubectl exec pod -- pytest tests -q", "ssh host 'cd repo; pytest tests -q'", From 8ed02ee4e73f88aa3b6e9ea338cfd6471b506626 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 07:42:21 +0530 Subject: [PATCH 36/52] A cd with no folder is a move wherever it is a word of its own `MOVE` read a `cd` before a separator or a line's end only after the text's start or a separator. A `cd` after a shell keyword or a word the shell runs it under (`then cd`, `{ cd`, `builtin cd`, `command cd`) goes to the home folder like any other, and the run under it was taken for one in the session's folder. `MOVE` now reads the word where no character but a blank or a separator stands before it. The end of a longer argument is still none (`ls /media/cd; pytest `). `startsNoRun` reads the character before the run's command without a default: it is called only where a separator stands in the text before the run. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/lib/test-gate.mjs | 10 ++++++---- integrations/codex-plugin/lib/test-gate.mjs | 10 ++++++---- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index cf9000e0388..9c112fa0701 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1311,11 +1311,13 @@ const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // a separator itself, and a run of blank lines is then read once. Nor is a // line's end read between `cd` and its folder: a `cd` with no folder goes to // the home folder, and is a move with no directory. A `cd` straight before a -// separator or a line's end is that move where it starts a command: the word -// at the end of an argument is none (`ls /media/cd; pytest `). Before a +// separator or a line's end is that move where it is a word of its own, after +// a keyword or a word the shell runs it under too (`then cd`, `builtin cd`), +// and an argument that is the word alone is read as one (`echo cd`). The end +// of a longer argument is none (`ls /media/cd; pytest `). Before a // space or a tab it counts as a move wherever it stands. const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; -const MOVE = /\bcd[ \t]|\b(?:pushd|popd)\s|(?:^|[;&|(\n])[ \t]*cd(?=[\s;&|)])/g; +const MOVE = /\bcd[ \t]|\b(?:pushd|popd)\s|(? word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path @@ -1385,7 +1387,7 @@ const startsNoRun = (head, tail) => { // that command runs beside it: what it prints and writes may come after // the run's. A `(` opens a group, which is not read. const start = head.length - head.split(/[;&|(\n]/).pop().length; - if (!/[;\n]/.test(head[start - 1] || "")) return false; + if (!/[;\n]/.test(head[start - 1])) return false; // The shell reads that `;`: no backslash stands before it, and no `#` that // starts a word stands before the run on its line, where the run is a // comment's text (`git diff --stat # then; pytest `). The line is diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index cf9000e0388..9c112fa0701 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1311,11 +1311,13 @@ const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // a separator itself, and a run of blank lines is then read once. Nor is a // line's end read between `cd` and its folder: a `cd` with no folder goes to // the home folder, and is a move with no directory. A `cd` straight before a -// separator or a line's end is that move where it starts a command: the word -// at the end of an argument is none (`ls /media/cd; pytest `). Before a +// separator or a line's end is that move where it is a word of its own, after +// a keyword or a word the shell runs it under too (`then cd`, `builtin cd`), +// and an argument that is the word alone is read as one (`echo cd`). The end +// of a longer argument is none (`ls /media/cd; pytest `). Before a // space or a tab it counts as a move wherever it stands. const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; -const MOVE = /\bcd[ \t]|\b(?:pushd|popd)\s|(?:^|[;&|(\n])[ \t]*cd(?=[\s;&|)])/g; +const MOVE = /\bcd[ \t]|\b(?:pushd|popd)\s|(? word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path @@ -1385,7 +1387,7 @@ const startsNoRun = (head, tail) => { // that command runs beside it: what it prints and writes may come after // the run's. A `(` opens a group, which is not read. const start = head.length - head.split(/[;&|(\n]/).pop().length; - if (!/[;\n]/.test(head[start - 1] || "")) return false; + if (!/[;\n]/.test(head[start - 1])) return false; // The shell reads that `;`: no backslash stands before it, and no `#` that // starts a word stands before the run on its line, where the run is a // comment's text (`git diff --stat # then; pytest `). The line is From 6ccc82af4fac3fe270b5814a380ca16f58931926 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 08:15:24 +0530 Subject: [PATCH 37/52] The limits name a run an earlier call left going, and the pages say pytest writes the report when its run ends A run that outlives its shell call is counted with the first report of its file whose run began before the call returned. A run of two paths, a node id or a mark that an earlier call left going began before that too, and is no file run, so it left no state: where its first case is in the file, the pending run is counted with its cases and seconds. `settle` reads this as it does for a command that is the run alone; a run after other commands now reaches it as well. The comment on `settle`, the hooks page, the README and the feature page's limits list say so. "The session's end" is the Claude Code session's in this module and its pages. The four sentences that used it for the end of pytest's run name that end and its hook (`pytest_sessionfinish`). Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 11 +++++++++-- integrations/claude-code-plugin/README.md | 2 +- integrations/claude-code-plugin/hooks/HOOKS.md | 12 +++++++++--- integrations/claude-code-plugin/lib/test-cost.mjs | 14 +++++++++----- integrations/codex-plugin/lib/test-cost.mjs | 14 +++++++++----- 5 files changed, 37 insertions(+), 16 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 85c876ab41f..2c27ed8eef6 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1820,8 +1820,8 @@ file an earlier run left. Nor does the summary line where a command before the r printed it: `tail -5 out.txt; pytest tests/test_big.py` shows the summary of the run that wrote `out.txt`, and where its own run outlives the call, the result file read with it is that earlier run's. That file was written before the command's own run began, -and a run that ended in its call wrote the file at its session's end, before pytest -printed the summary. So where other +and a run that ended in its call wrote the file when it ended (`pytest_sessionfinish`), +before pytest printed the summary. So where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the result file is the command's only when it was written no more than 10 s before the hook read it. A command that is the run alone prints no summary line but @@ -1988,6 +1988,13 @@ What it does not do: - the result file of a run of the same file that something else started while a run that outlived its shell call was in that call, such as a script in the background, is counted as that run's when a command that is not the other run reads it; +- so is the result file of a run that an earlier shell call left going, in the + background or past its timeout, and that counts as neither itself (two paths, a node + id, a mark), where its first case is in the test file of the run that outlived its + call. After `pytest -q tests/test_big.py tests/test_small.py > out.txt 2>&1 &`, a + `pytest -q tests/test_big.py` that outlives its call while that run goes on is counted + with the cases and seconds of the run of two paths, where a hook reads that run's + result file before its own; - a row whose file was removed stays, unprinted, until a session measures a slow whole run of another file; - the row is an ordinary memory row, so recall can serve its sentence, and two diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 3f0f636afee..8835a2aa09b 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `cd` stands before the run that does not start the command, or that starts it in a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `): further on it may be the text of a heredoc or of a quoted argument. Sixth, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `cd` stands before the run that does not start the command, or that starts it in a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `): further on it may be the text of a heredoc or of a quoted argument. Sixth, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index a6f2486c233..4cd403694f4 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1569,8 +1569,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that wrote `out.txt`, and where its own run outlives the call, the report read with it is that earlier run's too. That report was written before the command's own run began, and a run that ended in its call - wrote the report at its session's end, before pytest printed the - summary. So for a run that a command + wrote the report when it ended (`pytest_sessionfinish`), before + pytest printed the summary. So for a run that a command which is no set-up stands before, or a comment line, which is read as one, the report is the command's only when it was written no more than 10 s before the hook read it (`OWN_REPORT_MS` in @@ -1602,7 +1602,13 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs): the 10 s bound is on a report read with its command, and - this one is read later. The launcher + this one is read later. So is the report of a run that an earlier + call left going, in the background or past its timeout, and that is + no file run (two paths, a node id, a mark): it left no state and + began before that time, and where its first case is in the pending + run's file and a hook reads it before the pending run's own, the + pending run is counted with the cases and seconds of what it ran. + The launcher reads the report once more at SessionEnd, before it removes the file, without reading a token. A run put in the background at once returns before pytest began, and is not counted. diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 2a82047d863..f895fb5f099 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -53,8 +53,8 @@ const CALL_TIMEOUT_SECONDS = 120; // does not: a run that outlived its call has the report's count only. const MAX_SKIPPED_SHARE = 0.1; // How long before its shell call's hook a run that ended in the call wrote -// its report: pytest writes it at the session's end, before it prints its -// summary, and the hook starts when the call returns. +// its report: pytest writes it when its run ends (`pytest_sessionfinish`), +// before it prints its summary, and the hook starts when the call returns. const OWN_REPORT_MS = 10_000; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. @@ -154,8 +154,11 @@ function add(state, run, cost) { * for the pending run's. So did the pytest of a command that stands before * the pending run in its call and ended after the call returned * (`./check.sh; pytest `, where the call times out in the script): - * `OWN_REPORT_MS` bounds a report read with its command, not this one. A - * run that began by the time an earlier pending + * `OWN_REPORT_MS` bounds a report read with its command, not this one. And + * so did a run that an earlier call left going and that is no file run + * (two paths, a node id, a mark), which left no state: where its first + * case is in the file, the pending run is counted with the cases and + * seconds of what it ran. A run that began by the time an earlier pending * run had (`dropped`) may be that run, whose report is no later run's. The * pending run is then settled; any other report leaves it pending. */ function settle(state, report) { @@ -184,7 +187,8 @@ function settle(state, report) { * `) shows that run's last line, and where its own run outlives the * call, the report read is that run's too. That report was written before * the command's own run began, and a run that ended in the call wrote its - * report at its session's end, before it printed the summary: the report of + * report when it ended (`pytest_sessionfinish`), before it printed the + * summary: the report of * such a command is its own only when it was written no more than * `OWN_REPORT_MS` before this read. A report that a command * before the run wrote within that time is not told apart from the run's, diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 2a82047d863..f895fb5f099 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -53,8 +53,8 @@ const CALL_TIMEOUT_SECONDS = 120; // does not: a run that outlived its call has the report's count only. const MAX_SKIPPED_SHARE = 0.1; // How long before its shell call's hook a run that ended in the call wrote -// its report: pytest writes it at the session's end, before it prints its -// summary, and the hook starts when the call returns. +// its report: pytest writes it when its run ends (`pytest_sessionfinish`), +// before it prints its summary, and the hook starts when the call returns. const OWN_REPORT_MS = 10_000; const MAX_PATH = 160; // The files whose runs a session's state holds, and the filtered runs of each. @@ -154,8 +154,11 @@ function add(state, run, cost) { * for the pending run's. So did the pytest of a command that stands before * the pending run in its call and ended after the call returned * (`./check.sh; pytest `, where the call times out in the script): - * `OWN_REPORT_MS` bounds a report read with its command, not this one. A - * run that began by the time an earlier pending + * `OWN_REPORT_MS` bounds a report read with its command, not this one. And + * so did a run that an earlier call left going and that is no file run + * (two paths, a node id, a mark), which left no state: where its first + * case is in the file, the pending run is counted with the cases and + * seconds of what it ran. A run that began by the time an earlier pending * run had (`dropped`) may be that run, whose report is no later run's. The * pending run is then settled; any other report leaves it pending. */ function settle(state, report) { @@ -184,7 +187,8 @@ function settle(state, report) { * `) shows that run's last line, and where its own run outlives the * call, the report read is that run's too. That report was written before * the command's own run began, and a run that ended in the call wrote its - * report at its session's end, before it printed the summary: the report of + * report when it ended (`pytest_sessionfinish`), before it printed the + * summary: the report of * such a command is its own only when it was written no more than * `OWN_REPORT_MS` before this read. A report that a command * before the run wrote within that time is not told apart from the run's, From 795af1a35905b3ad88d8592f64523a2eac230a6b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 08:43:05 +0530 Subject: [PATCH 38/52] test(plugin): a run put in the background after other commands is no file run A command that reads the output an earlier run saved and then puts its own run in the background returns at once: `tail -5 out.txt; pytest > out2.txt 2>&1 &`. Its output shows the earlier run's last line, and the report read with it is that run's, written moments before. `fileRun` takes the line for the command's run, and the report is counted as a whole run of the named file. `./check.sh; pytest &` does the same with the suite of the script. The cases fail here: four command shapes that `fileRun` returns a run for, and two that leave the earlier run's cases and seconds in the session's state. `&>`, `|&` and `&&` after the run put nothing in the background, and a background run after set-up alone stays a file run: those cases pass. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../tests/test-cost.test.mjs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 88ed732483d..69573496283 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -256,9 +256,15 @@ test("a run that follows commands which name no test runner is a file run", () = `python - <<'E'\n# set the per-file limit\nE\npytest ${FILE}`, // An inline script piped into a reader: the pipe ends on the script's own line. `python - <<'E' 2>&1 | tail -2\nprint(1 << 4 | 1)\nE\npytest ${FILE}`, + // `&>` and `|&` send the run's output on and `&&` waits on the run: none puts it in the background. + `git diff --stat; pytest ${FILE} -q &> /tmp/out.txt; tail -5 /tmp/out.txt`, + `git diff --stat; python -m pytest -q ${FILE} |& tail -5`, + `git diff --stat; pytest ${FILE} -q && echo passed`, ]) { assert.deepEqual(fileRun(command), whole, command); } + // A run put in the background after set-up alone is a file run: no command before it prints a last line. + assert.deepEqual(fileRun(`export A=1; pytest ${FILE} > /tmp/out.txt 2>&1 &`), { ...whole, afterSetUpOnly: true }); // The folder of the one `cd`, and a run filtered with -k. assert.deepEqual(fileRun(`cd pkg && git stash -q; pytest ${FILE} -k parse`), { ...whole, dir: "pkg", whole: false }); // A `cd` that starts the command is the shell's own, whatever stands between it and the run, and @@ -412,6 +418,12 @@ test("a command with two pytest runs, two paths, another selection or no run of `sleep 600 & pytest ${FILE}`, `git stash -q; ( pytest ${FILE})`, `git stash -q; (\npytest ${FILE})`, + // A run put in the background after a command that is no set-up, alone or with what reads its + // output: its call returns before it ends, so a last line the output shows is another run's. + `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} > /tmp/out2.txt 2>&1 &`, + `./check.sh; pytest ${FILE} &`, + `git diff --stat; pytest ${FILE} 2>&1 | tail -5 &`, + `git diff --stat; pytest ${FILE} > /tmp/out.txt 2>&1 & echo started`, // A set-up command after another command joins the run like any other: the run may not start. `sed -i 's/a/b/' src/parser.py; cd pkg && pytest ${FILE}`, `tail -5 /tmp/out.txt; source .venv/bin/activate && pytest ${FILE}`, @@ -861,6 +873,18 @@ test("a report written before a command's own run could end is not the command's assert.deepEqual(runs(), {}); fs.rmSync(sessionStatePath("test-cost", SESSION)); + // The command puts its own run in the background and returns at once: the + // last line it shows and the report read with it are the earlier run's, + // however shortly before the hook that run wrote it. A script's suite + // leaves both the same way. + for (const command of [ + `tail -5 /tmp/out.txt; python -m pytest -q ${FILE} > /tmp/out2.txt 2>&1 &`, + `./check.sh; pytest ${FILE} &`, + ]) { + note(command, "8145 passed in 152.44s (0:02:32)", report({ tests: 8145, time: "152.4" }), -3000); + assert.equal(runs(), null, command); + } + // A command that is the run alone prints no line but its own: its report // counts however long before the hook it was written, and whatever shell // call of the session returned while the run was in its call. So does the From dafdac24cbacc4d3e68922d3100fb382817ca983 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 08:51:48 +0530 Subject: [PATCH 39/52] A run put in the background after other commands is no file run `startsNoRun` lets commands that start no pytest stand before a run, and one of them may print the last line of an earlier run. Where a `&` then puts the command's own run in the background, the call does not wait for it: `tail -5 out.txt; pytest > out2.txt 2>&1 &` returns at once with the earlier run's last line, and a report that run wrote moments before is within `OWN_REPORT_MS`. The cases and seconds of a run of two paths, or of the suite of a script, were stored as a whole run of the named file. `startsNoRun` now refuses a run whose side of the command holds a `&` that is no part of `&&`, `&>`, `>&` or `|&` (`BACKGROUND`). `fileRun` returns nothing for such a command, as before other commands could stand before a run. A background run after set-up alone is a file run as it was: no command before it prints a last line. Six comment paragraphs that broke in the middle of a line are wrapped again, in `lib/test-cost.mjs` and `lib/test-gate.mjs`. The hooks page, the README and the feature page name the new case. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 7 +- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 13 ++-- .../claude-code-plugin/lib/test-cost.mjs | 29 ++++---- .../claude-code-plugin/lib/test-gate.mjs | 66 +++++++++++-------- integrations/codex-plugin/lib/test-cost.mjs | 29 ++++---- integrations/codex-plugin/lib/test-gate.mjs | 66 +++++++++++-------- 7 files changed, 120 insertions(+), 92 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 2c27ed8eef6..cdaf1037391 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1803,7 +1803,12 @@ session's private state, by the file: close no parenthesis and no quote opened before them: a run in a group that waits on an earlier command (`python edit.py && (git diff --stat; pytest tests/test_big.py)`) and the text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`) count - as neither. After such commands a `cd` is followed only where it starts the command + as neither. So does a run that a `&` puts in the background after such commands, alone + or with what reads its output + (`tail -5 out.txt; pytest tests/test_big.py > out2.txt 2>&1 &`): the call does not wait + for the run, and a summary line its output shows may be an earlier run's. The `&` of + `&&`, `&>` and `|&` puts nothing in the background. After such commands a `cd` is + followed only where it starts the command (`cd pkg && sed -i 's/a/b/' src/parser.py; pytest tests/test_big.py`): further on it may be the text of a heredoc or of a quoted argument, as a `cd pkg` line under `cat > run.sh <<'E'`, and the run counts as neither. So does a run after a `cd` that diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 8835a2aa09b..07aa07c83c2 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `cd` stands before the run that does not start the command, or that starts it in a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `): further on it may be the text of a heredoc or of a quoted argument. Sixth, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, a `cd` stands before the run that does not start the command, or that starts it in a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `): further on it may be the text of a heredoc or of a quoted argument. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 4cd403694f4..cd393fa6443 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1485,8 +1485,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that before the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or the commands of a session that edits and then checks in one shell call (an inline script, `git diff --stat`, `sed`). After such commands the - run is noted as nothing in the six cases that follow; `startsNoRun` - reads the first four. + run is noted as nothing in the seven cases that follow; `startsNoRun` + reads the first five. First, the text before the run names a test runner (`startsRunner`), holds `pytest` or `py.test` in any word (`.pytest_cache`, `pytest.ini`), or holds something that ends the shell where a command @@ -1518,14 +1518,19 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that opened before them: the run is in a group that waits on an earlier command (`edit && (git diff; pytest )`), or it is the text of a quoted argument (`git commit -m "fix; pytest "`). - Fifth, a `cd` stands before the run that does not start the command, + Fifth, a `&` puts the run in the background, alone or with what reads + its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the + call does not wait for the run, so a last line its output shows may + be one a command before the run printed (`BACKGROUND`). The `&` of + `&&`, `&>` and `|&` puts nothing in the background. + Sixth, a `cd` stands before the run that does not start the command, or that starts it in a group. Further on, a `cd` may be the text of a heredoc or of a quoted argument, which is not read (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run). A group ends before the run (`(cd pkg && git stash -q); pytest `). The text after a `cd` that starts the command outside a group is not read for a parenthesis. - Sixth, the text before the run holds the word `ssh`, `docker`, + Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in a set-up command's value too (`ranHere`): what follows one may run elsewhere, so `docker compose up -d db; pytest ` is noted as nothing. diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index f895fb5f099..ad2aea90479 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -12,14 +12,14 @@ // may stand before the run in its shell call, and may print the last line of // a run that ended earlier: the report is then the command's only when it was // written moments before the hook read it (`OWN_REPORT_MS`), as a run that -// ended in the call writes it. A run that -// outlives its shell call writes the file after that call's hook ran: a -// report read later is its when pytest began the run that wrote it before -// that call returned, and the launcher reads the file once more before it -// removes it at the session's end (`settleRun`). The file is one a session: a -// pytest run that ends before a hook read it replaces it, and the session's -// start after a compaction empties it (`startReport`). The run that outlived -// its call is then not counted. +// ended in the call writes it. A run that outlives its shell call writes the +// file after that call's hook ran: a report read later is its when pytest +// began the run that wrote it before that call returned, and the launcher +// reads the file once more before it removes it at the session's end +// (`settleRun`). The file is one a session: a pytest run that ends before a +// hook read it replaces it, and the session's start after a compaction +// empties it (`startReport`). The run that outlived its call is then not +// counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -188,13 +188,12 @@ function settle(state, report) { * call, the report read is that run's too. That report was written before * the command's own run began, and a run that ended in the call wrote its * report when it ended (`pytest_sessionfinish`), before it printed the - * summary: the report of - * such a command is its own only when it was written no more than - * `OWN_REPORT_MS` before this read. A report that a command - * before the run wrote within that time is not told apart from the run's, - * nor is one an earlier run wrote that shortly before the call returned. Any - * other report is the pending run's when it is of that run's file and its - * run began by the time the run's command returned (`settle`), and no run's + * summary: the report of such a command is its own only when it was written + * no more than `OWN_REPORT_MS` before this read. A report that a command + * before the run wrote within that time is not told apart from the run's, nor + * is one an earlier run wrote that shortly before the call returned. Any + * other report is the pending run's when it is of that run's file and its run + * began by the time the run's command returned (`settle`), and no run's * otherwise. So a run that was put in the background before pytest began is * not counted. * diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index 9c112fa0701..b937e3dce5f 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1373,13 +1373,16 @@ const SHELL_COMMENT = /(?:^|[\s;&|()])#/; // (`make install test`), and it reads no `test` before a lower-case letter // but at a word's start (`make run-testsuite`). const BUILDS_TEST = new RegExp(String.raw`(?`, `>&`) or of `|&`. +const BACKGROUND = /(?])&(?![&>])/; // True where the commands of `head` that are no set-up cannot pass for the // run `tail` starts with, as a session writes them that edits and then checks // in one shell call (an inline script, `git diff --stat`, `sed`): none starts -// pytest itself, the one before the run has ended when the run starts, and -// the run starts whatever they returned. Quotes are not read. `head` is read -// once from the run backwards and once line by line, so a long one costs time -// in proportion to its length. +// pytest itself, the one before the run has ended when the run starts, the +// run starts whatever they returned, and no `&` puts it in the background. +// Quotes are not read. `head` is read once from the run backwards and once +// line by line, so a long one costs time in proportion to its length. const startsNoRun = (head, tail) => { // `;` or a line's end stands before the run's simple command: the command // before it has ended, and the run starts whatever it returned. After `&&` @@ -1435,7 +1438,12 @@ const startsNoRun = (head, tail) => { // Nor a quote: the run is then the text of a quoted argument (`git commit // -m "fix; pytest "`). `head` is not read for an open parenthesis // or quote, since an inline script holds its own. - !['"', "'"].some((quote) => tail.split(quote).length % 2 === 0) + !['"', "'"].some((quote) => tail.split(quote).length % 2 === 0) && + // Nor does a `&` put the run in the background (`pytest > out.txt + // 2>&1 &`): its call does not wait for the run, so a last line the output + // shows may be one a command before the run printed. The `&` of `&&`, + // `&>` and `|&` puts nothing there. + !BACKGROUND.test(tail) ); }; @@ -1503,28 +1511,30 @@ const counted = (line, kinds) => * the visible `output` shows (`LAST_LINE`), read without its colours. `cases` * is the cases that line counts, all but the deselected: the result file's * `tests`, but for a case whose teardown raised an error, which the line - * counts twice and the file once. - * `failed` is the failures and errors among them and `skipped` the skipped - * ones, apart from the expected failures. All four are null where the output - * holds no such line: the run did not finish inside the call. A run with no - * `-k` whose last line counts deselected cases is none: a selection its words - * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings - * file). Nor is a run pytest ended before its last case, which the line - * above its last one says (`CUT_SHORT`): - * its last line and its result file count the cases it got to. Nor is a run - * that anything follows in the command but `tail`, `head`, `grep` and `echo` - * (`onlyRuns`), a redirect to a file aside: a runner started after it - * (`&& make test`, `; tox`, a second pytest with no space before it, which + * counts twice and the file once. `failed` is the failures and errors among + * them and `skipped` the skipped ones, apart from the expected failures. All + * four are null where the output holds no such line: the run did not finish + * inside the call. A run with no `-k` whose last line counts deselected cases + * is none: a selection its words do not show left cases out (one in + * `PYTEST_ADDOPTS` or the settings file). Nor is a run pytest ended before + * its last case, which the line above its last one says (`CUT_SHORT`): its + * last line and its result file count the cases it got to. Nor is a run that + * anything follows in the command but `tail`, `head`, `grep` and `echo` + * (`onlyRuns`), a redirect to a file aside: a runner started after it (`&& + * make test`, `; tox`, a second pytest with no space before it, which * `PYTEST` does not count) writes the session's result file and prints the - * last line. Quotes are not read there or in the run's words (`PYTEST`), so - * a run piped into `grep -E "passed|failed"` is none, and neither is one - * with `-k "parse and (empty or nested)"`. Nor is a run that a command stands + * last line. Quotes are not read there or in the run's words (`PYTEST`), so a + * run piped into `grep -E "passed|failed"` is none, and neither is one with + * `-k "parse and (empty or nested)"`. Nor is a run that a command stands * before which may start pytest too, after which the run may not start, or * beside which it runs (`make test; pytest `, `python edit.py && pytest * `, `sleep 600 & pytest `): the last line and the result file - * may then be that command's. What may stand before - * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or other - * commands that cannot pass for it (`startsNoRun`). + * may then be that command's. What may stand before the run is `cd`, + * `export`, `source` and `.` (`onlySetsUp`), or other commands that cannot + * pass for it (`startsNoRun`). A run that a `&` puts in the background after + * such commands is none either (`tail -5 out.txt; pytest &`): its call + * does not wait for it, and the last line the output shows may be another + * run's. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1536,11 +1546,11 @@ const counted = (line, kinds) => * not start the command where `afterSetUpOnly` is false). The word after a * flag that may take a value is that value and no path (`BARE`); a short flag * written with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A - * long flag may take none (`--no-header`), and - * the word after it is then a second path: a run with such a word that names - * a Python file is none, and the others are `values`. The caller drops a run - * where one of them names a folder (`--no-header tests`, and `--cov src` - * too): the flag may take no value. + * long flag may take none (`--no-header`), and the word after it is then a + * second path: a run with such a word that names a Python file is none, and + * the others are `values`. The caller drops a run where one of them names a + * folder (`--no-header tests`, and `--cov src` too): the flag may take no + * value. */ export function fileRun(command, output = "") { // A redirect between descriptors is left out: `PYTEST` ends a run's words diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index f895fb5f099..ad2aea90479 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -12,14 +12,14 @@ // may stand before the run in its shell call, and may print the last line of // a run that ended earlier: the report is then the command's only when it was // written moments before the hook read it (`OWN_REPORT_MS`), as a run that -// ended in the call writes it. A run that -// outlives its shell call writes the file after that call's hook ran: a -// report read later is its when pytest began the run that wrote it before -// that call returned, and the launcher reads the file once more before it -// removes it at the session's end (`settleRun`). The file is one a session: a -// pytest run that ends before a hook read it replaces it, and the session's -// start after a compaction empties it (`startReport`). The run that outlived -// its call is then not counted. +// ended in the call writes it. A run that outlives its shell call writes the +// file after that call's hook ran: a report read later is its when pytest +// began the run that wrote it before that call returned, and the launcher +// reads the file once more before it removes it at the session's end +// (`settleRun`). The file is one a session: a pytest run that ends before a +// hook read it replaces it, and the session's start after a compaction +// empties it (`startReport`). The run that outlived its call is then not +// counted. // // hooks/loom-prompt-pack.mjs reads the repository's one memory row by its key // beside a bug report's search and prints one line under the pointers @@ -188,13 +188,12 @@ function settle(state, report) { * call, the report read is that run's too. That report was written before * the command's own run began, and a run that ended in the call wrote its * report when it ended (`pytest_sessionfinish`), before it printed the - * summary: the report of - * such a command is its own only when it was written no more than - * `OWN_REPORT_MS` before this read. A report that a command - * before the run wrote within that time is not told apart from the run's, - * nor is one an earlier run wrote that shortly before the call returned. Any - * other report is the pending run's when it is of that run's file and its - * run began by the time the run's command returned (`settle`), and no run's + * summary: the report of such a command is its own only when it was written + * no more than `OWN_REPORT_MS` before this read. A report that a command + * before the run wrote within that time is not told apart from the run's, nor + * is one an earlier run wrote that shortly before the call returned. Any + * other report is the pending run's when it is of that run's file and its run + * began by the time the run's command returned (`settle`), and no run's * otherwise. So a run that was put in the background before pytest began is * not counted. * diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index 9c112fa0701..b937e3dce5f 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1373,13 +1373,16 @@ const SHELL_COMMENT = /(?:^|[\s;&|()])#/; // (`make install test`), and it reads no `test` before a lower-case letter // but at a word's start (`make run-testsuite`). const BUILDS_TEST = new RegExp(String.raw`(?`, `>&`) or of `|&`. +const BACKGROUND = /(?])&(?![&>])/; // True where the commands of `head` that are no set-up cannot pass for the // run `tail` starts with, as a session writes them that edits and then checks // in one shell call (an inline script, `git diff --stat`, `sed`): none starts -// pytest itself, the one before the run has ended when the run starts, and -// the run starts whatever they returned. Quotes are not read. `head` is read -// once from the run backwards and once line by line, so a long one costs time -// in proportion to its length. +// pytest itself, the one before the run has ended when the run starts, the +// run starts whatever they returned, and no `&` puts it in the background. +// Quotes are not read. `head` is read once from the run backwards and once +// line by line, so a long one costs time in proportion to its length. const startsNoRun = (head, tail) => { // `;` or a line's end stands before the run's simple command: the command // before it has ended, and the run starts whatever it returned. After `&&` @@ -1435,7 +1438,12 @@ const startsNoRun = (head, tail) => { // Nor a quote: the run is then the text of a quoted argument (`git commit // -m "fix; pytest "`). `head` is not read for an open parenthesis // or quote, since an inline script holds its own. - !['"', "'"].some((quote) => tail.split(quote).length % 2 === 0) + !['"', "'"].some((quote) => tail.split(quote).length % 2 === 0) && + // Nor does a `&` put the run in the background (`pytest > out.txt + // 2>&1 &`): its call does not wait for the run, so a last line the output + // shows may be one a command before the run printed. The `&` of `&&`, + // `&>` and `|&` puts nothing there. + !BACKGROUND.test(tail) ); }; @@ -1503,28 +1511,30 @@ const counted = (line, kinds) => * the visible `output` shows (`LAST_LINE`), read without its colours. `cases` * is the cases that line counts, all but the deselected: the result file's * `tests`, but for a case whose teardown raised an error, which the line - * counts twice and the file once. - * `failed` is the failures and errors among them and `skipped` the skipped - * ones, apart from the expected failures. All four are null where the output - * holds no such line: the run did not finish inside the call. A run with no - * `-k` whose last line counts deselected cases is none: a selection its words - * do not show left cases out (one in `PYTEST_ADDOPTS` or the settings - * file). Nor is a run pytest ended before its last case, which the line - * above its last one says (`CUT_SHORT`): - * its last line and its result file count the cases it got to. Nor is a run - * that anything follows in the command but `tail`, `head`, `grep` and `echo` - * (`onlyRuns`), a redirect to a file aside: a runner started after it - * (`&& make test`, `; tox`, a second pytest with no space before it, which + * counts twice and the file once. `failed` is the failures and errors among + * them and `skipped` the skipped ones, apart from the expected failures. All + * four are null where the output holds no such line: the run did not finish + * inside the call. A run with no `-k` whose last line counts deselected cases + * is none: a selection its words do not show left cases out (one in + * `PYTEST_ADDOPTS` or the settings file). Nor is a run pytest ended before + * its last case, which the line above its last one says (`CUT_SHORT`): its + * last line and its result file count the cases it got to. Nor is a run that + * anything follows in the command but `tail`, `head`, `grep` and `echo` + * (`onlyRuns`), a redirect to a file aside: a runner started after it (`&& + * make test`, `; tox`, a second pytest with no space before it, which * `PYTEST` does not count) writes the session's result file and prints the - * last line. Quotes are not read there or in the run's words (`PYTEST`), so - * a run piped into `grep -E "passed|failed"` is none, and neither is one - * with `-k "parse and (empty or nested)"`. Nor is a run that a command stands + * last line. Quotes are not read there or in the run's words (`PYTEST`), so a + * run piped into `grep -E "passed|failed"` is none, and neither is one with + * `-k "parse and (empty or nested)"`. Nor is a run that a command stands * before which may start pytest too, after which the run may not start, or * beside which it runs (`make test; pytest `, `python edit.py && pytest * `, `sleep 600 & pytest `): the last line and the result file - * may then be that command's. What may stand before - * the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or other - * commands that cannot pass for it (`startsNoRun`). + * may then be that command's. What may stand before the run is `cd`, + * `export`, `source` and `.` (`onlySetsUp`), or other commands that cannot + * pass for it (`startsNoRun`). A run that a `&` puts in the background after + * such commands is none either (`tail -5 out.txt; pytest &`): its call + * does not wait for it, and the last line the output shows may be another + * run's. * * A run of another part of the file is none: a node id after the path, any * other option of `PARTIAL` (a mark, `--lf`, `--sw` and `--deselect` may run @@ -1536,11 +1546,11 @@ const counted = (line, kinds) => * not start the command where `afterSetUpOnly` is false). The word after a * flag that may take a value is that value and no path (`BARE`); a short flag * written with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A - * long flag may take none (`--no-header`), and - * the word after it is then a second path: a run with such a word that names - * a Python file is none, and the others are `values`. The caller drops a run - * where one of them names a folder (`--no-header tests`, and `--cov src` - * too): the flag may take no value. + * long flag may take none (`--no-header`), and the word after it is then a + * second path: a run with such a word that names a Python file is none, and + * the others are `values`. The caller drops a run where one of them names a + * folder (`--no-header tests`, and `--cov src` too): the flag may take no + * value. */ export function fileRun(command, output = "") { // A redirect between descriptors is left out: `PYTEST` ends a run's words From 949acc1795018f13b8442374badd52f868bcbd8b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 09:19:05 +0530 Subject: [PATCH 40/52] test(plugin): a case collected from a data file with the test file's stem is not the file's pytest builds a case's class from its node id's path with `/` turned into `.`. A case it collects from a data file itself has that file's path as its class: `tests.test_big.cases.yaml` for `tests/test_big/cases.yaml`, and `tests.test_big.yaml` for `tests/test_big.yaml`. Both start with the module of `tests/test_big.py`, so `ofFile` takes the report for one a run of that file wrote. The cases fail here: three such reports read with a whole run of the file, which are counted as that run, and one read while a run of the file is pending, which settles it. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../tests/test-cost.test.mjs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 69573496283..cf0b6e72783 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -778,6 +778,25 @@ test("a report whose first case names a data file is the run's when the case's c note(classname); assert.equal(runs()?.files, undefined, classname); } + // A case pytest collected from a data file has that file's path as its + // class: one under a folder or a name with the test file's stem is not + // the test file's, from pytest's root at the checkout or at the folder. + for (const source of ["tests/test_big/cases.yaml", "tests/test_big.yaml", "test_big/cases.yaml"]) { + note(source.replaceAll("/", "."), source); + assert.equal(runs()?.files, undefined, source); + } + // Nor is it a pending run's: the run stays pending. + noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, report: null, cwd }); + const collected = report({ + tests: 9000, + time: "300.1", + file: "tests/test_big/cases.yaml", + classname: "tests.test_big.cases.yaml", + }); + noteCommand(SESSION, { command: "pgrep -f pytest", output: "", report: read(collected), cwd }); + assert.equal(runs().files, undefined); + assert.equal(runs().pending.file, file); + fs.rmSync(sessionStatePath("test-cost", SESSION)); // A case in a Python file is that file's, whatever its class: one a class // of this file's module takes from another file is not counted. note("tests.test_big.Suite", "tests/test_other.py"); From 7f15810d3895b10af7a79d672b75d1be365b1eb0 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 09:29:31 +0530 Subject: [PATCH 41/52] A case collected from a data file with the test file's stem is not the file's `ofFile` takes a report whose first case names a data file for the run's when the case's class is under the module of the run's file. pytest builds the class from the node id's path with `/` turned into `.`, so a case it collects from a data file itself has that file's path as its class: `tests.test_big.cases.yaml` for `tests/test_big/cases.yaml`. That class is under the module of `tests/test_big.py`, and a suite run whose first case came from such a file settled a pending run of the test file with the suite's cases and seconds. `ofFile` refuses a data file whose path starts with the matched module's path followed by `/` or `.`. A data-driven suite that keeps its data files under a folder named after its test file is not counted; the limits list says so. The limits list and the hooks page also name a run that outlives its call after a command that printed an earlier run's summary line: its output shows a summary, so it is not kept as the pending run. The feature page lists what may stand before a run as one sub-bullet for each refusal, and the passages of both pages that broke in the middle of a line are wrapped again. `tests/unit/session_content_senders.json` pins the bytes of `lib/test-cost.mjs` for its reviewed `memory.get` read. The pin is renewed: `costLine` and `identity`, which build that read, are as on `main`. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 110 +++++++------ integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 150 +++++++++--------- .../claude-code-plugin/lib/test-cost.mjs | 12 +- integrations/codex-plugin/lib/test-cost.mjs | 12 +- tests/unit/session_content_senders.json | 4 +- 6 files changed, 159 insertions(+), 131 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index cdaf1037391..b6ee4fb7d25 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1772,47 +1772,50 @@ session's private state, by the file: (`make test || pytest tests/test_big.py`, `make build && pytest tests/test_big.py`, `sleep 600 & pytest tests/test_big.py`): the result file and the summary line may then be that command's. What may stand before the run is `cd`, `export`, `source` and - `.`, or the commands of a session that edits and then checks in one shell call, such as - `sed -i 's/a/b/' src/parser.py; git diff --stat; pytest tests/test_big.py`: they name - no test runner, their text holds no `pytest` or `py.test` (`.pytest_cache` and - `pytest.ini` hold it) and nothing that ends the shell where a command fails - (`exit`, `errexit`, a `set` with `-e` among its flags, as `set -e` and `set -u -e`), - and `;` or a line's end stands before the run's own command, not `&&`, `||`, `&`, a - pipe or a parenthesis. A build tool with `test` after no letter further on in its - command counts as a test runner there, inside a word too and whatever stands before - it: `make install test` runs the tests, and a package, a target or a path of such a - name counts too (`npm install test-utils`, `make run-testsuite`, - `go build ./internal/testutil/...`). Nor does the text before the run hold the word - `ssh`, `docker`, `podman` or `kubectl`, in a set-up command's value too: what follows - one may run elsewhere, so `docker compose up -d db; pytest tests/test_big.py` counts - as neither. - After `&&` or `||` the run waits on what the command before it returned. After `&` or - a pipe the run always starts, and that command runs beside it: what it prints and - writes may come after the run's. The `;` is one the shell reads: a run after `\;`, or - after a `#` that starts a word on its line ahead of the line's first quote, counts as - neither - (`git diff --stat # then; pytest tests/test_big.py` holds a comment and no run). A - `#` after a quote may be an argument's, as in `sed -i '5a\ # note' src/parser.py`, - and decides nothing. One of `&&`, `||`, `&` or a pipe at the end of the line above the - run counts as one before the run on its line, with or without a comment between them - (`git diff --stat &&` on the line above the run), and so does one at the end of a line - that holds `<<`: under `git apply <<'P' &&`, the run after the patch waits on - `git apply`. Where a heredoc ends is not read, so a line of an inline script's text - that holds `<<` and ends in one of them counts too. A list that ended before the run - decides nothing: `git stash pop || true; pytest tests/test_big.py` counts. The run and what follows it - close no parenthesis and no quote opened before them: a run in a group that waits on an - earlier command (`python edit.py && (git diff --stat; pytest tests/test_big.py)`) and - the text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`) count - as neither. So does a run that a `&` puts in the background after such commands, alone - or with what reads its output - (`tail -5 out.txt; pytest tests/test_big.py > out2.txt 2>&1 &`): the call does not wait - for the run, and a summary line its output shows may be an earlier run's. The `&` of - `&&`, `&>` and `|&` puts nothing in the background. After such commands a `cd` is - followed only where it starts the command - (`cd pkg && sed -i 's/a/b/' src/parser.py; pytest tests/test_big.py`): further on it - may be the text of a heredoc or of a quoted argument, as a `cd pkg` line under - `cat > run.sh <<'E'`, and the run counts as neither. So does a run after a `cd` that - starts the command in a group (`(cd pkg && git stash -q); pytest tests/test_big.py`); + `.`, or the commands of a session that edits and then checks in one shell call, such + as `sed -i 's/a/b/' src/parser.py; git diff --stat; pytest tests/test_big.py`. After + such commands the run counts as neither where: + - the text before the run names a test runner, holds `pytest` or `py.test` + (`.pytest_cache` and `pytest.ini` hold it), or holds something that ends the shell + where a command fails: `exit`, `errexit`, or a `set` with `-e` among its flags, as + `set -e` and `set -u -e`. A build tool with `test` after no letter further on in + its command counts as a test runner there, inside a word too and whatever stands + before it: `make install test` runs the tests, and a package, a target or a path + of such a name counts too (`npm install test-utils`, `make run-testsuite`, + `go build ./internal/testutil/...`); + - `&&`, `||`, `&`, a pipe or a parenthesis stands before the run's own command, not + `;` or a line's end. After `&&` or `||` the run waits on what the command before + it returned. After `&` or a pipe the run always starts, and that command runs + beside it: what it prints and writes may come after the run's. One of `&&`, `||`, + `&` or a pipe at the end of the line above the run counts as one before the run on + its line, with or without a comment between them (`git diff --stat &&` on the line + above the run). So does one at the end of a line that holds `<<`: under + `git apply <<'P' &&`, the run after the patch waits on `git apply`. Where a + heredoc ends is not read, so a line of an inline script's text that holds `<<` and + ends in one of them counts too. A list that ended before the run decides nothing: + `git stash pop || true; pytest tests/test_big.py` counts; + - the shell does not read the `;` before the run: a backslash stands before it, or a + `#` that starts a word stands before the run on its line, ahead of the line's + first quote (`git diff --stat # then; pytest tests/test_big.py` holds a comment + and no run). A `#` after a quote may be an argument's, as in + `sed -i '5a\ # note' src/parser.py`, and decides nothing; + - the run and what follows it close a parenthesis or a quote opened before them: the + run is in a group that waits on an earlier command + (`python edit.py && (git diff --stat; pytest tests/test_big.py)`), or it is the + text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`); + - a `&` puts the run in the background, alone or with what reads its output + (`tail -5 out.txt; pytest tests/test_big.py > out2.txt 2>&1 &`): the call does not + wait for the run, and a summary line its output shows may be an earlier run's. The + `&` of `&&`, `&>` and `|&` puts nothing in the background; + - a `cd` stands before the run that does not start the command, or that starts it in + a group (`(cd pkg && git stash -q); pytest tests/test_big.py`). A `cd` is followed + where it starts the command + (`cd pkg && sed -i 's/a/b/' src/parser.py; pytest tests/test_big.py`): further on + it may be the text of a heredoc or of a quoted argument, as a `cd pkg` line under + `cat > run.sh <<'E'`; + - the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in + a set-up command's value too: what follows one may run elsewhere, so + `docker compose up -d db; pytest tests/test_big.py` counts as neither; - a run after a `cd` with no folder counts as neither: `cd; pytest tests/test_big.py` runs in the home folder. @@ -1826,18 +1829,19 @@ printed it: `tail -5 out.txt; pytest tests/test_big.py` shows the summary of the that wrote `out.txt`, and where its own run outlives the call, the result file read with it is that earlier run's. That file was written before the command's own run began, and a run that ended in its call wrote the file when it ended (`pytest_sessionfinish`), -before pytest printed the summary. So where other -commands than `cd`, `export`, `source` and `.` stand before the run (a comment line -counts as one), the result file is the command's only when it was written no more than -10 s before the hook read it. A command that is the run alone prints no summary line but -its own, and its result file has no such bound. Neither has the result file of a run -with only `cd`, `export`, `source` and `.` before it, which is taken as the command's -own. +before pytest printed the summary. So where other commands than `cd`, `export`, +`source` and `.` stand before the run (a comment line counts as one), the result file is +the command's only when it was written no more than 10 s before the hook read it. A +command that is the run alone prints no summary line but its own, and its result file +has no such bound. Neither has the result file of a run with only `cd`, `export`, +`source` and `.` before it, which is taken as the command's own. A case that a data-driven suite reads from a data file names that file in the result file, not the test file that collected it. Such a case is in the command's test file when its class is under that file's module (`tests.test_big.Suite` for -`tests/test_big.py`). +`tests/test_big.py`). A case pytest collected from a data file itself has that file's +path as its class, so a data file under a folder or a name with the test file's stem +(`tests/test_big/cases.yaml`, `tests/test_big.yaml`) is not in the test file. A run that outlives its shell call writes the file after the hook ran: it is read after the next shell command that names a test runner, or when the session ends. That file is @@ -1937,6 +1941,14 @@ What it does not do: - a run that other commands stand before is not counted where its result file was written more than 10 s before the hook read it, as by a pytest that takes that long to print its summary and end after it wrote the file; +- a run that outlives its shell call is not counted where a command before it printed + the summary line of an earlier run + (`tail -5 out.txt; pytest tests/test_big.py | tail -5`): its output shows a summary + line, so it is not kept as a run that outlives its call, and the result file it + writes later is not read as its own; +- a data-driven suite whose data files are under a folder named after its test file + (`tests/test_big/` for `tests/test_big.py`) is not counted: its cases are not told + apart from the ones pytest collects from such a file itself; - a command before the run that starts pytest under no runner's name, such as a script of the repository, is not told apart from an edit. Its result file and summary line are counted as the run's where the script ended within 10 s of the call's return and diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 07aa07c83c2..c0a620f28d6 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, a `cd` stands before the run that does not start the command, or that starts it in a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `): further on it may be the text of a heredoc or of a quoted argument. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, a `cd` stands before the run that does not start the command, or that starts it in a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `): further on it may be the text of a heredoc or of a quoted argument. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module, and the data file is under no folder or name with the test file's stem, as `tests/test_big/` for `tests/test_big.py`: pytest gives a case it collects from such a file the same class). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index cd393fa6443..fee840ebbcf 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1480,13 +1480,12 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that line. So is a run that a command stands before which may start pytest too, after which the run may not start, or beside which it runs (`make test || pytest `, `python edit.py && pytest `, - `sleep 600 & pytest `): the result file and the last line may - then be that command's. What may stand - before the run is `cd`, `export`, `source` and `.` (`onlySetsUp`), or - the commands of a session that edits and then checks in one shell call - (an inline script, `git diff --stat`, `sed`). After such commands the - run is noted as nothing in the seven cases that follow; `startsNoRun` - reads the first five. + `sleep 600 & pytest `): the result file and the last line may then + be that command's. What may stand before the run is `cd`, `export`, + `source` and `.` (`onlySetsUp`), or the commands of a session that edits + and then checks in one shell call (an inline script, `git diff --stat`, + `sed`). After such commands the run is noted as nothing in the seven + cases that follow; `startsNoRun` reads the first five. First, the text before the run names a test runner (`startsRunner`), holds `pytest` or `py.test` in any word (`.pytest_cache`, `pytest.ini`), or holds something that ends the shell where a command @@ -1534,22 +1533,19 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that `podman` or `kubectl`, in a set-up command's value too (`ranHere`): what follows one may run elsewhere, so `docker compose up -d db; pytest ` is noted as nothing. - A list that ended before the run decides - nothing: `git stash pop || true; pytest ` is a run. The text - before the run is not read for an open - quote or parenthesis: an inline script holds its own. A script that - starts pytest under another name is not told apart, nor is a command - put in the background earlier in the call - (`./check.sh & sleep 1; pytest `), nor a shell - that ends another way (`exec`). Quotes are not read, - so a `|`, `;`, `&`, `<`, backquote or + A list that ended before the run decides nothing: + `git stash pop || true; pytest ` is a run. The text before the run + is not read for an open quote or parenthesis: an inline script holds its + own. A script that starts pytest under another name is not told apart, + nor is a command put in the background earlier in the call + (`./check.sh & sleep 1; pytest `), nor a shell that ends another + way (`exec`). Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` are noted as nothing. So is a run - with no `-k` among its words whose last line counts deselected cases: - a selection the words do not show left cases out, one in - `PYTEST_ADDOPTS` or the settings file. A run that outlived its shell - call shows no last + with no `-k` among its words whose last line counts deselected cases: a + selection the words do not show left cases out, one in `PYTEST_ADDOPTS` + or the settings file. A run that outlived its shell call shows no last line, and such a run is counted as a whole run with the cases it ran. A whole run started with xdist workers (`-n`) counts with the seconds it took: the row does not say how its run was started, so a session that @@ -1558,65 +1554,69 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that (`--no-header tests`), so a run with such a word that names a Python file or a folder is noted as nothing too. The file is the one the command names, from the payload's folder and the command's one `cd`, - where it is there. A run after a move the hook does not follow is - noted as nothing: a second `cd`, `pushd`, a `cd` with no folder - (`cd; pytest ` runs in the home folder), a `cd` in a subshell - that closed, or a `cd` to a folder written with anything but letters, - digits and `._/-` (a quoted or escaped name, an option, `$`, `~`). + where it is there. A run after a move the hook does not follow is noted + as nothing: a second `cd`, `pushd`, a `cd` with no folder + (`cd; pytest ` runs in the home folder), a `cd` in a subshell that + closed, or a `cd` to a folder written with anything but letters, digits + and `._/-` (a quoted or escaped name, an option, `$`, `~`). The report is the command's when the command's visible output shows - pytest's summary line with the cases, the failures and the seconds - the report holds, the seconds within a second or a twentieth of them, - and the report's first case is in the file the command names: a run - the option did not reach writes no report, and the one read after it - is an earlier run's, which the seconds of two short runs do not tell - apart. Nor does the line where a command before the run printed it: + pytest's summary line with the cases, the failures and the seconds the + report holds, the seconds within a second or a twentieth of them, and + the report's first case is in the file the command names: a run the + option did not reach writes no report, and the one read after it is an + earlier run's, which the seconds of two short runs do not tell apart. + Nor does the line where a command before the run printed it: `tail -5 out.txt; pytest ` shows the last line of the run that wrote `out.txt`, and where its own run outlives the call, the report - read with it is that earlier run's too. That report was written - before the command's own run began, and a run that ended in its call - wrote the report when it ended (`pytest_sessionfinish`), before - pytest printed the summary. So for a run that a command - which is no set-up stands before, or a comment line, which is read - as one, the report is the command's only when it was written no more - than 10 s before the hook read it (`OWN_REPORT_MS` in - lib/test-cost.mjs). A command that is the run alone prints no line - but its own, and its report has no such bound. Neither has the - report of a run with only `cd`, `export`, `source` and `.` before it: - it is taken as the command's own, whatever a file that `source` or - `.` read printed. The first case - is in the file where its `file` - attribute names it from pytest's root. A case that a data-driven suite - reads from a data file names that file, which is no Python file: it is - in the file where its `classname` is under the file's module (`ofFile` - in lib/test-cost.mjs). The summary is pytest's last line, whatever it counts - (`8000 deselected in 1.20s` and `no tests ran in 0.01s` too), read - without the colours of a pytest told to colour its output. A run - whose output shows no such line may not have ended: one that outlives - its shell call writes the file after the hook ran. It is kept as the - session's pending run, with the time its command returned. Any other - report the hook reads is the pending run's when its first case is in - the pending run's file and the run that wrote it began by that time, - and no run's otherwise: pytest began it at the time the file was - written less the seconds of its `testsuite`, and a run that a later - command started, by any launcher and whether or not a hook ran for that - command, began after it. A run of the file that something else started - while the pending run was in its call, such as a script in the + read with it is that earlier run's too. That report was written before + the command's own run began, and a run that ended in its call wrote the + report when it ended (`pytest_sessionfinish`), before pytest printed the + summary. So for a run that a command which is no set-up stands before, + or a comment line, which is read as one, the report is the command's + only when it was written no more than 10 s before the hook read it + (`OWN_REPORT_MS` in lib/test-cost.mjs). A command that is the run alone + prints no line but its own, and its report has no such bound. Neither + has the report of a run with only `cd`, `export`, `source` and `.` + before it: it is taken as the command's own, whatever a file that + `source` or `.` read printed. The first case is in the file where its + `file` attribute names it from pytest's root. A case that a data-driven + suite reads from a data file names that file, which is no Python file: + it is in the file where its `classname` is under the file's module + (`ofFile` in lib/test-cost.mjs). A case pytest collected from a data + file itself has that file's path as its `classname`, so a data file + under a folder or a name with the test file's stem + (`tests/test_big/cases.yaml` and `tests/test_big.yaml` for + `tests/test_big.py`) is not in the file. The summary is pytest's last + line, whatever it counts (`8000 deselected in 1.20s` and + `no tests ran in 0.01s` too), read without the colours of a pytest told + to colour its output. A run whose output shows no such line may not have + ended: one that outlives its shell call writes the file after the hook + ran. It is kept as the session's pending run, with the time its command + returned. Any other report the hook reads is the pending run's when its + first case is in the pending run's file and the run that wrote it began + by that time, and no run's otherwise: pytest began it at the time the + file was written less the seconds of its `testsuite`, and a run that a + later command started, by any launcher and whether or not a hook ran for + that command, began after it. A run of the file that something else + started while the pending run was in its call, such as a script in the background, began before that time too: its report, read with a command - that is not that run, is counted as the pending run's. So is the - report of a pytest that a command before the pending run started in - the same call and that ended after the call returned - (`./check.sh; pytest `, where the call times out while the - script runs): the 10 s bound is on a report read with its command, and - this one is read later. So is the report of a run that an earlier - call left going, in the background or past its timeout, and that is - no file run (two paths, a node id, a mark): it left no state and - began before that time, and where its first case is in the pending - run's file and a hook reads it before the pending run's own, the - pending run is counted with the cases and seconds of what it ran. - The launcher - reads the report once more at SessionEnd, before it removes the file, - without reading a token. A run put in the background at once returns - before pytest began, and is not counted. + that is not that run, is counted as the pending run's. So is the report + of a pytest that a command before the pending run started in the same + call and that ended after the call returned + (`./check.sh; pytest `, where the call times out while the script + runs): the 10 s bound is on a report read with its command, and this one + is read later. So is the report of a run that an earlier call left + going, in the background or past its timeout, and that is no file run + (two paths, a node id, a mark): it left no state and began before that + time, and where its first case is in the pending run's file and a hook + reads it before the pending run's own, the pending run is counted with + the cases and seconds of what it ran. The launcher reads the report once + more at SessionEnd, before it removes the file, without reading a token. + A run put in the background at once returns before pytest began, and is + not counted. Nor is a run that outlives its call after a command that + printed an earlier run's last line + (`tail -5 out.txt; pytest | tail -5`): its output shows a last + line, so the run is not kept as pending. A run with no last line in sight is not kept where the report read with its command is of its file and no pending run's: the run wrote it in its call, and the command cut the line (`| head -30`, diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index ad2aea90479..ccba487d019 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -103,13 +103,21 @@ function located(run, cwd) { * root, a folder at or above the file's. A case that a data-driven suite * reads from a data file names that file, which is no Python file: the * report is then the file's when the case's class is under the file's - * module, which pytest names from its root too. */ + * module, which pytest names from its root too. A case pytest collected + * from a data file itself has that file's path as its class, with `/` + * turned into `.`: a data file under a folder or a name with the test + * file's stem (`tests/test_big/cases.yaml`, `tests/test_big.yaml`) is not + * taken for one the test file read. */ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); const parts = file.replace(/\.py$/, "").split("/"); - return parts.some((_, at) => `${cost.classname}.`.startsWith(`${parts.slice(at).join(".")}.`)); + return parts.some((_, at) => { + const stem = parts.slice(at); + const under = `${cost.classname}.`.startsWith(`${stem.join(".")}.`); + return under && ![".", "/"].some((next) => cost.file.startsWith(`${stem.join("/")}${next}`)); + }); } /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index ad2aea90479..ccba487d019 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -103,13 +103,21 @@ function located(run, cwd) { * root, a folder at or above the file's. A case that a data-driven suite * reads from a data file names that file, which is no Python file: the * report is then the file's when the case's class is under the file's - * module, which pytest names from its root too. */ + * module, which pytest names from its root too. A case pytest collected + * from a data file itself has that file's path as its class, with `/` + * turned into `.`: a data file under a folder or a name with the test + * file's stem (`tests/test_big/cases.yaml`, `tests/test_big.yaml`) is not + * taken for one the test file read. */ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); const parts = file.replace(/\.py$/, "").split("/"); - return parts.some((_, at) => `${cost.classname}.`.startsWith(`${parts.slice(at).join(".")}.`)); + return parts.some((_, at) => { + const stem = parts.slice(at); + const under = `${cost.classname}.`.startsWith(`${stem.join(".")}.`); + return under && ![".", "/"].some((next) => cost.file.startsWith(`${stem.join("/")}${next}`)); + }); } /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 334b24da49c..f0b79309b3c 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -414,7 +414,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "872a5c986dc1ddbcc9bccc47f77925a45030a858069784efbf5cb61b1cf738bf", + "integrations/claude-code-plugin/lib/test-cost.mjs": "1ffe0646c41c3fd3f1a6c6955f02d81c505f7dc3b2e313e771f5317364a8345c", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -430,7 +430,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "872a5c986dc1ddbcc9bccc47f77925a45030a858069784efbf5cb61b1cf738bf", + "integrations/codex-plugin/lib/test-cost.mjs": "1ffe0646c41c3fd3f1a6c6955f02d81c505f7dc3b2e313e771f5317364a8345c", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From ea36e779a49644add637140502b0c8ff1c4d131e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 10:02:30 +0530 Subject: [PATCH 42/52] test(plugin): a move by another spelling is no file run, and a data file with the test file's path is not the file's `MOVE` reads `cd` before a line's end only where no character but a blank or a separator stands before it, so `\cd` on the line above a run is no move: the run answers the gate as one in the session's folder, and `fileRun` returns it with no folder. `main` reads `cd` before any blank wherever the word stands. After a command that is no set-up, `fileRun` also returns a run under `"cd";` or `'cd'`, which move to the home folder too. `ofFile` refuses a data file whose path is the test file's, less `.py`, followed by `.` or `/`, and not one whose path is exactly that: a file `tests/test_big` that pytest collects has the class `tests.test_big`. The cases fail here: `\cd` above a run in both readers, the quoted spellings in `fileRun`, and a report whose first case is in `tests/test_big`, read with a whole run of `tests/test_big.py`. `ls /media/cd` and `export OUT=/media/cd` on the line above a run move to the refused lists, where `main` has them, and so does `ls /media/cd;` before a file run, which `main` refuses as a command that is no set-up. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../tests/test-cost.test.mjs | 27 +++++++++++++------ .../tests/test-gate.test.mjs | 10 ++++--- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index cf0b6e72783..e6159facf10 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -144,9 +144,8 @@ test("a command's one pytest run of one test file is whole or filtered with -k", // What sets the shell up may stand before it. `source .venv/bin/activate && export PYTHONPATH=src; pytest ${FILE}`, `. .venv/bin/activate; pytest ${FILE} -q`, - // The word `cd` at the end of a value is no move, before a line's end too. + // The word `cd` at the end of a value is no move before a separator. `export OUT=/media/cd; pytest ${FILE}`, - `export OUT=/media/cd\npytest ${FILE}`, // What reads the run's output may follow it. `pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt; echo exit=$?`, ]) { @@ -239,9 +238,6 @@ test("a run that follows commands which name no test runner is a file run", () = `cat >> src/parser.py <<'E'\nclass Finder:\n found = False\nE\ntimeout 590 python -m pytest -q ${FILE}`, `git checkout src/parser.py; sed -i 's/a/b/' src/parser.py; echo 'x = 1' >> /tmp/t.py; pytest ${FILE} -q > /tmp/out.txt 2>&1; tail -5 /tmp/out.txt`, `rm /tmp/ex.py; pytest ${FILE}`, - // The word `cd` at the end of an argument is no move, before a line's end too. - `ls /media/cd; pytest ${FILE}`, - `ls /media/cd\npytest ${FILE}`, // A build tool with no test target among its words. `make install; pytest ${FILE}`, // The run starts whatever a command before it returned, an `||` list too. @@ -363,6 +359,16 @@ test("a command with two pytest runs, two paths, another selection or no run of `[ -d pkg ] || { cd\n}\npytest ${FILE}`, `builtin cd; pytest ${FILE}`, `command cd\npytest ${FILE}`, + // The word before a line's end is a move wherever it stands, and `\cd` is `cd`. + `\\cd\npytest ${FILE}`, + `\\cd; pytest ${FILE}`, + `export OUT=/media/cd\npytest ${FILE}`, + // After a command that is no set-up, the word anywhere but at the command's start may be a move + // by another spelling. + `"cd"; pytest ${FILE}`, + `git diff --stat; 'cd'\npytest ${FILE}`, + `ls /media/cd; pytest ${FILE}`, + `git diff --stat; popd; pytest ${FILE}`, // A folder that is not written plainly: its name is cut at a space, or is an option. `cd "/work/My Projects/app" && pytest ${FILE}`, `cd /work/My\\ Projects/app && pytest ${FILE}`, @@ -779,9 +785,14 @@ test("a report whose first case names a data file is the run's when the case's c assert.equal(runs()?.files, undefined, classname); } // A case pytest collected from a data file has that file's path as its - // class: one under a folder or a name with the test file's stem is not - // the test file's, from pytest's root at the checkout or at the folder. - for (const source of ["tests/test_big/cases.yaml", "tests/test_big.yaml", "test_big/cases.yaml"]) { + // class: a path that starts with the test file's, less `.py`, is not the + // test file's, from pytest's root at the checkout or at the folder. + for (const source of [ + "tests/test_big/cases.yaml", + "tests/test_big.yaml", + "tests/test_big", + "test_big/cases.yaml", + ]) { note(source.replaceAll("/", "."), source); assert.equal(runs()?.files, undefined, source); } diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index c8c29740cff..e9a3143ea3a 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1265,10 +1265,8 @@ test("a run's paths are read from the directory its command moved to", () => { answered([edit(), bash("pytest tests -q", "3 passed in 0.10s", { cwd: ROOT })], RUN_GATE, "/r/sub"), true, ); - // The word `cd` at the end of an argument is no move, before a line's end too. - for (const command of ["ls /media/cd; pytest tests -q", "ls /media/cd\npytest tests -q"]) { - assert.equal(answered([edit(), bash(command, "3 passed in 0.10s")]), true, command); - } + // The word `cd` at the end of an argument is no move before a separator. + assert.equal(answered([edit(), bash("ls /media/cd; pytest tests -q", "3 passed in 0.10s")]), true); // A move this reader does not follow, and a run outside the checkout. const inPython = { ...RUN_GATE, @@ -1290,6 +1288,10 @@ test("a run's paths are read from the directory its command moved to", () => { "[ -d sub ] || { cd\n}\npytest tests -q", "builtin cd; pytest tests -q", "command cd\npytest tests -q", + // The word before a line's end is a move wherever it stands, and `\cd` is `cd`. + "\\cd\npytest tests -q", + "\\cd; pytest tests -q", + "ls /media/cd\npytest tests -q", "docker exec app pytest tests -q", "kubectl exec pod -- pytest tests -q", "ssh host 'cd repo; pytest tests -q'", From e05dc2bef01ba0e40bff6e3c4d746df9f5ae53b4 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 10:12:42 +0530 Subject: [PATCH 43/52] A move by another spelling is no file run, and a data file with the test file's path is not the file's `MOVE` reads `cd`, `pushd` and `popd` before a blank wherever the word stands, a line's end included, as on `main`: `\cd` on the line above a run is a move again, in the test gate and in `fileRun`. A `cd` straight before `;`, `&`, `|` or `)` is still one where it is a word of its own, and after a backslash too. `ls /media/cd` on the line above a run is a move with no folder again, as on `main`. After a command that is no set-up, `fileRun` refuses a run where the word `cd`, `pushd` or `popd` stands anywhere before it but as the one `cd` that starts the command (`MOVE_WORD`): `"cd"; pytest ` moves to the home folder by a spelling `MOVE` does not read. `ls /media/cd; pytest ` is no file run either. What stands after set-up alone is read as before. `ofFile` refuses a data file whose path starts with the test file's, less `.py`, whatever follows: `tests/test_big`, which pytest gives the class `tests.test_big`, was taken for a file `tests/test_big.py` read. A data-driven suite whose data files are under `tests/test_big_cases/` is not counted; the limits list says so. `tests/unit/session_content_senders.json` pins the bytes of `lib/test-cost.mjs` for its reviewed `memory.get` read. The pin is renewed: `costLine` and `identity`, which build that read, are as on `main`. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 22 ++++++++-------- integrations/claude-code-plugin/README.md | 2 +- .../claude-code-plugin/hooks/HOOKS.md | 19 +++++++------- .../claude-code-plugin/lib/test-cost.mjs | 8 +++--- .../claude-code-plugin/lib/test-gate.mjs | 26 +++++++++++-------- integrations/codex-plugin/lib/test-cost.mjs | 8 +++--- integrations/codex-plugin/lib/test-gate.mjs | 26 +++++++++++-------- tests/unit/session_content_senders.json | 4 +-- 8 files changed, 61 insertions(+), 54 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index b6ee4fb7d25..2b02d92dd92 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1807,12 +1807,12 @@ session's private state, by the file: (`tail -5 out.txt; pytest tests/test_big.py > out2.txt 2>&1 &`): the call does not wait for the run, and a summary line its output shows may be an earlier run's. The `&` of `&&`, `&>` and `|&` puts nothing in the background; - - a `cd` stands before the run that does not start the command, or that starts it in - a group (`(cd pkg && git stash -q); pytest tests/test_big.py`). A `cd` is followed - where it starts the command - (`cd pkg && sed -i 's/a/b/' src/parser.py; pytest tests/test_big.py`): further on - it may be the text of a heredoc or of a quoted argument, as a `cd pkg` line under - `cat > run.sh <<'E'`; + - the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one + `cd` that starts the command, outside a group + (`cd pkg && sed -i 's/a/b/' src/parser.py; pytest tests/test_big.py` counts, + `(cd pkg && git stash -q); pytest tests/test_big.py` and + `ls /media/cd; pytest tests/test_big.py` do not): further on the word may be the + text of a heredoc or a move by another spelling; - the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in a set-up command's value too: what follows one may run elsewhere, so `docker compose up -d db; pytest tests/test_big.py` counts as neither; @@ -1840,8 +1840,8 @@ A case that a data-driven suite reads from a data file names that file in the re file, not the test file that collected it. Such a case is in the command's test file when its class is under that file's module (`tests.test_big.Suite` for `tests/test_big.py`). A case pytest collected from a data file itself has that file's -path as its class, so a data file under a folder or a name with the test file's stem -(`tests/test_big/cases.yaml`, `tests/test_big.yaml`) is not in the test file. +path as its class, so a data file whose path starts with the test file's, less `.py` +(`tests/test_big/cases.yaml`), is not in the test file. A run that outlives its shell call writes the file after the hook ran: it is read after the next shell command that names a test runner, or when the session ends. That file is @@ -1946,9 +1946,9 @@ What it does not do: (`tail -5 out.txt; pytest tests/test_big.py | tail -5`): its output shows a summary line, so it is not kept as a run that outlives its call, and the result file it writes later is not read as its own; -- a data-driven suite whose data files are under a folder named after its test file - (`tests/test_big/` for `tests/test_big.py`) is not counted: its cases are not told - apart from the ones pytest collects from such a file itself; +- a data-driven suite is not counted where the path of its data files starts with its + test file's, less `.py` (`tests/test_big_cases/` for `tests/test_big.py`): its cases + are not told apart from the ones pytest collects from such a file itself; - a command before the run that starts pytest under no runner's name, such as a script of the repository, is not told apart from an edit. Its result file and summary line are counted as the run's where the script ended within 10 s of the call's return and diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index c0a620f28d6..4f920eb71ff 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, a `cd` stands before the run that does not start the command, or that starts it in a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `): further on it may be the text of a heredoc or of a quoted argument. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module, and the data file is under no folder or name with the test file's stem, as `tests/test_big/` for `tests/test_big.py`: pytest gives a case it collects from such a file the same class). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module, and the data file's path does not start with the test file's, less `.py`, as `tests/test_big/` for `tests/test_big.py`: pytest gives a case it collects from such a file the same class). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index fee840ebbcf..2d895c0b5b4 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1522,13 +1522,12 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that call does not wait for the run, so a last line its output shows may be one a command before the run printed (`BACKGROUND`). The `&` of `&&`, `&>` and `|&` puts nothing in the background. - Sixth, a `cd` stands before the run that does not start the command, - or that starts it in a group. Further on, a `cd` may be the text of a - heredoc or of a quoted argument, which is not read - (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run). A group ends - before the run (`(cd pkg && git stash -q); pytest `). The text - after a `cd` that starts the command outside a group is not read for - a parenthesis. + Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere + but as the one `cd` that starts the command, outside a group + (`MOVE_WORD` in lib/test-gate.mjs). Further on, the word may be the + text of a heredoc (`cat > run.sh <<'E'`, `cd pkg`, `E`, then the run) + or a move by another spelling (`"cd"; pytest `). A group ends + before the run (`(cd pkg && git stash -q); pytest `). Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in a set-up command's value too (`ranHere`): what follows one may run elsewhere, so @@ -1584,9 +1583,9 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that it is in the file where its `classname` is under the file's module (`ofFile` in lib/test-cost.mjs). A case pytest collected from a data file itself has that file's path as its `classname`, so a data file - under a folder or a name with the test file's stem - (`tests/test_big/cases.yaml` and `tests/test_big.yaml` for - `tests/test_big.py`) is not in the file. The summary is pytest's last + whose path starts with the test file's, less `.py` + (`tests/test_big/cases.yaml` for `tests/test_big.py`), is not in the + file. The summary is pytest's last line, whatever it counts (`8000 deselected in 1.20s` and `no tests ran in 0.01s` too), read without the colours of a pytest told to colour its output. A run whose output shows no such line may not have diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index ccba487d019..80115f95a6b 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -105,9 +105,9 @@ function located(run, cwd) { * report is then the file's when the case's class is under the file's * module, which pytest names from its root too. A case pytest collected * from a data file itself has that file's path as its class, with `/` - * turned into `.`: a data file under a folder or a name with the test - * file's stem (`tests/test_big/cases.yaml`, `tests/test_big.yaml`) is not - * taken for one the test file read. */ + * turned into `.`: a data file whose path starts with the test file's, + * less `.py` (`tests/test_big/cases.yaml`, `tests/test_big`), is not taken + * for one the test file read. */ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; @@ -116,7 +116,7 @@ function ofFile(run, cost) { return parts.some((_, at) => { const stem = parts.slice(at); const under = `${cost.classname}.`.startsWith(`${stem.join(".")}.`); - return under && ![".", "/"].some((next) => cost.file.startsWith(`${stem.join("/")}${next}`)); + return under && !cost.file.startsWith(stem.join("/")); }); } diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index b937e3dce5f..fddce5f2f1d 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1310,14 +1310,15 @@ const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // Only spaces and tabs are read between a separator and `cd`: a line's end is // a separator itself, and a run of blank lines is then read once. Nor is a // line's end read between `cd` and its folder: a `cd` with no folder goes to -// the home folder, and is a move with no directory. A `cd` straight before a -// separator or a line's end is that move where it is a word of its own, after -// a keyword or a word the shell runs it under too (`then cd`, `builtin cd`), -// and an argument that is the word alone is read as one (`echo cd`). The end -// of a longer argument is none (`ls /media/cd; pytest `). Before a -// space or a tab it counts as a move wherever it stands. +// the home folder, and is a move with no directory. Before a blank the word +// counts as a move wherever it stands. Straight before a separator it is one +// where it is a word of its own, `\cd` too, after a keyword or a word the +// shell runs it under (`then cd`, `builtin cd`): the end of a longer argument +// is none (`ls /media/cd; pytest `). const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; -const MOVE = /\bcd[ \t]|\b(?:pushd|popd)\s|(? word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path @@ -1542,8 +1543,9 @@ const counted = (line, kinds) => * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second * `cd`, `pushd`, a `cd` with no folder, one in a subshell that closed, one - * to a folder that is not written plainly, `PLAIN_FOLDER`, or one that does - * not start the command where `afterSetUpOnly` is false). The word after a + * to a folder that is not written plainly, `PLAIN_FOLDER`, or, where + * `afterSetUpOnly` is false, the word `cd`, `pushd` or `popd` anywhere but + * at the command's start, `MOVE_WORD`). The word after a * flag that may take a value is that value and no path (`BARE`); a short flag * written with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A * long flag may take none (`--no-header`), and the word after it is then a @@ -1572,10 +1574,12 @@ export function fileRun(command, output = "") { // starts the command, outside a group. Further on it may be the text of a // heredoc or of a quoted argument (`cat > run.sh <<'E'`, `cd pkg`, `E`, // then the run), which is not read, and neither is the text after the `cd` - // for the end of a group: an edit holds its own parentheses. + // for the end of a group: an edit holds its own parentheses. The word of a + // move anywhere else there may be one by a spelling `MOVE` does not read + // (`"cd"; pytest `). const followed = cd.length < 2 && - (head.match(MOVE) || []).length === cd.length && + (head.match(afterSetUpOnly ? MOVE : MOVE_WORD) || []).length === cd.length && cd.every( (m) => PLAIN_FOLDER.test(m[1]) && diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index ccba487d019..80115f95a6b 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -105,9 +105,9 @@ function located(run, cwd) { * report is then the file's when the case's class is under the file's * module, which pytest names from its root too. A case pytest collected * from a data file itself has that file's path as its class, with `/` - * turned into `.`: a data file under a folder or a name with the test - * file's stem (`tests/test_big/cases.yaml`, `tests/test_big.yaml`) is not - * taken for one the test file read. */ + * turned into `.`: a data file whose path starts with the test file's, + * less `.py` (`tests/test_big/cases.yaml`, `tests/test_big`), is not taken + * for one the test file read. */ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; @@ -116,7 +116,7 @@ function ofFile(run, cost) { return parts.some((_, at) => { const stem = parts.slice(at); const under = `${cost.classname}.`.startsWith(`${stem.join(".")}.`); - return under && ![".", "/"].some((next) => cost.file.startsWith(`${stem.join("/")}${next}`)); + return under && !cost.file.startsWith(stem.join("/")); }); } diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index b937e3dce5f..fddce5f2f1d 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1310,14 +1310,15 @@ const ENDED = /^!{3,} .*(?:stopping after \d+ failures|Interrupted: ).* !{3,}$/; // Only spaces and tabs are read between a separator and `cd`: a line's end is // a separator itself, and a run of blank lines is then read once. Nor is a // line's end read between `cd` and its folder: a `cd` with no folder goes to -// the home folder, and is a move with no directory. A `cd` straight before a -// separator or a line's end is that move where it is a word of its own, after -// a keyword or a word the shell runs it under too (`then cd`, `builtin cd`), -// and an argument that is the word alone is read as one (`echo cd`). The end -// of a longer argument is none (`ls /media/cd; pytest `). Before a -// space or a tab it counts as a move wherever it stands. +// the home folder, and is a move with no directory. Before a blank the word +// counts as a move wherever it stands. Straight before a separator it is one +// where it is a word of its own, `\cd` too, after a keyword or a word the +// shell runs it under (`then cd`, `builtin cd`): the end of a longer argument +// is none (`ls /media/cd; pytest `). const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; -const MOVE = /\bcd[ \t]|\b(?:pushd|popd)\s|(? word.replace(/^["']|["']$/g, ""); // pytest flags known to take no value. The word after any other flag written // without `=` may be its value (`--cov src`, `--rootdir sub`), not a path @@ -1542,8 +1543,9 @@ const counted = (line, kinds) => * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second * `cd`, `pushd`, a `cd` with no folder, one in a subshell that closed, one - * to a folder that is not written plainly, `PLAIN_FOLDER`, or one that does - * not start the command where `afterSetUpOnly` is false). The word after a + * to a folder that is not written plainly, `PLAIN_FOLDER`, or, where + * `afterSetUpOnly` is false, the word `cd`, `pushd` or `popd` anywhere but + * at the command's start, `MOVE_WORD`). The word after a * flag that may take a value is that value and no path (`BARE`); a short flag * written with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A * long flag may take none (`--no-header`), and the word after it is then a @@ -1572,10 +1574,12 @@ export function fileRun(command, output = "") { // starts the command, outside a group. Further on it may be the text of a // heredoc or of a quoted argument (`cat > run.sh <<'E'`, `cd pkg`, `E`, // then the run), which is not read, and neither is the text after the `cd` - // for the end of a group: an edit holds its own parentheses. + // for the end of a group: an edit holds its own parentheses. The word of a + // move anywhere else there may be one by a spelling `MOVE` does not read + // (`"cd"; pytest `). const followed = cd.length < 2 && - (head.match(MOVE) || []).length === cd.length && + (head.match(afterSetUpOnly ? MOVE : MOVE_WORD) || []).length === cd.length && cd.every( (m) => PLAIN_FOLDER.test(m[1]) && diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index f0b79309b3c..e6b83f08dd8 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -414,7 +414,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "1ffe0646c41c3fd3f1a6c6955f02d81c505f7dc3b2e313e771f5317364a8345c", + "integrations/claude-code-plugin/lib/test-cost.mjs": "b9c5da742199fd0a2bc630bcb478addecb88042619912625147b3f01d3f98487", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -430,7 +430,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "1ffe0646c41c3fd3f1a6c6955f02d81c505f7dc3b2e313e771f5317364a8345c", + "integrations/codex-plugin/lib/test-cost.mjs": "b9c5da742199fd0a2bc630bcb478addecb88042619912625147b3f01d3f98487", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 07f0e92ee9f2d035c4b070d07ed41e554d17096f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 10:42:31 +0530 Subject: [PATCH 44/52] The cost tests hold the clock in a way Node 18 runs The two tests that hold the clock used the options form of the test runner's mock timers, which Node 18 does not accept, so both failed there. They now replace Date.now, the one clock call the cost module makes. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../claude-code-plugin/tests/test-cost.test.mjs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index e6159facf10..f4ad78c1fee 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -831,11 +831,21 @@ test("a report whose first case names a data file is the run's when the case's c }); }); +/** Holds `Date.now` still for the test and returns the function that moves it + * on by seconds. Node 18's mock timers cannot hold the clock. */ +const heldClock = (t) => { + let now = Date.now(); + t.mock.method(Date, "now", () => now); + return (seconds) => { + now += seconds * 1000; + }; +}; + test("a run after other commands in its shell call is counted with the report it wrote in that call", { skip: WINDOWS, }, (t) => { // The clock stands still, so a report is as old at the hook as the test writes it. - t.mock.timers.enable({ apis: ["Date"], now: Date.now() }); + heldClock(t); inTmp(t, (cwd, file) => { const note = (command, output, xml, after) => noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); @@ -866,8 +876,7 @@ test("a run after other commands in its shell call is counted with the report it test("a report written before a command's own run could end is not the command's, where a command before the run may have printed its summary", { skip: WINDOWS, }, (t) => { - t.mock.timers.enable({ apis: ["Date"], now: Date.now() }); - const later = (seconds) => t.mock.timers.tick(seconds * 1000); + const later = heldClock(t); inTmp(t, (cwd, file) => { const note = (command, output, xml, after) => noteCommand(SESSION, { command, output, report: read(xml, after), cwd }); From 864c685e200263d9cd3c0c908b1b4256058e75a8 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 11:20:58 +0530 Subject: [PATCH 45/52] test(plugin): a class under a package of the test file's name is not the file's With a folder `tests/test_big/` beside `tests/test_big.py`, a data-driven test file in the folder gives its cases a class under `tests.test_big` too. The test notes such a report with a run of `tests/test_big.py`, and while that run is pending: it fails, the report is stored as a whole run of the file. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- .../claude-code-plugin/tests/test-cost.test.mjs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index f4ad78c1fee..11d68ef89ce 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -828,6 +828,23 @@ test("a report whose first case names a data file is the run's when the case's c }); noteCommand(SESSION, { command: "pgrep -f pytest", output: "", report: read(driven), cwd }); assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + // A folder of the test file's name beside it is a package, and a test + // file in it has its classes under the same module: the report is not + // the run's, read with the run's command or while the run is pending. + fs.mkdirSync(path.join(cwd, "tests/test_big")); + note("tests.test_big.test_inner.Suite.parse.test"); + assert.equal(runs()?.files, undefined); + noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, report: null, cwd }); + const inner = report({ + tests: 9000, + time: "300.1", + file: "tests/data/parse.test", + classname: "tests.test_big.test_inner.Suite.parse.test", + }); + noteCommand(SESSION, { command: "pgrep -f pytest", output: "", report: read(inner), cwd }); + assert.equal(runs().files, undefined); + assert.equal(runs().pending.file, file); }); }); From 1dc1d0c8a2fa11498b3435dbb205b860d9de4531 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 11:27:23 +0530 Subject: [PATCH 46/52] A class under a package of the test file's name is not the file's `ofFile` took a data-driven report for the run's where the first case's class is under the module of the run's file. A test file in a folder of that name (`tests/test_big/test_inner.py` beside `tests/test_big.py`) has its classes under the same module, so its report was stored as a whole run of `tests/test_big.py`. No report whose first case names a data file is the run's now where that folder stands beside the test file. A data-driven suite with such a folder is not counted; the limits list says so. `BACKGROUND` no longer reads a `>` before the `&`: `fileRun` takes a redirect between descriptors out before the test, and `onlyRuns` refuses every other `>&`. No result changes. The gate test holds `echo cd; pytest tests -q`, and the `fileRun` docstring is rewrapped. `tests/unit/session_content_senders.json` pins the bytes of `lib/test-cost.mjs` for its reviewed `memory.get` read. The pin is renewed: `costLine` and `identity`, which build that read, are as on `main`. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 5 ++++- .../claude-code-plugin/hooks/HOOKS.md | 3 ++- .../claude-code-plugin/lib/test-cost.mjs | 5 ++++- .../claude-code-plugin/lib/test-gate.mjs | 19 +++++++++---------- .../tests/test-gate.test.mjs | 2 ++ integrations/codex-plugin/lib/test-cost.mjs | 5 ++++- integrations/codex-plugin/lib/test-gate.mjs | 19 +++++++++---------- tests/unit/session_content_senders.json | 4 ++-- 8 files changed, 36 insertions(+), 26 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 2b02d92dd92..f01836cab9b 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1841,7 +1841,8 @@ file, not the test file that collected it. Such a case is in the command's test when its class is under that file's module (`tests.test_big.Suite` for `tests/test_big.py`). A case pytest collected from a data file itself has that file's path as its class, so a data file whose path starts with the test file's, less `.py` -(`tests/test_big/cases.yaml`), is not in the test file. +(`tests/test_big/cases.yaml`), is not in the test file. Nor is any such case where a +folder of that name stands beside the test file. A run that outlives its shell call writes the file after the hook ran: it is read after the next shell command that names a test runner, or when the session ends. That file is @@ -1949,6 +1950,8 @@ What it does not do: - a data-driven suite is not counted where the path of its data files starts with its test file's, less `.py` (`tests/test_big_cases/` for `tests/test_big.py`): its cases are not told apart from the ones pytest collects from such a file itself; +- nor is one whose test file has a folder of its name, less `.py`, beside it: its cases + are not told apart from those of a test file in that folder; - a command before the run that starts pytest under no runner's name, such as a script of the repository, is not told apart from an edit. Its result file and summary line are counted as the run's where the script ended within 10 s of the call's return and diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 2d895c0b5b4..593ac969449 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1585,7 +1585,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that file itself has that file's path as its `classname`, so a data file whose path starts with the test file's, less `.py` (`tests/test_big/cases.yaml` for `tests/test_big.py`), is not in the - file. The summary is pytest's last + file. Nor is any such case where a folder of that name stands beside the + test file. The summary is pytest's last line, whatever it counts (`8000 deselected in 1.20s` and `no tests ran in 0.01s` too), read without the colours of a pytest told to colour its output. A run whose output shows no such line may not have diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 80115f95a6b..6ba0d91eff3 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -107,11 +107,14 @@ function located(run, cwd) { * from a data file itself has that file's path as its class, with `/` * turned into `.`: a data file whose path starts with the test file's, * less `.py` (`tests/test_big/cases.yaml`, `tests/test_big`), is not taken - * for one the test file read. */ + * for one the test file read. Nor is any data file where a folder of that + * name stands beside the test file: a test file in it has its classes + * under the same module. */ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); + if (isDirectory(run.file.replace(/\.py$/, ""))) return false; const parts = file.replace(/\.py$/, "").split("/"); return parts.some((_, at) => { const stem = parts.slice(at); diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index fddce5f2f1d..f7963740923 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1375,8 +1375,8 @@ const SHELL_COMMENT = /(?:^|[\s;&|()])#/; // but at a word's start (`make run-testsuite`). const BUILDS_TEST = new RegExp(String.raw`(?`, `>&`) or of `|&`. -const BACKGROUND = /(?])&(?![&>])/; +// part of `&&`, `&>` or `|&`. +const BACKGROUND = /(?])/; // True where the commands of `head` that are no set-up cannot pass for the // run `tail` starts with, as a session writes them that edits and then checks // in one shell call (an inline script, `git diff --stat`, `sed`): none starts @@ -1545,14 +1545,13 @@ const counted = (line, kinds) => * `cd`, `pushd`, a `cd` with no folder, one in a subshell that closed, one * to a folder that is not written plainly, `PLAIN_FOLDER`, or, where * `afterSetUpOnly` is false, the word `cd`, `pushd` or `popd` anywhere but - * at the command's start, `MOVE_WORD`). The word after a - * flag that may take a value is that value and no path (`BARE`); a short flag - * written with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A - * long flag may take none (`--no-header`), and the word after it is then a - * second path: a run with such a word that names a Python file is none, and - * the others are `values`. The caller drops a run where one of them names a - * folder (`--no-header tests`, and `--cov src` too): the flag may take no - * value. + * at the command's start, `MOVE_WORD`). The word after a flag that may take a + * value is that value and no path (`BARE`); a short flag written with its + * value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag may take + * none (`--no-header`), and the word after it is then a second path: a run + * with such a word that names a Python file is none, and the others are + * `values`. The caller drops a run where one of them names a folder + * (`--no-header tests`, and `--cov src` too): the flag may take no value. */ export function fileRun(command, output = "") { // A redirect between descriptors is left out: `PYTEST` ends a run's words diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index e9a3143ea3a..e56bf1d8a44 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1288,6 +1288,8 @@ test("a run's paths are read from the directory its command moved to", () => { "[ -d sub ] || { cd\n}\npytest tests -q", "builtin cd; pytest tests -q", "command cd\npytest tests -q", + // An argument that is the word alone is not told apart from those. + "echo cd; pytest tests -q", // The word before a line's end is a move wherever it stands, and `\cd` is `cd`. "\\cd\npytest tests -q", "\\cd; pytest tests -q", diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 80115f95a6b..6ba0d91eff3 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -107,11 +107,14 @@ function located(run, cwd) { * from a data file itself has that file's path as its class, with `/` * turned into `.`: a data file whose path starts with the test file's, * less `.py` (`tests/test_big/cases.yaml`, `tests/test_big`), is not taken - * for one the test file read. */ + * for one the test file read. Nor is any data file where a folder of that + * name stands beside the test file: a test file in it has its classes + * under the same module. */ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); + if (isDirectory(run.file.replace(/\.py$/, ""))) return false; const parts = file.replace(/\.py$/, "").split("/"); return parts.some((_, at) => { const stem = parts.slice(at); diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index fddce5f2f1d..f7963740923 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1375,8 +1375,8 @@ const SHELL_COMMENT = /(?:^|[\s;&|()])#/; // but at a word's start (`make run-testsuite`). const BUILDS_TEST = new RegExp(String.raw`(?`, `>&`) or of `|&`. -const BACKGROUND = /(?])&(?![&>])/; +// part of `&&`, `&>` or `|&`. +const BACKGROUND = /(?])/; // True where the commands of `head` that are no set-up cannot pass for the // run `tail` starts with, as a session writes them that edits and then checks // in one shell call (an inline script, `git diff --stat`, `sed`): none starts @@ -1545,14 +1545,13 @@ const counted = (line, kinds) => * `cd`, `pushd`, a `cd` with no folder, one in a subshell that closed, one * to a folder that is not written plainly, `PLAIN_FOLDER`, or, where * `afterSetUpOnly` is false, the word `cd`, `pushd` or `popd` anywhere but - * at the command's start, `MOVE_WORD`). The word after a - * flag that may take a value is that value and no path (`BARE`); a short flag - * written with its value (`-rf`, `-kparse`, `-n4`) takes none after it. A - * long flag may take none (`--no-header`), and the word after it is then a - * second path: a run with such a word that names a Python file is none, and - * the others are `values`. The caller drops a run where one of them names a - * folder (`--no-header tests`, and `--cov src` too): the flag may take no - * value. + * at the command's start, `MOVE_WORD`). The word after a flag that may take a + * value is that value and no path (`BARE`); a short flag written with its + * value (`-rf`, `-kparse`, `-n4`) takes none after it. A long flag may take + * none (`--no-header`), and the word after it is then a second path: a run + * with such a word that names a Python file is none, and the others are + * `values`. The caller drops a run where one of them names a folder + * (`--no-header tests`, and `--cov src` too): the flag may take no value. */ export function fileRun(command, output = "") { // A redirect between descriptors is left out: `PYTEST` ends a run's words diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index e6b83f08dd8..23e9b6dec3c 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -414,7 +414,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "b9c5da742199fd0a2bc630bcb478addecb88042619912625147b3f01d3f98487", + "integrations/claude-code-plugin/lib/test-cost.mjs": "598f9b392dc194fed74b7e87a9bd88bf00c3de1210683f1eca6e8731aaccd654", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -430,7 +430,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "b9c5da742199fd0a2bc630bcb478addecb88042619912625147b3f01d3f98487", + "integrations/codex-plugin/lib/test-cost.mjs": "598f9b392dc194fed74b7e87a9bd88bf00c3de1210683f1eca6e8731aaccd654", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From 089119aff53c41707a8a57285c8cad5e023a0479 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 11:34:10 +0530 Subject: [PATCH 47/52] test(plugin): the gate holds a carriage return between a separator and cd `CD` reads only spaces and tabs between a separator and `cd`, and the shell reads no carriage return as a blank: `make build;\r cd sub && pytest tests -q` moves nowhere, and answers no ask. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- integrations/claude-code-plugin/tests/test-gate.test.mjs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index e56bf1d8a44..95217568d92 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1290,6 +1290,8 @@ test("a run's paths are read from the directory its command moved to", () => { "command cd\npytest tests -q", // An argument that is the word alone is not told apart from those. "echo cd; pytest tests -q", + // The shell reads no carriage return as a blank between a separator and `cd`. + "make build;\r cd sub && pytest tests -q", // The word before a line's end is a move wherever it stands, and `\cd` is `cd`. "\\cd\npytest tests -q", "\\cd; pytest tests -q", From 6b3ddca8f6669c2e5b80ed4f84f5bc6cde60cc36 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 12:13:15 +0530 Subject: [PATCH 48/52] A data-driven case is refused by its class being its data file's path, not by the path's start A suite whose data folder's name starts with its test file's (tests/test_big_cases for tests/test_big.py) was refused though its cases' classes tell them apart, and a data file under a folder with a dot in its name was counted. The class of a case pytest collects from a data file is that file's path with / turned into ., so that is what is refused. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 14 ++++++-------- integrations/claude-code-plugin/README.md | 2 +- integrations/claude-code-plugin/hooks/HOOKS.md | 9 ++++----- .../claude-code-plugin/lib/test-cost.mjs | 17 +++++++---------- .../claude-code-plugin/tests/test-cost.test.mjs | 9 +++++++-- integrations/codex-plugin/lib/test-cost.mjs | 17 +++++++---------- tests/unit/session_content_senders.json | 4 ++-- 7 files changed, 34 insertions(+), 38 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index f01836cab9b..6f78e547b5f 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1840,9 +1840,9 @@ A case that a data-driven suite reads from a data file names that file in the re file, not the test file that collected it. Such a case is in the command's test file when its class is under that file's module (`tests.test_big.Suite` for `tests/test_big.py`). A case pytest collected from a data file itself has that file's -path as its class, so a data file whose path starts with the test file's, less `.py` -(`tests/test_big/cases.yaml`), is not in the test file. Nor is any such case where a -folder of that name stands beside the test file. +path as its class, with `/` turned into `.` (`tests.test_big.cases.yaml` for +`tests/test_big/cases.yaml`): it is not in the test file. Nor is any such case where a +folder of the test file's name, less `.py`, stands beside it. A run that outlives its shell call writes the file after the hook ran: it is read after the next shell command that names a test runner, or when the session ends. That file is @@ -1947,11 +1947,9 @@ What it does not do: (`tail -5 out.txt; pytest tests/test_big.py | tail -5`): its output shows a summary line, so it is not kept as a run that outlives its call, and the result file it writes later is not read as its own; -- a data-driven suite is not counted where the path of its data files starts with its - test file's, less `.py` (`tests/test_big_cases/` for `tests/test_big.py`): its cases - are not told apart from the ones pytest collects from such a file itself; -- nor is one whose test file has a folder of its name, less `.py`, beside it: its cases - are not told apart from those of a test file in that folder; +- a data-driven suite is not counted where its test file has a folder of its name, + less `.py`, beside it: its cases are not told apart from those of a test file in that + folder; - a command before the run that starts pytest under no runner's name, such as a script of the repository, is not told apart from an edit. Its result file and summary line are counted as the run's where the script ended within 10 s of the call's return and diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 4f920eb71ff..3b9b6ebe1ff 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module, and the data file's path does not start with the test file's, less `.py`, as `tests/test_big/` for `tests/test_big.py`: pytest gives a case it collects from such a file the same class). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 593ac969449..09d6f74cabe 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1582,11 +1582,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that suite reads from a data file names that file, which is no Python file: it is in the file where its `classname` is under the file's module (`ofFile` in lib/test-cost.mjs). A case pytest collected from a data - file itself has that file's path as its `classname`, so a data file - whose path starts with the test file's, less `.py` - (`tests/test_big/cases.yaml` for `tests/test_big.py`), is not in the - file. Nor is any such case where a folder of that name stands beside the - test file. The summary is pytest's last + file itself has that file's path as its `classname`, with `/` turned + into `.` (`tests.test_big.cases.yaml` for `tests/test_big/cases.yaml`): + it is not in the file. Nor is any such case where a folder of the test + file's name, less `.py`, stands beside it. The summary is pytest's last line, whatever it counts (`8000 deselected in 1.20s` and `no tests ran in 0.01s` too), read without the colours of a pytest told to colour its output. A run whose output shows no such line may not have diff --git a/integrations/claude-code-plugin/lib/test-cost.mjs b/integrations/claude-code-plugin/lib/test-cost.mjs index 6ba0d91eff3..4fa734e37fb 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -105,22 +105,19 @@ function located(run, cwd) { * report is then the file's when the case's class is under the file's * module, which pytest names from its root too. A case pytest collected * from a data file itself has that file's path as its class, with `/` - * turned into `.`: a data file whose path starts with the test file's, - * less `.py` (`tests/test_big/cases.yaml`, `tests/test_big`), is not taken - * for one the test file read. Nor is any data file where a folder of that - * name stands beside the test file: a test file in it has its classes - * under the same module. */ + * turned into `.` (`tests.test_big.cases.yaml`, `tests/test_big/cases.yaml`): + * it is not taken for one the test file read. Nor is any data file where a + * folder of the test file's name, less `.py`, stands beside it: a test file + * in it has its classes under the same module. */ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); if (isDirectory(run.file.replace(/\.py$/, ""))) return false; + const klass = `${cost.classname}.`; + if (klass.startsWith(`${cost.file.replaceAll("/", ".")}.`)) return false; const parts = file.replace(/\.py$/, "").split("/"); - return parts.some((_, at) => { - const stem = parts.slice(at); - const under = `${cost.classname}.`.startsWith(`${stem.join(".")}.`); - return under && !cost.file.startsWith(stem.join("/")); - }); + return parts.some((_, at) => klass.startsWith(`${parts.slice(at).join(".")}.`)); } /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 11d68ef89ce..65072c51873 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -785,13 +785,14 @@ test("a report whose first case names a data file is the run's when the case's c assert.equal(runs()?.files, undefined, classname); } // A case pytest collected from a data file has that file's path as its - // class: a path that starts with the test file's, less `.py`, is not the - // test file's, from pytest's root at the checkout or at the folder. + // class: it is not the test file's, from pytest's root at the checkout + // or at the folder, nor under a folder with a dot in its name. for (const source of [ "tests/test_big/cases.yaml", "tests/test_big.yaml", "tests/test_big", "test_big/cases.yaml", + "tests.test_big/cases.yaml", ]) { note(source.replaceAll("/", "."), source); assert.equal(runs()?.files, undefined, source); @@ -818,6 +819,10 @@ test("a report whose first case names a data file is the run's when the case's c assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }, classname); fs.rmSync(sessionStatePath("test-cost", SESSION)); } + // So is a case read from a folder whose name starts with the file's. + note("tests.test_big.Suite.parse.test", "tests/test_big_cases/parse.test"); + assert.deepEqual(runs(), { files: { [file]: { whole: { tests: 8000, seconds: 140 } } } }); + fs.rmSync(sessionStatePath("test-cost", SESSION)); // A pending run's report, read with a later command, is told the same way. noteCommand(SESSION, { command: `pytest ${FILE} -q`, output: STARTED, report: null, cwd }); const driven = report({ diff --git a/integrations/codex-plugin/lib/test-cost.mjs b/integrations/codex-plugin/lib/test-cost.mjs index 6ba0d91eff3..4fa734e37fb 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -105,22 +105,19 @@ function located(run, cwd) { * report is then the file's when the case's class is under the file's * module, which pytest names from its root too. A case pytest collected * from a data file itself has that file's path as its class, with `/` - * turned into `.`: a data file whose path starts with the test file's, - * less `.py` (`tests/test_big/cases.yaml`, `tests/test_big`), is not taken - * for one the test file read. Nor is any data file where a folder of that - * name stands beside the test file: a test file in it has its classes - * under the same module. */ + * turned into `.` (`tests.test_big.cases.yaml`, `tests/test_big/cases.yaml`): + * it is not taken for one the test file read. Nor is any data file where a + * folder of the test file's name, less `.py`, stands beside it: a test file + * in it has its classes under the same module. */ function ofFile(run, cost) { const file = run.file.split(path.sep).join("/"); if (!cost.file) return false; if (cost.file.endsWith(".py")) return file.endsWith(`/${cost.file}`); if (isDirectory(run.file.replace(/\.py$/, ""))) return false; + const klass = `${cost.classname}.`; + if (klass.startsWith(`${cost.file.replaceAll("/", ".")}.`)) return false; const parts = file.replace(/\.py$/, "").split("/"); - return parts.some((_, at) => { - const stem = parts.slice(at); - const under = `${cost.classname}.`.startsWith(`${stem.join(".")}.`); - return under && !cost.file.startsWith(stem.join("/")); - }); + return parts.some((_, at) => klass.startsWith(`${parts.slice(at).join(".")}.`)); } /** Add what `run` cost to `state`: `cost` is `runCost` of the head of the diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 23e9b6dec3c..6a309a9e44f 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -414,7 +414,7 @@ "integrations/claude-code-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/claude-code-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/claude-code-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/claude-code-plugin/lib/test-cost.mjs": "598f9b392dc194fed74b7e87a9bd88bf00c3de1210683f1eca6e8731aaccd654", + "integrations/claude-code-plugin/lib/test-cost.mjs": "e24a50e1bab07b29f3e107b2e81bf05531af85c7ae700810825eeba5344acf3e", "integrations/codex-plugin/hooks/loom-code-shunt.mjs": "f4f761e9f5ed207c8cf4abd6759c1401f9354cddcae2b9065bda9835d778f04b", "integrations/codex-plugin/hooks/loom-flush.mjs": "a7634c8a3115aa98f0d7f5d098469cc3a87af4018fb2737c1a90fd27fc19c6e0", "integrations/codex-plugin/hooks/loom-namespace-health.mjs": "5f2bd718a88587c5f66b9823317bc77c18ce6a124f0602368b254d2c8c733ddb", @@ -430,7 +430,7 @@ "integrations/codex-plugin/lib/session-brief.mjs": "3aee492198a400ed0fa5fee733b4a4e04463efcc4d0b22ff760e1b765a76e28b", "integrations/codex-plugin/lib/session-start.mjs": "60675fae31105740885c3b76a34f50e7d18e31447d792bbea5e7c03fc1b30627", "integrations/codex-plugin/lib/task-inbox.mjs": "33fbb1040e9b6db936928a66e4b90555a556220415f4e6394f6d2cd67821dcfc", - "integrations/codex-plugin/lib/test-cost.mjs": "598f9b392dc194fed74b7e87a9bd88bf00c3de1210683f1eca6e8731aaccd654", + "integrations/codex-plugin/lib/test-cost.mjs": "e24a50e1bab07b29f3e107b2e81bf05531af85c7ae700810825eeba5344acf3e", "integrations/cursor/cursor-session-hook.sh": "71064260b50c8aee803523c4981fed8ebc9afab69be25e2ed472a727a538db03", "integrations/generic/ingest.sh": "23b2410ce557114d83598ebd603431bd387f6af0ee9f1a7f4decb347d89b3e12", "sdk/python/loom/integrations/agno.py": "74aa83737e754b5fa65cbd568bb4d18abbf401aa21f56ababaa20b1f099fc4cc", From a6ec97d448ebe5f02eebd69d62d7642dfdd84312 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 12:34:49 +0530 Subject: [PATCH 49/52] A run under a line that starts with # and ends in a joining operator is no file run Such a line was dropped as a comment, and the operator at its end with it. It may be the end of a quoted argument that spans lines, so the run under it waits on the command before it. The pages also name the quoted run that a count of quotes does not tell, and the plugin page names the folder beside the test file. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 8 ++++++-- integrations/claude-code-plugin/README.md | 2 +- integrations/claude-code-plugin/hooks/HOOKS.md | 8 ++++++-- integrations/claude-code-plugin/lib/test-gate.mjs | 8 +++++--- integrations/claude-code-plugin/tests/test-cost.test.mjs | 4 ++++ integrations/codex-plugin/lib/test-gate.mjs | 8 +++++--- 6 files changed, 27 insertions(+), 11 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 6f78e547b5f..b33d2a32af5 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1792,7 +1792,9 @@ session's private state, by the file: above the run). So does one at the end of a line that holds `<<`: under `git apply <<'P' &&`, the run after the patch waits on `git apply`. Where a heredoc ends is not read, so a line of an inline script's text that holds `<<` and - ends in one of them counts too. A list that ended before the run decides nothing: + ends in one of them counts too. So does one at the end of a line that starts with + `#`, which may be the end of a quoted argument. A list that ended before the run + decides nothing: `git stash pop || true; pytest tests/test_big.py` counts; - the shell does not read the `;` before the run: a backslash stands before it, or a `#` that starts a word stands before the run on its line, ahead of the line's @@ -1971,7 +1973,9 @@ What it does not do: - a run that never starts because the shell ends in a way the command's text does not name, such as an `exec` before it, is kept as one that outlives its call. So is a run in a comment that starts after a quote on its line - (`echo 'done' # then; pytest tests/test_big.py`); + (`echo 'done' # then; pytest tests/test_big.py`), and a run in a quoted argument + where a quote of the same kind stands inside a later one + (`git commit -m 'fix; pytest tests/test_big.py' && echo "it's in"`); - the session keeps one run that outlives its call. A later one of another test file takes its place, and the earlier run is not counted. A later one of the same file and the other kind, whole after `-k` or `-k` after whole, drops both, since the earlier diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 3b9b6ebe1ff..66372691318 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch, or of a line that starts with `#`. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself, and no folder of the test file's name, less `.py`, stands beside it). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 09d6f74cabe..302c06002c7 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1505,7 +1505,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that (`edit &&`, then `# check`, then the run). So does one at the end of a line that holds `<<`: `git apply <<'P' &&` joins the run after the patch to `git apply`. Where a heredoc ends is not read, so a line of - an inline script's text counts too. + an inline script's text counts too. So does one at the end of a line + that starts with `#`, which may be the end of a quoted argument. Third, the shell does not read the `;` before the run: a backslash stands before it, or a `#` that starts a word stands before the run on its line, ahead of the line's first quote @@ -1516,7 +1517,10 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that Fourth, the run and what follows it close a parenthesis or a quote opened before them: the run is in a group that waits on an earlier command (`edit && (git diff; pytest )`), or it is the text of a - quoted argument (`git commit -m "fix; pytest "`). + quoted argument (`git commit -m "fix; pytest "`). Quotes are + counted, not paired, so a quoted run is not told where a quote of the + same kind stands inside a later one + (`git commit -m 'fix; pytest ' && echo "it's in"`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, so a last line its output shows may diff --git a/integrations/claude-code-plugin/lib/test-gate.mjs b/integrations/claude-code-plugin/lib/test-gate.mjs index f7963740923..eaa7540490f 100644 --- a/integrations/claude-code-plugin/lib/test-gate.mjs +++ b/integrations/claude-code-plugin/lib/test-gate.mjs @@ -1402,7 +1402,8 @@ const startsNoRun = (head, tail) => { return false; // The last line before the run that is no comment, up to the end of its // last command: the shell reads past a comment line. - const before = head.slice(0, start).replace(/^[ \t]*#[^\n]*$/gm, ""); + const lines = head.slice(0, start).split("\n"); + const before = lines.filter((text) => !/^[ \t]*#/.test(text)).join("\n"); let end = before.length; while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; const line = before.slice(before.lastIndexOf("\n", end - 1) + 1, end); @@ -1416,8 +1417,9 @@ const startsNoRun = (head, tail) => { // Nor does a line that opens a heredoc: the run under the heredoc's text // waits on that line's command (`git apply <<'P' &&`, the patch, `P`, the // run). Where a heredoc ends is not read, so a line of an inline script's - // text that holds `<<` counts too. - !before.split("\n").some((opens) => opens.includes("<<") && JOINS.test(opens)) && + // text that holds `<<` counts too. Nor does a line that starts with `#`: + // it may be the end of a quoted argument that spans lines (`#12" &&`). + !lines.some((text) => /<<|^[ \t]*#/.test(text) && JOINS.test(text)) && // `head` names no pytest (`pytest.main` in an inline script): a command // that starts pytest prints a last line and writes the result file, and // both are read as the run's where the run outlives its call. diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index 65072c51873..d20506738f7 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -409,6 +409,7 @@ test("a command with two pytest runs, two paths, another selection or no run of `make run-testsuite; pytest ${FILE}`, `go build ./internal/testutil/...; pytest ${FILE}`, `npm run build:testdata; pytest ${FILE}`, + `npm install test-utils; pytest ${FILE}`, // The run may not start where `&&` or `||` joins it to a command that is no set-up, and after `&` // or a pipe that command runs beside it: on the run's line or at the end of the line before it, // with or without a comment between them. @@ -439,6 +440,8 @@ test("a command with two pytest runs, two paths, another selection or no run of `python - <&1 | tail -5`, + // So does one at the end of a line that starts with `#`, which may end a quoted argument. + `git commit -qm "parser: keep the prefix\n#12" &&\npython -m pytest -q ${FILE} 2>&1 | tail -5`, // Or in a group that waits on an earlier command, or in a shell that a failed command ends. `python /tmp/edit.py && (git diff --stat; pytest ${FILE})`, `set -e\npython /tmp/edit.py\npython -m pytest -q ${FILE} 2>&1 | tail -5`, @@ -463,6 +466,7 @@ test("a command with two pytest runs, two paths, another selection or no run of `docker exec app pytest ${FILE}`, // What follows `ssh`, `docker`, `podman` or `kubectl` anywhere before the run may run elsewhere. `docker compose up -d db; pytest ${FILE}`, + `podman build -q .; pytest ${FILE}`, `ssh build 'make assets'; pytest ${FILE}`, `export NOTE="see kubectl logs"; pytest ${FILE}`, `echo "pytest ${FILE}"`, diff --git a/integrations/codex-plugin/lib/test-gate.mjs b/integrations/codex-plugin/lib/test-gate.mjs index f7963740923..eaa7540490f 100644 --- a/integrations/codex-plugin/lib/test-gate.mjs +++ b/integrations/codex-plugin/lib/test-gate.mjs @@ -1402,7 +1402,8 @@ const startsNoRun = (head, tail) => { return false; // The last line before the run that is no comment, up to the end of its // last command: the shell reads past a comment line. - const before = head.slice(0, start).replace(/^[ \t]*#[^\n]*$/gm, ""); + const lines = head.slice(0, start).split("\n"); + const before = lines.filter((text) => !/^[ \t]*#/.test(text)).join("\n"); let end = before.length; while (end > 0 && /[;\s]/.test(before[end - 1])) end -= 1; const line = before.slice(before.lastIndexOf("\n", end - 1) + 1, end); @@ -1416,8 +1417,9 @@ const startsNoRun = (head, tail) => { // Nor does a line that opens a heredoc: the run under the heredoc's text // waits on that line's command (`git apply <<'P' &&`, the patch, `P`, the // run). Where a heredoc ends is not read, so a line of an inline script's - // text that holds `<<` counts too. - !before.split("\n").some((opens) => opens.includes("<<") && JOINS.test(opens)) && + // text that holds `<<` counts too. Nor does a line that starts with `#`: + // it may be the end of a quoted argument that spans lines (`#12" &&`). + !lines.some((text) => /<<|^[ \t]*#/.test(text) && JOINS.test(text)) && // `head` names no pytest (`pytest.main` in an inline script): a command // that starts pytest prints a last line and writes the result file, and // both are read as the run's where the run outlives its call. From 5ffc0a11180fe612792cfdbcffd3c853861b999a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 12:58:27 +0530 Subject: [PATCH 50/52] The pages say which word before a run refuses it, and what a run after set-up alone is not read for The word that names another machine refuses a run only with a blank after it. A run in a comment, after an escaped separator or in a quoted argument is kept where only set-up stands before it. A test holds the lone & at the end of the line above the run. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 11 +++++++---- integrations/claude-code-plugin/README.md | 2 +- integrations/claude-code-plugin/hooks/HOOKS.md | 3 ++- .../claude-code-plugin/tests/test-cost.test.mjs | 1 + 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index b33d2a32af5..133ee7a16d9 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1815,9 +1815,9 @@ session's private state, by the file: `(cd pkg && git stash -q); pytest tests/test_big.py` and `ls /media/cd; pytest tests/test_big.py` do not): further on the word may be the text of a heredoc or a move by another spelling; - - the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in - a set-up command's value too: what follows one may run elsewhere, so - `docker compose up -d db; pytest tests/test_big.py` counts as neither; + - the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl` with + a blank after it, in a set-up command's value too: what follows one may run + elsewhere, so `docker compose up -d db; pytest tests/test_big.py` counts as neither; - a run after a `cd` with no folder counts as neither: `cd; pytest tests/test_big.py` runs in the home folder. @@ -1975,7 +1975,10 @@ What it does not do: in a comment that starts after a quote on its line (`echo 'done' # then; pytest tests/test_big.py`), and a run in a quoted argument where a quote of the same kind stands inside a later one - (`git commit -m 'fix; pytest tests/test_big.py' && echo "it's in"`); + (`git commit -m 'fix; pytest tests/test_big.py' && echo "it's in"`). Where only + `cd`, `export`, `source` and `.` stand before the run, a run in a comment, after + `\;` or in a quoted argument is kept too + (`export NOTE="built; pytest tests/test_big.py"`); - the session keeps one run that outlives its call. A later one of another test file takes its place, and the earlier run is not counted. A later one of the same file and the other kind, whole after `-k` or `-k` after whole, drops both, since the earlier diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 66372691318..c20b0486513 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch, or of a line that starts with `#`. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl`, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself, and no folder of the test file's name, less `.py`, stands beside it). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch, or of a line that starts with `#`. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl` with a blank after it, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself, and no folder of the test file's name, less `.py`, stands beside it). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 302c06002c7..668434a6da0 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1533,7 +1533,8 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that or a move by another spelling (`"cd"; pytest `). A group ends before the run (`(cd pkg && git stash -q); pytest `). Seventh, the text before the run holds the word `ssh`, `docker`, - `podman` or `kubectl`, in a set-up command's value too (`ranHere`): + `podman` or `kubectl` with a blank after it, in a set-up command's + value too (`ranHere`): what follows one may run elsewhere, so `docker compose up -d db; pytest ` is noted as nothing. A list that ended before the run decides nothing: diff --git a/integrations/claude-code-plugin/tests/test-cost.test.mjs b/integrations/claude-code-plugin/tests/test-cost.test.mjs index d20506738f7..ccab6ea4f73 100644 --- a/integrations/claude-code-plugin/tests/test-cost.test.mjs +++ b/integrations/claude-code-plugin/tests/test-cost.test.mjs @@ -423,6 +423,7 @@ test("a command with two pytest runs, two paths, another selection or no run of `cat /tmp/names.txt |\n# the names\npytest ${FILE}`, `cat /tmp/names.txt | pytest ${FILE}`, `sleep 600 & pytest ${FILE}`, + `sleep 600 &\npytest ${FILE}`, `git stash -q; ( pytest ${FILE})`, `git stash -q; (\npytest ${FILE})`, // A run put in the background after a command that is no set-up, alone or with what reads its From bd9f29ae342c4fa8632d6b81e00065a7fccdc443 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 13:19:13 +0530 Subject: [PATCH 51/52] The pages state the quote refusal as the count the code takes A run after other commands is refused where it and what follows hold an odd number of either quote, which one apostrophe after the run is too. The pages said a quote opened before the run. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 10 ++++++---- integrations/claude-code-plugin/README.md | 2 +- integrations/claude-code-plugin/hooks/HOOKS.md | 14 ++++++++------ 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 133ee7a16d9..657be880db0 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1801,10 +1801,12 @@ session's private state, by the file: first quote (`git diff --stat # then; pytest tests/test_big.py` holds a comment and no run). A `#` after a quote may be an argument's, as in `sed -i '5a\ # note' src/parser.py`, and decides nothing; - - the run and what follows it close a parenthesis or a quote opened before them: the - run is in a group that waits on an earlier command - (`python edit.py && (git diff --stat; pytest tests/test_big.py)`), or it is the - text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`); + - the run and what follows it close a parenthesis they did not open, or hold an odd + number of `"` or of `'`: the run is in a group that waits on an earlier command + (`python edit.py && (git diff --stat; pytest tests/test_big.py)`), or it may be the + text of a quoted argument (`git commit -m "fix; pytest tests/test_big.py"`). One + apostrophe after the run is such a number too + (`git diff --stat; pytest tests/test_big.py -q; echo "it's done"`); - a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest tests/test_big.py > out2.txt 2>&1 &`): the call does not wait for the run, and a summary line its output shows may be an earlier run's. The diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index c20b0486513..ce0be345d74 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch, or of a line that starts with `#`. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run closes a parenthesis or a quote opened before it (`git commit -m "fix; pytest "`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl` with a blank after it, in the value of an `export` too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself, and no folder of the test file's name, less `.py`, stands beside it). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch, or of a line that starts with `#`. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run and what follows it close a parenthesis they did not open, or hold an odd number of `"` or of `'`: the run may be the text of a quoted argument (`git commit -m "fix; pytest "`), and one apostrophe after it counts too (`git diff --stat; pytest -q; echo "it's done"`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl` with a blank after it, in a set-up command's argument too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself, and no folder of the test file's name, less `.py`, stands beside it). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 668434a6da0..3f01858ca1a 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1514,12 +1514,14 @@ not hard. Run `pytest -n auto`.``). A prohibition in a sentence that Quotes are not read, so a `#` after one may be an argument's, as in `sed -i '5a\ # note' src/parser.py`, and a comment that starts there is not told apart. - Fourth, the run and what follows it close a parenthesis or a quote - opened before them: the run is in a group that waits on an earlier - command (`edit && (git diff; pytest )`), or it is the text of a - quoted argument (`git commit -m "fix; pytest "`). Quotes are - counted, not paired, so a quoted run is not told where a quote of the - same kind stands inside a later one + Fourth, the run and what follows it close a parenthesis they did not + open, or hold an odd number of `"` or of `'`: the run is in a group + that waits on an earlier command (`edit && (git diff; pytest )`), + or it may be the text of a quoted argument + (`git commit -m "fix; pytest "`). Quotes are counted, not + paired: one apostrophe after the run refuses it + (`git diff --stat; pytest -q; echo "it's done"`), and a quoted + run is not told where a quote of the same kind stands inside a later one (`git commit -m 'fix; pytest ' && echo "it's in"`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the From c0a6e71d9597bf546cb02145438cf4cb6561670b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 6 Dec 2026 13:43:23 +0530 Subject: [PATCH 52/52] The pages say a data-driven case counts where its data file is no Python file A case that names another Python file is that file's, whatever its class. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/integrations/claude-code.md | 7 ++++--- integrations/claude-code-plugin/README.md | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 657be880db0..487323f6e76 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1841,9 +1841,10 @@ has no such bound. Neither has the result file of a run with only `cd`, `export` `source` and `.` before it, which is taken as the command's own. A case that a data-driven suite reads from a data file names that file in the result -file, not the test file that collected it. Such a case is in the command's test file -when its class is under that file's module (`tests.test_big.Suite` for -`tests/test_big.py`). A case pytest collected from a data file itself has that file's +file, not the test file that collected it. Where the data file is no Python file, such +a case is in the command's test file when its class is under that file's module +(`tests.test_big.Suite` for `tests/test_big.py`). A case that names another Python +file is that file's. A case pytest collected from a data file itself has that file's path as its class, with `/` turned into `.` (`tests.test_big.cases.yaml` for `tests/test_big/cases.yaml`): it is not in the test file. Nor is any such case where a folder of the test file's name, less `.py`, stands beside it. diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index ce0be345d74..fbd4bb5c458 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -324,7 +324,7 @@ Failures that share a message are one group, the most frequent first, at most th Loom adds no option on Windows, under Codex (which names no such file), with an invalid `server_url` (the hooks stop before it), where the checkout's `addopts` or your own `PYTEST_ADDOPTS` already names a result file (`--junitxml`) or turns pytest's result-file plugin off (`-p no:junitxml`), or for a command Claude Code runs in its sandbox, which cannot write the temp directory. A run whose command line names its own result file keeps it, written in the `xunit1` family unless the command names one (`-o junit_family=xunit2`), and gets no digest; a command that runs pytest twice reports the last run; a pytest that a test starts inherits the option; a settings file in another folder than the root, `tests` or `test` is not read, so a result file its `addopts` names is replaced by the session's for that session; a pytest run that a background command started, or a command that reads as no test runner, is reported on the next test command's result, which is why the digest names the session's last pytest run. A pytest that refuses the option (one started with `-p no:junitxml`) fails once where the command itself names `-p no:junitxml`: the hook reads the refusal from the command's text, or from the output of any shell command that shows it, removes the option for the rest of the session, a compaction or a resume included, and tells the session to run the command again. Where a Makefile, tox, nox or a script passes `-p no:junitxml`, each run fails until one shows its output; `PYTEST_ADDOPTS= pytest ...` runs one command without it. The file is removed when the session ends. `LOOM_TEST_REPORT=off`, or `--config test_report=false`, turns the report off from the session's next start. It is pytest only. -**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch, or of a line that starts with `#`. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run and what follows it close a parenthesis they did not open, or hold an odd number of `"` or of `'`: the run may be the text of a quoted argument (`git commit -m "fix; pytest "`), and one apostrophe after it counts too (`git diff --stat; pytest -q; echo "it's done"`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl` with a blank after it, in a set-up command's argument too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself, and no folder of the test file's name, less `.py`, stands beside it). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): +**What a whole run costs.** A session that does not know what a whole run of a data-driven test file costs runs it to check a change where a `-k` selection of its cases answers in seconds. With the memory plane on and session memory not switched off, the test report also notes what a pytest run cost, for a shell command that holds one pytest run naming one test file: the number of cases and the seconds pytest writes at the head of the result file. A whole run of two cases or more counts when no case failed (a file of one case has no `-k` selection smaller than itself), and a run filtered with `-k` counts as filtered where it ran fewer cases than the whole file. A run that skipped more than a tenth of its cases counts as neither; for a run that outlives its shell call an expected failure (`xfail`) counts as skipped. A run of another part of the file (a node id, `-m`, `--lf`, `--sw`, `--deselect`), a command with two pytest runs or two paths, a run that anything follows in its command but `tail`, `head`, `grep` and `echo` (`&& make test`: a runner started after it writes the result file and prints the summary) and a run that only collects count as neither, and so does a run with no `-k` in its command whose summary counts deselected cases: a selection the command does not show left cases out. `cd`, `export`, `source` and `.` may stand before the run, joined to it in any way (`cd pkg && pytest `). Other commands may stand before it too, as in a session that edits and then checks in one shell call (`sed -i 's/a/b/' src/parser.py; git diff --stat; pytest `), and the run then counts as neither in the cases that follow. First, the text before the run names a test runner, a build tool with `test` after no letter further on in its command, inside a word too (`make install test`, `go build ./internal/testutil/...`), a `set` with `-e` among its flags, `errexit` or `exit`, or holds `pytest` or `py.test` anywhere (`.pytest_cache`, `pytest.ini`): such a command may start pytest itself or end the shell, and the result file and the summary are then the earlier command's (`make test || pytest `). Second, anything but `;` or a line's end joins the run to the command before it (`python edit.py && pytest `, `tail -5 out.txt; cd pkg && pytest `, `sleep 600 & pytest `): after `&&` or `||` the run may not start, and after `&` or a pipe that command runs beside the run and may print and write after it. One of those operators at the end of the line before the run joins them too, and so does one at the end of a line that holds `<<`, as `git apply <<'P' &&` above a patch, or of a line that starts with `#`. Third, the run stands after `\;`, or after a `#` that starts a word on its line ahead of the line's first quote (`git diff --stat # then; pytest ` holds a comment and no run). Fourth, the run and what follows it close a parenthesis they did not open, or hold an odd number of `"` or of `'`: the run may be the text of a quoted argument (`git commit -m "fix; pytest "`), and one apostrophe after it counts too (`git diff --stat; pytest -q; echo "it's done"`). Fifth, a `&` puts the run in the background, alone or with what reads its output (`tail -5 out.txt; pytest > out2.txt 2>&1 &`): the call does not wait for the run, and a summary its output shows may be an earlier run's; the `&` of `&&`, `&>` and `|&` puts nothing in the background. Sixth, the word `cd`, `pushd` or `popd` stands before the run anywhere but as the one `cd` that starts the command, outside a group (`git diff --stat; cd pkg; pytest `, `(cd pkg && git stash -q); pytest `, `ls /media/cd; pytest `): further on it may be the text of a heredoc or a move by another spelling. Seventh, the text before the run holds the word `ssh`, `docker`, `podman` or `kubectl` with a blank after it, in a set-up command's argument too (`docker compose up -d db; pytest `): what follows one may run elsewhere. Quotes are not read, so a `|`, `;`, `&`, `<`, backquote or parenthesis inside one counts as if unquoted: a run piped into `grep -E "passed|failed"` and one with `-k "parse and (empty or nested)"` count as neither. A run pytest ended before its last case (a failure limit, an error at collection, an interrupt) counts as neither where its output shows the line pytest prints about it. A whole run started with xdist workers (`-n`) counts with the seconds it took. The result file is the command's when the command's output shows pytest's summary with the cases, the failures and the seconds the file holds, and its first case is in the test file the command names (for a case read from a data file that is no Python file, its class is under that file's module and is not the data file's own path with `/` turned into `.`, the class pytest gives a case it collects from a data file itself, and no folder of the test file's name, less `.py`, stands beside it). Where other commands than `cd`, `export`, `source` and `.` stand before the run (a comment line counts as one), the file also was written no more than 10 s before the hook read it: `tail -5 out.txt; pytest ` shows an earlier run's summary, and where its own run outlives the call the file read with it is that earlier run's, written before the command's run began. A run that outlives its shell call is read after the next shell command that names a test runner, or when the session ends, and counts when pytest began it before that call returned: the result file of a run that a later command started counts for none, and a run put in the background before pytest began is not counted. The session keeps one such run: a later one of another test file takes its place, and a later one of the same file and the other kind (whole after `-k`, or `-k` after whole) drops both; the result file of a run that was replaced or dropped counts for no run the session keeps later. A run that ended in its call and whose command cut the summary (`| head -30`) is not kept. The result file of a run of the same file that something else started while that run was in its call, such as a script in the background, is taken for it. So is the result file of a run of two paths, a node id or a mark that an earlier shell call left going, where its first case is in that file and a hook reads it before the kept run's own: the kept run is then counted with the other run's cases and seconds. So is the result file of a pytest that a command before that run started in the same call and that ended after the call returned (`./check.sh; pytest `, where the call times out while the script runs), with no 10 s bound. The session has one result file: where the session's next pytest run ends before a hook has read it, that run's file replaces it and the run that outlived its call is not counted. The SessionStart hook runs again after a compaction and empties the result file: a run that outlived its shell call and ended before the compaction, with its result file not yet read, is not counted either. At the session's end what it measured goes to the repository's one memory row (key `repo:/test-cost/pytest`, in the session's namespace): ```text In the repository tagged repo:, a whole run of tests/test_big.py collects about 8000 cases and takes about 140 s; a run of it filtered with -k takes about 2 s.