Files
civitai__civitai/scripts/test-component-run.mjs
Zachary Lowden 6de64ee5a8 fix(tests): unzero the preview / component-tests tier, and make a zero-collected run say so (#4531)
* fix(tests): unzero the component tier — one mock factory was aborting the whole run

`preview / component-tests` was reporting `failure` on `main` while executing ZERO
tests. Reproduced deterministically (3/3 at d353f785c3, and in isolation): the whole
`component` project aborts before any reporter prints, with no `Test Files` line, no
per-file results, and exit 1.

Root cause, one file:
`src/tests/pages/apps/review/review-queue-nav.browser.test.tsx:30` mocks
`~/providers/FeatureFlagsProvider` with a WHOLESALE factory naming only
`useFeatureFlags`. The review queue page's row now renders the review entry point,
which reads flags through `useOptionalFeatureFlags`, so the named import has nothing
to bind to:

  SyntaxError: The requested module '/src/providers/FeatureFlagsProvider.tsx'
  does not provide an export named 'useOptionalFeatureFlags'

In the node `unit` project that would fail ONE file. In BROWSER mode it kills the run:
vitest resolves a manual mock over the browser-to-node channel inside a Playwright
route handler that does not catch (`@vitest/browser-playwright/dist/index.js`,
`await module.resolve()` inside `page.route`), so the rejection escapes as an
Unhandled Rejection in the orchestrator.

The printed error names neither the file nor the real cause. It is wrapped twice --
once by the browser mocker, once again on the node side -- and the innermost `cause`
is dropped in transit, so all you see is the generic "[vitest] There was an error when
mocking a module ... make sure there are no top level variables inside", which points
at hoisting and is wrong. The root cause above was recovered by temporarily patching
`createHelpfulError` in the browser tester bundle to inline `cause.stack`; the file was
then confirmed by bisecting the 50 candidate files down to one.

This is the SECOND time this class has bitten (see the header of
`src/components/AppBlocks/__tests__/featureFlagsMockCompleteness.test.ts`, which fixed
six sibling suites in the AppBlocks directory and deliberately scoped its guard there).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(ci): make the component tier fail LOUDLY on zero collected, not silently

The `preview / component-tests` tier could report `failure` having executed ZERO
tests, and nothing anywhere said so. The shared `npm-report-only-suite` Tekton task
computes its verdict from the runner's EXIT CODE alone, so an abort that collected
nothing and a genuine list of red assertions both render as `component:fail` /
"Component suite failed" -- same words, same colour, same place. That is the shape
that trains people to click through a tier.

`pnpm test:component` now runs through `scripts/test-component-run.mjs`, which asks
vitest for a JSON report and hands it to `scripts/ci/assert-component-suite-ran.mjs`.
That gate prints a ledger -- `N executed, N skipped, across N files; N failed suites,
N failed tests` -- and fails when nothing was collected, or when the executed count
falls below a floor (1240, ~55% of the 2254 measured on a full green run of 201 files
on 2026-08-31).

Deliberate limits, each of which is a way this could have been wrong:

- It can only ever ADD a failure. Vitest's own exit code is passed straight through
  when the ledger is satisfied, so a red suite stays red for its own reason.
- EXECUTED, not TOTAL. `numTotalTests` counts skipped tests, so a suite that
  self-skipped wholesale would satisfy a total-based floor having run nothing.
- `failed` counts as executed. A guard that scored a red run as "did not run" would
  fire on every genuine failure, and the tier would then be red for two different
  reasons that nobody could tell apart -- the exact confusion this removes.
- A signal-killed runner short-circuits the gate entirely. The CI task wraps this in
  `timeout(1)` and distinguishes "timeout" from "fail" on purpose; a killed run also
  writes no report, so relabelling it "collected nothing" would be a wrong answer
  rather than a missing one.
- A narrowed run (a file argument, or `-t`) skips the FLOOR but not the zero check:
  the collected count is then a property of the filter, but a single-file run that
  collects nothing is the cheapest reproduction of the abort and is precisely when
  someone is debugging it.

The message enumerates every cause it cannot tell apart rather than asserting one --
an absence is the observable the most causes share, and a guard that names the wrong
one sends the next reader hunting a bug that is not there. All three named have been
observed on this suite; two of them were observed while writing this change, and the
browser-crash one arrives wearing the mock error's headline with the real cause on
the `Caused by:` line.

Verification:
- 16 unit tests over JSON fixtures (`scripts/__tests__/`), covering zero, the floor
  boundary both sides, all-red, all-skipped, narrowed both ways, import-failed
  suites, and a missing/unparseable report.
- Mutation-checked: 9 mutants of the gate, ALL KILLED, each by the specific named
  test written for it (verified per-test, not "some test failed"), against a green
  16/16 baseline.
- End-to-end negative control: reverting the one-line fix in the previous commit and
  running through the wrapper produces the ledger's abort message and exit 1, from
  the missing-report branch.
- End-to-end positive: the full suite through `pnpm run test:component`.

Docs corrected while here: CONTRIBUTING said component tests "don't run in CI at all"
and put the file count at 106; they do run, report-only, in the preview pipeline, and
there are 201 files with ~2,250 tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tests): the zero-collected message overstated a PARTIAL abort

