diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index b56aaaf1f5..487323f6e7 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -1767,18 +1767,87 @@ 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, 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`. 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. 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 + 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 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 + `&` of `&&`, `&>` and `|&` puts nothing in the background; + - 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` 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. 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. +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 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. + +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. 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. 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 @@ -1875,6 +1944,44 @@ 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; +- 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 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 + 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; +- 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 + (`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"`). 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 @@ -1909,6 +2016,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/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index ef26da16a0..3713cd5752 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.189", + "version": "1.2.190", "description": "Shared long-term memory and code intelligence for Claude Code, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 4c106c8e49..fbd4bb5c45 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) 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. diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 45db58b2df..3f01858ca1 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -1477,19 +1477,81 @@ 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, - so a `|`, `;`, `&`, `<`, backquote or + 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. + 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. 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 + (`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 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 + 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, 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` 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: + `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 @@ -1498,34 +1560,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` 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. 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 + 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). A case pytest collected from a data + 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 + ended: one that outlives its shell call writes the file after the hook + ran. It is kept as the session's pending run, with the time its command + returned. Any other report the hook reads is the pending run's when its + first case is in the pending run's file and the run that wrote it began + by that time, and no run's otherwise: pytest began it at the time the + file was written less the seconds of its `testsuite`, and a run that a + later command started, by any launcher and whether or not a hook ran for + that command, began after it. A run of the file that something else + started while the pending run was in its call, such as a script in the background, began before that time too: its report, read with a command - that is not that run, is counted as the pending run's. The launcher - reads the report once more at SessionEnd, before it removes the file, - without reading a token. A run put in the background at once returns - before pytest began, and is not counted. + 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 ef209e4c86..4fa734e37f 100644 --- a/integrations/claude-code-plugin/lib/test-cost.mjs +++ b/integrations/claude-code-plugin/lib/test-cost.mjs @@ -8,14 +8,18 @@ // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private // state, for a session whose end may store them: for each file, the costliest -// whole run that passed and its latest runs filtered with -k. A run that -// outlives its shell call writes the file after that call's hook ran: a -// report read later is its when pytest began the run that wrote it before -// that call returned, and the launcher reads the file once more before it -// removes it at the session's end (`settleRun`). The file is one a session: a -// pytest run that ends before a hook read it replaces it, and the session's -// start after a compaction empties it (`startReport`). The run that outlived -// its call is then not counted. +// 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: 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 @@ -48,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 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. const MAX_FILES = 8; @@ -92,8 +100,25 @@ 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. 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`, `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) => klass.startsWith(`${parts.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 @@ -134,7 +159,14 @@ 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. 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) { @@ -157,10 +189,21 @@ function settle(state, report) { * file (`fileRun`) and its output shows pytest's summary with the cases, the * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The - * seconds alone do not tell two short runs apart. 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. + * 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 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 + * 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 @@ -189,6 +232,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && + (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 a99a8e1081..eaa7540490 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`(?`). +const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; +const MOVE = /\b(?:cd|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 @@ -1336,16 +1349,106 @@ 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)); +// 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 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 `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`(?` 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 +// 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 `&&` + // 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 + // 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 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); + 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 + // `), and a command put in the background earlier is not read + // (`./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 + // run). Where a heredoc ends is not read, so a line of an inline script's + // 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. + !/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) && + // 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 )`). + !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) && + // 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) + ); +}; /** 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, @@ -1401,48 +1504,56 @@ 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 - * `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 + * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values, + * 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 `-k` whose last line counts deselected cases + * is none: a selection its words do not show left cases out (one in + * `PYTEST_ADDOPTS` or the settings file). Nor is a run pytest ended before + * its last case, which the line above its last one says (`CUT_SHORT`): its + * last line and its result file count the cases it got to. Nor is a run that + * anything follows in the command but `tail`, `head`, `grep` and `echo` + * (`onlyRuns`), a redirect to a file aside: a runner started after it (`&& + * make test`, `; tox`, a second pytest with no space before it, which * `PYTEST` does not count) writes the session's result file and prints the - * last line. Quotes are not read there or in the run's words (`PYTEST`), so - * a run piped into `grep -E "passed|failed"` is none, and neither is one - * with `-k "parse and (empty or nested)"`. Nor is a run that anything stands - * before in the command but `cd`, `export`, `source` and `.` (`onlySetsUp`): - * a command before it may start pytest too (`make test || pytest `), - * and where the run does not start, the last line and the result file are - * that command's. + * 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`). 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 * every case; the rest run none), or a cluster of short flags that may hold * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second - * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder that is - * not written plainly, `PLAIN_FOLDER`). The word after a flag that may take - * a value is that value and no path (`BARE`); a short flag written with its + * `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. + * 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 @@ -1451,16 +1562,32 @@ 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)) return null; + if (runs.length !== 1) return null; + const head = text.slice(0, runs[0].index); + const tail = text.slice(runs[0].index); + 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(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)]; + // After a command that is no set-up, a `cd` is the shell's own where it + // 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. 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 && - cd.every((m) => PLAIN_FOLDER.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); + (head.match(afterSetUpOnly ? MOVE : MOVE_WORD) || []).length === cd.length && + cd.every( + (m) => + PLAIN_FOLDER.test(m[1]) && + (afterSetUpOnly + ? !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 = []; const values = []; @@ -1494,6 +1621,7 @@ export function fileRun(command, output = "") { failed: summary ? counted(summary, "failed|errors?") : null, skipped: summary ? counted(summary, "skipped") : null, values, + afterSetUpOnly, }; } @@ -1550,8 +1678,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/claude-code-plugin/lib/test-report.mjs b/integrations/claude-code-plugin/lib/test-report.mjs index bf6b17197f..42840cc6e2 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 21f575ba6c..ccab6ea4f7 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(" /tmp/out.txt 2>&1; tail -5 /tmp/out.txt; echo exit=$?`, ]) { @@ -184,6 +210,103 @@ test("a command's one pytest run of one test file is whole or filtered with -k", } }); +test("a run that follows commands which name no test runner is a file run", () => { + const whole = { + path: FILE, + dir: "", + whole: true, + seconds: null, + cases: null, + failed: null, + skipped: null, + values: [], + afterSetUpOnly: false, + }; + // 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}`, + // 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`, + // 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}`, + // 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 + // 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", 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, + // 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 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. + assert.deepEqual(fileRun(`# check the parser\npytest ${FILE}`), whole); + // 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 + // run: back from the run over the separators and the comments, and forward + // 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", "#", "<< "]) { + 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}`); + 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", () => { for (const command of [ `pytest ${FILE} -q; pytest ${FILE} -k parse`, @@ -225,12 +348,38 @@ 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}`, + // 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}`, + // 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}`, `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`, @@ -245,11 +394,82 @@ 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}`, + // 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}`, + // So is `test` after no letter inside a word and before a lower-case letter, which `RUNNER` does not read. + `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. + `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}`, + `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 + // 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}`, + // 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`, + // 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`, + `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}"`, + // 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. `pytest ${FILE} -q 2>&1 | grep -E "passed|failed"`, `pytest ${FILE} -k "parse and (empty or nested)" -q`, // Run elsewhere, or not run. `docker exec app pytest ${FILE}`, + // 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}"`, `grep -rn pytest ${FILE}`, "make test", @@ -548,6 +768,207 @@ 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) => { + 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), 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 pytest collected from a data file has that file's path as its + // 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); + } + // 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"); + 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)); + } + // 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({ + 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 } } } }); + 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); + }); +}); + +/** 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. + heldClock(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`; + // 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 } } } }); + // 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 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 }); + }); +}); + +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) => { + const later = heldClock(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 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); + 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 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); + 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]] } } }); + fs.rmSync(sessionStatePath("test-cost", SESSION)); + + // 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)); + + // 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 + // 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); + assert.deepEqual(stored(), { [file]: { whole: { tests: 8000, seconds: 140 } } }); + note( + `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 } } }); + }); +}); + test("a command that is no file run, or names a file that is not there, leaves no state", { skip: WINDOWS, }, (t) => { @@ -566,6 +987,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); }); }); @@ -978,6 +1402,54 @@ 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`; + // 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 })); +}); + +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 suite = report({ tests: 9000, time: "300.1" }); + 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, 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"), []); +}); + test("a session whose prompts read no row stores nothing", { skip: WINDOWS }, async (t) => { const server = await loom(t); const box = sandbox(t, server); @@ -1060,7 +1532,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); diff --git a/integrations/claude-code-plugin/tests/test-gate.test.mjs b/integrations/claude-code-plugin/tests/test-gate.test.mjs index d78b0905b2..95217568d9 100644 --- a/integrations/claude-code-plugin/tests/test-gate.test.mjs +++ b/integrations/claude-code-plugin/tests/test-gate.test.mjs @@ -1265,11 +1265,37 @@ 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 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, + 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: 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", + // 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", + // 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", + "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'", @@ -1277,6 +1303,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"]) { diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index c361cc263d..d12cda0ad6 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.189", + "version": "1.2.190", "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 ef209e4c86..4fa734e37f 100644 --- a/integrations/codex-plugin/lib/test-cost.mjs +++ b/integrations/codex-plugin/lib/test-cost.mjs @@ -8,14 +8,18 @@ // run's seconds. hooks/loom-test-report.mjs notes them for a command that is // one pytest run of one test file (`noteCommand`), in the session's private // state, for a session whose end may store them: for each file, the costliest -// whole run that passed and its latest runs filtered with -k. A run that -// outlives its shell call writes the file after that call's hook ran: a -// report read later is its when pytest began the run that wrote it before -// that call returned, and the launcher reads the file once more before it -// removes it at the session's end (`settleRun`). The file is one a session: a -// pytest run that ends before a hook read it replaces it, and the session's -// start after a compaction empties it (`startReport`). The run that outlived -// its call is then not counted. +// 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: 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 @@ -48,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 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. const MAX_FILES = 8; @@ -92,8 +100,25 @@ 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. 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`, `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) => klass.startsWith(`${parts.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 @@ -134,7 +159,14 @@ 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. 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) { @@ -157,10 +189,21 @@ function settle(state, report) { * file (`fileRun`) and its output shows pytest's summary with the cases, the * failures and the seconds the report holds: a run the option did not reach * writes no report, and the one read after it is an earlier run's. The - * seconds alone do not tell two short runs apart. 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. + * 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 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 + * 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 @@ -189,6 +232,7 @@ export function noteCommand(sessionId, { command, output, report, cwd }) { run && !open && cost && + (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 a99a8e1081..eaa7540490 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`(?`). +const CD = /(?:^|[;&|(\n])[ \t]*cd[ \t]+([^\s;&|)]+)/g; +const MOVE = /\b(?:cd|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 @@ -1336,16 +1349,106 @@ 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)); +// 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 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 `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`(?` 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 +// 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 `&&` + // 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 + // 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 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); + 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 + // `), and a command put in the background earlier is not read + // (`./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 + // run). Where a heredoc ends is not read, so a line of an inline script's + // 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. + !/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) && + // 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 )`). + !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) && + // 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) + ); +}; /** 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, @@ -1401,48 +1504,56 @@ 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 - * `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 + * else to run: `{ path, dir, whole, seconds, cases, failed, skipped, values, + * 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 `-k` whose last line counts deselected cases + * is none: a selection its words do not show left cases out (one in + * `PYTEST_ADDOPTS` or the settings file). Nor is a run pytest ended before + * its last case, which the line above its last one says (`CUT_SHORT`): its + * last line and its result file count the cases it got to. Nor is a run that + * anything follows in the command but `tail`, `head`, `grep` and `echo` + * (`onlyRuns`), a redirect to a file aside: a runner started after it (`&& + * make test`, `; tox`, a second pytest with no space before it, which * `PYTEST` does not count) writes the session's result file and prints the - * last line. Quotes are not read there or in the run's words (`PYTEST`), so - * a run piped into `grep -E "passed|failed"` is none, and neither is one - * with `-k "parse and (empty or nested)"`. Nor is a run that anything stands - * before in the command but `cd`, `export`, `source` and `.` (`onlySetsUp`): - * a command before it may start pytest too (`make test || pytest `), - * and where the run does not start, the last line and the result file are - * that command's. + * 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`). 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 * every case; the rest run none), or a cluster of short flags that may hold * one. Nor is a run that does not write the session's result file * (`OWN_REPORT`), or one after a move the reader cannot follow (a second - * `cd`, `pushd`, a `cd` in a subshell that closed, or to a folder that is - * not written plainly, `PLAIN_FOLDER`). The word after a flag that may take - * a value is that value and no path (`BARE`); a short flag written with its + * `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. + * 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 @@ -1451,16 +1562,32 @@ 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)) return null; + if (runs.length !== 1) return null; + const head = text.slice(0, runs[0].index); + const tail = text.slice(runs[0].index); + 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(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)]; + // After a command that is no set-up, a `cd` is the shell's own where it + // 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. 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 && - cd.every((m) => PLAIN_FOLDER.test(m[1]) && !closesParen(head.slice(m.index + m[0].length))); + (head.match(afterSetUpOnly ? MOVE : MOVE_WORD) || []).length === cd.length && + cd.every( + (m) => + PLAIN_FOLDER.test(m[1]) && + (afterSetUpOnly + ? !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 = []; const values = []; @@ -1494,6 +1621,7 @@ export function fileRun(command, output = "") { failed: summary ? counted(summary, "failed|errors?") : null, skipped: summary ? counted(summary, "skipped") : null, values, + afterSetUpOnly, }; } @@ -1550,8 +1678,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-report.mjs b/integrations/codex-plugin/lib/test-report.mjs index bf6b17197f..42840cc6e2 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 || "", }; } diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 334b24da49..6a309a9e44 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": "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": "872a5c986dc1ddbcc9bccc47f77925a45030a858069784efbf5cb61b1cf738bf", + "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",