@srobroek/pi-code-quality 0.0.0-stage → 0.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +191 -0
  2. package/LICENSE +202 -0
  3. package/README.md +150 -2
  4. package/agents/adversarial-challenger.md +29 -0
  5. package/extensions/quality.js +4583 -0
  6. package/package.json +40 -4
  7. package/skills/prototype-logic/LICENSE +21 -0
  8. package/skills/prototype-logic/NOTICE +26 -0
  9. package/skills/prototype-logic/SKILL.md +76 -0
  10. package/skills/quality-code-design/LICENSE-mattpocock-skills +21 -0
  11. package/skills/quality-code-design/NOTICE +63 -0
  12. package/skills/quality-code-design/SKILL.md +63 -0
  13. package/skills/quality-code-design/references/contracts.md +37 -0
  14. package/skills/quality-code-design/references/debugging.md +85 -0
  15. package/skills/quality-code-design/references/deep-modules.md +67 -0
  16. package/skills/quality-code-design/references/dependencies.md +81 -0
  17. package/skills/quality-code-design/references/encapsulation.md +148 -0
  18. package/skills/quality-code-design/references/feature-flags.md +189 -0
  19. package/skills/quality-code-design/references/go.md +110 -0
  20. package/skills/quality-code-design/references/lifecycle.md +66 -0
  21. package/skills/quality-code-design/references/middleware.md +55 -0
  22. package/skills/quality-code-design/references/other-paradigms.md +44 -0
  23. package/skills/quality-code-design/references/persistence.md +52 -0
  24. package/skills/quality-code-design/references/python.md +100 -0
  25. package/skills/quality-code-design/references/release.md +59 -0
  26. package/skills/quality-code-design/references/review.md +121 -0
  27. package/skills/quality-code-design/references/rust.md +140 -0
  28. package/skills/quality-code-design/references/safe-mutation.md +33 -0
  29. package/skills/quality-code-design/references/security.md +65 -0
  30. package/skills/quality-code-design/references/simplicity.md +165 -0
  31. package/skills/quality-code-design/references/solid.md +165 -0
  32. package/skills/quality-code-design/references/supporting-principles.md +78 -0
  33. package/skills/quality-code-design/references/telemetry.md +54 -0
  34. package/skills/quality-code-design/references/test-first.md +78 -0
  35. package/skills/quality-code-design/references/typescript.md +93 -0
  36. package/skills/quality-code-design/references/verification.md +53 -0
  37. package/skills/quality-code-policy/SKILL.md +34 -0
  38. package/skills/quality-profiling/SKILL.md +48 -0
  39. package/skills/quality-profiling/references/hygiene.md +27 -0
  40. package/skills/quality-profiling/references/reading-profiles.md +21 -0
  41. package/skills/quality-profiling/references/system.md +51 -0
  42. package/skills/quality-test-audit/SKILL.md +122 -0
  43. package/skills/quality-test-audit/references/catalog.md +108 -0
  44. package/skills/quality-test-audit/references/evidence.md +123 -0
  45. package/skills/quality-test-audit/references/report.md +75 -0
  46. package/skills/quality-testing/SKILL.md +62 -0
  47. package/skills/quality-testing/references/bad-tests.md +258 -0
  48. package/skills/quality-testing/references/doubles.md +49 -0
  49. package/skills/quality-testing/references/good-tests.md +90 -0
  50. package/skills/quality-testing/references/maintenance.md +96 -0
  51. package/skills/quality-testing/references/review-tests.md +72 -0
  52. package/skills/quality-testing/references/shared-contracts.md +30 -0
  53. package/skills/quality-testing/references/signals.md +50 -0
  54. package/skills/quality-testing/references/test-budget.md +81 -0
  55. package/skills/quality-testing/references/what-to-test.md +58 -0