The headline said "THE COMPONENT SUITE COLLECTED NOTHING ... nothing executed", and
the code contradicts it in the case that actually happens most: the JSON reporter
writes at the END of a run, so an abort part-way through leaves no report at all.
Measured while writing this: a run that aborted 68 files into 201 had 68 files
scrolled past as green, wrote nothing, and got told nothing executed.

Both halves of that were wrong to assert. Tests HAD executed, and a reader who
scrolls up and sees green lines is entitled to believe the message is confused --
or, worse, to believe the green lines are coverage.

So the headline is now "THIS RUN PRODUCED NO ACCOUNTABLE RESULT", which is true of
both shapes, and the diagnosis says explicitly that an abort can land part-way and
that whatever scrolled past is unaccounted for rather than confirmed. The
missing-report branch says why the report is absent (the reporter writes at the end)
and that a partial run and a run that never started are indistinguishable from
there -- which is the reason neither counts as one that ran.

No behaviour change: the same runs fail, with the same exit code. The four test
assertions that pinned the old headline move with it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tests): close six findings from the adversarial audit of this PR

An adversarial audit of #4531 found two ways the new guard reproduced the very
pathology it was written to remove, plus four smaller gaps. All six are fixed here;
nothing about the payload fix in c32aa06e8d changes.

1. A SIGNAL WAS RELABELLED AS A TEST FAILURE. `child.on('exit')` returned a hardcoded
   143 for EVERY signal. `report-only-suite-task.yaml` branches on 137 to report
   `oom-killed` -- "this is an OUT-OF-MEMORY kill, not a timeout; raise the task's
   memory limit" -- and before this wrapper existed an OOM-killer SIGKILL on vitest
   reached that task as 137, because pnpm re-raises. With a constant 143 it matched no
   branch and fell through to `RC=1`, verdict `fail`, rendered "Component suite
   failed". A memory problem reported as a test failure, on the same tier, in the same
   words. Now `128 + os.constants.signals[sig]`, so 137/143/130 come out right and the
   mapping cannot drift from the names node hands back. The comment above the branch
   claimed it passed the status through; it does now.

2. A CALLER `--outputFile` MADE A GREEN RUN REPORT "COLLECTED NOTHING". Measured by
   the auditor: `pnpm test:component <file> --outputFile=/tmp/x.json` wrote an 18/18
   green report to the caller's path, left the wrapper's path empty, and printed the
   full "this tier verified NOTHING on this commit" diagnosis naming three causes,
   none of them real. `.github/workflows/lint.yml` runs the SIBLING unit tier with
   exactly that flag, so it is a copy-paste away. Now refused up front with the fix in
   the message.

3. `isNarrowed` WAS WRONG IN BOTH DIRECTIONS ON SPACE-SEPARATED FLAGS. `--max-workers 1`
   -- the form CONTRIBUTING steers people towards for sizing a run on a shared box --
   put `1` in a positional slot, so the run scored "narrowed" and THE FLOOR WAS SILENTLY
   TURNED OFF; same for `--reporter`, `--retry`, `--bail`, `--project`, `--pool`. In the
   other direction `--shard=1/4` scored NOT narrowed, so a healthy sharded run would
   fail the floor while being told "Do NOT lower the floor to make this green" --
   misdirection, not merely a false red. Value-taking flags now consume their value, and
   `--shard`/`--changed`/`--related` narrow explicitly.

4. WINDOWS. `spawn()` of `vitest.cmd` without `shell` has failed since the node
   18.20.2/20.12.2 CVE fix; `scripts/test-unit-run.mjs` already sets
   `shell: process.platform === 'win32'` for this reason. Added. And a spawn failure
   (rc 127) now short-circuits instead of handing the gate a missing report and getting
   forty lines about mock factories and dead browsers.

5. THE REPORT IS NOW DELETED BEFORE THE RUN, not only after. Cleanup after the run is
   skipped by exactly the paths that leave a stale report behind (a signal death, a
   throw), so a healthy 2254-test report could survive into a later run that aborted
   before writing one -- the gate reading it, printing a green ledger, and passing:
   silently inert in precisely its own use case.

6. THE GATE COMPUTED A FILE COUNT AND NEVER CHECKED IT. Replaced with a LEDGER, which
   is the stronger of the two checks: it walks `src/` for every `*.browser.test.tsx` and
   fails when one is absent from the report, NAMING it. The test floor sits at ~55%, so
   ~45% of the suite could stop being collected while the gate stayed green -- and the
   incident this whole guard descends from is exactly that shape (six files contributing
   0 of 438, nothing red). The expectation is re-derived every run, so there is no
   constant to go stale. Skipped when narrowed, and when the walk finds nothing -- an
   empty walk is not a measurement, and it SAYS so rather than passing quietly.

Also: the fixed factory now names all THREE hooks the flags module exports.
`useFeatureFlagsReady` is the third and has four live consumers; none is in this page's
graph today, which is the only reason naming two loads at all. The comment said "BOTH
hooks", which reads as "the module has exactly two" -- and it is the template the PR
proposes copying to fifty files.

Verification:
- 27 unit tests (was 16), including the on-disk ledger against a fixture tree that
  contains a `node_modules/` and a non-browser `.test.tsx` neither of which may count.
