From 48270c04397ac496534a6a259742b3b4c16c56f9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 10:39:36 +0100 Subject: [PATCH 01/13] Record the reading cost --- docs/reading-cost.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 02047e31..67247ab3 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -3661,3 +3661,11 @@ Read most (opens and searches): - `bin/task_bench/bench_folder.py` 2 - `bin/task_bench/feature_tasks.py` 2 - `docs/decisions.md` 2 + +## Reading cost, chunk a2b51a47f8f9, finished 2026-11-26T09:29:04Z + +51817 new input tokens before the first commit. + +Read most (opens and searches): + +- `principles/technical-principles.md` 2 -- 2.52.0 From ffe2048b73bc2c9dcffec3e67328628f650aa00e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 10:39:36 +0100 Subject: [PATCH 02/13] Plant task-bench's bugs in TypeScript and PHP, from Stryker's and Infection's killed mutants --- README.md | 4 +- bin/mutate_changes/in_diff_tools.py | 10 +- bin/task_bench/main.py | 29 +-- bin/task_bench/php_bugs.py | 105 ++++++++++ bin/task_bench/plant.py | 7 +- bin/task_bench/planted_mutant.py | 3 +- bin/task_bench/test_php_bugs.py | 259 +++++++++++++++++++++++++ bin/task_bench/test_plant.py | 4 +- bin/task_bench/test_task_bench.py | 4 +- bin/task_bench/test_typescript_bugs.py | 247 +++++++++++++++++++++++ bin/task_bench/typescript_bugs.py | 117 +++++++++++ 11 files changed, 765 insertions(+), 24 deletions(-) create mode 100644 bin/task_bench/php_bugs.py create mode 100644 bin/task_bench/test_php_bugs.py create mode 100644 bin/task_bench/test_typescript_bugs.py create mode 100644 bin/task_bench/typescript_bugs.py diff --git a/README.md b/README.md index 72747703..0af7783e 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter. - `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it. - `subagent-rung [--plan] ` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule. -- `task-bench --image --test []` plants bugs that the tests catch, in the Go, Python and Rust files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams. +- `task-bench --image --test []` plants bugs that the tests catch, in the Go, PHP, Python, Rust, TypeScript and JavaScript files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams. - `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show ` one item's row and detail; `add …` files an item under the next free ID, `edit …` sets an item's cells or detail, and `move --release ` sets an item's release; `finish ` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags. - `touch-predictions record ...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once. - `wait-for [] [--timeout ]` waits until a file a background job writes holds a line matching the pattern, and prints it. @@ -286,7 +286,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format. - `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. - `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive. -- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, Python and Rust files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers. +- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, PHP, Python, Rust, TypeScript and JavaScript files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers. - `test_env.py` serves the tests. - `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards. - `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. diff --git a/bin/mutate_changes/in_diff_tools.py b/bin/mutate_changes/in_diff_tools.py index e8d198f6..51938b63 100644 --- a/bin/mutate_changes/in_diff_tools.py +++ b/bin/mutate_changes/in_diff_tools.py @@ -12,6 +12,9 @@ from git_cli.git_repo import Git # cargo-mutants' exit codes for a run that finished: every mutant caught, some missed, and some timed out. CARGO_FINISHED = frozenset({0, 2, 3}) CARGO_OUTCOMES = ("caught", "missed", "timeout", "unviable") +INFECTION = "vendor/bin/infection" # the project's own, as Composer installs it +# npx runs the project's own @stryker-mutator/core, else one an earlier npx run cached, and installs none. +STRYKER = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run"] GREMLINS_UNKILLED = frozenset({"LIVED", "NOT COVERED"}) # What Gremlins v0.6.0 needs of the diff it reads from git: one run of lines per hunk is all it mutates, so a hunk holds the changed # lines and none around them, nor a neighbouring change; it takes each file's path after a b/; and it reads no colour codes. A user's git @@ -118,8 +121,7 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in """For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line naming the files with no package.json above them, if any. - Stryker runs in the nearest folder above each file that holds a package.json. npx runs the project's own @stryker-mutator/core, else - one an earlier npx run cached, and installs none.""" + Stryker runs in the nearest folder above each file that holds a package.json.""" report: list[str] = [] unplaced: list[str] = [] for folder, files in sorted(by_folder(top, changed, ("package.json",)).items()): @@ -128,7 +130,7 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in unplaced = sorted(files) continue mutate = ",".join(f"{path}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines)) - ran = run(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder)) + ran = run([*STRYKER, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder)) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else whole_output(f"Stryker in {label(folder)}", ran) report.extend([f"Stryker in {label(folder)}:", *ran.output.splitlines()]) @@ -137,7 +139,7 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in def run_infection(top: str, base: str, run: Run, jobs: int) -> list[str] | Failure: """A line naming where Infection ran, top, then its own report of the mutants on the lines the branch changes since base.""" - ran = run(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top) + ran = run([INFECTION, "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else whole_output("Infection", ran) return ["Infection in the checkout's top:", *ran.output.splitlines()] diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index b19aa4b4..935d77f0 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -15,13 +15,16 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream. - Plant. It copies the tree at the base and runs a mutation tool there, over the files that hold the places `larv-review places` prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, mutmut 3 over - the Python files, as `mutmut run`, and cargo-mutants over the Rust files, as `cargo mutants`. No other language is planted - in so far. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of + the Python files, as `mutmut run`, cargo-mutants over the Rust files, as `cargo mutants`, Infection over the PHP files, as + `vendor/bin/infection`, and Stryker over the TypeScript and JavaScript files, as `npx stryker run`. No other language is + planted in so far. Infection and Stryker run at the copy's top, with the project's config for the tool there. Stryker's json + reporter must write where it does by default, `reports/mutation/mutation.json`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of them, 5 by default, have become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where, planted at each side, a test fails and prints a message that says more than the test's name. The bench reads that message - from `go test`'s output for a Go file, from pytest's for a Python file and from `cargo test`'s for a Rust file, so --test must - run the tests of each language the places name, with that runner: pytest as it prints by default, or with --tb=short, and - `cargo test` without --nocapture. Any other mutant is passed over, so a change to the very lines of a bug is not benched. + from `go test`'s output for a Go file, from pytest's for a Python file, from `cargo test`'s for a Rust file, from PHPUnit's + for a PHP file and from `node --test`'s for a TypeScript or JavaScript file, so --test must run the tests of each language the + places name, with that runner: pytest as it prints by default, or with --tb=short, `cargo test` without --nocapture, PHPUnit + as it prints by default, and `node --test` with its spec reporter. Any other mutant is passed over, so a change to the very lines of a bug is not benched. - Run. Haiku fixes each bug --runs times at each side, 5 by default, the sides in turn. A fix starts from a copy of that side's tree with the bug in it, committed once, so git doesn't show which line the bug is on. In the copy, in a container, `claude -p --strict-mcp-config --disable-slash-commands --no-session-persistence --model claude-haiku-5-5 --effort low` works with every @@ -40,9 +43,10 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream. so the image needs curl and bash; the result names the version. Haiku works in that image. So does --test: sh runs that text at the copy's top, with no network, so the image must hold what the tests would otherwise download. --prefix is shell text that runs the mutation tool, on the host, as mutate-changes' --prefix does: sh runs ` "$@"` with -the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins and -cargo-mutants run in the copy of the base, and mutmut in a copy of the folder there that holds its settings; $PWD is the folder -the tool runs in. Without --prefix, the bench runs the `gremlins`, the `mutmut` or the `cargo` on the host's PATH. For example, +the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins, +cargo-mutants, Infection and Stryker run in the copy of the base, and mutmut in a copy of the folder there that holds its settings; +$PWD is the folder the tool runs in. Without --prefix, the bench runs the `gremlins`, the `mutmut`, the `cargo` or the `npx` on +the host's PATH, or the copy's own `vendor/bin/infection`. For example, for Go, for Python and then for Rust: docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \ @@ -54,7 +58,8 @@ for Go, for Python and then for Rust: rust:1.100.0 sh -c 'cargo install --quiet --locked cargo-mutants@27.1.0 && exec "$@"' sh Where the places name files in more than one language, the one prefix gets each tool's command, Gremlins' first and -cargo-mutants' last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`, `mutmut` or `cargo`, as here for Go +Stryker's last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`, +`vendor/bin/infection`, `mutmut`, `cargo` or `npx`, as here for Go and Python: sh -c 'case "$1" in @@ -152,7 +157,7 @@ not, unless a bench or a gather is using it. So gather a bench before the next o Exit 1, saying why, on an unknown or repeated argument, a missing --image or --test, a --seed, --bugs or --runs that is no whole number from 1, a --tasks that is none of bugs, features, data-sources and shipped-features, or no token; and where git, docker or a mutation tool -fails, the seats' places don't name any Go, Python or Rust file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks +fails, the seats' places don't name any file in a language the bench plants bugs in, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks features or data-sources it exits 1 on a --seed, --bugs or --prefix; where no config names the checkout or its config sets no `bench-tasks`, or the folder holds no task of that kind, one that lacks a part, or a `generate-register` that is no executable file, each before docker runs; and where the tests fail at a side without the acceptance tests, or no task counts. @@ -359,11 +364,11 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str]) def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure: - """What plans a bench of bugs: of the mutants the tests kill in the Go, Python and Rust files of the tree at base that hold a place + """What plans a bench of bugs: of the mutants the tests kill in the files of the tree at base that are in a language of plant's LANGUAGES and hold a place in places, those --seed draws first become bugs, until --bugs of them have.""" files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()] if not files: - return Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.") + return Failure("The places the seats found hard don't name any file that the base holds in a language the bench plants bugs in, so there is nowhere to plant a bug.") run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg) mutants = killed_mutants(base, files, run, CPUS_PER_SLOT) return mutants if isinstance(mutants, Failure) else functools.partial(planted_tasks, mutants=mutants, seed=int(given["--seed"]), bugs=int(given["--bugs"])) diff --git a/bin/task_bench/php_bugs.py b/bin/task_bench/php_bugs.py new file mode 100644 index 00000000..38c6ccee --- /dev/null +++ b/bin/task_bench/php_bugs.py @@ -0,0 +1,105 @@ +"""The bugs task-bench plants in PHP: Infection's killed mutants, each read from the diff in its JSON log, and the message PHPUnit +prints when a test fails on one.""" +import json +import os +import pathlib +import re + +from failure import Failure +from mutate_changes import in_diff_tools +from task_bench.planted_mutant import Mutant +from mutate_changes.tool_process import failed, remove, Run, scratch_folder + +# The heading of PHPUnit's list of the tests that failed, or of those that threw: `There were 3 failures:`. +LISTED = re.compile(r"^There (?:was|were) \d+ (?:error|failure)s?:$") +# A listed test, by its number in the list: `1) Probe\Tests\PickTest::testNamesOne`, or with ` with data set #0 (1, 'one')` after it. +TEST = re.compile(r"^\d+\) (\S+)") +# What ends a listed test's message: the file and line that failed, as `/w/tests/PickTest.php:12`, the line between the two +# lists, or the summary's heading. +AFTER_MESSAGE = re.compile(r"^(?:\S.*\.php:\d+|--|ERRORS!|FAILURES!)$") +TEST_FILE = re.compile(r"Test\.php\b") + + +def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure: + """The mutants in `files` that the tests of the tree at top kill, as Infection finds them there. One whose diff doesn't fit the + source Infection logged with it is left out. + + Infection runs at top, with the Infection config and the vendor folder there.""" + scratch = scratch_folder(top) + if isinstance(scratch, Failure): + return scratch + try: + log = pathlib.Path(scratch, "log.json") + ran = run([in_diff_tools.INFECTION, f"--filter={','.join(files)}", f"--threads={jobs}", "--no-progress", f"--logger-json={os.path.relpath(log, top)}"], top) + if isinstance(ran, Failure) or ran.code: + return ran if isinstance(ran, Failure) else failed("Infection", ran) + killed = [(logged["mutator"], logged["diff"]) for logged in json.loads(log.read_bytes())["killed"]] + return [mutant for mutator, diff in killed if (mutant := planted(mutator, diff, files))] + except (OSError, ValueError, KeyError, TypeError) as failure: + return Failure(f"could not read Infection's log in {scratch}: {failure}") + finally: + remove(scratch) + + +def planted(mutator: dict, diff: str, files: list[str]) -> Mutant | None: + """A mutant of Infection's log as the lines it changes, or None where it is in none of `files` or `changed` finds no lines. + + The log names a file by its whole path where Infection ran, which is another than top's where a container ran it. So the file is + the longest of `files` that ends that path.""" + logged = mutator["originalFilePath"] + path = max((path for path in files if logged == path or logged.endswith(f"/{path}")), key=len, default=None) + start = mutator["originalStartLine"] + found = changed(diff, mutator["originalSourceCode"].split("\n"), start) if path else None + return Mutant(path, found[0], f"{path}:{start} {mutator['mutatorName']}", found[1], found[2]) if path and found else None + + +def changed(diff: str, lines: list[str], start: int) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None: + """The lines a mutant changes, from the diff Infection 0.35.12 logs for it: the number of the first, from 1, those lines as the + file has them, and what the mutant has in their place. An unchanged line between two changed ones is in both. + + The diff's one hunk gives no line numbers. So the hunk's lines are found among `lines`, the file's, around `start`, the line + Infection logs as the one the mutated code starts on. None where the diff holds no change, or where its lines stand around + `start` nowhere or more than once.""" + hunk = diff.partition("@@ @@\n")[2].split("\n") + # An empty line of the file is an empty line of the hunk; any other line opens with a space, a minus or a plus. + body = [(line[:1] if line[:1] in ("-", "+") else " ", line[1:]) for line in hunk] + at = [index for index, (kind, _) in enumerate(body) if kind != " "] + old = [text for kind, text in body if kind != "+"] + held = [first for first in range(max(start - len(old), 0), start) if lines[first:first + len(old)] == old] + if not at or len(held) != 1: + return None + span = body[at[0]:at[-1] + 1] + was = tuple(text.encode() for kind, text in span if kind != "+") + now = tuple(text.encode() for kind, text in span if kind != "-") + # Each line of the hunk before the first changed one is a line of the file. + return held[0] + at[0] + 1, was, now + + +def task_text(output: str) -> str | None: + """What Haiku is told of a planted bug: the message of the first test with one in PHPUnit's list of the tests that threw or + failed, without the test's name, class or file, so it says what goes wrong and not which test shows it. + + None where PHPUnit lists no such test, as on a passing run, a file that fails to parse or a run with --testdox, or where each + message only names its test.""" + messages: list[tuple[str, list[str]]] = [] + listing = within = False + for line in output.splitlines(): + if LISTED.match(line): + listing, within = True, False + elif listing and (test := TEST.match(line)): + messages.append((test[1], [])) + within = True + elif AFTER_MESSAGE.match(line): + within = False + elif within: + messages[-1][1].append(line) + kept = (kept_lines(test, message) for test, message in messages) + return next(("\n".join(lines) for lines in kept if lines), None) + + +def kept_lines(test: str, message: list[str]) -> list[str]: + """A message's lines, without the empty ones and those that name the test: the whole of `Probe\\Tests\\PickTest::testNamesOne`, + its class with or without the namespace, its method, or a test's file.""" + of_class, _, method = test.partition("::") + names = {test, of_class, of_class.rpartition("\\")[2], method} - {""} + return [text for text in message if text and not TEST_FILE.search(text) and not any(name in text for name in names)] diff --git a/bin/task_bench/plant.py b/bin/task_bench/plant.py index 52c0400b..cb40a9b1 100644 --- a/bin/task_bench/plant.py +++ b/bin/task_bench/plant.py @@ -6,8 +6,8 @@ import re import typing from failure import Failure -from task_bench import go_bugs, python_bugs, rust_bugs -from mutate_changes.changed_lines import is_test +from task_bench import go_bugs, php_bugs, python_bugs, rust_bugs, typescript_bugs +from mutate_changes.changed_lines import is_test, STRYKER from task_bench.planted_mutant import Mutant from mutate_changes.tool_process import Run @@ -28,8 +28,11 @@ class Language(typing.NamedTuple): LANGUAGES = ( Language("Go", (".go",), go_bugs.killed_mutants, go_bugs.task_text), + Language("PHP", (".php",), php_bugs.killed_mutants, php_bugs.task_text), Language("Python", (".py",), python_bugs.killed_mutants, python_bugs.task_text), Language("Rust", (".rs",), rust_bugs.killed_mutants, rust_bugs.task_text), + # Stryker mutates JavaScript as it does TypeScript, and `node --test` reports both alike. + Language("TypeScript", STRYKER, typescript_bugs.killed_mutants, typescript_bugs.task_text), ) diff --git a/bin/task_bench/planted_mutant.py b/bin/task_bench/planted_mutant.py index ba6f31f8..45400067 100644 --- a/bin/task_bench/planted_mutant.py +++ b/bin/task_bench/planted_mutant.py @@ -11,7 +11,8 @@ class Mutant(typing.NamedTuple): """A mutant the project's tests killed, as the lines it changes in the tree its tool ran in: the number of the first, from 1, those lines as the tree has them, and what the mutant has in their place. Where it only adds lines, the number is that of the line they go in before. name is what the report calls the bug it becomes: the path and line, then what the tool tells the - mutant by, which is Gremlins' column and mutator, or mutmut's name. cargo-mutants' own name for a mutant holds all of it.""" + mutant by, which is Gremlins' or Stryker's column and mutator, Infection's mutator, or mutmut's name. cargo-mutants' own name for a mutant + holds all of it.""" path: str line: int diff --git a/bin/task_bench/test_php_bugs.py b/bin/task_bench/test_php_bugs.py new file mode 100644 index 00000000..75513d82 --- /dev/null +++ b/bin/task_bench/test_php_bugs.py @@ -0,0 +1,259 @@ +"""task-bench's PHP planter: which files Infection mutates, how its log's diffs become mutants and what PHPUnit's output tells Haiku. + +PICK's diffs and FAILING are what Infection 0.35.12 and PHPUnit 12.5.45 wrote for a small project on PHP 8.5.13, and each logged +mutant holds the keys the planter reads. The other diffs and outputs are made up in the same form.""" +import json +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from task_bench.php_bugs import changed, killed_mutants, task_text +from failure import Failure +from task_bench.planted_mutant import Mutant, mutated +from mutate_changes.tool_process import Ran + +PICK = """ $items */ + public static function sum(array $items, int $floor): int + { + $sum = 0; + foreach ($items as $item) { + if ($item >= $floor) { + $sum += $item; + } + } + return $sum; + } + + public static function label(int $count): string + { + return $count === 1 + ? 'one item' + : $count . ' items'; + } +} +""" +LINES = PICK.split("\n") +OPERATOR_DIFF = "@@ @@\n \t{\n \t\t$sum = 0;\n \t\tforeach ($items as $item) {\n-\t\t\tif ($item >= $floor) {\n+\t\t\tif ($item > $floor) {\n \t\t\t\t$sum += $item;\n \t\t\t}\n \t\t}" +# Infection prints the lines of a statement it rewrote with its own indent, and leaves the ones between them as they were. +FOREACH_DIFF = ( + "@@ @@\n \tpublic static function sum(array $items, int $floor): int\n \t{\n \t\t$sum = 0;\n-\t\tforeach ($items as $item) {\n-\t\t\tif ($item >= $floor) {\n" + "+\t\tforeach ([] as $item) {\n+ if ($item >= $floor) {\n \t\t\t\t$sum += $item;\n \t\t\t}\n-\t\t}\n+ }\n \t\treturn $sum;\n \t}" +) +TERNARY_DIFF = ( + "@@ @@\n\n \tpublic static function label(int $count): string\n \t{\n-\t\treturn $count === 1\n-\t\t\t? 'one item'\n-\t\t\t: $count . ' items';\n" + "+\t\treturn $count === 1 ? $count . ' items' : 'one item';\n \t}\n }" +) +# An empty line of the file stands in the diff without the space that opens an unchanged line. +VISIBILITY_DIFF = ( + "@@ @@\n \t\treturn $sum;\n \t}\n\n-\tpublic static function label(int $count): string\n+\tprotected static function label(int $count): string\n" + " \t{\n \t\treturn $count === 1\n \t\t\t? 'one item'" +) +OPERATOR_NOW = (b"\t\t\tif ($item > $floor) {",) + + +def logged(mutator: str, line: int, diff: str, path: str = "/w/src/Pick.php", source: str = PICK) -> dict: + return {"mutator": {"mutatorName": mutator, "originalSourceCode": source, "originalFilePath": path, "originalStartLine": line}, "diff": diff} + + +# Three failed tests. +FAILING = """PHPUnit 12.5.45 by Sebastian Bergmann and contributors. + +Runtime: PHP 8.5.13 +Configuration: /w/phpunit.xml + +FFF 3 / 3 (100%) + +Time: 00:00.002, Memory: 18.00 MB + +There were 3 failures: + +1) Probe\\Tests\\PickTest::testAddsTheItemsAtOrAboveTheFloor +Failed asserting that 3 is identical to 5. + +/w/tests/PickTest.php:12 + +2) Probe\\Tests\\PickTest::testNamesOne +one is singular +Failed asserting that two strings are identical. +--- Expected ++++ Actual +@@ @@ +-'one item' ++'' + +/w/tests/PickTest.php:17 + +3) Probe\\Tests\\PickTest::testNamesMany +Failed asserting that two arrays are equal. +--- Expected ++++ Actual +@@ @@ + Array ( +- 'text' => '3 items' ++ 'text' => '3' + ) + +/w/tests/PickTest.php:22 + +FAILURES! +Tests: 3, Assertions: 3, Failures: 3. +""" +PASSING = "PHPUnit 12.5.45 by Sebastian Bergmann and contributors.\n\n... 3 / 3 (100%)\n\nOK (3 tests, 3 assertions)\n" + + +def failing(test: str, *lines: str) -> str: + return "\n".join(["F 1 / 1 (100%)", "", "There was 1 failure:", "", f"1) {test}", *lines, "", "FAILURES!", "Tests: 1, Assertions: 1, Failures: 1.", ""]) + + +class ChangedTest(unittest.TestCase): + def test_is_the_line_an_operator_mutant_changes(self): + self.assertEqual(changed(OPERATOR_DIFF, LINES, 12), (12, (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW)) + + def test_is_every_line_from_the_first_changed_one_to_the_last(self): + was = tuple(line.encode() for line in LINES[10:15]) + now = (b"\t\tforeach ([] as $item) {", b" if ($item >= $floor) {", b"\t\t\t\t$sum += $item;", b"\t\t\t}", b" }") + self.assertEqual(changed(FOREACH_DIFF, LINES, 11), (11, was, now)) + + def test_a_mutant_may_have_fewer_lines_than_it_replaces(self): + was = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';") + self.assertEqual(changed(TERNARY_DIFF, LINES, 21), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",))) + + def test_reads_an_empty_line_of_the_diff_as_an_unchanged_empty_line(self): + self.assertEqual(changed(VISIBILITY_DIFF, LINES, 19), (19, (b"\tpublic static function label(int $count): string",), (b"\tprotected static function label(int $count): string",))) + + def test_finds_the_lines_around_the_mutants_start_line_where_the_file_holds_them_twice(self): + twice = ["\t\t$a = 1;", "\t\treturn $a >= 2;", "\t}", "", "\t\t$a = 1;", "\t\treturn $a >= 2;", "\t}"] + diff = "@@ @@\n \t\t$a = 1;\n-\t\treturn $a >= 2;\n+\t\treturn $a > 2;\n \t}" + self.assertEqual(changed(diff, twice, 2), (2, (b"\t\treturn $a >= 2;",), (b"\t\treturn $a > 2;",))) + self.assertEqual(changed(diff, twice, 6), (6, (b"\t\treturn $a >= 2;",), (b"\t\treturn $a > 2;",))) + + def test_is_none_where_the_diffs_lines_do_not_stand_around_the_start_line(self): + self.assertIsNone(changed(OPERATOR_DIFF, LINES, 20)) + self.assertIsNone(changed(OPERATOR_DIFF.replace("$sum = 0", "$sum = 1"), LINES, 12)) + self.assertIsNone(changed(OPERATOR_DIFF, LINES, 0)) + + def test_is_none_where_the_diff_holds_no_change_or_no_hunk(self): + self.assertIsNone(changed("@@ @@\n \t{\n \t\t$sum = 0;", LINES, 10)) + self.assertIsNone(changed("", LINES, 10)) + + def test_what_it_returns_plants_as_the_mutant(self): + for diff, start in ((OPERATOR_DIFF, 12), (FOREACH_DIFF, 11), (TERNARY_DIFF, 21), (VISIBILITY_DIFF, 19)): + with self.subTest(start=start): + line, was, now = changed(diff, LINES, start) + planted = mutated(PICK.encode(), Mutant("src/Pick.php", line, "a name", was, now)) + self.assertEqual(planted.split(b"\n")[line - 1], now[0]) + self.assertEqual(len(planted.split(b"\n")), len(LINES) - len(was) + len(now)) + + +class KilledMutantsTest(unittest.TestCase): + def setUp(self): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.top = pathlib.Path(folder.name) + self.ran: list[tuple[list[str], str]] = [] + + def infection(self, log: dict | str | None, code: int = 0): + """A run that writes Infection's log where its --logger-json names, or none where log is None.""" + def run(argv: list[str], cwd: str) -> Ran: + self.ran.append((argv, cwd)) + if log is not None: + path = next(argument.partition("=")[2] for argument in argv if argument.startswith("--logger-json=")) + pathlib.Path(cwd, path).write_text(log if isinstance(log, str) else json.dumps(log), encoding="utf-8") + return Ran(code, "the tool's last words\n") + return run + + def test_runs_infection_over_the_files_at_the_top_with_a_json_log_in_a_scratch_folder(self): + killed_mutants(str(self.top), ["src/Pick.php", "src/Last.php"], self.infection({"killed": []}), 3) + (argv, cwd), = self.ran + self.assertEqual(cwd, str(self.top)) + self.assertEqual(argv[:4], ["vendor/bin/infection", "--filter=src/Pick.php,src/Last.php", "--threads=3", "--no-progress"]) + self.assertRegex(argv[4], r"^--logger-json=\.mutate-changes-[^/]+/log\.json$") + self.assertEqual(len(argv), 5) + + def test_is_each_killed_mutant_as_the_lines_it_changes(self): + log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF), logged("Ternary", 21, TERNARY_DIFF)], "escaped": [logged("PublicVisibility", 19, VISIBILITY_DIFF)]} + found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1) + ternary = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';") + self.assertEqual(found, [ + Mutant("src/Pick.php", 12, "src/Pick.php:12 GreaterThanOrEqualTo", (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW), + Mutant("src/Pick.php", 21, "src/Pick.php:21 Ternary", ternary, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)), + ]) + + def test_names_a_file_by_its_path_from_the_top_wherever_infection_saw_the_tree(self): + log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF, path) for path in ("/w/src/Pick.php", "src/Pick.php", "/w/lib/src/Pick.php", "/w/src/Other.php", "/w/src/NotPick.php")]} + found = killed_mutants(str(self.top), ["src/Pick.php", "lib/src/Pick.php", "Pick.php"], self.infection(log), 1) + self.assertEqual([mutant.path for mutant in found], ["src/Pick.php", "src/Pick.php", "lib/src/Pick.php"]) + + def test_leaves_out_a_mutant_whose_diff_does_not_fit_its_source(self): + log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF, source="= floor) { + sum += item; + } + } + return sum; +} + +export const tag = (n: number): string => "é😀" + (n > 1 ? "s" : ""); +""".encode() +LINES = PICK.split(b"\n") + + +def reported(mutator: str, replacement: str, start: tuple[int, int], end: tuple[int, int], status: str = "Killed") -> dict: + return {"mutatorName": mutator, "replacement": replacement, "status": status, "location": {"start": {"line": start[0], "column": start[1]}, "end": {"line": end[0], "column": end[1]}}} + + +OPERATOR = reported("EqualityOperator", "item > floor", (4, 7), (4, 20)) +BLOCK = reported("BlockStatement", "{}", (4, 22), (6, 4)) +# Stryker counts a column in UTF-16 code units: the string before this condition holds one character of two units. +AFTER_WIDE_TEXT = reported("ConditionalExpression", "true", (11, 52), (11, 57)) +# Three failed tests, the last two in a suite. +FAILING = """ +> test +> node --test "src/**/*.test.ts" + +✖ adds the items at or above the floor (1.654962ms) +▶ label + ✖ names one (0.432991ms) + ✖ names many (1.398742ms) +✖ label (2.262912ms) +ℹ tests 3 +ℹ suites 1 +ℹ pass 0 +ℹ fail 3 +ℹ cancelled 0 +ℹ skipped 0 +ℹ todo 0 +ℹ duration_ms 164.424758 + +✖ failing tests: + +test at src/pick.test.ts:5:1 +✖ adds the items at or above the floor (1.654962ms) + AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + + 3 !== 5 + + at TestContext. (file:///w/src/pick.test.ts:6:9) + at Test.runInAsyncScope (node:async_hooks:227:14) + at startSubtestAfterBootstrap (node:internal/test_runner/harness:387:17) { + generatedMessage: true, + code: 'ERR_ASSERTION', + actual: 3, + expected: 5, + operator: 'strictEqual', + diff: 'simple' + } + +test at src/pick.test.ts:10:2 +✖ names one (0.432991ms) + AssertionError [ERR_ASSERTION]: one is singular + + '' !== 'one item' + + at TestContext. (file:///w/src/pick.test.ts:11:10) + at Array.map () { + generatedMessage: false, + code: 'ERR_ASSERTION', + actual: '', + expected: 'one item', + operator: 'strictEqual', + diff: 'simple' + } + +test at src/pick.test.ts:13:2 +✖ names many (1.398742ms) + AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + + actual - expected + + { + + text: '' + - text: '3 items' + } + + at TestContext. (file:///w/src/pick.test.ts:14:10) { + generatedMessage: true, + code: 'ERR_ASSERTION', + actual: [Object], + expected: [Object], + operator: 'deepStrictEqual', + diff: 'simple' + } +""" +PASSING = "✔ adds the items at or above the floor (1.3494ms)\nℹ tests 1\nℹ pass 1\nℹ fail 0\n" + + +def failing(test: str, *lines: str) -> str: + return "\n".join([f"✖ {test} (1.2ms)", "ℹ fail 1", "", "✖ failing tests:", "", "test at src/pick.test.ts:5:1", f"✖ {test} (1.2ms)", *lines, ""]) + + +class ChangedTest(unittest.TestCase): + def test_is_the_line_with_the_replacement_between_the_mutants_columns(self): + self.assertEqual(changed(OPERATOR["location"], "item > floor", LINES), (4, (b"\t\tif (item >= floor) {",), (b"\t\tif (item > floor) {",))) + + def test_is_every_line_a_mutant_spans(self): + was = (b"\t\tif (item >= floor) {", b"\t\t\tsum += item;", b"\t\t}") + self.assertEqual(changed(BLOCK["location"], "{}", LINES), (4, was, (b"\t\tif (item >= floor) {}",))) + + def test_a_replacement_of_more_lines_is_as_many_lines(self): + self.assertEqual(changed(OPERATOR["location"], "item >\n\t\t\tfloor", LINES), (4, (LINES[3],), (b"\t\tif (item >", b"\t\t\tfloor) {"))) + + def test_counts_a_column_in_utf_16_code_units(self): + now = 'export const tag = (n: number): string => "é😀" + (true ? "s" : "");'.encode() + self.assertEqual(changed(AFTER_WIDE_TEXT["location"], "true", LINES), (11, (LINES[10],), (now,))) + + def test_is_none_where_the_file_holds_no_such_line_or_column(self): + for start, end in (((0, 1), (1, 2)), ((12, 1), (13, 1)), ((4, 7), (99, 1)), ((4, 40), (4, 41)), ((4, 0), (4, 3)), ((4, 9), (4, 7)), ((5, 1), (4, 3))): + with self.subTest(start=start, end=end): + self.assertIsNone(changed(reported("M", "x", start, end)["location"], "x", LINES)) + + def test_what_it_returns_plants_as_the_mutant(self): + line, was, now = changed(BLOCK["location"], "{}", LINES) + planted = mutated(PICK, Mutant("src/pick.ts", line, "a name", was, now)) + self.assertEqual(planted, PICK.replace(b" {\n\t\t\tsum += item;\n\t\t}", b" {}")) + + +class KilledMutantsTest(unittest.TestCase): + def setUp(self): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.top = pathlib.Path(folder.name) + self.ran: list[tuple[list[str], str]] = [] + + def stryker(self, files: dict[str, list[dict]] | None, code: int = 0, text: str | None = None): + """A run that writes Stryker's report of these files' mutants, or none where files is None.""" + def run(argv: list[str], cwd: str) -> Ran: + self.ran.append((argv, cwd)) + if files is not None: + report = self.top / "reports/mutation/mutation.json" + report.parent.mkdir(parents=True) + report.write_text(text if text is not None else json.dumps({"files": {path: {"source": PICK.decode(), "mutants": mutants} for path, mutants in files.items()}}), encoding="utf-8") + return Ran(code, "the tool's last words\n") + return run + + def test_runs_stryker_over_the_files_at_the_top_with_its_json_reporter(self): + killed_mutants(str(self.top), ["src/pick.ts", "src/last.ts"], self.stryker({}), 3) + expected = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", "src/pick.ts,src/last.ts", "--concurrency", "3", "--reporters", "json"] + self.assertEqual(self.ran, [(expected, str(self.top))]) + + def test_is_each_killed_mutant_as_the_lines_it_changes(self): + found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR, BLOCK]}), 1) + self.assertEqual(found, [ + Mutant("src/pick.ts", 4, "src/pick.ts:4:7 EqualityOperator", (LINES[3],), (b"\t\tif (item > floor) {",)), + Mutant("src/pick.ts", 4, "src/pick.ts:4:22 BlockStatement", tuple(LINES[3:6]), (b"\t\tif (item >= floor) {}",)), + ]) + + def test_leaves_out_a_mutant_no_test_killed(self): + others = [reported("EqualityOperator", "item < floor", (4, 7), (4, 20), status) for status in ("Survived", "NoCoverage", "Timeout", "CompileError", "RuntimeError", "Ignored")] + self.assertEqual(killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": others}), 1), []) + + def test_leaves_out_a_mutant_in_another_file_or_at_a_place_the_file_does_not_hold(self): + files = {"src/other.ts": [OPERATOR], "src/pick.ts": [reported("EqualityOperator", "x", (40, 1), (40, 2)), OPERATOR]} + found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files), 1) + self.assertEqual([mutant.name for mutant in found], ["src/pick.ts:4:7 EqualityOperator"]) + + def test_removes_the_report_and_the_folders_stryker_made_for_it(self): + killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}), 1) + self.assertEqual(list(self.top.iterdir()), []) + + def test_keeps_a_reports_folder_that_holds_something_else(self): + (self.top / "reports").mkdir() + (self.top / "reports/coverage.txt").write_text("kept", encoding="utf-8") + killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}), 1) + self.assertEqual(sorted(str(path.relative_to(self.top)) for path in (self.top / "reports").rglob("*")), ["reports/coverage.txt"]) + + def test_fails_where_stryker_exits_nonzero_and_still_removes_the_report(self): + found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}, code=1), 1) + self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words")) + self.assertFalse((self.top / "reports").exists()) + + def test_passes_on_a_run_that_could_not_start(self): + failure = Failure("npx could not start: No such file or directory") + self.assertIs(killed_mutants(str(self.top), ["src/pick.ts"], lambda argv, cwd: failure, 1), failure) + + def test_fails_where_stryker_wrote_no_report_or_one_it_cannot_read(self): + for files, text in ((None, None), ({}, "not json"), ({}, '{"files": {"src/pick.ts": {"source": ""}}}'), ({}, '{"files": {"src/pick.ts": {"source": "", "mutants": [{"status": "Killed"}]}}}')): + with self.subTest(text=text): + found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files, text=text), 1) + self.assertIsInstance(found, Failure) + self.assertIn("could not read Stryker's report at reports/mutation/mutation.json", found.reason) + + +class TaskTextTest(unittest.TestCase): + def test_is_the_first_failed_tests_error_without_the_tests_name_file_or_stack(self): + self.assertEqual(task_text(FAILING), "AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n3 !== 5") + + def test_is_none_on_a_passing_run_or_output_that_lists_no_failing_test(self): + self.assertIsNone(task_text(PASSING)) + self.assertIsNone(task_text("SyntaxError: Unexpected token\n at node:internal/modules/esm/loader:1:1\n")) + self.assertIsNone(task_text("")) + + def test_leaves_out_each_line_that_names_the_test_or_its_file(self): + output = failing("adds the items", " Error: adds the items failed", " got 3 in src/pick.test.ts", " want 5", " at TestContext. (file:///w/src/pick.test.ts:6:9)") + self.assertEqual(task_text(output), "want 5") + + def test_is_none_where_the_error_does_not_say_anything_beyond_the_test(self): + self.assertIsNone(task_text(failing("adds the items", " Error: adds the items failed", " at TestContext. (file:///w/src/pick.test.ts:6:9)"))) + + def test_takes_the_first_failed_test_that_has_an_error(self): + first = failing("adds", " Error: adds", " at TestContext. (file:///w/src/pick.test.ts:6:9)") + second = "\n".join(["test at src/pick.test.ts:9:1", "✖ labels (0.4ms)", " Error: no label", " at label (file:///w/src/pick.ts:12:9)", ""]) + self.assertEqual(task_text(first + "\n" + second), "Error: no label") + + def test_an_error_without_a_stack_ends_at_its_test(self): + output = failing("adds", " 'a string was thrown'") + "\ntest at src/pick.test.ts:9:1\n✖ labels (0.4ms)\n Error: no label\n" + self.assertEqual(task_text(output), "'a string was thrown'") + + def test_an_error_runs_to_the_end_of_the_output(self): + self.assertEqual(task_text("✖ failing tests:\n\ntest at a.test.ts:1:1\n✖ adds (1ms)\n Error: got 3\n want 5"), "Error: got 3\nwant 5") + + def test_a_line_before_the_list_of_failing_tests_is_no_error(self): + self.assertIsNone(task_text("✖ adds (1ms)\n Error: printed by the test itself\nℹ fail 1\n\n✖ failing tests:\n\ntest at a.test.ts:1:1\n✖ adds (1ms)\n")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/task_bench/typescript_bugs.py b/bin/task_bench/typescript_bugs.py new file mode 100644 index 00000000..e2641417 --- /dev/null +++ b/bin/task_bench/typescript_bugs.py @@ -0,0 +1,117 @@ +"""The bugs task-bench plants in TypeScript and JavaScript: Stryker's killed mutants, re-applied from its JSON report, and the error +`node --test` prints when a test fails on one.""" +import contextlib +import json +import pathlib +import re +import sys + +from failure import Failure +from mutate_changes import in_diff_tools +from task_bench.planted_mutant import Mutant +from mutate_changes.tool_process import failed, Run + +# Where Stryker 10.1.1's json reporter writes, from the folder it runs in. Only the project's own Stryker config can set another +# path, so the planter reads this one. +REPORT = "reports/mutation/mutation.json" +# The heading of `node --test`'s list of the failed tests, as its spec reporter prints it, each with its error. +FAILING_TESTS = "✖ failing tests:" +# Where a listed test stands, the line before its name: `test at src/pick.test.ts:5:1`. +TEST_PLACE = re.compile(r"^test at \S+:\d+:\d+$") +# A listed test's name and how long it ran: `✖ adds the items (1.654962ms)`. +TEST = re.compile(r"^✖ (.+) \(\d+(?:\.\d+)?ms\)$") +# A line of the error's stack, which follows its message: ` at TestContext. (file:///w/src/pick.test.ts:6:9)`. +STACK = re.compile(r"^\s+at ") +TEST_FILE = re.compile(r"\.(?:spec|test)\.[cm]?[jt]sx?\b") + + +def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure: + """The mutants in `files` that the tests of the tree at top kill, as Stryker finds them there. One at a place its file doesn't + hold is left out. + + Stryker runs at top, with the Stryker config and the package.json there.""" + report = pathlib.Path(top, REPORT) + try: + ran = run([*in_diff_tools.STRYKER, "--mutate", ",".join(files), "--concurrency", str(jobs), "--reporters", "json"], top) + if isinstance(ran, Failure) or ran.code: + return ran if isinstance(ran, Failure) else failed("Stryker", ran) + reported = json.loads(report.read_bytes())["files"] + return [mutant for path in files if path in reported for mutant in file_mutants(path, reported[path])] + except (OSError, ValueError, KeyError, TypeError) as failure: + return Failure(f"could not read Stryker's report at {REPORT}: {failure}") + finally: + remove_report(report) + + +def remove_report(report: pathlib.Path) -> None: + """Remove Stryker's report, and the two folders Stryker made for it where they hold nothing else. Where the report can't be + removed, say so on stderr: it tells where each mutant is, and a bug's tree is a copy of this one.""" + try: + report.unlink(missing_ok=True) + except OSError as failure: + print(f"could not remove {report}: {failure}", file=sys.stderr) + with contextlib.suppress(OSError): + report.parent.rmdir() + report.parent.parent.rmdir() + + +def file_mutants(path: str, reported: dict) -> list[Mutant]: + """The killed mutants of the file at path, from what Stryker's report holds of it: the source Stryker read, and each mutant.""" + lines = reported["source"].encode().split(b"\n") + killed = [mutant for mutant in reported["mutants"] if mutant["status"] == "Killed"] + found = [(mutant, changed(mutant["location"], mutant["replacement"], lines)) for mutant in killed] + return [Mutant(path, lines_changed[0], f"{path}:{mutant['location']['start']['line']}:{mutant['location']['start']['column']} {mutant['mutatorName']}", lines_changed[1], lines_changed[2]) for mutant, lines_changed in found if lines_changed] + + +def changed(location: dict, replacement: str, lines: list[bytes]) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None: + """The lines a mutant changes; `lines` are its file's. Stryker's report gives the code the mutant puts in, and where the code it + replaces starts and ends: each a line and a column, both from 1, the end's column the first one after that code. Returned are + the number of the first line, those lines as the file has them, and what the mutant has in their place. None where the file + holds no such lines or columns.""" + start, end = location["start"], location["end"] + if not 1 <= start["line"] <= end["line"] <= len(lines) or (start["line"], start["column"]) > (end["line"], end["column"]): + return None + before, after = cut(lines[start["line"] - 1], start["column"]), cut(lines[end["line"] - 1], end["column"]) + if before is None or after is None: + return None + now = before[0] + replacement.encode() + after[1] + return start["line"], tuple(lines[start["line"] - 1:end["line"]]), tuple(now.split(b"\n")) + + +def cut(line: bytes, column: int) -> tuple[bytes, bytes] | None: + """A line's bytes before a column and from it on. Stryker counts a column in UTF-16 code units, as JavaScript counts a string's + length, so a character outside the Basic Multilingual Plane is two columns. None where the line holds no such column, or is not + UTF-8.""" + try: + units = line.decode().encode("utf-16-le") + at = 2 * (column - 1) + if not 0 <= at <= len(units): + return None + return units[:at].decode("utf-16-le").encode(), units[at:].decode("utf-16-le").encode() + except UnicodeError: + return None + + +def task_text(output: str) -> str | None: + """What Haiku is told of a planted bug: the error of the first failed test that has one in `node --test`'s list of failing + tests, without the test's name or file and without the stack, so it says what goes wrong and not which test shows it. + + None where the output lists no failing test with an error, as on a passing run, a file that fails to load or a reporter other + than spec, or where each error only names its test.""" + listed = f"\n{output}".partition(f"\n{FAILING_TESTS}\n")[2] + errors: list[tuple[str, list[str]]] = [] + within = False + for line in listed.splitlines(): + if test := TEST.match(line): + errors.append((test[1], [])) + within = True + elif TEST_PLACE.match(line) or STACK.match(line): + within = False + elif within: + errors[-1][1].append(line.strip()) + kept = (kept_lines(test, error) for test, error in errors) + return next(("\n".join(lines) for lines in kept if lines), None) + + +def kept_lines(test: str, error: list[str]) -> list[str]: + return [text for text in error if text and test not in text and not TEST_FILE.search(text)] -- 2.52.0 From 632023ed21165e337be54756926d969bac6082df Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 10:42:42 +0100 Subject: [PATCH 03/13] Sort the two planters' imports --- bin/task_bench/php_bugs.py | 2 +- bin/task_bench/typescript_bugs.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/task_bench/php_bugs.py b/bin/task_bench/php_bugs.py index 38c6ccee..7bd57360 100644 --- a/bin/task_bench/php_bugs.py +++ b/bin/task_bench/php_bugs.py @@ -5,10 +5,10 @@ import os import pathlib import re +from mutate_changes.tool_process import failed, remove, Run, scratch_folder from failure import Failure from mutate_changes import in_diff_tools from task_bench.planted_mutant import Mutant -from mutate_changes.tool_process import failed, remove, Run, scratch_folder # The heading of PHPUnit's list of the tests that failed, or of those that threw: `There were 3 failures:`. LISTED = re.compile(r"^There (?:was|were) \d+ (?:error|failure)s?:$") diff --git a/bin/task_bench/typescript_bugs.py b/bin/task_bench/typescript_bugs.py index e2641417..b407fc78 100644 --- a/bin/task_bench/typescript_bugs.py +++ b/bin/task_bench/typescript_bugs.py @@ -6,10 +6,10 @@ import pathlib import re import sys +from mutate_changes.tool_process import failed, Run from failure import Failure from mutate_changes import in_diff_tools from task_bench.planted_mutant import Mutant -from mutate_changes.tool_process import failed, Run # Where Stryker 10.1.1's json reporter writes, from the folder it runs in. Only the project's own Stryker config can set another # path, so the planter reads this one. -- 2.52.0 From 47084dc3dfa0e320127fde1515d504d3488a9ddb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 11:03:39 +0100 Subject: [PATCH 04/13] Test the planters' edges that mutants survived --- bin/task_bench/php_bugs.py | 8 +++++--- bin/task_bench/test_php_bugs.py | 6 ++++++ bin/task_bench/test_typescript_bugs.py | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/bin/task_bench/php_bugs.py b/bin/task_bench/php_bugs.py index 7bd57360..9543efe9 100644 --- a/bin/task_bench/php_bugs.py +++ b/bin/task_bench/php_bugs.py @@ -48,9 +48,11 @@ def planted(mutator: dict, diff: str, files: list[str]) -> Mutant | None: the longest of `files` that ends that path.""" logged = mutator["originalFilePath"] path = max((path for path in files if logged == path or logged.endswith(f"/{path}")), key=len, default=None) + if path is None: + return None start = mutator["originalStartLine"] - found = changed(diff, mutator["originalSourceCode"].split("\n"), start) if path else None - return Mutant(path, found[0], f"{path}:{start} {mutator['mutatorName']}", found[1], found[2]) if path and found else None + found = changed(diff, mutator["originalSourceCode"].split("\n"), start) + return Mutant(path, found[0], f"{path}:{start} {mutator['mutatorName']}", found[1], found[2]) if found else None def changed(diff: str, lines: list[str], start: int) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None: @@ -59,7 +61,7 @@ def changed(diff: str, lines: list[str], start: int) -> tuple[int, tuple[bytes, The diff's one hunk gives no line numbers. So the hunk's lines are found among `lines`, the file's, around `start`, the line Infection logs as the one the mutated code starts on. None where the diff holds no change, or where its lines stand around - `start` nowhere or more than once.""" + `start` nowhere or more than once, as do those of a diff with a second hunk.""" hunk = diff.partition("@@ @@\n")[2].split("\n") # An empty line of the file is an empty line of the hunk; any other line opens with a space, a minus or a plus. body = [(line[:1] if line[:1] in ("-", "+") else " ", line[1:]) for line in hunk] diff --git a/bin/task_bench/test_php_bugs.py b/bin/task_bench/test_php_bugs.py index 75513d82..deebb7da 100644 --- a/bin/task_bench/test_php_bugs.py +++ b/bin/task_bench/test_php_bugs.py @@ -145,6 +145,9 @@ class ChangedTest(unittest.TestCase): self.assertIsNone(changed("@@ @@\n \t{\n \t\t$sum = 0;", LINES, 10)) self.assertIsNone(changed("", LINES, 10)) + def test_is_none_where_the_diff_holds_a_second_hunk(self): + self.assertIsNone(changed(OPERATOR_DIFF + "\n@@ @@\n \t\t\t}\n-\t\t}\n+\t\t};\n \t\treturn $sum;", LINES, 15)) + def test_what_it_returns_plants_as_the_mutant(self): for diff, start in ((OPERATOR_DIFF, 12), (FOREACH_DIFF, 11), (TERNARY_DIFF, 21), (VISIBILITY_DIFF, 19)): with self.subTest(start=start): @@ -242,6 +245,9 @@ class TaskTextTest(unittest.TestCase): self.assertEqual(task_text(failing("Probe\\Tests\\PickTest::testNamesOne", *lines)), "got 3, want 5") self.assertEqual(task_text(failing("Probe\\Tests\\PickTest::testNamesOne with data set #0 (1, 'one')", *lines)), "got 3, want 5") + def test_reads_a_listed_test_that_names_no_class(self): + self.assertEqual(task_text(failing("testNamesOne", "got 3, want 5")), "got 3, want 5") + def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self): self.assertIsNone(task_text(failing("Probe\\Tests\\PickTest::testNamesOne", "testNamesOne failed", "", "/w/tests/PickTest.php:17"))) diff --git a/bin/task_bench/test_typescript_bugs.py b/bin/task_bench/test_typescript_bugs.py index 9939a0fe..4e5d7fb5 100644 --- a/bin/task_bench/test_typescript_bugs.py +++ b/bin/task_bench/test_typescript_bugs.py @@ -3,6 +3,8 @@ output tells Haiku. PICK's mutants and FAILING are what Stryker 10.1.1 and Node.js 24.19.0 wrote for a small project, the mutants with the keys the planter reads. The other mutants and outputs are made up in the same form.""" +import contextlib +import io import json import pathlib import sys @@ -130,6 +132,13 @@ class ChangedTest(unittest.TestCase): def test_a_replacement_of_more_lines_is_as_many_lines(self): self.assertEqual(changed(OPERATOR["location"], "item >\n\t\t\tfloor", LINES), (4, (LINES[3],), (b"\t\tif (item >", b"\t\t\tfloor) {"))) + def test_reaches_the_files_first_column_and_its_last_line(self): + self.assertEqual(changed(reported("M", "", (1, 1), (1, 8))["location"], "", LINES[:2]), (1, (LINES[0],), (LINES[0][7:],))) + self.assertEqual(changed(reported("M", "0", (2, 12), (2, 13))["location"], "0", LINES[:2]), (2, (LINES[1],), (LINES[1],))) + + def test_a_mutant_that_replaces_no_code_adds_its_own(self): + self.assertEqual(changed(reported("M", "!", (4, 7), (4, 7))["location"], "!", LINES), (4, (LINES[3],), (b"\t\tif (!item >= floor) {",))) + def test_counts_a_column_in_utf_16_code_units(self): now = 'export const tag = (n: number): string => "é😀" + (true ? "s" : "");'.encode() self.assertEqual(changed(AFTER_WIDE_TEXT["location"], "true", LINES), (11, (LINES[10],), (now,))) @@ -199,6 +208,15 @@ class KilledMutantsTest(unittest.TestCase): self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words")) self.assertFalse((self.top / "reports").exists()) + def test_says_on_stderr_only_that_it_could_not_remove_a_report(self): + def blocked(argv: list[str], cwd: str) -> Ran: + (self.top / "reports/mutation/mutation.json/held").mkdir(parents=True) + return Ran(0, "") + for run, said in ((self.stryker(None), ""), (blocked, f"could not remove {self.top}/reports/mutation/mutation.json: ")): + with self.subTest(said=said), contextlib.redirect_stderr(io.StringIO()) as stderr: + self.assertIsInstance(killed_mutants(str(self.top), ["src/pick.ts"], run, 1), Failure) + self.assertEqual(stderr.getvalue()[:len(said) or None], said) + def test_passes_on_a_run_that_could_not_start(self): failure = Failure("npx could not start: No such file or directory") self.assertIs(killed_mutants(str(self.top), ["src/pick.ts"], lambda argv, cwd: failure, 1), failure) -- 2.52.0 From 76de4fa497c94594220da8dec99aa3558e810adb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 11:42:20 +0100 Subject: [PATCH 05/13] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20findin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 874e417e27403f74ebaaa04b3c8a61a94a8cfe5b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 11:42:20 +0100 Subject: [PATCH 06/13] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1=20(0=20misread);=20run=20both?= =?UTF-8?q?=20tools=20in=20a=20scratch=20copy,=20read=20Infection's=20two?= =?UTF-8?q?=20sources,=20end=20PHPUnit's=20list,=20spell=20glob=20characte?= =?UTF-8?q?rs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/mutate_changes/in_diff_tools.py | 14 ++- bin/mutate_changes/test_mutate_changes.py | 14 ++- bin/task_bench/php_bugs.py | 85 +++++++------- bin/task_bench/scratch_copy.py | 24 ++++ bin/task_bench/test_php_bugs.py | 136 ++++++++++++---------- bin/task_bench/test_scratch_copy.py | 52 +++++++++ bin/task_bench/test_typescript_bugs.py | 68 +++++------ bin/task_bench/typescript_bugs.py | 44 +++---- 8 files changed, 268 insertions(+), 169 deletions(-) create mode 100644 bin/task_bench/scratch_copy.py create mode 100644 bin/task_bench/test_scratch_copy.py diff --git a/bin/mutate_changes/in_diff_tools.py b/bin/mutate_changes/in_diff_tools.py index 51938b63..2118459c 100644 --- a/bin/mutate_changes/in_diff_tools.py +++ b/bin/mutate_changes/in_diff_tools.py @@ -2,6 +2,7 @@ import json import os import pathlib +import re import typing from mutate_changes.changed_lines import by_folder, label, runs @@ -14,7 +15,7 @@ CARGO_FINISHED = frozenset({0, 2, 3}) CARGO_OUTCOMES = ("caught", "missed", "timeout", "unviable") INFECTION = "vendor/bin/infection" # the project's own, as Composer installs it # npx runs the project's own @stryker-mutator/core, else one an earlier npx run cached, and installs none. -STRYKER = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run"] +STRYKER_RUN = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run"] GREMLINS_UNKILLED = frozenset({"LIVED", "NOT COVERED"}) # What Gremlins v0.6.0 needs of the diff it reads from git: one run of lines per hunk is all it mutates, so a hunk holds the changed # lines and none around them, nor a neighbouring change; it takes each file's path after a b/; and it reads no colour codes. A user's git @@ -117,6 +118,13 @@ def outcome_lines(path: pathlib.Path) -> list[str]: # Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't # tell from a run that broke, so either fails the run. +def glob_escaped(path: str) -> str: + """A path as a glob that matches it. Stryker 10.1.1 reads each entry of --mutate as a glob, in which `app/[slug]/page.tsx` + matches `app/s/page.tsx` and not the file of that name. It reads a backslash as a slash, so no character can be escaped: a `?` + stands for each one a glob gives a meaning, and matches it.""" + return re.sub(r"[][!()*+@{}]", "?", path) + + def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: int) -> list[str] | Failure: """For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line naming the files with no package.json above them, if any. @@ -129,8 +137,8 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in if not os.path.isfile(os.path.join(top, folder, "package.json")): unplaced = sorted(files) continue - mutate = ",".join(f"{path}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines)) - ran = run([*STRYKER, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder)) + mutate = ",".join(f"{glob_escaped(path)}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines)) + ran = run([*STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder)) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else whole_output(f"Stryker in {label(folder)}", ran) report.extend([f"Stryker in {label(folder)}:", *ran.output.splitlines()]) diff --git a/bin/mutate_changes/test_mutate_changes.py b/bin/mutate_changes/test_mutate_changes.py index f214a5df..c84542fd 100644 --- a/bin/mutate_changes/test_mutate_changes.py +++ b/bin/mutate_changes/test_mutate_changes.py @@ -17,12 +17,12 @@ from mutate_changes.changed_lines import added_lines, by_folder, not_mutated, ru from mutate_changes.mutmut_tool import copy_files, Ended, Folder, mutate_folder, NO_MUTANT, reported from mutate_changes.mutmut_mutants import crash_in_mutmut, function_keys, mutant_globs, mutated_lines, named, statuses from failure import Failure +from mutate_changes.in_diff_tools import glob_escaped, run_stryker, with_plain_git_diff from mutate_changes.bare_imports import imported_by_file_name from test_env import isolated_env from mutate_changes.mutmut_setup import left_out, mutmut_config from mutate_changes import main from mutate_changes.tool_process import Ran, run_tool, scratch_folder -from mutate_changes.in_diff_tools import with_plain_git_diff SOURCE = "def double(n):\n\treturn n * 2\n\n\nclass Pt:\n\tdef moved(self, by=1):\n\t\treturn self.x + by\n" # The shape of the file mutmut 3 writes under mutants/: the original of each function and its mutants, with the original's lines. @@ -163,6 +163,18 @@ class InDiffTools(unittest.TestCase): self.assertEqual((env["GIT_CONFIG_COUNT"], env["GIT_CONFIG_KEY_0"], env["GIT_CONFIG_KEY_6"], "GIT_CONFIG_KEY_7" in env), ("7", "diff.context", "diff.interHunkContext", False)) + def test_a_path_goes_to_stryker_with_a_question_mark_for_each_character_a_glob_gives_a_meaning(self): + self.assertEqual(glob_escaped("app/[slug]/(shop)/{a}/b!c*d+e@f.tsx"), "app/?slug?/?shop?/?a?/b?c?d?e?f.tsx") + self.assertEqual(glob_escaped("src/pick-one_two.test.ts"), "src/pick-one_two.test.ts") + + def test_stryker_is_handed_a_changed_file_whose_path_holds_a_globs_characters_as_a_glob_that_matches_it(self): + with tempfile.TemporaryDirectory() as top: + pathlib.Path(top, "package.json").write_text("{}") + ran: list[list[str]] = [] + run_stryker(top, {"app/[slug]/page.tsx": frozenset({3, 4})}, lambda argv, cwd: ran.append(argv) or Ran(0, ""), 1) + self.assertEqual(ran[0][5:7], ["--mutate", "app/?slug?/page.tsx:3-4"]) + + class MutmutSetup(unittest.TestCase): def test_the_config_mutates_the_sources_and_copies_each_entry_of_the_folder(self): for existing in ("", "[mutmut]\nsource_paths = old.py\nalso_copy = old\n"): diff --git a/bin/task_bench/php_bugs.py b/bin/task_bench/php_bugs.py index 9543efe9..5c8627bb 100644 --- a/bin/task_bench/php_bugs.py +++ b/bin/task_bench/php_bugs.py @@ -1,17 +1,21 @@ -"""The bugs task-bench plants in PHP: Infection's killed mutants, each read from the diff in its JSON log, and the message PHPUnit -prints when a test fails on one.""" +"""The bugs task-bench plants in PHP: Infection's killed mutants, each read from the two sources in its JSON log, and the message +PHPUnit prints when a test fails on one.""" import json -import os import pathlib import re -from mutate_changes.tool_process import failed, remove, Run, scratch_folder +from mutate_changes.tool_process import failed, remove, Run from failure import Failure from mutate_changes import in_diff_tools from task_bench.planted_mutant import Mutant +from task_bench.scratch_copy import scratch_copy +# Where Infection writes its JSON log, from the copy's top. +LOG = "infection-log.json" # The heading of PHPUnit's list of the tests that failed, or of those that threw: `There were 3 failures:`. LISTED = re.compile(r"^There (?:was|were) \d+ (?:error|failure)s?:$") +# The heading of another list PHPUnit prints in the same form: `There was 1 risky test:`, `1 test triggered 1 deprecation:`. +OTHER_LIST = re.compile(r"^(?:There (?:was|were) \d+ |\d+ tests? triggered \d+ ).+:$") # A listed test, by its number in the list: `1) Probe\Tests\PickTest::testNamesOne`, or with ` with data set #0 (1, 'one')` after it. TEST = re.compile(r"^\d+\) (\S+)") # What ends a listed test's message: the file and line that failed, as `/w/tests/PickTest.php:12`, the line between the two @@ -21,65 +25,56 @@ TEST_FILE = re.compile(r"Test\.php\b") def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure: - """The mutants in `files` that the tests of the tree at top kill, as Infection finds them there. One whose diff doesn't fit the - source Infection logged with it is left out. + """The mutants in `files` that the tests of the tree at top kill, as Infection finds them in a copy of that tree. - Infection runs at top, with the Infection config and the vendor folder there.""" - scratch = scratch_folder(top) - if isinstance(scratch, Failure): - return scratch + Infection runs at the copy's top, with the Infection config there. It ends without an error whatever score that config + asks for, since the files' score is not the project's.""" + copied = scratch_copy(top) + if isinstance(copied, Failure): + return copied + scratch, copy = copied try: - log = pathlib.Path(scratch, "log.json") - ran = run([in_diff_tools.INFECTION, f"--filter={','.join(files)}", f"--threads={jobs}", "--no-progress", f"--logger-json={os.path.relpath(log, top)}"], top) + ran = run([in_diff_tools.INFECTION, f"--filter={','.join(files)}", f"--threads={jobs}", "--no-progress", "--min-msi=0", "--min-covered-msi=0", f"--logger-json={LOG}"], copy) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else failed("Infection", ran) - killed = [(logged["mutator"], logged["diff"]) for logged in json.loads(log.read_bytes())["killed"]] - return [mutant for mutator, diff in killed if (mutant := planted(mutator, diff, files))] - except (OSError, ValueError, KeyError, TypeError) as failure: - return Failure(f"could not read Infection's log in {scratch}: {failure}") + killed = [logged["mutator"] for logged in json.loads(pathlib.Path(copy, LOG).read_bytes())["killed"]] + return [mutant for mutator in killed if (mutant := planted(mutator, files))] + except (OSError, ValueError, KeyError, TypeError, AttributeError) as failure: + return Failure(f"could not read Infection's log, {LOG} in {copy}: {failure}") finally: remove(scratch) -def planted(mutator: dict, diff: str, files: list[str]) -> Mutant | None: - """A mutant of Infection's log as the lines it changes, or None where it is in none of `files` or `changed` finds no lines. +def planted(mutator: dict, files: list[str]) -> Mutant | None: + """A mutant of Infection's log as the lines it changes, or None where it is in none of `files` or doesn't change any line. - The log names a file by its whole path where Infection ran, which is another than top's where a container ran it. So the file is - the longest of `files` that ends that path.""" + The log names a file by its whole path where Infection ran. That path ends with the file's path from the top, and where it + ends with more than one of `files`, the longest is the file.""" logged = mutator["originalFilePath"] path = max((path for path in files if logged == path or logged.endswith(f"/{path}")), key=len, default=None) if path is None: return None - start = mutator["originalStartLine"] - found = changed(diff, mutator["originalSourceCode"].split("\n"), start) - return Mutant(path, found[0], f"{path}:{start} {mutator['mutatorName']}", found[1], found[2]) if found else None + found = changed(mutator["originalSourceCode"], mutator["mutatedSourceCode"]) + return Mutant(path, found[0], f"{path}:{mutator['originalStartLine']} {mutator['mutatorName']}", found[1], found[2]) if found else None -def changed(diff: str, lines: list[str], start: int) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None: - """The lines a mutant changes, from the diff Infection 0.35.12 logs for it: the number of the first, from 1, those lines as the - file has them, and what the mutant has in their place. An unchanged line between two changed ones is in both. - - The diff's one hunk gives no line numbers. So the hunk's lines are found among `lines`, the file's, around `start`, the line - Infection logs as the one the mutated code starts on. None where the diff holds no change, or where its lines stand around - `start` nowhere or more than once, as do those of a diff with a second hunk.""" - hunk = diff.partition("@@ @@\n")[2].split("\n") - # An empty line of the file is an empty line of the hunk; any other line opens with a space, a minus or a plus. - body = [(line[:1] if line[:1] in ("-", "+") else " ", line[1:]) for line in hunk] - at = [index for index, (kind, _) in enumerate(body) if kind != " "] - old = [text for kind, text in body if kind != "+"] - held = [first for first in range(max(start - len(old), 0), start) if lines[first:first + len(old)] == old] - if not at or len(held) != 1: +def changed(original: str, mutated: str) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None: + """The lines a mutant changes, from the file's source and the mutant's, both of which Infection 0.35.12 logs: the number of + the first line that differs, from 1, the file's lines from there to the last that differs, and what the mutant has in their + place. An unchanged line between two changed ones is in both. None where the two sources are the same.""" + was, now = original.split("\n"), mutated.split("\n") + if was == now: return None - span = body[at[0]:at[-1] + 1] - was = tuple(text.encode() for kind, text in span if kind != "+") - now = tuple(text.encode() for kind, text in span if kind != "-") - # Each line of the hunk before the first changed one is a line of the file. - return held[0] + at[0] + 1, was, now + shorter = min(len(was), len(now)) + first = next((index for index in range(shorter) if was[index] != now[index]), shorter) + after = next((count for count in range(shorter - first) if was[-1 - count] != now[-1 - count]), shorter - first) + return first + 1, tuple(line.encode() for line in was[first:len(was) - after]), tuple(line.encode() for line in now[first:len(now) - after]) def task_text(output: str) -> str | None: - """What Haiku is told of a planted bug: the message of the first test with one in PHPUnit's list of the tests that threw or - failed, without the test's name, class or file, so it says what goes wrong and not which test shows it. + """What Haiku is told of a planted bug: the message of the first test that has a message in PHPUnit's list of the tests that + threw or failed, without the test's name, class or file, so it says what goes wrong and not which test shows it. A test in + another of PHPUnit's lists, such as the risky tests, did not fail. None where PHPUnit lists no such test, as on a passing run, a file that fails to parse or a run with --testdox, or where each message only names its test.""" @@ -88,6 +83,8 @@ def task_text(output: str) -> str | None: for line in output.splitlines(): if LISTED.match(line): listing, within = True, False + elif OTHER_LIST.match(line): + listing = within = False elif listing and (test := TEST.match(line)): messages.append((test[1], [])) within = True diff --git a/bin/task_bench/scratch_copy.py b/bin/task_bench/scratch_copy.py new file mode 100644 index 00000000..1ce30b75 --- /dev/null +++ b/bin/task_bench/scratch_copy.py @@ -0,0 +1,24 @@ +"""A copy of a tree for a mutation tool to run in, so that what the tool writes there goes with the copy.""" +import os +import shutil + +from failure import Failure +from mutate_changes.tool_process import remove, scratch_folder + + +def scratch_copy(top: str) -> tuple[str, str] | Failure: + """A new scratch folder in top, and in it a copy of top's other entries, links kept as links: the two folders' paths. The + caller removes the scratch folder. + + A mutation tool leaves files where it runs: its cache, and each log the project's config asks for, which tells where every + mutant is. A bug's tree is a copy of top, so the tool runs in this copy and top stays as it was.""" + scratch = scratch_folder(top) + if isinstance(scratch, Failure): + return scratch + copy = os.path.join(scratch, "copy") + try: + shutil.copytree(top, copy, symlinks=True, ignore=lambda folder, names: [os.path.basename(scratch)] if folder == top else []) + except OSError as failure: + remove(scratch) + return Failure(f"could not copy {top} into {scratch}: {failure}") + return scratch, copy diff --git a/bin/task_bench/test_php_bugs.py b/bin/task_bench/test_php_bugs.py index deebb7da..edea21b7 100644 --- a/bin/task_bench/test_php_bugs.py +++ b/bin/task_bench/test_php_bugs.py @@ -1,7 +1,7 @@ -"""task-bench's PHP planter: which files Infection mutates, how its log's diffs become mutants and what PHPUnit's output tells Haiku. +"""task-bench's PHP planter: which files Infection mutates, how its log's mutants become lines and what PHPUnit's output tells Haiku. -PICK's diffs and FAILING are what Infection 0.35.12 and PHPUnit 12.5.45 wrote for a small project on PHP 8.5.13, and each logged -mutant holds the keys the planter reads. The other diffs and outputs are made up in the same form.""" +The four mutants of PICK and FAILING are what Infection 0.35.12 and PHPUnit 12.5.45 wrote for a small project on PHP 8.5.13. Each +logged mutant is cut down to the keys the planter reads. The other mutants and outputs are made up in the same form.""" import json import pathlib import sys @@ -42,29 +42,25 @@ final class Pick } """ LINES = PICK.split("\n") -OPERATOR_DIFF = "@@ @@\n \t{\n \t\t$sum = 0;\n \t\tforeach ($items as $item) {\n-\t\t\tif ($item >= $floor) {\n+\t\t\tif ($item > $floor) {\n \t\t\t\t$sum += $item;\n \t\t\t}\n \t\t}" + + +def with_lines(first: int, count: int, *now: str) -> str: + """PICK with `count` lines from line `first` on replaced by `now`: the mutated source Infection logged for such a mutant.""" + return "\n".join([*LINES[:first - 1], *now, *LINES[first - 1 + count:]]) + + +OPERATOR = with_lines(12, 1, "\t\t\tif ($item > $floor) {") # Infection prints the lines of a statement it rewrote with its own indent, and leaves the ones between them as they were. -FOREACH_DIFF = ( - "@@ @@\n \tpublic static function sum(array $items, int $floor): int\n \t{\n \t\t$sum = 0;\n-\t\tforeach ($items as $item) {\n-\t\t\tif ($item >= $floor) {\n" - "+\t\tforeach ([] as $item) {\n+ if ($item >= $floor) {\n \t\t\t\t$sum += $item;\n \t\t\t}\n-\t\t}\n+ }\n \t\treturn $sum;\n \t}" -) -TERNARY_DIFF = ( - "@@ @@\n\n \tpublic static function label(int $count): string\n \t{\n-\t\treturn $count === 1\n-\t\t\t? 'one item'\n-\t\t\t: $count . ' items';\n" - "+\t\treturn $count === 1 ? $count . ' items' : 'one item';\n \t}\n }" -) -# An empty line of the file stands in the diff without the space that opens an unchanged line. -VISIBILITY_DIFF = ( - "@@ @@\n \t\treturn $sum;\n \t}\n\n-\tpublic static function label(int $count): string\n+\tprotected static function label(int $count): string\n" - " \t{\n \t\treturn $count === 1\n \t\t\t? 'one item'" -) +FOREACH = with_lines(11, 5, "\t\tforeach ([] as $item) {", " if ($item >= $floor) {", "\t\t\t\t$sum += $item;", "\t\t\t}", " }") +TERNARY = with_lines(21, 3, "\t\treturn $count === 1 ? $count . ' items' : 'one item';") +VISIBILITY = with_lines(19, 1, "\tprotected static function label(int $count): string") OPERATOR_NOW = (b"\t\t\tif ($item > $floor) {",) -def logged(mutator: str, line: int, diff: str, path: str = "/w/src/Pick.php", source: str = PICK) -> dict: - return {"mutator": {"mutatorName": mutator, "originalSourceCode": source, "originalFilePath": path, "originalStartLine": line}, "diff": diff} +def logged(mutator: str, line: int, mutated_source: str, path: str = "/w/src/Pick.php", source: str = PICK) -> dict: + return {"mutator": {"mutatorName": mutator, "originalSourceCode": source, "mutatedSourceCode": mutated_source, "originalFilePath": path, "originalStartLine": line}} -# Three failed tests. FAILING = """PHPUnit 12.5.45 by Sebastian Bergmann and contributors. Runtime: PHP 8.5.13 @@ -116,45 +112,36 @@ def failing(test: str, *lines: str) -> str: class ChangedTest(unittest.TestCase): def test_is_the_line_an_operator_mutant_changes(self): - self.assertEqual(changed(OPERATOR_DIFF, LINES, 12), (12, (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW)) + self.assertEqual(changed(PICK, OPERATOR), (12, (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW)) def test_is_every_line_from_the_first_changed_one_to_the_last(self): was = tuple(line.encode() for line in LINES[10:15]) now = (b"\t\tforeach ([] as $item) {", b" if ($item >= $floor) {", b"\t\t\t\t$sum += $item;", b"\t\t\t}", b" }") - self.assertEqual(changed(FOREACH_DIFF, LINES, 11), (11, was, now)) + self.assertEqual(changed(PICK, FOREACH), (11, was, now)) def test_a_mutant_may_have_fewer_lines_than_it_replaces(self): was = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';") - self.assertEqual(changed(TERNARY_DIFF, LINES, 21), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",))) + self.assertEqual(changed(PICK, TERNARY), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",))) - def test_reads_an_empty_line_of_the_diff_as_an_unchanged_empty_line(self): - self.assertEqual(changed(VISIBILITY_DIFF, LINES, 19), (19, (b"\tpublic static function label(int $count): string",), (b"\tprotected static function label(int $count): string",))) + def test_a_mutant_may_only_remove_a_line_or_only_add_one(self): + self.assertEqual(changed("a\nb\nc", "a\nc"), (2, (b"b",), ())) + self.assertEqual(changed("a\nc", "a\nb\nc"), (2, (), (b"b",))) - def test_finds_the_lines_around_the_mutants_start_line_where_the_file_holds_them_twice(self): - twice = ["\t\t$a = 1;", "\t\treturn $a >= 2;", "\t}", "", "\t\t$a = 1;", "\t\treturn $a >= 2;", "\t}"] - diff = "@@ @@\n \t\t$a = 1;\n-\t\treturn $a >= 2;\n+\t\treturn $a > 2;\n \t}" - self.assertEqual(changed(diff, twice, 2), (2, (b"\t\treturn $a >= 2;",), (b"\t\treturn $a > 2;",))) - self.assertEqual(changed(diff, twice, 6), (6, (b"\t\treturn $a >= 2;",), (b"\t\treturn $a > 2;",))) + def test_a_line_counts_as_unchanged_before_the_change_or_after_it_never_both(self): + self.assertEqual(changed("a\nb\nb", "a\nb"), (3, (b"b",), ())) + self.assertEqual(changed("b\nb\nc", "b\nc"), (2, (b"b",), ())) - def test_is_none_where_the_diffs_lines_do_not_stand_around_the_start_line(self): - self.assertIsNone(changed(OPERATOR_DIFF, LINES, 20)) - self.assertIsNone(changed(OPERATOR_DIFF.replace("$sum = 0", "$sum = 1"), LINES, 12)) - self.assertIsNone(changed(OPERATOR_DIFF, LINES, 0)) + def test_reaches_the_first_line_and_the_last(self): + self.assertEqual(changed("a\nb", "c\nb"), (1, (b"a",), (b"c",))) + self.assertEqual(changed("a\nb", "a\nc"), (2, (b"b",), (b"c",))) - def test_is_none_where_the_diff_holds_no_change_or_no_hunk(self): - self.assertIsNone(changed("@@ @@\n \t{\n \t\t$sum = 0;", LINES, 10)) - self.assertIsNone(changed("", LINES, 10)) - - def test_is_none_where_the_diff_holds_a_second_hunk(self): - self.assertIsNone(changed(OPERATOR_DIFF + "\n@@ @@\n \t\t\t}\n-\t\t}\n+\t\t};\n \t\treturn $sum;", LINES, 15)) + def test_is_none_where_the_mutant_changes_no_line(self): + self.assertIsNone(changed(PICK, PICK)) def test_what_it_returns_plants_as_the_mutant(self): - for diff, start in ((OPERATOR_DIFF, 12), (FOREACH_DIFF, 11), (TERNARY_DIFF, 21), (VISIBILITY_DIFF, 19)): - with self.subTest(start=start): - line, was, now = changed(diff, LINES, start) - planted = mutated(PICK.encode(), Mutant("src/Pick.php", line, "a name", was, now)) - self.assertEqual(planted.split(b"\n")[line - 1], now[0]) - self.assertEqual(len(planted.split(b"\n")), len(LINES) - len(was) + len(now)) + for source in (OPERATOR, FOREACH, TERNARY, VISIBILITY): + line, was, now = changed(PICK, source) + self.assertEqual(mutated(PICK.encode(), Mutant("src/Pick.php", line, "a name", was, now)), source.encode()) class KilledMutantsTest(unittest.TestCase): @@ -162,28 +149,30 @@ class KilledMutantsTest(unittest.TestCase): folder = tempfile.TemporaryDirectory() self.addCleanup(folder.cleanup) self.top = pathlib.Path(folder.name) - self.ran: list[tuple[list[str], str]] = [] + (self.top / "src").mkdir() + (self.top / "src/Pick.php").write_text(PICK, encoding="utf-8") + self.ran: list[tuple[list[str], str, str]] = [] def infection(self, log: dict | str | None, code: int = 0): - """A run that writes Infection's log where its --logger-json names, or none where log is None.""" + """A run that writes Infection's log where its --logger-json names, or none where log is None, and another log beside it.""" def run(argv: list[str], cwd: str) -> Ran: - self.ran.append((argv, cwd)) + self.ran.append((argv, cwd, pathlib.Path(cwd, "src/Pick.php").read_text(encoding="utf-8"))) + pathlib.Path(cwd, "infection.html").write_text("every mutant", encoding="utf-8") if log is not None: path = next(argument.partition("=")[2] for argument in argv if argument.startswith("--logger-json=")) pathlib.Path(cwd, path).write_text(log if isinstance(log, str) else json.dumps(log), encoding="utf-8") return Ran(code, "the tool's last words\n") return run - def test_runs_infection_over_the_files_at_the_top_with_a_json_log_in_a_scratch_folder(self): + def test_runs_infection_over_the_files_in_a_copy_of_the_tree_with_a_json_log_and_no_score_to_reach(self): killed_mutants(str(self.top), ["src/Pick.php", "src/Last.php"], self.infection({"killed": []}), 3) - (argv, cwd), = self.ran - self.assertEqual(cwd, str(self.top)) - self.assertEqual(argv[:4], ["vendor/bin/infection", "--filter=src/Pick.php,src/Last.php", "--threads=3", "--no-progress"]) - self.assertRegex(argv[4], r"^--logger-json=\.mutate-changes-[^/]+/log\.json$") - self.assertEqual(len(argv), 5) + (argv, cwd, source), = self.ran + self.assertRegex(cwd, rf"^{self.top}/\.mutate-changes-[^/]+/copy$") + self.assertEqual(source, PICK) + self.assertEqual(argv, ["vendor/bin/infection", "--filter=src/Pick.php,src/Last.php", "--threads=3", "--no-progress", "--min-msi=0", "--min-covered-msi=0", "--logger-json=infection-log.json"]) def test_is_each_killed_mutant_as_the_lines_it_changes(self): - log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF), logged("Ternary", 21, TERNARY_DIFF)], "escaped": [logged("PublicVisibility", 19, VISIBILITY_DIFF)]} + log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR), logged("Ternary", 21, TERNARY)], "escaped": [logged("PublicVisibility", 19, VISIBILITY)]} found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1) ternary = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';") self.assertEqual(found, [ @@ -191,19 +180,23 @@ class KilledMutantsTest(unittest.TestCase): Mutant("src/Pick.php", 21, "src/Pick.php:21 Ternary", ternary, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)), ]) + def test_names_a_mutant_by_the_line_infection_logs_for_it(self): + found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": [logged("Foreach_", 11, FOREACH), logged("Ternary", 20, TERNARY)]}), 1) + self.assertEqual([(mutant.line, mutant.name) for mutant in found], [(11, "src/Pick.php:11 Foreach_"), (21, "src/Pick.php:20 Ternary")]) + def test_names_a_file_by_its_path_from_the_top_wherever_infection_saw_the_tree(self): - log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF, path) for path in ("/w/src/Pick.php", "src/Pick.php", "/w/lib/src/Pick.php", "/w/src/Other.php", "/w/src/NotPick.php")]} + log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR, path) for path in ("/w/src/Pick.php", "src/Pick.php", "/w/lib/src/Pick.php", "/w/src/Other.php", "/w/src/NotPick.php")]} found = killed_mutants(str(self.top), ["src/Pick.php", "lib/src/Pick.php", "Pick.php"], self.infection(log), 1) self.assertEqual([mutant.path for mutant in found], ["src/Pick.php", "src/Pick.php", "lib/src/Pick.php"]) - def test_leaves_out_a_mutant_whose_diff_does_not_fit_its_source(self): - log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF, source=" Ran: - self.ran.append((argv, cwd)) + self.ran.append((argv, cwd, pathlib.Path(cwd, "src/pick.ts").read_bytes())) + report = pathlib.Path(cwd, "reports/mutation/mutation.json") + report.parent.mkdir(parents=True) + pathlib.Path(cwd, "reports/stryker-incremental.json").write_text("every mutant", encoding="utf-8") if files is not None: - report = self.top / "reports/mutation/mutation.json" - report.parent.mkdir(parents=True) report.write_text(text if text is not None else json.dumps({"files": {path: {"source": PICK.decode(), "mutants": mutants} for path, mutants in files.items()}}), encoding="utf-8") return Ran(code, "the tool's last words\n") return run - def test_runs_stryker_over_the_files_at_the_top_with_its_json_reporter(self): + def test_runs_stryker_over_the_files_in_a_copy_of_the_tree_with_its_json_reporter(self): killed_mutants(str(self.top), ["src/pick.ts", "src/last.ts"], self.stryker({}), 3) - expected = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", "src/pick.ts,src/last.ts", "--concurrency", "3", "--reporters", "json"] - self.assertEqual(self.ran, [(expected, str(self.top))]) + (argv, cwd, source), = self.ran + self.assertEqual(argv, ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", "src/pick.ts,src/last.ts", "--concurrency", "3", "--reporters", "json"]) + self.assertRegex(cwd, rf"^{self.top}/\.mutate-changes-[^/]+/copy$") + self.assertEqual(source, PICK) + + def test_names_a_file_whose_path_holds_a_globs_characters_by_a_glob_that_matches_it(self): + killed_mutants(str(self.top), ["app/[slug]/page.tsx", "src/pick.ts"], self.stryker({}), 1) + self.assertEqual(self.ran[0][0][6], "app/?slug?/page.tsx,src/pick.ts") def test_is_each_killed_mutant_as_the_lines_it_changes(self): found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR, BLOCK]}), 1) @@ -193,29 +201,18 @@ class KilledMutantsTest(unittest.TestCase): found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files), 1) self.assertEqual([mutant.name for mutant in found], ["src/pick.ts:4:7 EqualityOperator"]) - def test_removes_the_report_and_the_folders_stryker_made_for_it(self): - killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}), 1) - self.assertEqual(list(self.top.iterdir()), []) + def test_leaves_the_tree_as_it_was_whatever_stryker_wrote(self): + for files in ({"src/pick.ts": [OPERATOR]}, None): + killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files, code=1), 1) + self.assertEqual(sorted(str(path.relative_to(self.top)) for path in self.top.rglob("*")), ["src", "src/pick.ts"]) - def test_keeps_a_reports_folder_that_holds_something_else(self): - (self.top / "reports").mkdir() - (self.top / "reports/coverage.txt").write_text("kept", encoding="utf-8") - killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}), 1) - self.assertEqual(sorted(str(path.relative_to(self.top)) for path in (self.top / "reports").rglob("*")), ["reports/coverage.txt"]) - - def test_fails_where_stryker_exits_nonzero_and_still_removes_the_report(self): + def test_reads_the_report_of_a_run_that_finished_under_the_score_its_config_asks_for(self): found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}, code=1), 1) - self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words")) - self.assertFalse((self.top / "reports").exists()) + self.assertEqual([mutant.name for mutant in found], ["src/pick.ts:4:7 EqualityOperator"]) - def test_says_on_stderr_only_that_it_could_not_remove_a_report(self): - def blocked(argv: list[str], cwd: str) -> Ran: - (self.top / "reports/mutation/mutation.json/held").mkdir(parents=True) - return Ran(0, "") - for run, said in ((self.stryker(None), ""), (blocked, f"could not remove {self.top}/reports/mutation/mutation.json: ")): - with self.subTest(said=said), contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsInstance(killed_mutants(str(self.top), ["src/pick.ts"], run, 1), Failure) - self.assertEqual(stderr.getvalue()[:len(said) or None], said) + def test_fails_where_stryker_exits_nonzero_without_a_report(self): + found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(None, code=1), 1) + self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words")) def test_passes_on_a_run_that_could_not_start(self): failure = Failure("npx could not start: No such file or directory") @@ -226,7 +223,12 @@ class KilledMutantsTest(unittest.TestCase): with self.subTest(text=text): found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files, text=text), 1) self.assertIsInstance(found, Failure) - self.assertIn("could not read Stryker's report at reports/mutation/mutation.json", found.reason) + self.assertIn("could not read Stryker's report, reports/mutation/mutation.json in ", found.reason) + + def test_fails_where_the_tree_cannot_be_copied(self): + found = killed_mutants(str(self.top / "missing"), ["src/pick.ts"], self.stryker({}), 1) + self.assertIsInstance(found, Failure) + self.assertEqual(self.ran, []) class TaskTextTest(unittest.TestCase): diff --git a/bin/task_bench/typescript_bugs.py b/bin/task_bench/typescript_bugs.py index b407fc78..f4aab212 100644 --- a/bin/task_bench/typescript_bugs.py +++ b/bin/task_bench/typescript_bugs.py @@ -1,20 +1,19 @@ """The bugs task-bench plants in TypeScript and JavaScript: Stryker's killed mutants, re-applied from its JSON report, and the error `node --test` prints when a test fails on one.""" -import contextlib import json import pathlib import re -import sys -from mutate_changes.tool_process import failed, Run +from mutate_changes.tool_process import failed, remove, Run from failure import Failure from mutate_changes import in_diff_tools from task_bench.planted_mutant import Mutant +from task_bench.scratch_copy import scratch_copy # Where Stryker 10.1.1's json reporter writes, from the folder it runs in. Only the project's own Stryker config can set another # path, so the planter reads this one. REPORT = "reports/mutation/mutation.json" -# The heading of `node --test`'s list of the failed tests, as its spec reporter prints it, each with its error. +# The heading of the list of failed tests that `node --test`'s spec reporter prints. Each test in it has its error. FAILING_TESTS = "✖ failing tests:" # Where a listed test stands, the line before its name: `test at src/pick.test.ts:5:1`. TEST_PLACE = re.compile(r"^test at \S+:\d+:\d+$") @@ -26,33 +25,28 @@ TEST_FILE = re.compile(r"\.(?:spec|test)\.[cm]?[jt]sx?\b") def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure: - """The mutants in `files` that the tests of the tree at top kill, as Stryker finds them there. One at a place its file doesn't - hold is left out. + """The mutants in `files` that the tests of the tree at top kill, as Stryker finds them in a copy of that tree. One at a place + its file doesn't hold is left out. - Stryker runs at top, with the Stryker config and the package.json there.""" - report = pathlib.Path(top, REPORT) + Stryker runs at the copy's top, with the Stryker config and the package.json there.""" + copied = scratch_copy(top) + if isinstance(copied, Failure): + return copied + scratch, copy = copied try: - ran = run([*in_diff_tools.STRYKER, "--mutate", ",".join(files), "--concurrency", str(jobs), "--reporters", "json"], top) - if isinstance(ran, Failure) or ran.code: + mutate = ",".join(in_diff_tools.glob_escaped(path) for path in files) + ran = run([*in_diff_tools.STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "json"], copy) + report = pathlib.Path(copy, REPORT) + # Stryker exits 1 too where it finished under the score the project's config sets as `thresholds.break`, which the files' + # score may be. Only a run that finished writes the report. + if isinstance(ran, Failure) or ran.code and not report.is_file(): return ran if isinstance(ran, Failure) else failed("Stryker", ran) reported = json.loads(report.read_bytes())["files"] return [mutant for path in files if path in reported for mutant in file_mutants(path, reported[path])] except (OSError, ValueError, KeyError, TypeError) as failure: - return Failure(f"could not read Stryker's report at {REPORT}: {failure}") + return Failure(f"could not read Stryker's report, {REPORT} in {copy}: {failure}") finally: - remove_report(report) - - -def remove_report(report: pathlib.Path) -> None: - """Remove Stryker's report, and the two folders Stryker made for it where they hold nothing else. Where the report can't be - removed, say so on stderr: it tells where each mutant is, and a bug's tree is a copy of this one.""" - try: - report.unlink(missing_ok=True) - except OSError as failure: - print(f"could not remove {report}: {failure}", file=sys.stderr) - with contextlib.suppress(OSError): - report.parent.rmdir() - report.parent.parent.rmdir() + remove(scratch) def file_mutants(path: str, reported: dict) -> list[Mutant]: @@ -93,7 +87,7 @@ def cut(line: bytes, column: int) -> tuple[bytes, bytes] | None: def task_text(output: str) -> str | None: - """What Haiku is told of a planted bug: the error of the first failed test that has one in `node --test`'s list of failing + """What Haiku is told of a planted bug: the error of the first test that has an error in `node --test`'s list of failing tests, without the test's name or file and without the stack, so it says what goes wrong and not which test shows it. None where the output lists no failing test with an error, as on a passing run, a file that fails to load or a reporter other -- 2.52.0 From ea4d2408b2c4f8dc8d6233faa32775f8d81dea6f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 11:42:20 +0100 Subject: [PATCH 07/13] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20say=20ho?= =?UTF-8?q?w=20the=20tools=20get=20their=20dependencies=20and=20which=20na?= =?UTF-8?q?mes=20count=20as=20tests,=20file=20item=20544?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/task_bench/main.py | 52 +++++++++++++++++++------------ bin/task_bench/test_task_bench.py | 4 +-- todo.md | 9 +++++- 3 files changed, 42 insertions(+), 23 deletions(-) diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index 935d77f0..7b799de0 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -14,17 +14,20 @@ origin's as last fetched, else main or master. Where --base names the head's own No model judges anything: the bench runs programs, and reads Haiku's own stream. - Plant. It copies the tree at the base and runs a mutation tool there, over the files that hold the places `larv-review places` - prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, mutmut 3 over - the Python files, as `mutmut run`, cargo-mutants over the Rust files, as `cargo mutants`, Infection over the PHP files, as - `vendor/bin/infection`, and Stryker over the TypeScript and JavaScript files, as `npx stryker run`. No other language is - planted in so far. Infection and Stryker run at the copy's top, with the project's config for the tool there. Stryker's json - reporter must write where it does by default, `reports/mutation/mutation.json`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of - them, 5 by default, have become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where, - planted at each side, a test fails and prints a message that says more than the test's name. The bench reads that message - from `go test`'s output for a Go file, from pytest's for a Python file, from `cargo test`'s for a Rust file, from PHPUnit's - for a PHP file and from `node --test`'s for a TypeScript or JavaScript file, so --test must run the tests of each language the - places name, with that runner: pytest as it prints by default, or with --tb=short, `cargo test` without --nocapture, PHPUnit - as it prints by default, and `node --test` with its spec reporter. Any other mutant is passed over, so a change to the very lines of a bug is not benched. + prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, Infection over the + PHP files, as `vendor/bin/infection`, mutmut 3 over the Python files, as `mutmut run`, cargo-mutants over the Rust files, as + `cargo mutants`, and Stryker over the TypeScript and JavaScript files, as `npx --no --package=@stryker-mutator/core stryker + run`, which runs the Stryker the project installs and downloads none. No other language is planted in so far. Infection and + Stryker each run at the top of a copy of that tree, with the project's config for the tool there, and the copy is removed + with all the tool wrote. Stryker's json reporter must write where it does by default, `reports/mutation/mutation.json`. + The bench takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of them, 5 by default, have + become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where, planted at each side, + a test fails and prints a message that says more than the test's name. The bench reads that message from `go test`'s output + for a Go file, from PHPUnit's for a PHP file, from pytest's for a Python file, from `cargo test`'s for a Rust file and from + `node --test`'s for a TypeScript or JavaScript file. So --test must run the tests of each language the places name, with + that runner: PHPUnit as it prints by default, pytest as it prints by default or with --tb=short, `cargo test` without + --nocapture, and `node --test --test-reporter=spec`. Any other mutant is passed over, so a change to the very lines of a + bug is not benched. - Run. Haiku fixes each bug --runs times at each side, 5 by default, the sides in turn. A fix starts from a copy of that side's tree with the bug in it, committed once, so git doesn't show which line the bug is on. In the copy, in a container, `claude -p --strict-mcp-config --disable-slash-commands --no-session-persistence --model claude-haiku-5-5 --effort low` works with every @@ -32,7 +35,10 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream. Claude home is new and empty, so the project's own CLAUDE.md, or AGENTS.md, in the copy is all the setup that loads. Its network reaches api.anthropic.com and nothing else. A fix ends after 30 minutes. - Check. The test command runs over the planted tree with each file that is no test as Haiku left it; a fix passes where it exits 0. - A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder. In a Rust file, each + A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder. The bench + tells a test by its path: a folder named `test`, `tests` or `__tests__`, or a file named `test_*.py`, `*_test.py`, + `*_test.go`, `*.test.*` or `*.spec.*`. A test of any other name counts as code, such as `src/PickTest.php` or + `src/pick-test.js`, so Haiku's change to it stands. In a Rust file, each inline `#[cfg(test)]` module stands as the planted file has it, and the rest is as Haiku left it. Where the planted file has such modules and Haiku's file lacks one of them, or its modules cannot be told apart, the planted file stands whole; where the planted file has none, or its modules cannot be told apart, Haiku's stands. A Rust mutant whose file's modules cannot be told apart, as where two share a name or a brace, string or comment @@ -43,11 +49,13 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream. so the image needs curl and bash; the result names the version. Haiku works in that image. So does --test: sh runs that text at the copy's top, with no network, so the image must hold what the tests would otherwise download. --prefix is shell text that runs the mutation tool, on the host, as mutate-changes' --prefix does: sh runs ` "$@"` with -the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins, -cargo-mutants, Infection and Stryker run in the copy of the base, and mutmut in a copy of the folder there that holds its settings; -$PWD is the folder the tool runs in. Without --prefix, the bench runs the `gremlins`, the `mutmut`, the `cargo` or the `npx` on -the host's PATH, or the copy's own `vendor/bin/infection`. For example, -for Go, for Python and then for Rust: +the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins and cargo-mutants +run in the copy of the base, Infection and Stryker in a copy of that copy, and mutmut in a copy of the folder there that holds +its settings; $PWD is the folder the tool runs in. That folder holds the files git tracks and no others, so for Infection and +Stryker the prefix first installs the project's dependencies there, as `composer install` and `npm ci` do. Infection also +needs PHP with a coverage driver, pcov or Xdebug. Without --prefix, the bench runs the `gremlins`, the `mutmut`, the `cargo` +or the `npx` on the host's PATH, or the tree's own `vendor/bin/infection`, which only a project that tracks `vendor` has. +For example, for Go, for Python, for Rust and then for TypeScript: docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \ sh -c 'shift; exec go run github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0 "$@"' sh @@ -57,6 +65,9 @@ for Go, for Python and then for Rust: docker run --rm --memory 16g --memory-swap 16g --user "$(id -u):$(id -g)" -e CARGO_HOME=/tmp/cargo -v "$PWD:$PWD" -w "$PWD" \ rust:1.100.0 sh -c 'cargo install --quiet --locked cargo-mutants@27.1.0 && exec "$@"' sh + docker run --rm --memory 16g --memory-swap 16g --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD:$PWD" -w "$PWD" \ + node:24.19.0-alpine3.24 sh -c 'npm ci --silent && exec "$@"' sh + Where the places name files in more than one language, the one prefix gets each tool's command, Gremlins' first and Stryker's last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`, `vendor/bin/infection`, `mutmut`, `cargo` or `npx`, as here for Go @@ -364,11 +375,12 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str]) def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure: - """What plans a bench of bugs: of the mutants the tests kill in the files of the tree at base that are in a language of plant's LANGUAGES and hold a place - in places, those --seed draws first become bugs, until --bugs of them have.""" + """What plans a bench of bugs. The bugs' files are those of the tree at base that hold a place in places and are in a language + of plant's LANGUAGES. Of the mutants the tests kill in those files, the ones --seed draws first become bugs, until --bugs of + them have.""" files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()] if not files: - return Failure("The places the seats found hard don't name any file that the base holds in a language the bench plants bugs in, so there is nowhere to plant a bug.") + return Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.") run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg) mutants = killed_mutants(base, files, run, CPUS_PER_SLOT) return mutants if isinstance(mutants, Failure) else functools.partial(planted_tasks, mutants=mutants, seed=int(given["--seed"]), bugs=int(given["--bugs"])) diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 5e0fa2ae..e6d60024 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -236,7 +236,7 @@ class BenchTest(unittest.TestCase): def test_the_command_line_fails_with_the_reason_where_the_places_or_the_bench_fail(self): argv = [part for name, value in self.given.items() for part in (name, value)] - for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any file that the base holds in a language the bench plants bugs in, so there is nowhere to plant a bug.\n")): + for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.\n")): with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as errors: self.assertEqual(main.main(argv, self.env, lambda home: places), 1) self.assertEqual((out.getvalue(), errors.getvalue().splitlines(keepends=True)[-1]), ("", said)) @@ -309,7 +309,7 @@ class BenchTest(unittest.TestCase): def test_fails_where_the_places_name_no_file_of_the_base_in_a_language_the_bench_plants_in(self): with contextlib.redirect_stderr(io.StringIO()): found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home) - self.assertEqual(found, Failure("The places the seats found hard don't name any file that the base holds in a language the bench plants bugs in, so there is nowhere to plant a bug.")) + self.assertEqual(found, Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.")) self.assertFalse(self.log.exists()) def test_fails_where_the_tests_fail_without_a_bug(self): diff --git a/todo.md b/todo.md index e5cdabae..1b62f0d5 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 544` +`Next ID = 545` ## Items @@ -23,6 +23,7 @@ | 538 | 0.17.0 | | | **Flag validation that checks a value other than the one the code goes on to use, such as before trimming, stripping or converting it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 | | 541 | 0.17.0 | | | **Find a Gitea pull request by its branch and head however many pull requests are newer, so `chunk-pr clean`, `chunk-pr merge` and `chunk-preflight` see an older one.** | 2 | 2 | 3 | 5 | 2 | 1 by 2 | 0.8 | | 539 | 0.17.0 | | | **Leave out of a `task-bench` fix a change Haiku makes to a Rust test kept in a file of its own.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 1 | 0.4 | +| 544 | 0.17.0 | | | **Leave out of a `task-bench` fix a change Haiku makes to a PHP or JavaScript test that PHPUnit or `node --test` finds by a name `is_test` does not know.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 1 | 0.4 | | 480 | 0.18.0 | | owner | **Resolve every path the tools use in one module: the release root (the folder the running code ships in), the config folder, the state folder and the Claude home. Then only that module names `~/.claude`, and the loop still runs from `~/.claude`.** | 3 | 2 | 3 | 6 | 6 | 1.6 by 3, code health by 3 | 2.4 | | 481 | 0.18.0 | 480 | owner | **Put the release's tools on `PATH` for every session the loop starts and every hook it runs, name them bare in the prose in place of `~/.claude/bin/`, and refuse the old spelling in new prose.** | 3 | 2 | 3 | 6 | 6 | 1.4 by 2, code health by 2 | 1.6 | | 482 | 0.19.0 | 478, 481 | owner | **Install the setup with `uv tool install` from a release tag, with `do-release` and `do-epic` on `PATH`, and replace `deploy-release` with `do-release self-update`.** | 3 | 2 | 3 | 6 | 7 | 1.6 by 4, 1.3 by 3 | 1.3 | @@ -219,6 +220,12 @@ Touches: - `bin/task_bench/test_task_bench.py` - `bin/task_bench/main.py`: lines 30-37 +### 544. Leave out of a `task-bench` fix a change Haiku makes to a PHP or JavaScript test that PHPUnit or `node --test` finds by a name `is_test` does not know. + +PHPUnit finds a test by `*Test.php`, wherever it stands, and `node --test` also by `*-test.js`, `*_test.js`, `test-*.js` and `test.js`, with `.ts`, `.mjs` and `.cjs` alike. `mutate_changes.changed_lines.is_test` tells a test by a folder named `test`, `tests` or `__tests__`, or by a name such as `*.test.*`, so `src/PickTest.php` and `src/pick-test.js` count as code. `checked_tree` in `bin/task_bench/runs.py` then takes such a file as Haiku left it, so a fix that edits or deletes the failing test passes, at both sides alike, and `place_files` in `bin/task_bench/plant.py` may hand the file to the mutation tool as code. The help's Check paragraph says so. + +Recommended: tell these names as tests inside task-bench, for a `.php` file and for the suffixes Stryker covers, and keep `is_test` as it is, since changing it would change what `mutate-changes` skips; item 539 does the same for Rust. A product-owner finding on item 527's chunk raised this. + ### 480. Resolve every path the tools use in one module: the release root (the folder the running code ships in), the config folder, the state folder and the Claude home. Then only that module names `~/.claude`, and the loop still runs from `~/.claude`. Part of the standalone-install plan lilleman approved on 2026-11-20. `do-release` and `do-epic` stand for the names item 478 picks. Today about 160 references in some 40 modules name `~/.claude`; `bin/loop_state/paths.py` holds a few. This item changes no behaviour. -- 2.52.0 From 014d085f2657b86df0735947d60f8d868f3ff72e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 11:42:20 +0100 Subject: [PATCH 08/13] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1=20(0=20misread);=20reworded=20?= =?UTF-8?q?in=20the=20two=20answers=20before=20this=20one?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 8b1c9ff1842d380b7cb0f50319a269f287f066f4 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 11:45:36 +0100 Subject: [PATCH 09/13] Fail the scratch copy's test on a socket, not a patched function --- bin/task_bench/test_scratch_copy.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/bin/task_bench/test_scratch_copy.py b/bin/task_bench/test_scratch_copy.py index f5524866..6580dcad 100644 --- a/bin/task_bench/test_scratch_copy.py +++ b/bin/task_bench/test_scratch_copy.py @@ -1,10 +1,10 @@ """The copy of a tree that a mutation tool runs in.""" import os import pathlib +import socket import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -40,11 +40,14 @@ class ScratchCopyTest(unittest.TestCase): self.assertTrue(os.path.isdir(os.path.join(copy, "src", os.path.basename(first)))) def test_fails_without_a_scratch_folder_left_where_the_tree_cannot_be_copied(self): - with unittest.mock.patch("shutil.copytree", side_effect=OSError("No space left on device")): - found = scratch_copy(str(self.top)) + # A socket is an entry that no copy can read. + held = socket.socket(socket.AF_UNIX) + self.addCleanup(held.close) + held.bind(str(self.top / "held")) + found = scratch_copy(str(self.top)) self.assertIsInstance(found, Failure) - self.assertRegex(found.reason, rf"^could not copy {self.top} into {self.top}/\.mutate-changes-[^/]+: No space left on device$") - self.assertEqual(sorted(path.name for path in self.top.iterdir()), [".hidden", "src"]) + self.assertRegex(found.reason, rf"^could not copy {self.top} into {self.top}/\.mutate-changes-[^/]+: ") + self.assertEqual(sorted(path.name for path in self.top.iterdir()), [".hidden", "held", "src"]) def test_passes_on_that_no_scratch_folder_could_be_made(self): found = scratch_copy(str(self.top / "missing")) -- 2.52.0 From 794adafb919078e07deec8cede063d539964875f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 12:08:55 +0100 Subject: [PATCH 10/13] Leave the scratch folder out of its own copy by name --- bin/task_bench/scratch_copy.py | 2 +- bin/task_bench/test_scratch_copy.py | 6 ------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/bin/task_bench/scratch_copy.py b/bin/task_bench/scratch_copy.py index 1ce30b75..88ade56a 100644 --- a/bin/task_bench/scratch_copy.py +++ b/bin/task_bench/scratch_copy.py @@ -17,7 +17,7 @@ def scratch_copy(top: str) -> tuple[str, str] | Failure: return scratch copy = os.path.join(scratch, "copy") try: - shutil.copytree(top, copy, symlinks=True, ignore=lambda folder, names: [os.path.basename(scratch)] if folder == top else []) + shutil.copytree(top, copy, symlinks=True, ignore=shutil.ignore_patterns(os.path.basename(scratch))) except OSError as failure: remove(scratch) return Failure(f"could not copy {top} into {scratch}: {failure}") diff --git a/bin/task_bench/test_scratch_copy.py b/bin/task_bench/test_scratch_copy.py index 6580dcad..3d85d2cb 100644 --- a/bin/task_bench/test_scratch_copy.py +++ b/bin/task_bench/test_scratch_copy.py @@ -33,12 +33,6 @@ class ScratchCopyTest(unittest.TestCase): _, copy = scratch_copy(str(self.top)) self.assertEqual(os.readlink(os.path.join(copy, "linked")), "src/missing.ts") - def test_copies_a_folder_below_the_top_that_has_the_scratch_folders_name(self): - first, _ = scratch_copy(str(self.top)) - (self.top / "src" / os.path.basename(first)).mkdir() - _, copy = scratch_copy(str(self.top)) - self.assertTrue(os.path.isdir(os.path.join(copy, "src", os.path.basename(first)))) - def test_fails_without_a_scratch_folder_left_where_the_tree_cannot_be_copied(self): # A socket is an entry that no copy can read. held = socket.socket(socket.AF_UNIX) -- 2.52.0 From 87f168c4c959ac1dc930d78587e7cd0e1b7bc360 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 12:35:53 +0100 Subject: [PATCH 11/13] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20drop=20a=20?= =?UTF-8?q?report=20the=20tree=20held=20before=20the=20run,=20move=20a=20c?= =?UTF-8?q?omment=20back=20to=20its=20function?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/mutate_changes/in_diff_tools.py | 4 ++-- bin/task_bench/test_typescript_bugs.py | 8 +++++++- bin/task_bench/typescript_bugs.py | 4 +++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/bin/mutate_changes/in_diff_tools.py b/bin/mutate_changes/in_diff_tools.py index 2118459c..ce675b59 100644 --- a/bin/mutate_changes/in_diff_tools.py +++ b/bin/mutate_changes/in_diff_tools.py @@ -116,8 +116,6 @@ def outcome_lines(path: pathlib.Path) -> list[str]: return path.read_text(encoding="utf-8", errors="replace").splitlines() if path.is_file() else [] -# Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't -# tell from a run that broke, so either fails the run. def glob_escaped(path: str) -> str: """A path as a glob that matches it. Stryker 10.1.1 reads each entry of --mutate as a glob, in which `app/[slug]/page.tsx` matches `app/s/page.tsx` and not the file of that name. It reads a backslash as a slash, so no character can be escaped: a `?` @@ -125,6 +123,8 @@ def glob_escaped(path: str) -> str: return re.sub(r"[][!()*+@{}]", "?", path) +# Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't +# tell from a run that broke, so either fails the run. def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: int) -> list[str] | Failure: """For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line naming the files with no package.json above them, if any. diff --git a/bin/task_bench/test_typescript_bugs.py b/bin/task_bench/test_typescript_bugs.py index bd7d1c00..86038c69 100644 --- a/bin/task_bench/test_typescript_bugs.py +++ b/bin/task_bench/test_typescript_bugs.py @@ -167,7 +167,7 @@ class KilledMutantsTest(unittest.TestCase): def run(argv: list[str], cwd: str) -> Ran: self.ran.append((argv, cwd, pathlib.Path(cwd, "src/pick.ts").read_bytes())) report = pathlib.Path(cwd, "reports/mutation/mutation.json") - report.parent.mkdir(parents=True) + report.parent.mkdir(parents=True, exist_ok=True) pathlib.Path(cwd, "reports/stryker-incremental.json").write_text("every mutant", encoding="utf-8") if files is not None: report.write_text(text if text is not None else json.dumps({"files": {path: {"source": PICK.decode(), "mutants": mutants} for path, mutants in files.items()}}), encoding="utf-8") @@ -214,6 +214,12 @@ class KilledMutantsTest(unittest.TestCase): found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(None, code=1), 1) self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words")) + def test_reads_no_report_that_the_tree_held_before_the_run(self): + (self.top / "reports/mutation").mkdir(parents=True) + (self.top / "reports/mutation/mutation.json").write_text(json.dumps({"files": {"src/pick.ts": {"source": PICK.decode(), "mutants": [OPERATOR]}}}), encoding="utf-8") + found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(None, code=1), 1) + self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words")) + def test_passes_on_a_run_that_could_not_start(self): failure = Failure("npx could not start: No such file or directory") self.assertIs(killed_mutants(str(self.top), ["src/pick.ts"], lambda argv, cwd: failure, 1), failure) diff --git a/bin/task_bench/typescript_bugs.py b/bin/task_bench/typescript_bugs.py index f4aab212..762e132f 100644 --- a/bin/task_bench/typescript_bugs.py +++ b/bin/task_bench/typescript_bugs.py @@ -35,8 +35,10 @@ def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Muta scratch, copy = copied try: mutate = ",".join(in_diff_tools.glob_escaped(path) for path in files) - ran = run([*in_diff_tools.STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "json"], copy) report = pathlib.Path(copy, REPORT) + # A report the project tracks would otherwise stand for this run's. + report.unlink(missing_ok=True) + ran = run([*in_diff_tools.STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "json"], copy) # Stryker exits 1 too where it finished under the score the project's config sets as `thresholds.break`, which the files' # score may be. Only a run that finished writes the report. if isinstance(ran, Failure) or ran.code and not report.is_file(): -- 2.52.0 From c259d5fbb24a9e40862e24b8867e148c9eb30bae Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 12:38:47 +0100 Subject: [PATCH 12/13] Finish item 527 in the plan --- CHANGELOG.md | 1 + todo.md | 14 -------------- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a53cab5a..a4523770 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `task-bench` plants bugs in TypeScript and JavaScript, from the mutants Stryker reports as killed, and reads the task it gives from the error `node --test` prints. - Testing principles now say that a test scanning rows for an exception asserts the exception exists, and that a data importer does not drop a row its own fixups complete. - task-bench leaves out of a fix a change Haiku makes to a Rust test module that stands in the file of the code it tests, and passes over a Rust mutant whose test modules it cannot tell apart. - loop-claude starts a chunk on a fresh session where its session's transcript is empty, in place of resuming a session claude cannot find, which failed three times and waited for the human. diff --git a/todo.md b/todo.md index 1b62f0d5..31d7959b 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 527 | 0.16.0 | | owner | **Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 | | 528 | 0.16.0 | | owner | **Plant bugs for `task-bench` in PHP, from the mutants Infection kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 | | 525 | 0.16.0 | | owner | **Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 7 | 1.1 by 3 | 0.3 | | 477 | 0.17.0 | | question | **Rewrite `## Goals` and `## Audience` for a setup others install and run apart from their own `~/.claude`.** | 1 | 1 | 2 | 2 | 2 | | 0.0 | @@ -113,19 +112,6 @@ ## Details -### 527. Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills. - -Stryker runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from its JSON report. Tell Haiku the failure the project's test runner prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no TypeScript. - -Touches: -- `bin/task_bench/typescript_bugs.py` -- `bin/task_bench/test_typescript_bugs.py` -- `bin/task_bench/plant.py`: `LANGUAGES` -- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest` -- `bin/mutate_changes/in_diff_tools.py`: `run_stryker` -- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner` -- `README.md`: lines 231-231, lines 281-281 - ### 528. Plant bugs for `task-bench` in PHP, from the mutants Infection kills. Infection runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from its JSON log. Tell Haiku the failure PHPUnit prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no PHP. -- 2.52.0 From 79ae24abf4a7e7044d835bd951fffaee883c11c5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 12:38:48 +0100 Subject: [PATCH 13/13] Finish item 528 in the plan --- CHANGELOG.md | 1 + todo.md | 14 -------------- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4523770..8aa1d128 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `task-bench` plants bugs in PHP, from the mutants Infection logs as killed, and reads the task it gives from the message PHPUnit prints. - `task-bench` plants bugs in TypeScript and JavaScript, from the mutants Stryker reports as killed, and reads the task it gives from the error `node --test` prints. - Testing principles now say that a test scanning rows for an exception asserts the exception exists, and that a data importer does not drop a row its own fixups complete. - task-bench leaves out of a fix a change Haiku makes to a Rust test module that stands in the file of the code it tests, and passes over a Rust mutant whose test modules it cannot tell apart. diff --git a/todo.md b/todo.md index 31d7959b..5ee32b6d 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 528 | 0.16.0 | | owner | **Plant bugs for `task-bench` in PHP, from the mutants Infection kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 | | 525 | 0.16.0 | | owner | **Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 7 | 1.1 by 3 | 0.3 | | 477 | 0.17.0 | | question | **Rewrite `## Goals` and `## Audience` for a setup others install and run apart from their own `~/.claude`.** | 1 | 1 | 2 | 2 | 2 | | 0.0 | | 478 | 0.17.0 | | question | **Name the project, its repo and its two commands, today proposed as `do-release` and `do-epic`.** | 1 | 1 | 2 | 2 | 1 | | 0.0 | @@ -112,19 +111,6 @@ ## Details -### 528. Plant bugs for `task-bench` in PHP, from the mutants Infection kills. - -Infection runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from its JSON log. Tell Haiku the failure PHPUnit prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no PHP. - -Touches: -- `bin/task_bench/php_bugs.py` -- `bin/task_bench/test_php_bugs.py` -- `bin/task_bench/plant.py`: `LANGUAGES` -- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest` -- `bin/mutate_changes/in_diff_tools.py`: `run_infection` -- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner` -- `README.md`: lines 231-231, lines 281-281 - ### 525. Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names. The second part of item 505, which says what a source-data task is and when a run counts. The country code of each comes from ISO 3166-1's user-assigned range (AA, QM–QZ, XA–XZ, ZZ), leaving out XK, which the EU and others use for Kosovo, so no task meets real data. Each register has the quirks real ones publish. -- 2.52.0