@@ -0,0 +1,53 @@
1
+ # Verification proportional to risk
2
+
3
+ Read when selecting tests or making verification or performance claims. Follow required project gates and the worker/lead division of verification responsibility. Hard bugs: [debugging.md](debugging.md). Test-first loop: [test-first.md](test-first.md). Test strategy in depth (levels, test budget, maintenance, doubles, flaky tests, test data, reviewing test changes): the `quality-testing` skill.
4
+
5
+ ## Acceptance and independent expectations
6
+
7
+ **Do:** derive checks from the requested behavior, contracts, and credible failures. Cover relevant boundaries, errors, and preserved behavior.
8
+ **Do not:** copy the implementation into the expected result, weaken an assertion to match generated behavior, or call an unavailable check a pass.
9
+
10
+ Bad: a rounding bug is "fixed" by changing the test's expected total to the new output.
11
+ Good: establish the rounding contract independently, add the disputed input, and compare the old and new behavior against that contract.
12
+
13
+ **Exception:** a check can require inaccessible production data, hardware, or timing. Use the best available trace or focused experiment, state its limit, and identify the missing evidence. Do not fabricate a result or block a harmless edit on unrelated infrastructure.
14
+
15
+ ## Fidelity and maintenance cost
16
+
17
+ **Do:** choose the smallest reliable check that can detect the failure. Use pure/unit tests for domain rules, real adapter/database checks for integration semantics, and a few end-to-end checks for critical journeys. Consider speed, maintainability, resource use, reliability, and fidelity together.
18
+ **Do not:** impose fixed test ratios or coverage quotas, or mock away the behavior at issue.
19
+
20
+ Bad: test a lost-update fix by mocking `save()` and asserting one call.
21
+ Good: exercise the relevant transaction/concurrency behavior against the database or a validated equivalent, while keeping pure calculations in small deterministic tests.
22
+
23
+ Bad: snapshot private helper call order, then rewrite snapshots after every behavior-preserving refactor.
24
+ Good: assert the public result, failure semantics, and meaningful side effects. Use real implementations when practical, validated fakes when needed, and mocks for specific otherwise hard-to-trigger conditions.
25
+
26
+ **Exception:** an injected timeout or provider failure can justify a mock. Contract-check a maintained fake where drift would conceal defects; do not demand live external calls in every test.
27
+
28
+ ## Choose additional techniques by the risk
29
+
30
+ **Do:** use property tests for invariants over varied inputs, fuzzing for parsers/untrusted formats, concurrency tests for ordering/atomicity, and mutation testing when ordinary tests fail to discriminate incorrect behavior.
31
+ **Do not:** install all of these techniques merely because code was written by an agent.
32
+
33
+ Bad: add an integration-test framework to a simple Bash file renamer.
34
+ Good: check quoting, spaces, collisions, exit status, and a representative temporary-directory run using the project's existing tools.
35
+
36
+ **Exception:** a small script with destructive effects needs stronger verification of those effects; keep the implementation simple while checking the actual risk.
37
+
38
+ ## User behavior and performance
39
+
40
+ **Do:** verify the changed interaction and relevant accessibility behavior for user-facing work. Support performance claims with a representative workload, baseline, environment, and observed result.
41
+ **Do not:** infer usability from compilation, or claim a speedup from code appearance or one noisy timing.
42
+
43
+ Bad: a keyboard-navigation change passes typecheck and is declared verified.
44
+ Good: exercise the affected focus path and supported controls, using available automated checks plus a targeted interaction check where required.
45
+
46
+ Bad: replace a readable implementation because it "looks slow."
47
+ Good: measure the affected path, identify the bottleneck, and compare behavior and resource cost after the change.
48
+
49
+ **Exception:** a security or correctness fix can proceed without a benchmark when it makes no performance claim. State an unavailable runtime check as an evidence gap.
50
+
51
+ Completion claims: report only checks run against the current head; release-state wording (merged, deployed, observed) is in [release.md](release.md).
52
+
53
+ Sources: [Google SMURF testing tradeoffs](https://testing.googleblog.com/2024/10/smurf-beyond-test-pyramid.html), [test fidelity and doubles](https://testing.googleblog.com/2024/02/increase-test-fidelity-by-avoiding-mocks.html), and [Software Engineering at Google on unit tests](https://abseil.io/resources/swe-book/html/ch12.html). These support contextual test selection, not universal test quotas.
@@ -0,0 +1,34 @@
1
+ ---
2
+ name: quality-code-policy
3
+ description: "Code policy: SOLID, DRY, tests, research-first reuse of standard libraries, middleware, OTel; load before code changes."
4
+ ---
5
+
6
+ # Maintainable code
7
+
8
+ MUST Load the `quality-code-design` skill (and only its task-relevant references) for adding new behavior or a capability, a refactor, a hard bug whose root cause remains unclear after reading the failure, or a code review. Small edits, mechanical changes, test-only fixes, config, docs and command runs do not need it. Read-only roles stay read-only.
9
+
10
+ MUST Prioritize SOLID, encapsulation, and protected invariants over YAGNI when they protect a real responsibility or boundary, using the language's own idioms. A library, ORM, or boundary with one consumer is justified when it reduces present total complexity; consumer count alone decides nothing.
11
+
12
+ MUST Apply DRY to knowledge that must change together, not to code that merely looks alike. Revisit structure whenever behavior changes.
13
+
14
+ MUST Use OpenFeature through one flag module with one provider over flags.yaml, SSM or AppConfig, chosen by need; ask before writing a missing provider. Decide once at the request or job edge and default to existing behavior. Libraries take caller decisions; plugins keep harness-specific options. See `quality-code-design`'s `feature-flags.md`.
15
+
16
+ MUST Before designing or writing code for a concern, research current best practice (official docs, Context7 when configured for the project, or the web) and compare the plan with the preferred-library standards: `lang-<language>-libraries`, `toolchain-api` for API styles, `aws-guidance` for AWS projects' Lambda and service-client work, else `toolchain-languages`. Prefer the repository's code, the standard library, the framework's features, then a listed library; write your own only for a named gap, and report each departure from a standard. A dependency the request did not name needs the user's approval.
17
+
18
+ MUST Keep one agent-readable engineering doc current in every repository: `docs/engineering.md` (see `architecture-docs-files`), linked from `AGENTS.md`. It records the stack (languages, toolchain versions, frameworks, key libraries and why), layout and dependency direction, standards with approved departures and their reasons, and how to build, test and lint. Read it before you work in the repo. A change that alters the stack (a new or removed dependency, a toolchain bump, a new crate or module, a new tool or a departure) updates it in the same PR; a reviewer treats a stale or missing doc as a finding. Report each departure from a listed library or practice, with its reason, in the report and the PR body.
19
+
20
+ MUST Put cross-cutting concerns (auth, validation, request ids, logging, tracing, metrics, error mapping, timeouts, retries, rate limits) in the framework's middleware, interceptors or decorators. Use one middleware model per surface: in TypeScript, Hono for HTTP APIs (Lambda included) and Connect for RPC; elsewhere ASGI/FastAPI, `net/http` wrappers or tower. `toolchain-api` compares Connect, gRPC and OpenAPI. Keep AWS Lambda handlers thin. Use Powertools for AWS Lambda in Python, TypeScript, Java and .NET when it fits an AWS project; Go and Rust use their runtime library, a structured logger and manual OTel. Instrument with OpenTelemetry over OTLP by default. `quality-code-design` has the rules in its `middleware.md` and `telemetry.md` references; each `lang-<language>-libraries` skill has the framework and SDK specifics.
21
+
22
+ MUST Use REUSE (`reuse annotate`, `LICENSES/`, `REUSE.toml`, `reuse lint` in CI) for per-file licence data instead of a custom licence guard. Keep a per-file licence exception at the file's boundary (its header or a narrow `REUSE.toml` path) and record third-party provenance in `NOTICE`. The `license-picker` skill's `references/reuse.md` has the setup.
23
+
24
+ MUST Scale planning and verification by uncertainty, consequences, and reversibility; file or line counts decide neither safety nor design. A PR request does not authorize a production release.
25
+
26
+ MUST Keep tests in step with the code, following the `quality-testing` skill (and `lang-<language>-testing` for idioms and tools): one behavior per test through the public interface, expected values worked out apart from the code, and a distinct risk per test, so search the existing tests and parametrize instead of copying. A refactor leaves tests unchanged; removed behavior takes its tests and fixtures in the same change. Never add a test that only checks removed code is gone, mirrors the implementation, re-checks what the compiler proves or exists for coverage, and never weaken an assertion or update a snapshot just to pass.
27
+
28
+ MUST Stub a dependency only when its contract exists and the implementation does not. With no contract, write the contract first; never invent the interface inside the stub. Never stub across a recorded decision (no "temporary" different library, engine or algorithm). Every stub is tracked work: no stub without a tracked swap task. In repositories that track work with bd, see the `beads-ledger` skill's `references/contracts-and-stubs.md` for the beads and edges. Design rules for writing a stub are in `quality-code-design`'s `contracts.md`.
29
+
30
+ MUST A swap replaces the stub with the real implementation, removes every `STUB(<task-id>)` marker, and proves that the real implementation passes the same conformance suite and that the consumer's tests pass against it. A swap that needs more than wiring exposes a contract gap: add a fixture that captures it to the contract in the same change. Before a release, no swap task is open, no `STUB(` marker remains in the tree (a CI grep, not a test), and every contract's staleness check passes.
31
+
32
+ MUST After an edit that spans files or changes a signature, run the project's type checker once through the shell before handing back, preferring its own script (`npm run typecheck`); `lang-<language>-quality` names the command.
33
+
34
+ MUST Refactor only within the requested change: fix the violations it introduces and report pre-existing ones. A major refactor needs the user's approval; a worker reports it to its lead instead of doing it.
@@ -0,0 +1,48 @@
1
+ ---
2
+ name: quality-profiling
3
+ description: Use when code, an endpoint, a build or a CLI is slow, regressed or uses too much memory; profile, benchmark, fix.
4
+ ---
5
+
6
+ # Performance profiling
7
+
8
+ This skill is the method only. Before you read code or measure, load the tooling skill for the language in scope with the skill tool, by the exact id below, in this same turn, even when the cause looks obvious. That skill has the commands, how to read their output, and pitfalls. The ids are not in the skills listing; the listed `lang-<language>` router is not the tooling skill.
9
+
10
+ | Code in scope | Tooling skill |
11
+ | --- | --- |
12
+ | TypeScript or JavaScript on Bun or Node | `lang-typescript-profiling` |
13
+ | Python | `lang-python-profiling` |
14
+ | Go | `lang-go-profiling` |
15
+ | Rust | `lang-rust-profiling` |
16
+
17
+ Whole commands, native code, or a language without a tooling skill: [system](references/system.md) (hyperfine, Linux perf, macOS Instruments).
18
+
19
+ TRIGGER
20
+ + Something got slow, regressed, times out, or uses too much CPU, memory, or IO.
21
+ + Asked to optimise, benchmark, compare two implementations, or set a performance budget.
22
+ - A correctness bug that only looks like slowness (hang, deadlock, infinite loop) → the `quality-code-design` skill's debugging reference first.
23
+ - Guessing at a fix without a measurement is not optimising; measure first.
24
+
25
+ ## Workflow
26
+
27
+ 1. **Target.** State the metric and the goal: p95 latency of `GET /orders` under 200 ms, peak RSS under 1 GiB, `build` under 30 s. No target: ask, or propose one and say so.
28
+ 2. **Reproduce with a fixed workload.** Same input, data size, flags, build mode (release/optimised), and concurrency every run. Script it so one command produces the number.
29
+ 3. **Baseline with variance.** Warm up, then take repeated samples (≥10 runs, or a tool that picks the count). Record mean or median *and* spread (stddev, min–max, or p50/p95/p99 for latency). Note machine, versions, and load. Read [hygiene](references/hygiene.md) before trusting any number.
30
+ 4. **Classify the bottleneck** before picking a profiler: CPU-bound (a core pinned), memory (RSS growth, GC time), IO or waiting (low CPU, high wall time), or lock/queue contention. Compare user+sys CPU time to wall time: close → CPU; far below → waiting.
31
+ 5. **Profile** the same fixed workload with a profiler of that type, using the commands from the language's tooling skill. A cause spotted by reading the code is a hypothesis until the profile confirms it. Read the result as in [reading profiles](references/reading-profiles.md).
32
+ 6. **One hypothesis, one change.** Write the hypothesis ("`parseRow` allocates per field; reusing a buffer cuts its 40% self time"), make only that change, and re-measure with the step-3 protocol.
33
+ 7. **Keep or revert.** Keep the change only when the difference exceeds the noise (non-overlapping spread, or a significance test such as `benchstat` or criterion's). Otherwise revert it; a neutral change that adds complexity is a regression.
34
+ 8. **Stop at the target.** Do not keep optimising past the goal unless asked.
35
+ 9. **Report** before/after with the same protocol: metric, workload, runs, mean±stddev or percentiles, machine and load, the change, and what the profile showed. Add a benchmark or budget check when the repository has a place for one.
36
+
37
+ ## Profiler types
38
+
39
+ | Question | Profiler type |
40
+ | --- | --- |
41
+ | Where does CPU time go? | On-CPU sampling profiler, read as a flame graph |
42
+ | Why is it slow while CPU is low? | Wall-clock or off-CPU sampling, tracing, block/lock profiles |
43
+ | What allocates, and what drives GC? | Allocation profile |
44
+ | What keeps memory alive, or leaks? | Heap snapshots compared over time |
45
+ | How long does the whole command take? | `hyperfine` ([system](references/system.md)) |
46
+ | Is variant B faster than A? | Micro-benchmark harness with warm-up and a significance test |
47
+
48
+ Prefer a sampling profiler first: tracing profilers distort small hot functions. Check the installed tool's `--help` before relying on a flag; versions change flags.
@@ -0,0 +1,27 @@
1
+ # Benchmark hygiene
2
+
3
+ A number is only as good as the conditions it was taken under. Record them with the result.
4
+
5
+ ## Control noise
6
+
7
+ - **Check load first.** Run `uptime` (or read `/proc/loadavg`) before and after. A load average above the core count means other work is competing; this matters on shared and agent-heavy machines, where a load of 50 is not unusual. When you cannot quiet the machine: run baseline and candidate interleaved in the same session (hyperfine with both commands, `-count` alternation, criterion's saved baseline), use more runs, prefer medians and minimums over means, and compare CPU time (user+sys) or instruction counts, which load disturbs less than wall time. Say in the report that the machine was loaded.
8
+ - **Isolate.** Close other heavy processes, stop watchers and dev servers you started, disable debug logging and tracing. On Linux, pin with `taskset -c 2 cmd` and set the governor to `performance`; on laptops, stay on mains power and watch for thermal throttling on long runs.
9
+ - **Same build.** Profile and benchmark the optimised build (release, `NODE_ENV=production`, no `--inspect`), with symbols kept for profiling (Rust `debug = true` in the profile, Go default builds keep them).
10
+ - **Warm up.** Discard the first runs: JIT tiering (JS, JVM, PyPy), disk and page caches, connection pools, lazy imports. Decide deliberately whether you measure cold start (drop caches with a `--prepare` step) or steady state (warm-up runs), and report which.
11
+ - **Fix the inputs.** Same data size and shape, seeded randomness, pinned dependency versions. Synthetic micro-inputs often miss the real hot path; prefer a captured real workload, trimmed.
12
+ - **Do not measure the harness.** For servers, the load generator must be faster than the server and run with a fixed concurrency and duration (`oha -z 30s -c 50 URL`, `wrk -t4 -c50 -d30s URL`, `bombardier`). Bun's docs warn that Node-based generators such as autocannon can be too slow for `Bun.serve`.
13
+
14
+ ## Statistics
15
+
16
+ - Report spread, not only the centre: mean±stddev for roughly symmetric timings, median and p95/p99 for latency, min for "best achievable" CPU work.
17
+ - Ten runs is a floor. Increase until the spread stabilises.
18
+ - Treat a difference smaller than the spread as no difference. Use the tool's comparison: `benchstat old.txt new.txt` (Go), criterion's change report (Rust), hyperfine's relative summary, mitata's `summary()`.
19
+ - Watch for bimodal results (GC pauses, cache hits vs misses); report both modes rather than averaging them away.
20
+ - A micro-benchmark proves the micro-case. Confirm the end-to-end metric from step 1 moved.
21
+
22
+ ## Micro-benchmark traps
23
+
24
+ - Dead-code elimination: consume the result (`black_box` in Rust, `do_not_optimize` in mitata, assign to a package-level sink in Go).
25
+ - Constant folding: feed inputs the compiler cannot see at build time.
26
+ - Setup inside the timed loop: keep it outside (Go `b.Loop()` only times the loop body).
27
+ - Allocation and GC cost hidden by short runs: also report allocations (`-benchmem`, `b.ReportAllocs()`, heap stats).
@@ -0,0 +1,21 @@
1
+ # Reading profiles
2
+
3
+ ## Flame graphs
4
+
5
+ - Each box is a stack frame; width is the share of samples where that frame was on the stack. The x-axis is not time (it is sorted alphabetically or merged); an icicle graph is the same thing drawn top-down. Firefox Profiler and Chrome DevTools also offer a time-ordered "flame chart" view, where x *is* time.
6
+ - **Self time** is the width of a box not covered by its children: work done in that function itself. **Total (inclusive) time** is the whole box width. Optimise wide boxes with large self time, or a wide parent whose many children each do a little (a loop calling something too often).
7
+ - Look for: one plateau dominating (the hot path); the same function under many parents (a shared helper worth fixing once); wide `GC`, `malloc`, `memmove` or runtime frames (allocation pressure); wide `read`, `poll`, `futex`, `epoll_wait` frames in a wall-clock profile (waiting, not computing).
8
+ - An on-CPU profile cannot show waiting. Low CPU with high latency needs a wall-clock or off-CPU profile, a trace, or request timing.
9
+ - Missing or `[unknown]` frames mean missing symbols or frame pointers: build with debug info, keep frame pointers, or use a DWARF unwinder.
10
+ - Use the inverted ("bottom-up", "reverse") view to rank functions by self time across all callers.
11
+ - Compare two profiles with a differential view (`pprof -diff_base`, Firefox Profiler compare, `difffolded.pl` from FlameGraph) rather than eyeballing.
12
+
13
+ ## Allocation and heap profiles
14
+
15
+ - **Allocation profile** (bytes or objects allocated, by stack): explains GC pressure and CPU spent allocating. Sort by allocated bytes; look for allocation in hot loops, repeated string building, per-call buffers, boxing.
16
+ - **Heap or retained profile** (live bytes at a point in time): explains RSS growth and leaks. Take two snapshots under the same workload, some time apart, and compare: the leak is what keeps growing. Follow the retainer path from the object to the GC root to see who holds it (caches without eviction, listeners never removed, closures capturing large scopes, global maps).
17
+ - Peak RSS can exceed the language heap (native buffers, mmap, allocator fragmentation). When the heap profile is flat but RSS grows, look at native memory (Bun's `heapStats().extraMemorySize`, `memray --native`, jemalloc or `heaptrack`).
18
+
19
+ ## Turning a profile into a hypothesis
20
+
21
+ Name the frame, its share, and the mechanism you suspect, then predict the effect: "`JSON.parse` is 38% self time on the 2 MB payload; streaming the array should cut p95 by about a third." A prediction you can check is what makes the re-measure meaningful.
@@ -0,0 +1,51 @@
1
+ # Commands, CLIs and the operating system
2
+
3
+ Sources: [hyperfine](https://github.com/sharkdp/hyperfine) (2.0 release notes), [perf examples](https://www.brendangregg.com/perf.html), [xctrace(1)](https://keith.github.io/xcode-man-pages/xctrace.1.html).
4
+
5
+ ## hyperfine (whole-command wall time)
6
+
7
+ ```sh
8
+ hyperfine --warmup 3 'mytool --input big.json' # baseline
9
+ hyperfine --warmup 3 'old/mytool in.json' 'new/mytool in.json' # first command is the reference
10
+ hyperfine --runs 30 --export-json result.json --export-markdown result.md 'cmd'
11
+ hyperfine --prepare 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches' 'cmd' # cold cache (Linux)
12
+ hyperfine -L branch main,perf-fix --setup 'git switch {branch} && make' './app'
13
+ hyperfine -P threads 1 8 --env 'THREADS={threads}' './app'
14
+ ```
15
+
16
+ hyperfine 2 changed defaults; check `hyperfine --version`:
17
+
18
+ - Commands run directly, without a shell. Pass `-S` for pipes, redirects, globs, `&&` or `~`. hyperfine 1.x always used a shell (`-N` disabled it).
19
+ - It reports wall time and peak memory by default; `--metrics time_wall_clock:ms,memory_peak_resident:MiB,instructions` picks others. `--time-unit`, `--sort` and `--reference` are gone.
20
+ - The `--export-json` schema is version 2 (`results[i].summary.time_wall_clock.mean`).
21
+
22
+ Without hyperfine: `/usr/bin/time -l cmd` (macOS) or `/usr/bin/time -v cmd` (Linux) for one run's wall, CPU and max RSS.
23
+
24
+ ## Linux perf
25
+
26
+ ```sh
27
+ perf stat -d ./app # counters: task-clock, cycles, instructions, IPC, cache and branch misses
28
+ perf record -F 99 -g ./app # sample on-CPU stacks at 99 Hz
29
+ perf record -F 99 -g -p PID sleep 30 # attach for 30 s
30
+ perf report # interactive; --stdio for text
31
+ perf script | stackcollapse-perf.pl | flamegraph.pl > out.svg # Brendan Gregg's FlameGraph scripts
32
+ ```
33
+
34
+ Use `--call-graph dwarf` when frame pointers are missing. Unprivileged use may need `kernel.perf_event_paranoid` lowered. `samply record ./app` gives the same data in Firefox Profiler with less setup. Off-CPU and IO latency: `offcputime` and `biolatency` from bcc/bpftrace, or `perf trace`.
35
+
36
+ ## macOS Instruments
37
+
38
+ Needs full Xcode (not only the Command Line Tools) for `xctrace`.
39
+
40
+ ```sh
41
+ xctrace list templates
42
+ xctrace record --template 'Time Profiler' --time-limit 30s --launch -- ./app --flag
43
+ xctrace record --template 'Allocations' --attach <pid>
44
+ open *.trace # inspect in Instruments
45
+ ```
46
+
47
+ Time Profiler for CPU, Allocations and Leaks for memory, System Trace for threads, syscalls and waiting. Without Xcode, `samply record` works on macOS and `sample <pid> 10` prints a quick call-tree sample.
48
+
49
+ ## Request latency
50
+
51
+ Measure from the client side with a fixed load (`oha -z 30s -c 50 URL`, `wrk`, `k6`) and report p50/p95/p99, not the mean. Then find where the time goes inside the request: server-side timing logs or tracing spans per stage (database, downstream calls, serialisation), the database's `EXPLAIN ANALYZE` for slow queries, and a wall-clock profile of the server under that load.
@@ -0,0 +1,122 @@
1
+ ---
2
+ name: quality-test-audit
3
+ description: "Use to audit, clean up, fix or strengthen a test suite on demand: flaky, slow, duplicate, obsolete and missing tests."
4
+ ---
5
+
6
+ # Test audit
7
+
8
+ Audit one test scope and recommend what to drop, merge, rewrite, simplify, add, speed up
9
+ and clean up. Then apply the approved changes without losing protection. Steps 1 to 5 change
10
+ nothing in the repository. Edit tests or code only after step 6 approves a plan. The rules for good tests, the budget and maintenance are in the
11
+ `quality-testing` skill; each language's tools are in the `lang-<language>-testing`
12
+ skill's `references/practice.md`.
13
+
14
+ ## Workflow
15
+
16
+ 1. **Scope.** When the user names no scope, ask for one: a directory, package or module,
17
+ the tests that a branch or diff touches, or the whole suite. Split a large suite into
18
+ one package per audit. Then:
19
+ - Work on a branch or a worktree with a clean tree, and record `git rev-parse HEAD`.
20
+ - Find the test command, the runner, and the coverage and mutation tools from the
21
+ project's configuration and the language's concerns table (`concerns.md` lists where it is).
22
+ - Before you run a runner, coverage or mutation tool, follow the install policy in the
23
+ `toolchain-languages` skill's `references/concerns.md`: detect the tool, recommend the
24
+ install command and ask permission before installing. A missing tool the user
25
+ declines is a recorded gap. Do not skip the check silently.
26
+ - List every runner that executes tests in the scope, including files outside the
27
+ main runner such as `node --test` scripts or a browser suite, so none is skipped
28
+ silently.
29
+ - Keep reports and scratch files in the system temporary directory, not the repository.
30
+ 2. **Baseline.** Measure the scope before you judge it ([evidence.md](references/evidence.md)):
31
+ - Run the scope once from a clean checkout without the project's build step, to find
32
+ hidden prerequisites. A conditional skip (`skipIf`) that hides a failure is a finding.
33
+ - Repeat the scoped run through the shell with one JUnit report per run in the system temporary
34
+ directory: 3 runs of each kind of random order (file order and test order within
35
+ a file, which catch different dependences) plus 3 in default order. Pass the report
36
+ paths, the exit codes and the `modes` to `quality_test_summarize`, which separates
37
+ order-dependent tests (fail only in shuffled runs) from flaky ones. Use 20 runs for a
38
+ suspected flaky test.
39
+ - Reproduce a suspected timing flake under deliberate CPU load (busy loops or parallel
40
+ workers) as well as idle: some only fail under load. Label each flake load-related
41
+ or order-related.
42
+ - Record the machine load. On a shared or busy machine wall time is noise: report the
43
+ summed test duration and user CPU beside it.
44
+ - Write a coverage report with branches, and per-test coverage where the runner has
45
+ it.
46
+ - Run mutation testing on the files under audit, and keep the report as the
47
+ baseline. When it cannot run on the scope (a runner pool requirement, a bundler step
48
+ that breaks the mutation tool), use hand-made forced faults as the evidence,
49
+ injected only into a disposable copy of the repository in the system temporary directory
50
+ (never the working tree), discarded afterwards. Record that.
51
+ - Read the output as evidence: thousands of identical stderr lines, a huge JUnit file
52
+ or connection-refused lines are findings (the summary flags noisy runs).
53
+ Record the gaps: a runner without JUnit output, no mutation tool, a scope too slow
54
+ to mutate.
55
+ 3. **Classify.** Check each test against [catalog.md](references/catalog.md). For each
56
+ candidate, record the test, the class, the evidence, the behavior it claims to protect,
57
+ and the test that keeps that protection. Then look for weak spots, the catalog's
58
+ Strengthen group: surviving mutants and uncovered branches of public behavior. Read
59
+ the suite as a whole too: its fixtures, conventions, runner settings and CI lanes.
60
+ 4. **Plan.** Give each candidate one action: delete, merge into a parametrized test,
61
+ rewrite through the public interface, simplify, move to a lower level, fix the flake at
62
+ its cause, quarantine, speed up, extend an existing test, add a test, or keep. Use the plan
63
+ table in [report.md](references/report.md). A delete or a merge names the test that
64
+ keeps the protection and the mutants that prove it. An added test names the behavior,
65
+ the mutant or branch it covers, and why no existing test can be extended. Write the
66
+ suite-level recommendations in the report's Recommendations section.
67
+ 5. **Challenge.** Give the plan and its evidence to `refactor-challenger` when it is
68
+ installed, otherwise to `adversarial-challenger`. Ask it to show, for each item, that
69
+ the change loses protection or that the evidence does not support it. Drop or
70
+ downgrade each refuted item.
71
+ 6. **Approve.** Show the plan table and the recommendations, and ask with the
72
+ `question` tool: apply all, apply a selection, or report only. Without a person to ask,
73
+ report the plan and stop.
74
+ 7. **Apply in batches.** Before the first batch, compare `git rev-parse HEAD` with the
75
+ commit from step 1. When HEAD moved, recheck each plan item against the merged
76
+ changes and re-measure before applying; drop the items that no longer hold. One kind of change in one area per batch, one commit per batch,
77
+ removals and additions in separate batches. Apply it yourself or through the `coder`
78
+ subagent. After each batch:
79
+ - the scoped suite passes in repeated random-order runs;
80
+ - `quality_test_compare` against the baseline shows no lost protection for coverage
81
+ and for mutants. Each entry it lists is either an equivalent or irrelevant mutant
82
+ that the user approves, or the batch is reverted;
83
+ - each added test failed first against a forced fault, and now kills the mutant or
84
+ covers the branch it was written for.
85
+ 8. **Report.** Use the report template in [report.md](references/report.md): before and
86
+ after counts, runtime, flaky tests, coverage and mutation score, each batch with its
87
+ commit, each approved loss, the recommendations not applied, the gaps, and the
88
+ follow-ups.
89
+
90
+ `quality_test_summarize` also counts timeout and assertion failures per test, and gives the
91
+ size, stderr lines and summed test time of each report.
92
+
93
+ Without the `quality_test_summarize` and `quality_test_compare` tools, run the commands
94
+ in [evidence.md](references/evidence.md) through the shell, and read the reports by hand.
95
+ Say in the report that the comparison was manual.
96
+
97
+ ## Rules
98
+
99
+ - MUST keep steps 1 to 5 read-only. Running tests and writing reports to the temp
100
+ directory is allowed.
101
+ - MUST NOT weaken an assertion, edit an expected value, or update a snapshot to make a
102
+ test pass.
103
+ - MUST prove each delete or merge with the test that keeps the protection and a mutation
104
+ comparison with no unexplained lost protection. Without a mutation tool, record the gap
105
+ and get explicit approval for each deletion.
106
+ - MUST treat "never fails" as a hypothesis until a mutation run or a forced red shows that
107
+ the test detects nothing.
108
+ - MUST NOT delete a characterization test without a behavior test that replaces it, or a
109
+ test of a requirement such as an audit, security or compatibility contract.
110
+ - MUST count a test that passes only on a retry as flaky, not as a pass. Quarantine only
111
+ with a tracked issue, an owner and an expiry date.
112
+ - MUST re-measure a stale plan: when HEAD moved since the baseline, recheck every item
113
+ against the merged changes before applying it.
114
+ - MUST prove a speed-up that changes production code, such as an option that skips an
115
+ expensive check in a tested function: identical output on real data, and a partial
116
+ mode that is visibly distinct, so it cannot pass as the full path.
117
+ - MUST commit each batch separately so that each one can be reverted.
118
+ - MUST add a test only for a behavior that a surviving mutant, an uncovered public branch
119
+ or a reported bug shows is unprotected. Extend an existing test or a parametrized case
120
+ list before adding a new test, and follow the `quality-testing` rules: one behavior,
121
+ the public interface, expected values from the requirement. Never add a test to raise
122
+ coverage alone.
@@ -0,0 +1,108 @@
1
+ # Candidate catalog
2
+
3
+ Read in step 3 of the audit. Each class names its signal, the evidence that confirms it,
4
+ and the default action. A signal makes a test or a gap a candidate; only the evidence
5
+ makes it a finding. The groups are Prune, Purge, Fix, Speed up, Simplify, Strengthen and
6
+ Keep, then the suite-level practices. Examples of most classes are in the `quality-testing` skill's
7
+ `references/bad-tests.md`.
8
+
9
+ ## Prune: tests that add no protection
10
+
11
+ | Class | Signal | Evidence that confirms it | Default action |
12
+ | --- | --- | --- | --- |
13
+ | Duplicate | Two tests with the same setup, action and assertion shape, or the same scenario at two levels | Every mutant that the test kills is also killed by another test, and the scenario has no separate risk | Delete, or merge into one parametrized test |
14
+ | Copied cases | Tests that differ only in literals | The same shape in each test | Merge into one parametrized test with readable case names |
15
+ | Removal check | Asserts that a function, export, module, attribute or file is missing | The assertion reads the module's structure; no caller-visible outcome is checked | Delete. When the removal is a requirement, replace it with a test of the forbidden outcome |
16
+ | Obsolete | Tests a behavior that the code no longer has, or tests through a deleted path that a shim keeps alive | The behavior is gone from the spec or the code; no caller uses it | Delete with its fixtures and data |
17
+ | Never fails | Runs code but would pass if the code returned a wrong value | The test kills no mutant in the code it covers, or survives a forced red | Make it assert the outcome, or delete it |
18
+ | Assertion-free | No assertion, or only "does not throw" where throwing is not the risk | Read the test | Assert the outcome, or delete it |
19
+ | Trivial | Getters, setters, constants, or what the type checker proves | Read the test; the build fails without the code anyway | Delete |
20
+
21
+ ## Purge: test assets that nothing uses
22
+
23
+ | Class | Signal | Evidence that confirms it | Default action |
24
+ | --- | --- | --- | --- |
25
+ | Unused snapshot | A snapshot or golden file that no test reads | The runner's obsolete or unreferenced snapshot report | Delete through the runner's own command |
26
+ | Unused fixture or builder | A fixture, factory, fake or helper with no caller | Search and the runner's fixture listing show no use | Delete |
27
+ | Orphan test data | Files under `testdata/`, `fixtures/` or similar that no test opens | Search for each file name and path | Delete |
28
+ | Dead quarantine | A skipped or quarantined test past its expiry, or with no issue | The skip marker, its date and its issue | Fix it or delete it, and close the issue |
29
+
30
+ ## Fix: tests that protect behavior badly
31
+
32
+ | Class | Signal | Evidence that confirms it | Default action |
33
+ | --- | --- | --- | --- |
34
+ | Flaky | Passes and fails across repeated runs | Mixed outcomes in the repeat report | Fix the cause (the `quality-testing` skill's `maintenance.md`), or quarantine |
35
+ | Coupled to the implementation | Tests private helpers, call order, or mocks of the module's own collaborators | The test breaks on a refactor that keeps behavior, or it asserts calls instead of outcomes | Rewrite through the public interface with real objects or a fake |
36
+ | Copied expected value | The expected value repeats the implementation's computation | Read the test | Replace it with a value from the requirement or a worked example |
37
+ | Checks around the interface | Reads a table, file or private field although a read operation exists | Read the test | Check through the read operation |
38
+ | Logic in the test | `if`, loops or exception handlers decide what to assert | Read the test | Parametrize with explicit cases |
39
+ | Eager | One test checks several behaviors | Several acts, or unrelated assertions | Split into one test per behavior |
40
+ | Leaks state | A test passes alone and fails after another, or only in shuffled runs | Fails in a shuffled run (`order-dependent` in the summary) and passes in default order; the leaked-state checklist in `maintenance.md` names the source | Reset the state in setup or teardown; never lengthen a timeout |
41
+ | Noisy run | Thousands of identical stderr errors, or a huge JUnit file | The summary's per-run stderr lines and file size; the repeated message | Fix the cause, usually a missing environment setup, so the run is quiet |
42
+ | Unmocked I/O | Connection-refused or DNS lines in the output; tests that reach the network | The error lines name a host or port the test never set up | Fake the boundary, or fail the test on unexpected requests |
43
+ | Silent skip or hidden prerequisite | Passes only after a build step or local service; a `skipIf` hides a failure | A run from a clean checkout without the build step, and the skip condition | Make the prerequisite explicit so the test fails with a clear message, or remove the skip |
44
+ | Oversized snapshot | A snapshot of a whole object or a long output | Its size, and updates accepted without review in the history | Assert the part that the behavior is about |
45
+
46
+ ## Speed up
47
+
48
+ | Class | Signal | Evidence that confirms it | Default action |
49
+ | --- | --- | --- | --- |
50
+ | Slow | Among the slowest tests by median time | The repeat report's slowest list | Find the cost: real I/O, sleeps, broad fixtures, a high level |
51
+ | Sleepy | Waits a fixed time | A sleep call in the test or its helpers | Await the condition, or fake the clock |
52
+ | Wrong level | An end-to-end or integration test that checks pure logic | The logic has no I/O dependency | Move the cases to unit tests; keep one wiring test |
53
+ | Speed-up that changes production code | An option that skips an expensive check in a tested function | Identical output on real data in full and partial mode | Make the partial mode visibly distinct (name, flag in the result) so it cannot pass as the full path |
54
+ | Expensive setup | A fixture rebuilt for each test without need, or a session fixture that leaks state | Fixture scope and durations | Narrow or widen the scope to match what the tests change |
55
+
56
+ ## Simplify: tests that are hard to read or change
57
+
58
+ | Class | Signal | Evidence that confirms it | Default action |
59
+ | --- | --- | --- | --- |
60
+ | Mystery guest | The outcome depends on a file, row, environment variable or global fixture the test does not show | Read the test and its fixtures | Build the data in the test, or name it in a builder call |
61
+ | General fixture | Many tests share one large setup and each uses a small part of it | Fixture size against the fields each test reads | Per-test builders with valid defaults |
62
+ | Obscure test | The action or the expected values sit in helpers, so the test body does not show the claim | Read the test body alone | Inline the action and the expected values; keep only setup in helpers |
63
+ | Long arrange | The setup is much longer than the act and the assert | Line counts per section | A builder or factory that states only the fields the test is about |
64
+ | Mock-heavy | Mock setup is longer than the test, or mocks return mocks | Read the test | A fake at the boundary, or the real collaborator |
65
+ | Over-abstracted helpers | Test helpers with flags, branches or their own tests | Read the helpers and their callers | Split them, or inline them where they hide the behavior |
66
+
67
+ ## Strengthen: behavior that no test protects
68
+
69
+ | Class | Signal | Evidence that confirms it | Default action |
70
+ | --- | --- | --- | --- |
71
+ | Surviving mutant | A mutant that changes caller-visible behavior survives | The baseline mutation report, and a reading that the mutant is not equivalent | Extend the test that covers the code with the case that kills it; add a test only when none fits |
72
+ | Uncovered public branch | An error path, boundary or branch of public behavior that no test runs | Branch coverage, read against the public contract | Add the case to the matching parametrized test, or add one test at the lowest level that reaches it |
73
+ | Bug without a regression test | A fixed bug in the history or the issue tracker whose trigger no test reproduces | The fix commit and the test diff beside it | Add one regression test that fails without the fix |
74
+ | Weak assertion | A test asserts less than the behavior promises: not-null, a length, or a substring where a value is known | Read the test against the requirement | Assert the exact outcome |
75
+
76
+ Skip a branch or mutant in trivial code, in generated code, or in code that the
77
+ `quality-testing` skill's `what-to-test.md` says needs no test. Record the skip.
78
+
79
+ ## Keep
80
+
81
+ Keep a test, even when it looks redundant, when it is the only test that kills a mutant,
82
+ when it is a contract test that a fake or a consumer relies on, or when it guards a
83
+ requirement such as an audit log, a security exclusion or a public API. Record why.
84
+
85
+ ## Suite practices
86
+
87
+ Read the suite as a whole and recommend changes in the report. Each recommendation
88
+ names the evidence and the place to change. Check:
89
+
90
+ - **Runner settings:** both kinds of random order (file order and test order within a
91
+ file) with the seed printed. Retries off, or recorded as flaky. A timeout per test, and
92
+ parallel runs where the tests are isolated.
93
+ - **Isolation by default:** the runner resets mocks, spies, stubbed globals and
94
+ environment variables before each test. Check the setting reaches every project of a
95
+ workspace: root options may not apply to projects with their own config. Prove it with
96
+ a probe test that leaks state on purpose and fails when the next test sees it.
97
+ - **CI lanes:** a fast unit lane on every change, an integration lane, mutation testing
98
+ on changed files, and a flaky-test lane for quarantined tests with their issues.
99
+ - **Coverage settings:** branch coverage on; exclusions that hide code nobody decided to
100
+ skip; a coverage target used as a gate.
101
+ - **Shared setup:** global or `autouse` fixtures, a large shared fixture file, or a
102
+ builder that hides the fields a test depends on.
103
+ - **Conventions:** test names, file layout, and assertion and mocking libraries that
104
+ differ across the suite for no reason.
105
+ - **Snapshots:** snapshot files in total, the largest ones, and how often they are
106
+ updated in bulk.
107
+ - **Tooling gaps:** a missing mutation tool, a missing JUnit reporter, or no
108
+ per-test coverage, with the tool from the language's `practice.md`.
@@ -0,0 +1,123 @@
1
+ # Evidence commands
2
+
3
+ Read in step 2 of the audit. Commands checked against official documentation on
4
+ 2026-11-12 (Rust and Python and Go mutation rows and the Rust shuffle rows: 2026-11-16); "not verified" marks a capability that was not confirmed, so do not rely on
5
+ it. Choose your own output paths in the OpenCode temp directory: most tools have no
6
+ default report file.
7
+
8
+ ## Repeated runs in random order, with JUnit output
9
+
10
+ | Runner | JUnit report | Random order, and replay of a seed |
11
+ | --- | --- | --- |
12
+ | pytest | `pytest --junitxml=<path>` | `pytest -p randomly`; replay with `--randomly-seed=<seed>` (`pytest-randomly`) |
13
+ | Vitest | `vitest run --reporter=junit --outputFile=<path>` | `--sequence.shuffle`; replay with `--sequence.seed=<seed>` |
14
+ | bun test | `bun test --reporter=junit --reporter-outfile=<path>` | `--randomize`; replay with `--seed <seed>` |
15
+ | Go | `gotestsum --junitfile <path> -- ./pkg/...` (`go test` has no JUnit flag) | `go test -shuffle=on`; replay with `-shuffle=<seed>`; add `-count=1` to skip cached results |
16
+ | Rust | `cargo nextest run --profile <name>` with `[profile.<name>.junit] path = "junit.xml"` in `.config/nextest.toml`; the report lands in `target/nextest/<name>/junit.xml` | nextest has no shuffle option (checked cargo-nextest 0.9.152, 2026-11-13). Use `cargo +nightly test -- -Z unstable-options --shuffle --shuffle-seed <seed>` (nightly only). For repeats use `cargo nextest run --stress-count N`, and `--flaky-result fail` so retries do not hide flakes |
17
+
18
+ File order and test order within a file are two different shuffles, and they catch
19
+ different order dependences: a dependence between two tests in one file passed every
20
+ file-order shuffle in a real audit. Run both, plus a default-order run, and pass a mode
21
+ per run to `quality_test_summarize` (`default`, `shuffle-files`, `shuffle-tests`).
22
+
23
+ | Runner | Shuffle file order | Shuffle tests within a file |
24
+ | --- | --- | --- |
25
+ | Vitest | `--sequence.shuffle.files` (root config only; checked 2026-11-15 against the 5.0 docs) | `--sequence.shuffle.tests` (per project). `--sequence.shuffle` turns on both |
26
+ | pytest | Not verified: `pytest-randomly` shuffles modules, classes and functions together; check its documentation for a separate switch | Same as the left cell |
27
+ | bun test | Not verified | `--randomize` (documented as shuffling test order; whether it also shuffles files was not verified) |
28
+ | Go | Not verified for package order | `go test -shuffle=on` shuffles tests and benchmarks of a package |
29
+ | Rust | Not verified | Nightly `cargo test -- -Z unstable-options --shuffle` only; nextest has none |
30
+
31
+ Run the command through the shell for the baseline: 3 default-order runs, 3 with file
32
+ order shuffled and 3 with test order shuffled (20 runs of the suspected mode for a flaky
33
+ test), with one report per run in the OpenCode temp directory, for example
34
+ `for i in 1 2 3; do vitest run --reporter=junit --outputFile=<dir>/default-$i.xml; done`, then
35
+ the same loop with `--sequence.shuffle.files` into `<dir>/files-$i.xml` and with
36
+ `--sequence.shuffle.tests` into `<dir>/tests-$i.xml`. Then call `quality_test_summarize` with
37
+ `reports` (the paths in run order), `modes` (`default`, `shuffle-files` or `shuffle-tests` for
38
+ each report, same length) and `exitCodes` (what each run returned, if you kept them). The
39
+ summary calls a test order-dependent only when it passed in a default run and failed in a
40
+ shuffled one; a shuffled failure without a default-order pass is inconclusive. A test that failed in
41
+ every default run but passed a shuffled run is listed on its own; when a default run skipped
42
+ it or lacked it, it is inconclusive too. A `findings:` line opens the output with the count
43
+ of each category. Without the tool,
44
+ keep each report under a distinct name and read them.
45
+
46
+ The tool also reports, per run, the report size in bytes, the number of lines in
47
+ `system-err` elements (a run above 1000 lines or 5 MB is flagged noisy; `noisyStderrLines` and `noisyFileBytes` change the limits) and the summed
48
+ test duration, and for each failing test how many failures were timeouts and how many
49
+ assertions or errors. The timeout class is a heuristic: the failure message or type
50
+ matches "timeout", "timed out" or "time-out".
51
+
52
+ ## Timing and machine load
53
+
54
+ Wall time on a shared or busy machine is noise. For each timed comparison record:
55
+
56
+ - the machine load before and after (`uptime`, or the CI runner's load) and what else
57
+ was running;
58
+ - the summed test duration (the tool's per-run figure) beside wall time;
59
+ - user CPU time, for example from `time <cmd>` (`user`) or `/usr/bin/time -v`.
60
+
61
+ Reproduce a suspected timing flake twice: idle, and under deliberate load. Load comes
62
+ from busy loops (one per core, for example `yes > /dev/null &` per core) or from running
63
+ the suite in parallel workers. A flake that failed 0 of 80 idle runs failed 19 of 60 with
64
+ the CPU saturated in a real audit. Label each flake load-related (only fails under load)
65
+ or order-related (fails in shuffled runs with idle CPU).
66
+
67
+ ## Coverage
68
+
69
+ | Runner | Command | Branches |
70
+ | --- | --- | --- |
71
+ | pytest | `pytest --cov=<pkg> --cov-branch --cov-report=lcov:<path>` (or `xml:<path>` for Cobertura) | Yes, with `--cov-branch` |
72
+ | Vitest | `vitest run --coverage --coverage.reporter=lcov`; reports go to `./coverage` | Yes, with the `v8` and `istanbul` providers |
73
+ | bun test | `bun test --coverage --coverage-reporter=lcov`; writes `coverage/lcov.info` | Not documented: lines and functions only |
74
+ | Go | `go test -coverprofile=<path> ./...` writes the Go cover profile | No: statement blocks only |
75
+ | Rust | `cargo llvm-cov nextest --lcov --output-path <path>` | Nightly only; the flag spelling was not verified |
76
+
77
+ Per-test coverage exists for pytest: `pytest --cov=<pkg> --cov-context=test
78
+ --cov-report=html` with `show_contexts = True` in the `[html]` section of the coverage
79
+ configuration shows which tests cover each line. No native equivalent was verified for
80
+ Vitest, bun test, Go or Rust; Stryker maps tests to mutants instead.
81
+
82
+ ## Mutation testing
83
+
84
+ | Language | Command scoped to the audit | Report for `quality_test_compare` |
85
+ | --- | --- | --- |
86
+ | Python | `mutmut run "<module>.<function>*"`; scope with `[tool.mutmut]` `source_paths` and `only_mutate`. For a comparable report use cosmic-ray | mutmut has no per-mutant export: `mutmut export-cicd-stats` writes summary counts only. With cosmic-ray, the third-party cosmic-ray-to-mutation-elements-adapter (`cr-to-stryker-report -f json`) emits mutation-testing-report-schema JSON that `quality_test_compare` reads |
87
+ | TypeScript | `npx stryker run --testRunner vitest --mutate "<file>" --reporters json` | `reports/mutation/mutation.json` (mutation-testing-report-schema) |
88
+ | Go | `gremlins unleash --diff "<base-ref>" --output=<path>`; fallback avito-tech go-mutesting | The JSON file named by `--output`. go-mutesting writes its own `report.json`, which `quality_test_compare` cannot read |
89
+ | Rust | `cargo mutants --file '<file>'` or `cargo mutants --in-diff <diff-file>`; add `--shard k/n` for a large scope. Keep the default `cargo test` so doctests count: with `--test-tool=nextest` doctests are skipped and doctest-only coverage shows as missed | `mutants.out/outcomes.json`, or the directory named by `--output` |
90
+
91
+ When mutation testing cannot run on a scope (a runner pool requirement, a bundler step
92
+ that breaks the mutation tool, a scope too slow), use hand-made forced faults as the
93
+ evidence. Steps 1 to 5 of the audit change nothing in the repository, so make the faults in
94
+ a disposable copy outside it: export the commit into the OpenCode temp directory (for
95
+ example `git archive HEAD | tar -x -C <dir>/faults`), install the dependencies there, change
96
+ the code so the behavior is wrong, and confirm the named test fails. Delete the copy when
97
+ done. Record each fault and its result, and say in the report that the evidence is manual.
98
+
99
+ Run the same command for the baseline and after each batch. Stryker's `--incremental`
100
+ reuses earlier results: run without it for the final comparison.
101
+
102
+ ## Unused assets
103
+
104
+ | Asset | Command |
105
+ | --- | --- |
106
+ | syrupy snapshots | `pytest --snapshot-details` lists unused snapshots; `pytest --snapshot-update` deletes them |
107
+ | Vitest snapshots | Obsolete snapshots fail CI by default; `vitest run -u` removes them |
108
+ | bun test snapshots | `bun test --update-snapshots` removes unused entries |
109
+ | insta snapshots | `cargo insta test --unreferenced=reject` lists them; `--unreferenced=delete` deletes them |
110
+ | pytest fixtures | `pytest --dead-fixtures` (`pytest-deadfixtures` 4) lists unused fixtures; compatibility with pytest 9 was not tested |
111
+ | Go and TypeScript fixtures, test data files | No tool was verified: search for each name and path |
112
+
113
+ Delete unused snapshots only through the runner's own command, in an approved batch.
114
+
115
+ ## Listing tests and timing them
116
+
117
+ | Runner | List without running | Slowest tests |
118
+ | --- | --- | --- |
119
+ | pytest | `pytest --collect-only -q` | `pytest --durations=10 --durations-min=1.0` |
120
+ | Vitest | `vitest list` | The JUnit report, or `--reporter=verbose` |
121
+ | bun test | Not verified | The JUnit report |
122
+ | Go | `go test -list . ./...` (top-level tests only) | `gotestsum --jsonfile <path>`, then `gotestsum tool slowest --jsonfile <path> --threshold 500ms` |
123
+ | Rust | `cargo nextest list` | The JUnit report |