- Mutation-checked: 17 mutants, ALL KILLED, each by its own named test. One SURVIVED on
  the first sweep -- `out.length > 0 ? out : null` was unreachable from the fixture,
  which had no `src/` at all, so the walk returned early. A second case with a `src/`
  that holds no browser tests reaches it; an empty array is TRUTHY, so that mutant would
  otherwise have armed a ledger over zero expected files and passed everything.
- The on-disk ledger run against the REAL tree: 201/201 green, and dropping one real
  file from the report fails and names it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tests): close audit round 2 — two regressions the round-1 fixes introduced

A delta re-audit of `6ceac37f33..7f005f0482` confirmed 4 of the 7 claims outright
(the signal mapping, the pre-run clear, the file ledger, the fixed factory) with its
own positive and negative controls, and found that two of the fixes had introduced
new defects of their own. Both are here, with the smaller findings.

🔴 THE ON-DISK LEDGER FALSE-FAILED A LEGITIMATE RUN, WITH A MESSAGE FORBIDDING THE FIX.
`--exclude`, `--dir` and `--root` were added to VALUE_FLAGS but not to
NARROWING_FLAGS. All three take a value AND genuinely shrink the collected file set,
so `pnpm test:component --exclude 'src/tests/**'` scored as a FULL run and the ledger
failed it naming up to 200 files -- asserting the include broke or the run died, and
telling the reader "Do NOT silence this by narrowing the walk", which is the only
thing that would have fixed it. `--config` joins them: it can replace the project's
`include` outright, which is the assumption the walk is built on. This is precisely
the shape the round was convened to prevent, produced by the round's own fix.

🔴 `shell: win32` WENT ON THE SHARED `run()`, SO IT ALSO WRAPPED THE GATE SPAWN.
The claim said this matched `scripts/test-unit-run.mjs`; it did not -- that file puts
`shell` on its vitest spawn only and deliberately leaves its `process.execPath` spawn
alone. Node with `shell: true` concatenates argv UNESCAPED (DEP0190), and the gate is
spawned as `process.execPath`, which on Windows is `C:\Program Files\nodejs\node.exe`.
So on the one platform the option exists to support, every `pnpm test:component` would
have failed at the gate step with a cmd.exe parse error rather than any of this
wrapper's messages. `shell` is now per-call.

Also:

- KEBAB AND CAMEL ARE THE SAME FLAG TO VITEST (cac camelCases every option key), so a
  hand-enumerated list has a hole wherever it carries one spelling and not the other --
  and it did: `--max-workers`/`--maxWorkers` were both listed, `--test-timeout` was
  not, so the kebab form silently disabled both checks. Spellings are now canonicalised
  rather than enumerated, and the test asserts them in PAIRS.
- `--output-file` (kebab) was NOT refused, so the exact defect the refusal exists for
  was still reachable -- under a test named "catches every spelling". Meanwhile
  `--outputFile.junit=` and `--outputFile.html=` WERE refused, though neither touches
  the `.json` key: object-form output paths are per-reporter, so that was over-strict
  and the stated reason ("the bare form sets the path for EVERY reporter") is true only
  of the bare form. Both directions fixed.
- The rc-127 short-circuit is keyed on a spawn-failure FLAG, not on the number. 127 is
  an exit code a runner can produce on its own, and relabelling that as "the binary
  could not be started" is a second wrong answer that also skips the gate on a run that
  happened.
- `--repo-root <dir>` did not consume its value, so with the flag FIRST the directory
  was read as the report path: "EISDIR: illegal operation on a directory" plus the
  whole abort diagnosis. Every test passed it last, which is why nothing caught it; the
  ledger tests now pass it first.
- `--related` removed. It is a vitest SUBCOMMAND, and this wrapper always spawns
  `vitest run …`, so it cannot arrive -- the entry and its assertion were both inert,
  the assertion pinning behaviour for an input the runner cannot receive.
- The factory now names all FOUR runtime exports of the flags module, including
  `FeatureFlagsProvider`. The comment said "EVERY runtime hook", which was narrower
  than the module -- and "not in this graph today" is exactly the reasoning that put
  this file in the diff.
- A comment the previous round made false: it said the positional rule would catch
  `-t foo` anyway. It stopped being true the moment `-t` was listed as value-taking --
  the value would now be CONSUMED -- so the explicit narrowing branch is load-bearing.
- CONTRIBUTING documents the refusal, the file ledger, and which flags narrow.

Coverage for the two claims that shipped with none: `main` now takes its collaborators
as injected defaults, so the ORDER of effects can be asserted rather than inspected.
The two `clearReport()` calls are byte-identical statements -- only their position
carries the meaning, so a refactor moving the first below the run reopens "a stale
report satisfies the next run's ledger" with every other test green.

Verification: 35 unit tests (was 27). Mutation-checked at 17 mutants, ALL KILLED, zero
survivors -- including re-running round 1's guards, because an audit fix resets the
gate. Real-tree controls re-run with the new argument parsing, flag first and flag
absent: 201/201 green, and dropping one real file fails and names it. ESLint on the
touched files is back to the base count; two `no-empty-function` errors this change
introduced are fixed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tests): close audit round 3 — the canonicaliser re-opened the class it closed

Round 3 verified 8 of round 2's 9 claims against the diff or against vitest's own
source (it read cac's `setDotProp` to confirm the `--outputFile.junit=` allowance is
genuinely safe, and `cliOptionsConfig` to confirm `-r`/`-c` really are root/config).
It found one regression and one coverage hole, both here.

