Files
gstack/test/paid-shards.test.ts
T
Garry Tan 943105f109 v1.91.8.0 test: smaller suite, derived paid selection, retired never-green evals (#2994)
* test: delete test-infrastructure dead code (G)

- exit-propagation drives the runner's real strict verdict
  (BunTestOutputClassifier + strictTestExitCode); delete the unused
  shardRunLooksTruncated predicate.
- delete skill-coverage-matrix registry + its gate (nothing reads it; the
  floor already iterates skillCensus()).
- delete touchfiles-facade export-parity tests (Bun fails missing imports
  at link time) and the duplicated E2E_TIERS tier-value test.
- delete brain-cache-spec TRANSPORT_DEFAULT_POLICY, SKILL_RUN_RETENTION_DAYS
  and the now-unused BrainTrustPolicy type with their literal tests.
  AUTOPLAN_PREFLIGHT_BUDGET_BYTES stays: skill-preflight-budget enforces it
  against real resolver output.
- delete audit-compliance's JSDoc-comment grep.

* test: replace product tests that fake the product with real-boundary tests (F)

- design: serve.test.ts drove an inline mirror server; now two tests run the
  real serve() on an ephemeral port (reload confinement, submit exit 0).
- setup-gbrain: rollback + voyage tests execute the template-extracted init
  blocks (3 sites) instead of drifted local bash copies.
- terminal-agent: internalHandler source greps replaced by a behavioral
  /internal/grant + /internal/revoke auth matrix (no/wrong/valid token).
- /health: server-security-surface and the server-auth / security-audit-r2 /
  sidebar-tabs source greps fold into one liveness-only check on the real
  body; the L4 sidecar wiring gets a behavioral /pty-inject-scan test.
- delete tautologies (browser-manager onDisconnect, memory-command #12),
  ios swiftui tap fixture self-check, memory-ingest put_page grep, detach
  source greps, sidebar-agent absence pins, dead-CSS pins + the dead CSS,
  security-audit-r2 Task 1 + the test-only meta-commands re-export,
  duplicate generated-SKILL.md checks.
- make-pdf coverage-gaps cases move into their owner test files.

* test: delete tests of dead eval code (A)

- A1: the retired Eng lexical oracle (evaluateEngSeedCoverage,
  isEngSeedDecisionAUQ), the completion-handoff detector and the retained
  corpus had no paid caller since v1.87.6; delete their 26 replay files,
  ~2.6k helper LOC and fixtures, and the dead blocks in 8 mixed files
  (live hasNativePlanTerminal / batching assertions stay).
- A2: dead viewport approvers in autoplan-artifact-permission and their 11
  replay files + fixtures; recorder/launcher cases stay.
- A3: never-wired oracles and seeders (autoplan-phase-order,
  eng-finding-fixture, ceo-paired-fixture, design-ui-scope,
  plan-skill-completion, pty-current-screen, required-reads,
  transcript-section-logger); plan-seed-submission now decodes through the
  production createPtyScreen; section manifests name their actual guard.
- A4: zero-reference helper exports, plus execGit and invokeAndObserve
  found by the reachability pass.
- 52 fixtures orphaned by the deletions; touchfile and selection-table
  entries for every deleted path.

* test: clean up the paid eval lane (B1-B4, B6, B7)

- B1: delete paid files that assert nothing or cannot pass meaningfully:
  skill-llm-eval-spec and skill-e2e-spec-execute (test.todo), gemini-e2e
  (+ gemini-session-runner; no gemini CLI in CI), ship-idempotency (red
  since v1.63), the two opus-4-7 *-sonnet overlay wrappers, conductor-prose
  (+ its source-evaluation replay), codex-e2e-plan-format; drop their keys,
  scripts and census rows.
- B2: skill-llm-eval grades browse/sections/command-list.md with one union
  judge that also carries the baseline score pin; regression-vs-baseline
  deleted (paid run: pass, c4/c4/a4).
- B3: memory-pipeline, ios-qa, ios-qa-swift-build and plan-tune-cathedral
  make no model calls; renamed out of the paid glob so they run on every
  PR. Swift builds need GSTACK_TEST_SWIFT=1; device stub deleted.
- B4: codex-e2e*, outside-voice, aside and ios-device cannot run in the CI
  image; excluded from the weekly lane with a tracked re-entry condition.
- B6: fold opus-47's negative routing controls into skill-routing-e2e
  journey-negatives (paid run: 3/3 unrouted) and delete the file.
- B7: delete the never-green brain-privacy-gate eval; a free
  gstack-skill-start test now proves consent precedes artifacts egress.

* test: retire the finding-count cluster and trim its helpers (C)

- C0/C1: the five never-green evals (skill-e2e-autoplan-chain and
  skill-e2e-plan-{ceo,eng,design,devex}-finding-count) failed on harness and
  budget, never on skill behavior; delete them, their touchfile/tier ids,
  AUTOPLAN_CHAIN_BUDGET and the dedicated eighth periodic slice (--slices 7).
- C2: delete the helper groups whose only paid consumers were those files
  (11 modules), trim claude-pty-runner and eng-seeded-coverage to the paid
  closure, and delete the free replay tests whose assertions exercised only
  that dead code (89 files, 135 orphaned fixtures). Blocks that used dead code
  only as input for a live subject keep their assertions: the multiSelect
  default moved to plan-review-decisions, runner PTY tests use inline caller
  policies, and the timer-safe budget checks moved to eng-finding-retry-budget.
- The eight production-touching files stay except ceo-current-decision-record
  (its template read only feeds the retired counter).
- CARVE_GUARDS.autoplan is behavioral 'none'; TODOS records the lost chain
  and per-finding cadence coverage with their re-entry tests.

* test: fold per-incident replay series into their detector owners (D)

Twelve detector families move into one owner test each: 73 incident files
become describe blocks in ceo-section-loading-fixture (stale-fill race),
model-overlays, coverage-audit-evidence, autoplan-phase-observer,
native-auto-decide, outside-voice-evidence, eng-first-review,
plan-count-completion, plan-count-file-permission, ceo-mode-option,
plan-scope-selection and plan-count-prerequisite. Each block keeps its original
code and fixture, so every case still runs; only tests asserting the incident
file's own touchfile registration are dropped (41). Touchfile lists that named
an incident now name its owner.

* test: start the plan-count history PTY on its readiness marker (H)

The fake CLI prints a startup marker and the runner waits for it instead of the
fixed 8 s startup sleep (8.6 s -> 0.9 s locally). eng-semantic-terminal's
sleeping registration cases went with C; plan-count-timeout keeps the fixed wait
because it asserts deadline behavior.

* test: derive paid touchfiles from each eval's static closure (E)

touchfiles.test.ts now checks, per key, that the paid file's static
test/helpers and test/fixtures closure (plus fixture paths it names in string
literals) is covered, and names the file, path, chain and key to fix when it is
not. Free *.test.ts files are no longer touchfiles, so editing a free replay
test stops selecting paid evals: 950 entries removed, 653 real closure paths
added. The hand-copied inventories go: periodic-fixture-selection,
fake-impeccable-touchfiles and 45 per-file selection examples. Selection for
the sample edits (plan-eng-review template, claude-pty-runner,
plan-count-fixture, gstack-config) loses no case under either profile.
CONTRIBUTING documents the rule and its lower bound.

* test: skip hollow tier shards and census judges in the paid planner (B5)

A paid file is now skipped for a tier lane only when every E2E id it registers
is known statically and none has that tier; ids come from the touchfile
registrations and literal testName/*IfSelected arguments, so a comment or
skill path that quotes another id cannot unschedule it, and computed names
keep today's scheduling. --list and the manifest show each skip as
"skipped: no E2E_TIERS id has tier <tier>". The weekly gate census drops the
LLM judges (--skip-judges); they still run in the periodic census and PR gate
lanes. Gate lane 52 -> 42 files, census 41; periodic 77 -> 69.

* test: run seven paid evals on the current default capture model (B8)

skill-e2e-{auq-matrix,plan-format,qa-bugs,retro,workflow} pinned
claude-opus-4-7 and skill-e2e-office-hours plus -brain-writeback pinned
claude-sonnet-4-6; none tests a historical model, so they now capture with
resolveEvalModel('capture'), and the free harness tests that execute these
registrations receive the same resolver. The paid re-pin run passed all of
them. skill-e2e-{design,office-hours-phase4,plan-prosons,plan} keep
claude-opus-4-7: six of their cases failed on the default model (three
timeouts, a missing report file, a format miss and a posture score of 3), so
per the plan's fallback they keep their pins with a TODOS entry. The pre-spend
estimate and drop threshold are in docs/test-audit-2026-09.md.

* test: guard the reduced suite against new test-of-test files

- test/test-of-test-ratchet.test.ts records the 228 free tests that import only
  test/ code and fails on a new one, naming the owner test to extend instead;
  a stale baseline entry fails with the remove instruction.
- test/helpers/resolve-repo-path.ts is the one specifier/literal resolver for
  the ratchet and the touchfile closure invariant, with its own unit tests.
- CONTRIBUTING "Test tiers" describes the paid-failure workflow (fix, then one
  row in the detector's owner test) and the ratchet; TEST_PORTFOLIO gains the
  detector -> owner-test table and no longer claims an Autoplan chain eval.
- TODOS: automatic exclusion policy for chronically red periodic files (P3),
  the deferred native-completion table collapse, the unused CEO payment
  seeder; the PTY readiness item is narrowed to the paid runner.
- docs/test-audit-2026-09.md collects the triage, security mapping, inventories,
  selection proof, behavior-commit decisions and retained false positives.

* v1.91.8.0 test: smaller suite, derived paid selection, retired never-green evals

Release metadata for the test-reduction branch: VERSION 1.91.8.0 (1.91.7.0 is
claimed by #2983), CHANGELOG with the measured before/after table and a
contributor section, durations re-recorded on Ubicloud standard-16 (857 files,
0 failures), the agents digest, CONTRIBUTING's after-measurement row, the B8
fallback TODOS entry, and the after metrics, kept-vs-plan notes, B8 run and
census estimate in docs/test-audit-2026-09.md.

* fix(ubicloud): skip retrieval globs that match nothing instead of reporting a failed pull

* test: count issue-numbered Design findings in the UI-scope gate eval
2026-09-29 08:58:49 -07:00

468 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Pins the paid-tier sharded runner (scripts/test-paid-shards.ts).
*
* Two properties matter, and both are why `test:gate` has never finished a run:
* 1. Enumeration + sharding — every file `test:gate`'s globs expand to gets
* its own process, and tier exclusion only ever fires on explicit evidence.
* 2. A spinning shard is killed externally and the run CONTINUES. The fake
* command here is a real busy loop, so an in-process timer could not save
* it — exactly the failure mode `sample` caught on the wedged run.
*/
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
const ROOT = path.resolve(import.meta.dir, '..');
import {
PAID_TEST_GLOBS,
classifyPaidTestFile,
collectPaidTestFiles,
computePaidDiffSelection,
diffSkipDecisionForFile,
formatSummary,
isAllSkippedPass,
isPaidTestFile,
knownTestNamesInSource,
partitionShardsByDiffSelection,
planPaidShards,
runPaidShards,
summarize,
summaryExitCode,
tierSkipReason,
buildRunManifest,
type ShardOutcome,
} from '../scripts/test-paid-shards';
describe('paid test enumeration', () => {
test('matches the globs package.json test:gate expands', () => {
expect(isPaidTestFile('test/skill-e2e-qa-workflow.test.ts')).toBe(true);
expect(isPaidTestFile('test/skill-llm-eval.test.ts')).toBe(true);
expect(isPaidTestFile('test/codex-e2e.test.ts')).toBe(true);
expect(isPaidTestFile('test/codex-e2e-sol-scope.test.ts')).toBe(true);
expect(isPaidTestFile('test/skill-e2e-triage-audit.test.ts')).toBe(true);
// Outside the globs: no dash, extra suffix, or a free test.
// 'test/skill-e2e.test.ts' is the DELETED pre-split monolith's name,
// kept here as a regression pin: its glob-invisibility is exactly how
// two gate tests went unexecuted for ~8 releases before the rehoming.
expect(isPaidTestFile('test/skill-e2e.test.ts')).toBe(false);
expect(isPaidTestFile('test/paid-shards.test.ts')).toBe(false);
// The 2026-08 orphan fix: these four were API-spending files OUTSIDE the
// globs — self-skipping in the free suite and absent from the paid
// census, so they could never run in any lane.
expect(isPaidTestFile('test/codex-e2e-recommendation-substance.test.ts')).toBe(true);
expect(isPaidTestFile('test/codex-e2e-plan-format.test.ts')).toBe(true);
expect(isPaidTestFile('test/llm-judge-recommendation.test.ts')).toBe(true);
expect(isPaidTestFile('test/carve-section-loading.test.ts')).toBe(true);
expect(isPaidTestFile('test/skill-llm-eval-spec.test.ts')).toBe(true);
});
test('discovers files and gives each one its own shard', () => {
const files = collectPaidTestFiles();
expect(files.length).toBeGreaterThan(0);
expect(files.every(isPaidTestFile)).toBe(true);
expect(PAID_TEST_GLOBS.length).toBe(6);
const shards = planPaidShards(files);
expect(shards.flat().sort()).toEqual([...files].sort());
expect(shards.every((shard) => shard.length === 1)).toBe(true);
});
});
describe('tier lane skip (B5)', () => {
const file = 'test/skill-e2e-sample.test.ts';
const touchfiles = { 'sample-gate': [file, 'sample/**'], 'sample-periodic': [file], other: ['x/**'] };
const tiers = { 'sample-gate': 'gate', 'sample-periodic': 'periodic', other: 'periodic' };
const reg = { 'sample-gate': [file] } as Record<string, string[]>;
test('a fully static file with only other-tier ids is skipped with its reason', () => {
const source = "describeIfSelected('Sample', ['sample-gate'], () => { testIfSelected('sample-gate', async () => {}); });";
expect(tierSkipReason(file, source, 'periodic', reg, tiers)).toBe('skipped: no E2E_TIERS id has tier periodic');
expect(tierSkipReason(file, source, 'gate', reg, tiers)).toBeNull();
});
test('a comment or path that quotes another-tier id cannot change the decision', () => {
const source = "// see 'other' and 'sample-periodic' for context\nconst dir = 'sample-periodic/fixtures';\n" +
"testIfSelected('sample-gate', async () => {});";
expect(tierSkipReason(file, source, 'periodic', reg, tiers)).toBe('skipped: no E2E_TIERS id has tier periodic');
expect(tierSkipReason(file, source, 'gate', reg, tiers)).toBeNull();
});
test('computed registrations, unregistered literal ids and id-less files keep today\'s scheduling', () => {
for (const source of [
"describeIfSelected(name, keys, () => {});",
"describeIfSelected('Sample', [...keys], () => {});",
"testConcurrentIfSelected(`sample-${label}`, async () => {});",
"runSkillTest({ testName: `sample-${label}` });",
"testIfSelected(caseName, async () => {});",
]) expect(tierSkipReason(file, source, 'periodic', reg, tiers)).toBeNull();
expect(tierSkipReason(file, "testIfSelected('sample-periodic', async () => {});", 'periodic', reg, tiers)).toBeNull();
expect(tierSkipReason(file, "testIfSelected('sample-gate', async () => {});", 'periodic', {}, tiers)).toBeNull();
expect(tierSkipReason(file, "testIfSelected('sample-gate', async () => {});", 'gate', touchfiles, tiers)).toBeNull();
});
test('the real constructed-name diagram file stays scheduled in both lanes', () => {
const source = fs.readFileSync(path.join(ROOT, 'test/skill-e2e-diagram.test.ts'), 'utf8');
for (const tier of ['gate', 'periodic'] as const) expect(tierSkipReason('test/skill-e2e-diagram.test.ts', source, tier)).toBeNull();
});
test('the weekly gate census alone drops the LLM judges, with the reason in the manifest', () => {
const census = buildRunManifest({ tier: 'gate', sliceCount: 7, evalsAll: true, skipJudges: true, env: { EVALS_ALL: '1' } });
const judge = census.entries.find(entry => entry.file === 'test/skill-llm-eval.test.ts');
expect(judge).toMatchObject({ status: 'excluded', reason: 'skipped: LLM judges run in the periodic census and PR gate lanes' });
for (const tier of ['gate', 'periodic'] as const) {
const lane = buildRunManifest({ tier, sliceCount: 7, evalsAll: true, env: { EVALS_ALL: '1' } });
expect(lane.entries.find(entry => entry.file === 'test/skill-llm-eval.test.ts')?.status).toBe('planned');
}
const workflow = fs.readFileSync(path.join(ROOT, '.github/workflows/evals-periodic.yml'), 'utf8');
expect(workflow.match(/--skip-judges/g)).toHaveLength(1);
expect(workflow).toMatch(/--tier gate --emit-plan \/tmp\/gate-census-plan\/manifest\.json --slices 7 --skip-judges/);
});
});
describe('tier classification', () => {
test('excludes only on an explicit other-tier guard', () => {
const gateGuard = "const shouldRun = !!process.env.EVALS && process.env.EVALS_TIER === 'gate';";
const periodicGuard = "const shouldRun = !!process.env.EVALS && process.env.EVALS_TIER === 'periodic';";
expect(classifyPaidTestFile(gateGuard, 'gate').included).toBe(true);
expect(classifyPaidTestFile(periodicGuard, 'gate').included).toBe(false);
expect(classifyPaidTestFile(gateGuard, 'periodic').included).toBe(false);
expect(classifyPaidTestFile(periodicGuard, 'periodic').included).toBe(true);
});
test('recognizes the consolidated e2e-gate helper guard (both forms)', () => {
// The shape test/helpers/e2e-gate.ts consumers use after consolidation.
const helperGate = "const describeE2E = describeE2ETier('gate');";
const helperPeriodic = "const describeE2E = describeE2ETier('periodic');";
const boolPeriodic = "const shouldRun = CODEX_AVAILABLE && e2eTierEnabled('periodic');";
expect(classifyPaidTestFile(helperGate, 'gate').included).toBe(true);
expect(classifyPaidTestFile(helperGate, 'periodic').included).toBe(false);
expect(classifyPaidTestFile(helperPeriodic, 'periodic').included).toBe(true);
expect(classifyPaidTestFile(helperPeriodic, 'gate').included).toBe(false);
expect(classifyPaidTestFile(boolPeriodic, 'gate').included).toBe(false);
expect(classifyPaidTestFile(boolPeriodic, 'periodic').included).toBe(true);
});
test('keeps files whose tier is decided per-test at runtime', () => {
// Naming an E2E_TIERS key is not evidence — 'retro' appears in the
// LLM-judge file, which test:gate does run.
const noGuard = "runSkillTest('retro', async () => {});";
expect(classifyPaidTestFile(noGuard, 'gate').included).toBe(true);
expect(classifyPaidTestFile(noGuard, 'periodic').included).toBe(true);
expect(classifyPaidTestFile('', 'gate').included).toBe(true);
});
test('the REAL external-CLI test files classify as periodic-only', () => {
// Synthetic guard shapes above can drift from the actual files — the
// inert-demotion defect class. Pin the real sources: a guard-shape edit
// in either file that silently runs it in gate fails here.
for (const file of ['test/codex-e2e.test.ts', 'test/codex-e2e-sol-scope.test.ts']) {
const source = fs.readFileSync(path.join(ROOT, file), 'utf8');
expect(classifyPaidTestFile(source, 'gate').included, `${file} leaked into gate tier`).toBe(false);
expect(classifyPaidTestFile(source, 'periodic').included, `${file} dropped from periodic tier`).toBe(true);
}
});
});
describe('shard execution', () => {
const BUSY_LOOP = 'const end = Date.now() + 600000; while (Date.now() < end) {}';
// PIN UPDATE (deliberate): the strict expectedFiles check is now enforced
// for injected fake commands too (drift fix toward the free runner's
// behavior), so a fake PASSING command must print a synthetic bun terminal
// summary — a summary-less exit 0 is the truncation class and reads FAILED.
const PASS_WITH_SUMMARY = 'console.log("ok"); console.log("Ran 1 tests across 1 files. [1ms]")';
const commandFor = (files: string[]) => {
if (files[0] === 'spin') return { command: process.execPath, args: ['-e', BUSY_LOOP] };
if (files[0] === 'fail') return { command: process.execPath, args: ['-e', 'process.exit(3)'] };
if (files[0] === 'silent-pass') return { command: process.execPath, args: ['-e', 'console.log("ok")'] };
return { command: process.execPath, args: ['-e', PASS_WITH_SUMMARY] };
};
test('a spinning shard times out, is killed, and the run continues', async () => {
const lines: string[] = [];
const summary = await runPaidShards([['spin'], ['fail'], ['pass']], {
timeoutMs: 1_200,
jobs: 1,
commandFor,
log: (line) => lines.push(line),
});
const byName = (name: string) => summary.outcomes.find((o) => o.files[0] === name) as ShardOutcome;
expect(byName('spin').status).toBe('timed-out');
expect(byName('fail').status).toBe('failed');
expect(byName('pass').status).toBe('passed');
// The run never aborted: every shard reports, none is 'never-started'.
expect(summary).toMatchObject({
total: 3, executed: 3, passed: 1, failed: 1, timedOut: 1, neverStarted: 0,
});
// The spinner was killed at the deadline, not left to burn a core.
expect(byName('spin').elapsedMs).toBeLessThan(30_000);
expect(byName('spin').groupPid).toBeGreaterThan(0);
if (process.platform !== 'win32') {
expect(() => process.kill(byName('spin').groupPid as number, 0)).toThrow();
}
// Heartbeat: a START and a terminal line per shard, with elapsed seconds.
expect(lines.filter((l) => l.includes(' START ')).length).toBe(3);
expect(lines.some((l) => /TIMED-OUT in \d+s/.test(l))).toBe(true);
expect(lines.some((l) => /PASSED in \d+s/.test(l))).toBe(true);
// 90s, not the default 30s: this test spawns/kills three real children
// (one a busy-loop burning a full core) while 5 sibling shard processes
// compete for 8 vCPUs — observed blowing exactly the 30s ceiling at
// 30009ms under full-suite load while passing in isolation in 1.4s.
// Every assertion above is event-based; the only latency claim is the
// <30s kill-deadline sanity bound, which stays.
}, 90_000);
test('exit 0 WITHOUT the terminal summary is FAILED — enforced for injected commands too', async () => {
// The invisible-non-execution backstop: previously the paid runner
// exempted injected commandFor from the expectedFiles check, so a fake
// that exited 0 without bun's terminal summary recorded 'passed'. Now it
// matches the free runner: enforcement always on.
const summary = await runPaidShards([['silent-pass']], {
timeoutMs: 30_000, jobs: 1, commandFor, log: () => {},
});
expect(summary.outcomes[0].status).toBe('failed');
}, 30_000);
test('shard output spools to a per-shard log file; failures name the path', async () => {
const logDir = fs.mkdtempSync(path.join(os.tmpdir(), 'paid-shard-logs-'));
const lines: string[] = [];
try {
const summary = await runPaidShards([['fail'], ['pass']], {
timeoutMs: 30_000, jobs: 2, commandFor, logDir, log: (line) => lines.push(line),
});
const byName = (name: string) => summary.outcomes.find((o) => o.files[0] === name) as ShardOutcome;
expect(byName('fail').status).toBe('failed');
expect(byName('pass').status).toBe('passed');
// One log per shard, named by slug, and it holds the child's full stream
// (nothing buffered in RAM: the file IS the record).
const logs = fs.readdirSync(logDir).sort();
expect(logs.length).toBe(2);
expect(logs.some((f) => f.includes('fail'))).toBe(true);
const passLog = logs.find((f) => f.includes('pass')) as string;
expect(fs.readFileSync(path.join(logDir, passLog), 'utf8')).toContain('Ran 1 tests across 1 files.');
// Every shard announces its log path up front; the FAILED terminal line
// repeats it, the PASSED one stays clean.
expect(lines.filter((l) => l.includes('full log:') && !l.includes('FAILED')).length).toBe(2);
const failLine = lines.find((l) => l.includes('FAILED')) as string;
expect(failLine).toContain(logDir);
const passLine = lines.find((l) => l.includes('PASSED')) as string;
expect(passLine).not.toContain(logDir);
} finally {
fs.rmSync(logDir, { recursive: true, force: true });
}
}, 30_000);
test('summarize reports shards that never ran', () => {
const summary = summarize([
{ shard: 1, files: ['a'], status: 'passed', exitCode: 0, elapsedMs: 1, groupPid: 1 },
{ shard: 2, files: ['b'], status: 'never-started', exitCode: null, elapsedMs: 0, groupPid: null },
]);
expect(summary).toMatchObject({ total: 2, executed: 1, passed: 1, neverStarted: 1 });
});
});
describe('parent-side diff shard skipping', () => {
const ALL_NAMES = ['alpha-test', 'beta-test', 'gamma-registered'];
const TOUCHFILES: Record<string, string[]> = {
'alpha-test': ['a/**'],
'beta-test': ['b/**'],
'gamma-registered': ['g/**', 'test/skill-e2e-gamma.test.ts'],
};
const SOURCES: Record<string, string> = {
'test/skill-e2e-alpha.test.ts': "runSkillTest('alpha-test', async () => {});",
'test/skill-e2e-beta.test.ts': 'describeIfSelected("beta", ["beta-test"], () => {});',
// Constructed testName — invisible by quotes, mapped only via registration.
'test/skill-e2e-gamma.test.ts': 'const name = buildName(); test(name, async () => {});',
// No recognizable names, no registration — the fail-open class.
'test/skill-e2e-opaque.test.ts': "const shouldRun = process.env.EVALS_TIER === 'periodic';",
'test/codex-e2e.test.ts': 'codex tests keyed off CODEX_E2E_TOUCHFILES',
};
const opts = {
readSource: (file: string) => {
if (!(file in SOURCES)) throw new Error(`unreadable: ${file}`);
return SOURCES[file];
},
allNames: ALL_NAMES,
e2eTouchfiles: TOUCHFILES,
};
test('knownTestNamesInSource matches only exact quoted strings', () => {
expect(knownTestNamesInSource("x 'alpha-test' y", ['alpha-test', 'beta-test'])).toEqual(['alpha-test']);
expect(knownTestNamesInSource('x "beta-test" y', ['alpha-test', 'beta-test'])).toEqual(['beta-test']);
expect(knownTestNamesInSource('`alpha-test`', ['alpha-test'])).toEqual(['alpha-test']);
// Substring inside a longer quoted string is not a hit.
expect(knownTestNamesInSource("'alpha-test-extended'", ['alpha-test'])).toEqual([]);
});
test('selected name in file → shard kept', () => {
const d = diffSkipDecisionForFile('test/skill-e2e-alpha.test.ts', new Set(['alpha-test']), opts);
expect(d.kept).toBe(true);
expect(d.reason).toContain('alpha-test');
});
test('no selected names in file → skipped-by-diff', () => {
const d = diffSkipDecisionForFile('test/skill-e2e-beta.test.ts', new Set(['alpha-test']), opts);
expect(d.kept).toBe(false);
expect(d.reason).toContain('mapped test(s)');
});
test('dep-list registration maps files with constructed test names', () => {
const selected = diffSkipDecisionForFile('test/skill-e2e-gamma.test.ts', new Set(['gamma-registered']), opts);
expect(selected.kept).toBe(true);
const unselected = diffSkipDecisionForFile('test/skill-e2e-gamma.test.ts', new Set(['alpha-test']), opts);
expect(unselected.kept).toBe(false);
});
test('FAIL-OPEN: unmapped file kept, child self-skip authoritative', () => {
const d = diffSkipDecisionForFile('test/skill-e2e-opaque.test.ts', new Set(['alpha-test']), opts);
expect(d.kept).toBe(true);
expect(d.reason).toContain('fail-open');
});
test('FAIL-OPEN: unreadable source kept', () => {
const d = diffSkipDecisionForFile('test/skill-e2e-missing.test.ts', new Set(['alpha-test']), opts);
expect(d.kept).toBe(true);
expect(d.reason).toContain('fail-open');
});
test('FAIL-OPEN: non-skill-e2e paid files always kept', () => {
const d = diffSkipDecisionForFile('test/codex-e2e.test.ts', new Set(['alpha-test']), opts);
expect(d.kept).toBe(true);
expect(d.reason).toContain('non-skill-e2e');
});
test('run-all selection (null) bypasses skipping entirely', () => {
const shards = [['test/skill-e2e-alpha.test.ts'], ['test/skill-e2e-beta.test.ts']];
const { runnable, skipped } = partitionShardsByDiffSelection(shards, null, opts);
expect(runnable).toEqual(shards);
expect(skipped).toEqual([]);
});
test('EVALS_ALL=1 yields run-all selection (no git consulted)', () => {
const selection = computePaidDiffSelection({ EVALS_ALL: '1' } as NodeJS.ProcessEnv);
expect(selection.selectedNames).toBeNull();
expect(selection.reason).toContain('EVALS_ALL=1');
expect(selection.totalTests).toBeGreaterThan(0);
});
test('partition drops only all-skippable shards', () => {
const shards = [
['test/skill-e2e-alpha.test.ts'],
['test/skill-e2e-beta.test.ts'],
['test/skill-e2e-opaque.test.ts'],
['test/codex-e2e.test.ts'],
];
const { runnable, skipped } = partitionShardsByDiffSelection(shards, new Set(['alpha-test']), opts);
expect(runnable).toEqual([
['test/skill-e2e-alpha.test.ts'],
['test/skill-e2e-opaque.test.ts'],
['test/codex-e2e.test.ts'],
]);
expect(skipped.length).toBe(1);
expect(skipped[0].files).toEqual(['test/skill-e2e-beta.test.ts']);
});
test('taxonomy: skipped-by-diff counted separately, never conflated with never-started', () => {
const summary = summarize([
{ shard: 1, files: ['a'], status: 'passed', exitCode: 0, elapsedMs: 1, groupPid: 1 },
{ shard: 2, files: ['b'], status: 'skipped-by-diff', exitCode: null, elapsedMs: 0, groupPid: null },
{ shard: 3, files: ['c'], status: 'never-started', exitCode: null, elapsedMs: 0, groupPid: null },
]);
expect(summary).toMatchObject({
total: 3, executed: 1, passed: 1, skippedByDiff: 1, neverStarted: 1,
});
const lines = formatSummary(summary);
expect(lines[1]).toContain('1 skipped by diff');
expect(lines[1]).toContain('1 never started');
expect(lines.some((l) => l.includes('skipped-by-diff') && l.includes('b'))).toBe(true);
});
test('exit code ignores skipped-by-diff shards (they are successes)', () => {
const allGood = summarize([
{ shard: 1, files: ['a'], status: 'passed', exitCode: 0, elapsedMs: 1, groupPid: 1 },
{ shard: 2, files: ['b'], status: 'skipped-by-diff', exitCode: null, elapsedMs: 0, groupPid: null },
]);
expect(summaryExitCode(allGood)).toBe(0);
const withFailure = summarize([
{ shard: 1, files: ['a'], status: 'failed', exitCode: 1, elapsedMs: 1, groupPid: 1 },
{ shard: 2, files: ['b'], status: 'skipped-by-diff', exitCode: null, elapsedMs: 0, groupPid: null },
]);
expect(summaryExitCode(withFailure)).toBe(1);
const withNeverStarted = summarize([
{ shard: 1, files: ['a'], status: 'never-started', exitCode: null, elapsedMs: 0, groupPid: null },
{ shard: 2, files: ['b'], status: 'skipped-by-diff', exitCode: null, elapsedMs: 0, groupPid: null },
]);
expect(summaryExitCode(withNeverStarted)).toBe(1);
});
});
// Green-by-skip census: "Ran N tests" counts skips, so a codex/gemini file
// whose every test self-skipped (binary absent on the runner) exits 0 and
// used to read as coverage in the weekly report. The census label keeps the
// pass (service availability is host state, not a repo regression) but must
// say the shard verified nothing.
describe('all-skipped pass census', () => {
const base = { shard: 1, files: ['test/codex-e2e.test.ts'], exitCode: 0, elapsedMs: 1200, groupPid: 1 };
test('isAllSkippedPass: pass with every test skipped → true', () => {
expect(isAllSkippedPass({ ...base, status: 'passed', executedTests: 8, skippedTests: 8 } as ShardOutcome)).toBe(true);
});
test('isAllSkippedPass: real work, a failure, or no data → false', () => {
// one test actually ran
expect(isAllSkippedPass({ ...base, status: 'passed', executedTests: 8, skippedTests: 7 } as ShardOutcome)).toBe(false);
// zero tests: that's the hollow-shard guard's territory, not this label's
expect(isAllSkippedPass({ ...base, status: 'passed', executedTests: 0, skippedTests: 0 } as ShardOutcome)).toBe(false);
// non-pass statuses never get the label
expect(isAllSkippedPass({ ...base, status: 'failed', executedTests: 8, skippedTests: 8 } as ShardOutcome)).toBe(false);
// stream gave no counts (crash/timeout) — unknown, not all-skipped
expect(isAllSkippedPass({ ...base, status: 'passed', executedTests: null, skippedTests: null } as ShardOutcome)).toBe(false);
});
test('wiring: a real child’s skip recap flows through runPaidShard into skippedTests', async () => {
// End-to-end through the actual spawn/classify path (not hand-built
// outcomes): a fake shard child prints bun’s recap shape with every test
// skipped; the outcome must carry the parsed counts and formatSummary
// must label it. This is the seam the unit tests above skip.
const ALL_SKIP = 'console.log(" 0 pass"); console.log(" 3 skip"); console.log(" 0 fail"); console.log("Ran 3 tests across 1 files. [5ms]")';
const summary = await runPaidShards([['all-skip']], {
timeoutMs: 30_000,
jobs: 1,
commandFor: () => ({ command: process.execPath, args: ['-e', ALL_SKIP] }),
log: () => {},
});
const outcome = summary.outcomes[0];
expect(outcome.status).toBe('passed');
expect(outcome.executedTests).toBe(3);
expect(outcome.skippedTests).toBe(3);
expect(isAllSkippedPass(outcome)).toBe(true);
const lines = formatSummary(summary);
expect(lines.find((l) => l.includes('all-skip'))).toContain('all 3 tests SKIPPED');
}, 30_000);
test('formatSummary labels an all-skipped pass and leaves real passes alone', () => {
const lines = formatSummary(summarize([
{ ...base, status: 'passed', executedTests: 8, skippedTests: 8 } as ShardOutcome,
{ shard: 2, files: ['test/skill-e2e-review.test.ts'], status: 'passed', exitCode: 0, elapsedMs: 900, groupPid: 2, executedTests: 3, skippedTests: 0 } as ShardOutcome,
]));
const codexLine = lines.find((l) => l.includes('codex-e2e'));
const reviewLine = lines.find((l) => l.includes('skill-e2e-review'));
expect(codexLine).toContain('all 8 tests SKIPPED');
expect(codexLine).toContain('verified nothing');
expect(reviewLine).not.toContain('SKIPPED');
});
});