🔴 A BOOLEAN FLAG SWALLOWED THE FILENAME AFTER IT — the same shape round 2 fixed,
re-introduced by round 2's own mechanism. `canonicalFlag` collapsed `.subkey` onto the
parent, so every dot-subkey inherited its parent's value-consuming behaviour, and the
two entries `--coverage.reporter`/`--coverage.provider` became a single `coverage` that
also matched the BARE `--coverage` — which takes no value (`argument: ""` in vitest's
`cliOptionsConfig`). So `pnpm test:component --coverage <file>` ate the FILE as
`--coverage`'s value, scored the run as full, and failed an 18/18 green single-file run
naming ~200 files as ABSENT while telling the reader not to narrow the walk. Same for
`--coverage.enabled <file>` and `--browser.headless <file>`. Measured base-vs-head, all
three flipped `true` to `false`. Matching is now on the full canonical PATH, so a
subkey is value-taking only if it is listed as one.

🔴 THREE MUTANTS SURVIVED A GREEN 35-TEST SUITE, AND EACH WAS THIS PR'S OWN HEADLINE
FAILURE. The injected fakes took no parameter, so nothing could observe the argv `main`
builds — the seam between the two modules this change exists to wire together. Dropping
`--narrowed` from the gate argv makes every narrowed run hard-fail both the floor and
the on-disk ledger; dropping `--outputFile.json=` makes every run report "does not
exist" plus the whole abort diagnosis; dropping `...argv` makes
`pnpm test:component <file>` silently run the entire suite behind a healthy-looking
ledger. Testing `isNarrowed` in isolation cannot see whether its answer is ever USED.
The fakes now capture their argument and three cases assert it; all three mutants die.

Also:
- `--repo-root` with no value was a silent fall-through to the real repo root, so a
  fixture report got graded against the 201 real files and failed with a confident
  diagnosis about the include breaking — produced by a typo. Now a usage error (exit 2).
- CONTRIBUTING: the sample ledger omitted `measured <date>`, which the real output
  carries; and "skips both checks but not the zero check" counted a different pair than
  the two enumerated four lines above. The checks are now numbered and the sentence
  names which ones a narrowed run skips.

Verification: 39 unit tests (was 35). Mutation-checked at 19 mutants, ALL KILLED, zero
survivors — the three that survived round 3, the round-3 fixes themselves, and every
guard from rounds 1 and 2 re-run, because an audit fix resets the gate. Real-tree
controls re-run: 201/201 green, one missing file still fails. ESLint clean on the
changed test file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tests): close audit round 4 — replace the flag LIST with a shape rule

Round 4 measured `isNarrowed` at base vs head across every one of vitest 4.1.11's 72
boolean options and 73 value-taking ones, and found the flag list had traded 22 loud
wrong answers for 25 quiet ones. Splitting `coverage` into two subkeys left
`--retry.count 2`, `--browser.name chromium` and sixteen more `coverage.*` paths
reading their VALUE as a filename, scoring a FULL run as narrowed and switching the
file ledger and the floor off with a one-line note. That is the direction this file's
own comments repeatedly name as the worse of the two.

🔴 THE LIST WAS THE PROBLEM, AND THREE ROUNDS WERE SPENT ON IT. Enumerating flag NAMES
missed `--test-timeout` next to `--testTimeout`. Canonicalising spellings then made
`--coverage <file>` swallow the file. Splitting into subkeys produced the 25 above.
vitest 4.1.11 has a 164-path option tree; a hand-maintained copy of it is wrong the day
it is written, and each fix moved the wrongness rather than removing it.

So the rule is now about the ARGUMENT, not the flag: a positional is a file filter if
it looks like a path, or if nothing before it could have been expecting a value. A
non-path token straight after a flag is that flag's value, WHATEVER the flag is —
correct for all 73 value-taking options without naming one of them, and correct for all
72 booleans too. `VALUE_FLAGS` is deleted. What remains is `NARROWING_FLAGS` (flags that
genuinely shrink the run and must be named, because omitting one fails LOUDLY) and a
five-entry `PATH_VALUE_FLAGS` for the only residual the shape cannot decide: a value
that is itself a path.

🔴 AND THE DECISION IS NOW A SENTENCE, NOT A BOOLEAN. No rule over an unknowable flag
list is right always; what must never happen is being wrong SILENTLY, because
`--narrowed` disables the two checks this whole change exists to add. `narrowingReason`
returns why, and the runner prints it: `--retry.count 2` reading `2` as a file filter is
obvious on sight and invisible otherwise.

Also:
- `canonicalFlag` camelCases only the FIRST dot segment, matching cac's own
  `camelcaseOptionName` (`name.split(".").map((v,i) => i===0 ? camelcase(v) : v)`).
  Camel-casing all of them made this wrapper accept `--coverage.reports-directory`,
  a spelling vitest does not — so the two would disagree about the next token.
- `--repo-root=<dir>` is parsed. Matching only the space form left the inline spelling
  falling through BOTH branches to the real repo root — byte-for-byte the failure the
  missing-value guard was added to close, reachable through one extra character. A
  value that is itself a flag is rejected too.

Verification: 45 unit tests (was 44 after the round's own additions; 39 before).
Mutation-checked at 23 mutants, ALL KILLED, zero survivors, each by its OWN named test.

🔴 THE FIRST SWEEP REPORTED FOUR SURVIVORS AND WAS WRONG ABOUT ALL FOUR, WHICH IS WORTH
RECORDING BECAUSE THE HARNESS HAD THIS PR'S OWN DEFECT. Two were mislabelled — killed by
a different test than the one named, which the sweep scores as SURVIVED. Of the other
two, one was a real gap (`--reporter=json AppNameCrumb`, now covered) and one was
`canonicalFlag`'s dot handling, which is equivalent for every input that has no dashed
subkey (also now covered). Along the way the harness itself was found reusing a JSON
report path without clearing it — the same stale-report defect fixed in the product two
commits ago — and now clears it and verifies the mutation reached disk before running.
A mutant reported SURVIVED is a claim about the instrument until the instrument has been
controlled.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* wip(tests): stop guessing which vitest flags take values

Safety commit of in-progress round-5 rework so it is not lost; the agent was
interrupted mid mutation-sweep. Verification is NOT complete — the sweep, the
red/green pair and the merged-tree re-run have not been reported. Do not merge
on this commit.

Round 5 measured both prior approaches against vitest 4.1.11's real option
table (170 long options, 74 boolean, 96 value-taking): the hand-maintained
list was wrong 73 times, the shape heuristic 74. The error count never moved,
only its direction. This removes the question instead of answering it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AEa6GDJyTiu2R146ndYsLK

* test(ci): finish the verification bacb8a2cf5 was pushed without

bacb8a2cf5 landed as a rescue commit marked `wip` because the session that wrote it
died with the change only in a working tree. The change itself is unaltered; this is
the verification it was missing, plus the merge of a main that moved twice underneath
it. Nothing here modifies the rule.

WHY THE RULE CHANGED, WITH THE NUMBER THAT JUSTIFIES IT. Round 5 of the audit
enumerated vitest 4.1.11's REAL CLI option table -- by calling `createCLI()` and reading
each cac option's `isBoolean` rather than by hand -- and ran `isNarrowed(['--<flag>',
'VALUE'])` against both revisions imported side by side:

  hand-maintained flag list   wrong on 73 options (every value-taking one)  QUIET
  shape heuristic             wrong on 74 options (every boolean one)       LOUD

73 versus 74. The heuristic did not beat the list; it moved the wrongness off one half
of the table onto the other. The direction improved, which is worth something, but the
error count did not -- and `pnpm test:component --coverage AppNameCrumb` would run one
test and then be failed against the 1240 floor with "the include broke or the run died".
That is a mis-posed question, so it is no longer asked: any argument at all means
narrowed.

Re-measured against the same table on the merged tree, with the same method:

  164 long options (72 boolean, 92 value-taking)
  UNSAFE-LOUD -- rule claims FULL so the floor and ledger fire on a partial run: 0
  no-argument invocation (what CI runs): NOT narrowed, so all three checks arm

(My enumeration walks the global + `run` commands and sees 164/72/92 where round 5's
saw 170/74/96; the traversal differs slightly, the conclusion does not.)

🔴 The comparison is one-directional ON PURPOSE, and the other direction is a real cost
rather than a rounding error: all 164 options now score as narrowed, so an arg-ful run
does not get the floor or the file ledger even when it was genuinely full. That is
affordable for one measured reason -- `pr-preview-pipeline.yaml` invokes
`pnpm run test:component` with NO arguments, so CI is the `argv.length === 0` path and
always gets all three. What is given up is enforcing a floor on an ad-hoc local run.
`VITEST_MAX_WORKERS=4` in the environment sizes a run without giving that up.

Verification on the MERGED tree (d77dd394db), all at load <= 16 with no browser-session
errors in any run quoted:

  no-arg full run (the CI path)   202 files / 2257 tests, exit 0, no NARROWED line,
                                  floor 1240 and the 202-file ledger both ARMED
  guard red arm                   exit 1, "THIS RUN PRODUCED NO ACCOUNTABLE RESULT",
                                  failing on the missing-report branch
  guard green arm                 exit 0, "2 executed, 0 skipped, across 1 files"
  gate unit tests                 37 passed
  mutation sweep                  20 mutants, ALL KILLED, zero survivors

🔴 The red arm was run NARROWED, deliberately: it proves `--narrowed` disables the floor
and the ledger and NOT the zero-collected check, which is the one failure this whole
change exists to catch.

THE MERGE. main moved twice; both times the only conflict was `package.json`, and both
times it was the same semantic hazard -- main editing `test:lint-rules` and this branch
editing `test:component`, adjacent lines of one object, where taking either side
wholesale silently reverts the other and makes the entire guard inert with every test
green. Resolved by parsing the merged JSON, not by reading the diff: `test:lint-rules`
now matches origin/main byte-for-byte and `test:component` is the wrapper. The wiring
guard added for exactly this was then checked against the bad resolution -- applying
main's `package.json` wholesale fails one test, the one written for it.

Round 5's two remaining 🟢 items are closed by the rework itself rather than separately:
the stale JSDoc described `VALUE_FLAGS`, which no longer exists, and the test whose
description claimed "a BOOLEAN flag does not swallow the filename after it" while
passing entirely through the path check is gone with the heuristic it tested. That one
was load-bearing -- a description asserting coverage its body did not provide is what
let the class through -- so its replacement asserts a property with no free parameters
instead, across both halves of the option table.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* style(tests): format the gate test file

The rescue commit was pushed before a prettier pass could run over the last edit to
this file, and `ESLint + Prettier (changed files)` caught it: the file is ADDED by this
PR, so it is covered by the added-files prettier gate. One line.

This red was MINE, not inherited — unlike `Unit tests (1)/(2)` (a redis integration
test that arrived from main) and `preview / smoke-tests` (#4516 changing
`reaction.toggle`), both of which are verified as pre-existing and are left alone.

CONTRIBUTING.md also reports unformatted, and that one is NOT actionable here: it is
already unformatted on origin/main, and it is modified rather than added, so the gate
(which reads `added.txt`) does not cover it. Reformatting it would bury this PR under an
unrelated whole-file diff.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 10:57:49 -05:00

316 lines
15 KiB
JavaScript

#!/usr/bin/env node
/**
* `pnpm run test:component` — runs the browser-mode `component` project AND asserts that it
* collected something.
*
* The assertion itself lives in `scripts/ci/assert-component-suite-ran.mjs`, which owns the
* reason it exists and is unit-tested against fixtures. This file is only the plumbing: run
* vitest with a JSON report beside the normal output, then hand that report to the gate.
*
* 🔴 IT NEVER TURNS RED INTO GREEN. Vitest's own exit code is passed through whenever the
* ledger is satisfied; the gate can only ever ADD a failure. Two paths deliberately bypass
* it — a signal-killed runner (see below) and a narrowed run (the gate's `--narrowed`).
*/
import { spawn } from 'node:child_process';
import { rmSync } from 'node:fs';
import { constants as osConstants } from 'node:os';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
// Under `node_modules/` so it is gitignored with the rest of it, and so it sits beside the
// install the run used rather than in a shared tmpdir two agents can collide in.
const REPORT = resolve(repoRoot, 'node_modules/.civitai-component-report.json');
const GATE = resolve(repoRoot, 'scripts/ci/assert-component-suite-ran.mjs');
const args = process.argv.slice(2);
/**
* A vitest flag's CANONICAL PATH: leading dashes off, `=value` off, the FIRST dot-segment kebab
* camelCased and later segments left verbatim — which is exactly cac's own
* `camelcaseOptionName`, `name.split(".").map((v,i) => i===0 ? camelcase(v) : v).join(".")`.
* `--output-file` and `--outputFile` both give `outputFile`; `--outputFile.json=x` gives
* `outputFile.json`.
*
* Kebab and camel are the same flag to vitest, which is why `--max-workers` and `--maxWorkers`
* both work — so anything comparing a flag by name has to normalise rather than enumerate
* spellings. Used ONLY by `conflictingOutputFile`, which needs to recognise one specific flag.
* Nothing here tries to decide whether a flag takes a value; see `narrowingReason` for why.
*/
export function canonicalFlag(arg) {
if (!arg.startsWith('-')) return null;
const stripped = arg.replace(/^--?/, '').split('=')[0];
const [head, ...rest] = stripped.split('.');
return [head.replace(/-+([a-zA-Z0-9])/g, (_, c) => c.toUpperCase()), ...rest].join('.');
}
/**
* WHY this run counts as narrowed, or `null` for a full run.
*
* 🔴 ANY ARGUMENT AT ALL MEANS NARROWED. THIS IS DELIBERATELY NOT A PARSER, AND FIVE ROUNDS OF
* AUDIT ARE THE REASON.
*
* The question "does this flag consume the next token?" was attacked twice and lost twice.
* Measured against vitest 4.1.11's REAL option table — enumerated by calling `createCLI()` and
* reading each cac option's `isBoolean`: 170 long options, 74 boolean, 96 value-taking:
*
* - a hand-maintained list of value-taking flags was wrong on 73 of them (every value-taking
* option), reading a flag's VALUE as a filename — the QUIET direction, both checks silently
* off;
* - replacing it with a shape heuristic ("is the token path-like?") was wrong on 74 (every
* BOOLEAN option), reading a real filter as a value — the LOUD direction, so
* `pnpm test:component --coverage AppNameCrumb` ran one test and then failed it against the
* 1240 floor and the on-disk ledger with "the include broke or the run died".
*
* 73 versus 74. The heuristic did not beat the list; it moved the wrongness off one set of
* options and onto the other. That is a mis-posed question, not one needing a better answer, so
* it is no longer asked.
*
* 🔴 WHAT THIS COSTS, STATED PLAINLY: an arg-ful run does not get the floor or the on-disk
* ledger, even when the argument was only `--max-workers 4` and the run really was full. That
* is affordable for exactly one reason, and it is a measured one rather than an assumption —
* `pr-preview-pipeline.yaml` invokes `pnpm run test:component` with NO arguments, so CI is the
* `argv.length === 0` path and always gets both checks. What is given up is enforcing a floor
* on an ad-hoc local run, which nobody needs.
*
* 🔴 AND THE ZERO-COLLECTED CHECK IS NOT SKIPPED — not here, not ever. `--narrowed` disables the
* floor and the ledger only. The failure this whole change exists for (a run that aborts having
* collected nothing) is caught on every invocation, including a single-file one, which is the
* cheapest reproduction of it and precisely when someone is debugging it.
*/
export function narrowingReason(argv) {
if (argv.length === 0) return null;
return (
`arguments were passed (${argv.map((a) => `\`${a}\``).join(' ')}), so what this run SHOULD ` +
'have collected is not knowable from here'
);
}
/**
* Whether the caller narrowed the run — the boolean the gate needs. `narrowingReason` owns the
* rule and the explanation.
*/
export function isNarrowed(argv) {
return narrowingReason(argv) !== null;
}
/**
* A caller-supplied `--outputFile` silently redirects the JSON report the gate reads.
*
* 🔴 MEASURED, AND IT IS THE WORST FAILURE THIS SCRIPT CAN PRODUCE: an 18/18 green single-file
* run reported "THE COMPONENT SUITE COLLECTED NOTHING … this tier verified NOTHING on this
* commit" and exited 1, because `--outputFile=<path>` clobbers the `--outputFile.json=` form
* appended below and the wrapper's report was never written. The diagnosis then names three
* causes, none of which is the real one. `.github/workflows/lint.yml` runs the SIBLING unit
* tier with exactly that flag, so anyone extending this tier by copying that line hits it.
*
* Refused rather than honoured: the bare `--outputFile=` form sets the path for EVERY reporter,
* so honouring it would point the default reporter at the same file. A loud config error with
* the fix in it beats either silent wrong answer.
*
* 🔴 SCOPED TO THE FORMS THAT ACTUALLY COLLIDE — the bare one and `.json`. An earlier revision
* refused `--outputFile.junit=` and `--outputFile.html=` too, neither of which touches the
* `.json` key: object-form output paths merge per reporter, so those are legitimate and
* refusing them was over-strict. It also missed `--output-file` entirely, which vitest accepts
* (cac camelCases option keys), leaving the exact defect this exists for reachable through the
* kebab spelling.
*/
export function conflictingOutputFile(argv) {
return argv.find((a) => ['outputFile', 'outputFile.json'].includes(canonicalFlag(a))) ?? null;
}
/**
* The shell's own convention: a process killed by signal N exits 128+N.
*
* 🔴 THIS USED TO BE A HARDCODED 143 FOR EVERY SIGNAL, AND THAT RE-CREATED THE EXACT
* MISLABELLING THIS WHOLE CHANGE EXISTS TO REMOVE. `report-only-suite-task.yaml` branches on
* 137 to report `oom-killed` — "this is an OUT-OF-MEMORY kill, not a timeout; raise the task's
* memory limit" — and on 124 for a timeout. Before this wrapper existed, an OOM-killer SIGKILL
* on vitest reached that task as 137 (pnpm re-raises). With a constant 143 the wrapper would
* hand it 143 instead, which matches no branch and falls through to `RC=1` — verdict `fail`,
* rendered as "Component suite failed". A memory problem would have been reported as a test
* failure, on the same tier, in the same words.
*
* `os.constants.signals` is the mapping node itself uses, so this cannot drift from the names
* node hands back.
*/
export function exitCodeForSignal(signal) {
const n = osConstants.signals[signal];
return typeof n === 'number' ? 128 + n : 143;
}
/**
* 🔴 `shell` IS PER-CALL, NOT SHARED, AND THAT DISTINCTION IS THE WHOLE POINT.
*
* The vitest spawn needs it on Windows: since the node 18.20.2/20.12.2 CVE fix, `spawn()` of a
* `.cmd`/`.bat` without a shell fails outright. `scripts/test-unit-run.mjs` does exactly this —
* and, deliberately, only for its vitest spawn.
*
* The GATE spawn must NOT have it. `shell: true` makes node concatenate argv UNESCAPED (it
* emits DEP0190 saying so), and the gate is spawned as `process.execPath`, which on Windows
* defaults to `C:\\Program Files\\nodejs\\node.exe`. Measured on this box with a spaced path:
* `{shell:false}` → status 0, `{shell:true}` → status 1, "Cannot find module". Putting `shell`
* on the shared helper therefore broke every `pnpm test:component` on Windows at the gate step,
* with a cmd.exe parse error instead of any of this wrapper's messages — on the exact platform
* the option was added to support.
*/
function run(bin, argv, { shell = false } = {}) {
return new Promise((done) => {
const child = spawn(bin, argv, { cwd: repoRoot, stdio: 'inherit', shell });
// The CI task wraps this in `timeout(1)`, which signals only its direct child. Forward
// so a budget overrun stops the runner instead of orphaning it.
const forward = (sig) => () => {
if (!child.killed) child.kill(sig);
};
process.on('SIGINT', forward('SIGINT'));
process.on('SIGTERM', forward('SIGTERM'));
child.on('error', (err) => {
console.error(`test:component: failed to spawn ${bin}: ${err.message}`);
done({ rc: 127, signal: null, spawnFailed: true });
});
child.on('exit', (code, signal) =>
done({ rc: signal ? exitCodeForSignal(signal) : code ?? 1, signal, spawnFailed: false })
);
});
}
function vitestBinPath() {
return resolve(
repoRoot,
'node_modules/.bin',
process.platform === 'win32' ? 'vitest.cmd' : 'vitest'
);
}
function clearReport() {
try {
rmSync(REPORT, { force: true });
} catch {
/* not worth failing a run over */
}
}
/**
* 🔴 THE COLLABORATORS ARE INJECTED SO THE ORDER OF EFFECTS CAN BE ASSERTED, NOT INSPECTED.
*
* Two things here are pure sequencing and cannot be seen from any output: the report is cleared
* BEFORE the runner starts, and a signal death or a failed spawn returns without consulting the
* gate. Both were shipped with no coverage; the two `clearReport()` calls are now identical
* statements, so nothing but their position carries the meaning, and a refactor that moves the
* first one below the run reopens "a stale report satisfies the next run's ledger" — the gate
* silently inert in exactly its own use case — with every test still green.
*
* Defaults are the real implementations, so the shipped path is the tested path minus the fakes.
*/
export async function main({
argv = args,
runVitest = (a) => run(vitestBinPath(), a, { shell: process.platform === 'win32' }),
runGate = (a) => run(process.execPath, a),
clear = clearReport,
log = console.error,
} = {}) {
const conflict = conflictingOutputFile(argv);
if (conflict) {
log(
`\ntest:component: refusing to run — \`${conflict}\` would redirect the JSON report this\n` +
`command reads to decide whether the suite collected anything (it writes\n` +
`--outputFile.json=${REPORT}).\n` +
'Left alone, that produces the worst output this script has: a fully GREEN run reported\n' +
'as an abort that verified nothing, naming causes none of which is real.\n' +
'Run vitest directly if you need your own report:\n' +
' pnpm exec vitest run --project component --reporter=json --outputFile=<path>'
);
return 2;
}
// 🔴 Cleared BEFORE the run, not only after. A previous run's report is a fully-formed
// healthy ledger; if this run then aborts before writing one, the gate reads the STALE file,
// prints a green ledger and passes. Cleanup after the run cannot close that, because the
// paths that skip it (a signal death, a throw) are the same ones that leave a stale report.
clear();
// `--reporter=default` is restated because naming a second reporter REPLACES the default
// set rather than adding to it — without it the human-readable output disappears and all
// that is left is a JSON file nobody reads.
const { rc, signal, spawnFailed } = await runVitest([
'run',
'--project',
'component',
'--reporter=default',
'--reporter=json',
`--outputFile.json=${REPORT}`,
...argv,
]);
/**
* 🔴 A TRUNCATED RUN IS NOT AN ABORTED ONE, AND MUST NOT BE RELABELLED AS ONE.
*
* The CI task wraps this in `timeout(1)` and reads the exit code to tell "timeout" from
* "fail" — it reports a budget overrun as an UNKNOWN verdict, deliberately, because no
* suite went red. A killed run also writes no JSON report, which looks exactly like the
* abort the gate exists to catch if you only look at the report. So a signal death
* short-circuits: pass the runner's own status through and make no claim about what was
* collected.
*
* (`timeout` signals only its direct child, which is the shell, so in the current CI
* wiring this fires only if something signals this process directly. It is here because
* the alternative — silently converting a kill into a confident "the suite collected
* nothing" — is a wrong answer, not a missing one.)
*/
if (signal) {
log(
`\ntest:component: the runner was killed by ${signal} — passing that through as ${rc}. ` +
'No claim is made about what it collected: a killed run writes no report, and that is ' +
'not the same as a run that collected nothing.'
);
return rc;
}
// 🔴 Same reasoning as the signal branch, for the case that produces no report for a reason
// the gate cannot describe: the runner never STARTED. `spawnFailed` is what `run()` reports
// when `spawn` itself errors. Handing that to the gate makes it print forty lines about mock
// factories, dead browsers and empty selections — none of which happened.
//
// Keyed on the FLAG, not on `rc === 127`: 127 is a real exit code a runner can produce on its
// own, and relabelling that as "the binary could not be started" is a second wrong answer.
if (spawnFailed) {
log(
'\ntest:component: the vitest binary could not be started, so nothing ran and there is ' +
'nothing to account for. Check that `pnpm install` has completed in this checkout.'
);
return rc;
}
// 🔴 SAY WHY, whenever the checks are being turned off. `--narrowed` disables the file
// ledger and the floor — the two checks this whole change exists to add — so a wrong
// narrowing decision is the QUIET failure, the one direction the comments here repeatedly
// name as worse than a loud one. Printing the token that caused it is what stops it being
// quiet: `--retry.count 2` reading `2` as a file filter is obviously wrong on sight, and
// invisible otherwise.
const reason = narrowingReason(argv);
if (reason) {
log(
`\ntest:component: NARROWED — ${reason}, so the file ledger and the floor are skipped. ` +
'The zero-collected check still applies. Run with NO arguments to get all three — that ' +
'is what CI does.'
);
}
const gate = await runGate([GATE, REPORT, ...(reason ? ['--narrowed'] : [])]);
// Best-effort, and AFTER the gate has read it. The load-bearing clear is the one BEFORE the
// run; this one only keeps the tree tidy.
clear();
// The gate can only ADD a failure — a green gate hands the runner's own verdict back.
return gate.rc !== 0 ? gate.rc : rc;
}
// Main-guard, so importing this from a test does not launch a browser suite.
if (
import.meta.url === `file://${process.argv[1]}` ||
process.argv[1] === fileURLToPath(import.meta.url)
) {
process.exit(await main());
}