Files
gstack/test/test-free-shards.test.ts
T
Garry TanandOpenAI Codex 636175d349 v1.87.6.0 fix: make checks reliable and everyday validation faster (#2898)
* fix: acknowledge seeded plans before invoking review skills

* fix: distinguish current plan input from conversation history

* fix: keep hermetic plan reviews on manual permissions

* fix: distinguish tool discovery from file permission ownership

* fix: preserve initial plan mode in observation tests

* fix: wait for scope decisions before writing review findings

* fix: carry autoplan decisions consistently into review artifacts

* test: retain native failure context in periodic assertions

* fix: advance active file permissions before queued questions

* fix: finish red-team attempts before retry and cleanup

* fix: finalize plan format captures and judges before retry

* fix: cancel setup-gbrain SDK attempts before fixture cleanup

* test: select periodic consumers of the bounded attempt helper

* fix native Bash permission cards and queued questions

* fix: preserve independent decisions and review scope

Keep CEO approach, engineering scope and outside-review choices from approving independent remedies together. Carry declared contracts through DX polish and resolve new gaps before editing the plan. Regenerate every host and retain existing stop boundaries.

Validation: 654 focused tests passed across nine files; all-host generation passed. Full free and periodic validation pending.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix: require approval before design plan amendments

Align the Design review philosophy and rating recipe with its section protocol: resolve one proposed fix, then apply only that approved decision and retain honest scores for declined fixes.

Validation: 469 focused tests passed across four files; all-host generation passed.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix: observe native question completion before transcript persistence

Match owned completion hooks to submitted choices, reject conflicting or late answers, and retain bounded failure evidence.

* test: recognize review posture in acknowledged native questions

Require the selected mode acknowledgement, a completed follow-up question, and its current decoded display while preserving existing posture assertions.

* fix: preserve settled CEO choices and isolate pending remedies

Resolve established approach gates with cited authority and keep independent fixes out of unrelated option commitments and plan amendments.

* fix: carry approved DX choices through later review steps

Choose documentation approaches within the accepted scope and map resolved confusion points without reopening them through a bulk menu.

* test: handle native settings-file edit prompts

Keep one-time owned-file approvals and retain the actual sampled Autoplan permission frame with its matching barrier state.

* test: accept standard CEO reply directives with tuning footers

Recognize the exact trailing preference footer and letter-list directive while preserving current-display and exact acknowledgement checks.

* test: scope split reviewers to their generated plan artifacts

* test: observe native Bash permissions and invocation results

* test: handle owned Bash prompts during mode preference checks

* test: preserve synchronous subprocess rejection in Codex fixture

* Fix periodic review handoff navigation

Recognize review-first and explicit manual-next-step labels while preserving exact action families, manual preference, and ambiguous-menu rejection.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Bind pending file permissions to distinct current targets

Allow one captured file request to own the complete current dialog while unrelated file work is pending. Preserve same-path ambiguity, exact input ownership, and one-time grant checks.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Make paired CEO verification choices genuinely unresolved

Start the positive control with proposed manual checks so its unchanged oracle measures two new coverage decisions. Preserve runtime contracts, targets, count bounds, and all assertions.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep CEO review options and verification within approved scope

Audit every offered option for independent add-ons and keep new verification depth pending until accepted. Preserve already requested coverage and trace plan changes to the actual decision.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Assemble DX review artifacts before appending the final report

Keep early DX evidence above decisions, update artifact sections in place, and append the report using the actual current file suffix. Re-read after deleting an existing report before choosing the append anchor.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep outside plan reviews exclusive and invocation-owned

Follow one preflight-selected backend, terminate failed Codex work before fallback, and allocate extra prompt/output files uniquely. Consume only the current invocation’s completed output.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Select periodic completion evaluations for report writer changes

Register the shared review resolver for eight missing consumers and regress selection for all nine completion cases without changing their IDs or tiers.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep permission ambiguity fixtures on the same normalized target

Use distinct raw spellings of one target in the four negative fixtures so they exercise the normalized duplicate-owner guard after exact current-file disambiguation. Preserve the existing exception, no-input, diagnostic and cleanup assertions.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Clarify preserved contracts in engineering review fixture

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Recognize the offered DX follow-up handoff

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Check independent commitments before presenting review options

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep Codex review output and status in one shell invocation

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Distinguish seeded plans from reports written by a test attempt

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Recover clipped Autoplan file approvals with bounded viewport resizing

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Recover clipped Bash approvals before binding the complete command

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Isolate setup message tests from the shared checkout

Run the real installer in a temporary payload with private config, require successful completion, and guard source and binary contents and mtimes.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Fix periodic native permission and report completion handling

Match the pinned CLI's soft wraps and clipped headings without granting from incomplete frames. Retire completed file requests, retain mode annotations, and ask section captures for a short final acknowledgement after their full report is saved.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Preserve review approvals and validate DX comparison artifacts

Keep independent remedies and approved amendments explicit. Give the synthetic DX review its existing documentation and validate peer comparison as required analysis alongside four native decisions. Add positive and negative semantic calibrations while preserving review counts, model budgets and prompt size limits.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Make the five-finding CEO fixture's application boundary explicit

Materialize the request adapter and service composition used by the synthetic payment application. Explicitly declare the revised unregistered-event and mail-telemetry assumptions while preserving uncaught handler errors, the original invoice path and all five unresolved findings.

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Keep CEO state-path checks scoped to directory preparation

Co-authored-by: OpenAI Codex <noreply@openai.com>

* Use checked ports and bounded cleanup in pair-agent tests

Discover the daemon port from its owned state file, retain startup diagnostics, and await failed-start cleanup. Add occupied-port, early-exit, deadline, and foreign-state regressions while preserving the existing HTTP assertions and hook budgets.

Co-authored-by: Codex <noreply@openai.com>

* Preserve queued edit identity and recover clipped Bash permissions

Distinguish separately queued unfinished edits from mutation of one native tool ID. Keep grants bound to an exact owned request and reject reused IDs, ambiguous inputs, and competing owners.

Support the pinned renderer's literal em dash and request a repaint when only the Bash card's top rule is clipped. Grants still require the complete fresh card and an exact native acknowledgment.

Validation: 413 integrated parser/event tests passed; private repaint controls and joint source review passed. Full canonical suite and native periodic rerun remain pending.

Co-authored-by: Codex <noreply@openai.com>

* Keep periodic reviews within their approved contracts and deliverables

Carry exact approvals through engineering review, preserve declared contracts when amending CEO plans, and keep prioritization at the requested decision level. Materialize the revised synthetic SDK reference contract while retaining the five original documentation gaps.

Accept the observed semicolon in the finite DX handoff menu and register the direct source dependencies used by the engineering cases. Regenerate canonical review documents without changing model budgets, retries, count bands, or native completion assertions.

Validation: all-host generation and 275 review, fixture, selection and parity tests passed. Full free-suite and native periodic validation remain pending.

Co-authored-by: Codex <noreply@openai.com>

* Keep Eng approval cadence and independence guards explicit

* Accept ordinary punctuation in manual review handoffs

* Recover file permissions alongside queued Bash calls

* Carry approved DX work through later review findings

* Clarify the synthetic auth internal failure decision

* Bound the periodic DX fixture to onboarding changes

* Recognize native Design review handoff labels

* Hold scope in the integration-choice review fixture

* Carry approved Design decisions through review evidence

* Capture listener state when feedback reload fails

* Exclude workspace caches before checking deprecated flags

* Verify Design UI scope against a seeded review plan

* Clarify plan review decisions and outside-voice approval flow

* Reject setup menus in the Design UI gate

* docs: require focused repair validation before final acceptance

* fix: separate review commitments within existing prompt budgets

* docs: align generation and contributor validation guidance

* fix: advance native review prompts and count acknowledged findings

* chore: bump version and changelog (v1.87.1.0)

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* chore: enforce cheap checks and side-effect-free validation previews

* fix: handle owned Fetch permissions and oversized native cards

* test: ground review fixtures in independent executable contracts

* fix: preserve review decisions and verify reports before completion

* test: construct the synthetic credential URL without a scanner false positive

* test: materialize DX examples and verify their actual local behavior

* fix: clarify CEO review decisions and execution order

* fix: clarify review workflow ordering and select Design quality checks

* Fix review decision gates and incomplete evaluation fixtures

Persist CEO and engineering commitment ledgers before menus, preserve exact
approvals, and distinguish implementation structure from feature scope.
Route Autoplan through the canonical CEO Step 0 ordering. Classify DX findings
before requesting approval and ground runtime claims in actual evidence.

Complete neutral non-target fixture contracts and accept the captured Design
handoff purpose without relaxing its ownership or acknowledgment checks.
Record runtime-capability verification in AGENTS.md validation discipline.

Validation: 1,335 focused tests passed across 21 files; build, all-host freshness,
skill validation (647 artifacts / 107 tracked), and credential checks passed.
Prior paid failures are preserved; behavioral acceptance remains pending.

* Fix review decision boundaries and owned Read prompts

Preserve exact approvals across review options, compare consistent DX milestones,
and keep proposed implementation separate from review evidence. Bind modern
Read prompts to one immutable native request and wait for its result.

Retain captured regression verdicts, correct fixture error names, improve import
probe diagnostics, and record focused-first validation discipline in AGENTS.md.

* Clarify CEO and engineering review decisions

Use explicit decision steps, one engineering ledger, and clear scope/write transitions. Preserve exact approvals and distinguish pending test requirements. Keep unrelated generated content unchanged.

* Fix review decision ordering and native evaluation interactions

* Clarify engineering decisions and test artifact order

* Clarify pending choices and approvals in CEO reviews

* Make CEO review phases sequential and clarify completion

* Fix Design board submission intent matching

* Seed an existing browser test baseline for Autoplan

* Document decision-log payloads before state initialization

* Preserve exact review scope and decide one change before drafting options

* Require input identity before repeating passing model judges

* Honor permitted storage throughout CEO review completion

* Match complete native permission text within the pinned renderer contract

* Align review approvals, independent choices, and bounded validation

* fix: preserve reopened approvals and declare fixture interfaces

* fix: isolate review artifacts and audit complete questions

* fix: match detector artifact permissions to configured storage

* fix: complete native permissions and review fixture workflows

* fix: order CEO review work and separate engineering guarantees

* fix: preserve native validation and separate review choices

* fix: clarify review decisions and judge complete report context

* fix: constrain review judgments and retain parse failures

* fix: compare each affected value before review decisions

* fix: make engineering review decisions and completion order explicit

* fix: give the complete Autoplan evaluation a bounded chain budget

* fix(cso): diagnose forbidden Docker endpoints before tool lookup

* fix(reviews): reconcile workflow contracts and generated artifacts after main integration

* fix(evals): migrate retained regressions to the native review harness

* fix(tests): close native harness and workflow integration regressions

* fix(evals): preserve complete permission context and native menu contracts

* fix(tests): capture synchronous command output without pipe drain stalls

* fix(reviews): clarify decision and completion ordering

* fix(reviews): separate decision readiness from final completion checks

* refactor(reviews): consolidate decision rules and completion branches

* fix(plan-eng-review): order preparation and clarify decision routing

* fix(plan-eng-review): restore size and question-format guard parity

* fix(plan-eng-review): clarify scope phases and blocked completion

* fix(plan-eng-review): unify review flow and report destination

* fix(plan-eng-review): define bootstrap and question stage ownership

* fix(plan-eng-review): clarify review structure and design lookup

* fix(plan-eng-review): render report examples and show saved decisions

* fix: consolidate Eng review decisions and select their evaluations

* test: cover overlapping terminal attachments and clean merged runner type

* fix: preserve Office Hours relationship closings during review updates

* fix: retain pasted review targets across slash invocations

* docs: preserve validation traces and correct release scope

* test: cover pasted targets in both review skills

* fix: validate report artifacts before recording success

* fix: redact source roots at CSO report boundaries

* fix: bind native Design questions before answering

* test: select report privacy and native recovery regressions

* test: bind rejection predicate in extracted observers

* fix: bind complete boxed native questions

* test: keep the Design UI fixture on native review

* fix: preserve review decisions and evaluation completion outcomes

* fix: clarify CEO approval and report completion order

* fix: align native review evaluation ownership and completion

* fix: bind review evaluators to native decisions and owned artifacts

* fix: validate review decisions against native outcomes

* fix: preserve review evidence and Autoplan phase handoffs

* test: bind review evidence to owned decisions and completion

* fix: retain owned native history across compaction

* fix(evals): validate current review decisions and setup choices

* fix: bind Autoplan reviews and phase completion to current amended input

* fix: reconcile native review evidence and close Autoplan phases

* test: recognize owned whole-candidate complexity decisions

* test: preserve report freshness for approved investigation handoffs

* fix: recognize scoped review findings and isolate dual voice fixtures

* fix: make review handoffs and question dispatch self-contained

* test: recognize complete CEO decisions and procedural pauses

* fix: bind current CEO comparison options and risk intervals

* test: bind engineering decisions and completion to owned evidence

* fix: publish Autoplan phase reports before continuing tools

* test: verify actual Autoplan dual-review dispatch evidence

* test: select dual review when shared evidence fixtures change

* fix: clarify plan review decisions and completion gates

* fix: make CEO review decisions and return paths explicit

* test: keep Autoplan prompt files inside attempt state

* test: preserve source whitespace across permission dialog wraps

* fix: publish Autoplan phase reports before continuing

* test: recognize current CEO comparisons and reject inactive records

* fix: reconcile engineering decision states before completion

* test: recognize complete Design decisions and reports

* test: verify current engineering decisions before navigation

* Recognize source-owned component reduction choices

* fix: recognize current CEO ledger and commitment grids

* test: supply RequestPolicy context to Eng count fixture

* fix: save complete engineering decisions before asking

* fix: bind Autoplan publication to the complete phase readback

* chore: prepare 1.87.5.0 reliability release

* fix: clarify engineering review completion and preserve log failures

* fix: bind CEO saved choices and current section ancestry

* fix(evals): bind review execution and completion evidence

* fix(plan-ceo-review): verify complete decisions before asking

* fix(evals): preserve complete engineering choice records

* fix(evals): preserve complete review outcomes and bounded fixtures

* fix(autoplan): publish phase reports before advancing

* fix(plan-ceo-review): validate option fields before asking

* fix(plan-eng-review): verify current decisions after answers

* fix(evals): bind review decisions and bound fixture scope

* fix(plan-ceo-review): verify decision rows and edit saved checkpoints

* fix(evals): bind review evidence and scope document lookup

* fix(plan-eng-review): update resolution state with its answer

* fix(reviews): preserve complete questions through dispatch

* fix(evals): recognize completed mode declarations

* fix(evals): define cache consistency at wrapper completion

* fix(evals): validate owned initial scope and completed review handoffs

* fix: assemble complete CEO decision fields before saving

* fix: authenticate automatic mode decisions without guessing selectors

* fix: bind engineering coverage to approved regression contracts

* fix(evals): supply review helpers to native Eng capture

* fix(plan-eng-review): preserve the full selected option scope

* fix(evals): recognize owned engineering seed and regression evidence

* fix(evals): bind engineering retry reports to native approvals

* docs: clarify release guarantees (v1.87.5.0)

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix(evals): recognize owned engineering decisions and handoffs

* fix(evals): bind engineering decisions and completion evidence

* fix(tests): align review contracts and selection fixtures

* fix(skills): restore review prompt size limits

* fix(plan-eng-review): clarify review execution and completion

* fix(evals): preserve configured retries through all supervision layers

* Clarify Engineering decisions and report completion

* Keep native decision assertions within their source boundary

* fix: recognize owned engineering decisions and completed navigation

* fix: bind completed auto decisions to their current review

* fix: recognize explicit CEO source attribution

* fix: dispatch verified CEO decisions without recomposing fields

* test: expose existing execution deadlines to review actors

* fix: distinguish CEO decision records from incidental headings

* test: bind split-scope choices to the registered native actor

* test: connect reviewed regressions to required evaluation coverage

* Clarify CEO decision routing and completion stages

* test: expose existing section review deadlines to fixture actors

* test: recognize complete native CEO pacing inventories

* test: exclude answered history from current CEO payloads

* test: detect phase entry through owned skill HOME aliases

* test: validate native review completion and owned report permissions

* fix: make Autoplan close packets carry the parent handoff steps

* test: assess source-bound HOLD decisions within the existing deadline

* fix: keep CEO native decision fields under one formatting authority

* test: register integrated review and permission dependencies

* test: align native review adapters and finding coverage

Preserve explicit AUTO decisions, apply native single-select defaults, and bind complete cropped questions and report permissions to their owned requests. Require seeded review findings instead of crediting setup menus.

Keep captured failure controls and additive selection dependencies. The integrated candidate passed 3,099 focused tests across 65 files; affected paid validation remains required before publication.

* fix(autoplan): require phase reports before advancing

* fix(evals): bind setup and evidence to complete attempts

* fix(evals): bind native answers and pending writes to fixture scope

Preserve complete option rows when native descriptions wrap, retain current
owned Write arguments before journal publication, and keep engineering and
DX answers within their declared fixture interfaces. Add captured free
regressions without increasing model budgets or relaxing completion checks.

* fix(autoplan): verify phase reports across native tool paths

Guard owned methodology reads and reviewer dispatches, detect complete driver
loads through Bash, and distinguish report-only edits from implementation
changes. Follow authenticated native UUID ancestry when journal writes arrive
out of order and verify earlier native content for cached phase reads.

Keep current close acknowledgment and parent publication in order, require CEO
entry before later phases, and register captured failure regressions.

* fix(evals): honor native input and collection lifecycles

Match complete native Edit panes and truncated question borders, reject stderr close before EOF, and stop the CEO split fixture once its acknowledged scope decisions are collected. Keep semantic validation, process failures, report requirements, and absolute deadlines authoritative.

Add captured-event and real-process regressions with selection dependencies. Focused checks pass; final integrated paid and full-suite acceptance remain pending.

* fix(autoplan): retain native session ownership across directory changes

Recover missed native UUID ancestry through the existing strict graph while preserving ordinary event order and legacy scoping. Bind publication hooks to Claude's original project directory while retaining current cwd for requested file paths.

Captured public-event regressions, existing caller checks, and a pinned native CLI loopback verify both fixes. Preserve failed attempts and require fresh paid and final full-suite acceptance.

* docs: align evaluation limits and completion version

* fix(autoplan): allow authenticated phase reads during journal streaming

* fix(evals): bind clipped native questions and owned edit dialogs

* fix: preserve overlay retries and bounded cleanup

* fix: recognize owned planning preludes in native questions

* docs: explain overlay scheduling and cleanup guarantees

* fix: require fresh publication after Autoplan phase reruns

* Release gstack 1.87.6

* fix: preserve CI paths, process identity, and test deadlines

* fix: keep informational setup commands independent of install probes

* fix: clarify plan review decisions and bound source audit reports

* Fix remaining Windows identity and native path CI failures

* Clarify CEO review decision and reviewer-result routing

* test: accept no-install planner in retry supervision

* fix(ceo-review): make review decisions and report completion explicit

* perf(test): add fast PR gates, input-keyed judge reuse and isolated free shards

* fix(test): start isolated CEO smoke from its existing project plan

* fix(test): repair CI fixture races and preserve retry evidence

* fix(ceo-review): clarify approvals, depth and saved completion

---------

Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-09-22 14:57:52 -04:00

889 lines
44 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.
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import {
isFreeTestFile,
collectFreeTestFiles,
detectWindowsFragility,
curateWindowsSafe,
stableHash,
assignFilesToShards,
buildShardArgs,
normalizeRelativePath,
runFreeShard,
FreeRunReporter,
buildRunEpilogue,
FREE_TEST_TIMEOUT_MS,
DEFAULT_WALL_TIMEOUT_MS,
PER_FILE_WALL_MS,
wallTimeoutForShard,
KNOWN_WINDOWS_INCOMPATIBLE,
TEST_ROOTS,
TREE_MUTATING,
WORKER_HOSTILE,
} from '../scripts/test-free-shards';
import {
loadFreeTestDurations,
packShardsByDuration,
wallTimeoutForPackedShard,
createFreeCiPlan,
validateFreeCiPlan,
verifyFreeCiResults,
eligibleFreeRetryFiles,
selectQuickFreeFiles,
QUICK_CORE,
type FreeCiResult,
DEFAULT_WALL_TIMEOUT_MS as WALL_BASE_MS,
} from '../scripts/test-free-shards';
const ROOT = path.resolve(import.meta.dir, '..');
describe('test-free-shards: isolated CI and explicit quick feedback', () => {
const files = Array.from({ length: 8 }, (_, i) => `test/sample-${i}.test.ts`);
const durations = Object.fromEntries(files.map((file, i) => [file, (i + 1) * 1_000]));
const plan = createFreeCiPlan(files, 4, durations, 'revision-a');
const receipts = (): FreeCiResult[] => plan.shards.map(shard => ({
planId: plan.id, revision: plan.revision, retry: null,
outcome: { shard: shard.shard, files: shard.files, status: 'passed', exitCode: 0,
elapsedMs: 10, groupPid: null, failingFiles: [], unattributedFailures: 0,
summary: { testsRan: shard.files.length, filesRan: shard.files.length, sawTerminalSummary: true } },
}));
test('one deterministic duration plan covers the complete census exactly once', () => {
expect(createFreeCiPlan([...files].reverse(), 4, durations, 'revision-a')).toEqual(plan);
expect(plan.shards.flatMap(shard => shard.files).sort()).toEqual(files);
expect(Math.max(...plan.shards.map(shard => shard.predictedMs))).toBe(9_000);
expect(() => validateFreeCiPlan(plan, files, 'revision-a')).not.toThrow();
expect(() => validateFreeCiPlan(plan, files.slice(1), 'revision-a')).toThrow(/every free file/);
expect(() => validateFreeCiPlan(plan, files, 'other-revision')).toThrow(/identity or revision/);
expect(() => validateFreeCiPlan({ ...plan, id: 'stale' }, files, 'revision-a')).toThrow(/identity/);
});
test('missing, duplicate, stale and partial receipts cannot clear the aggregate', () => {
expect(() => verifyFreeCiResults(plan, receipts())).not.toThrow();
expect(() => verifyFreeCiResults(plan, receipts().slice(1))).toThrow(/Missing or duplicate/);
const duplicate = receipts(); duplicate[1] = duplicate[0];
expect(() => verifyFreeCiResults(plan, duplicate)).toThrow(/identity, shard or file/);
const stale = receipts(); stale[0].revision = 'old';
expect(() => verifyFreeCiResults(plan, stale)).toThrow(/identity, shard or file/);
const partial = receipts(); partial[0].outcome.files = [];
expect(() => verifyFreeCiResults(plan, partial)).toThrow(/file coverage/);
});
test('timeout, truncation and false exit-zero receipts remain failures', () => {
for (const status of ['timed-out', 'failed'] as const) {
const failed = receipts(); failed[0].outcome.status = status;
failed[0].outcome.unattributedFailures = 1;
expect(() => verifyFreeCiResults(plan, failed)).toThrow(/Failed or incomplete/);
}
const inconsistent = receipts(); inconsistent[0].outcome.exitCode = 1;
expect(() => verifyFreeCiResults(plan, inconsistent)).toThrow(/Inconsistent passing/);
});
test('claimed success requires terminal evidence that every planned file executed', () => {
const absent = receipts(); delete absent[0].outcome.summary;
expect(() => verifyFreeCiResults(plan, absent)).toThrow(/execution summary/);
const truncated = receipts(); truncated[0].outcome.summary!.sawTerminalSummary = false;
expect(() => verifyFreeCiResults(plan, truncated)).toThrow(/execution summary/);
const partial = receipts(); partial[0].outcome.summary!.filesRan = plan.shards[0].files.length - 1;
expect(() => verifyFreeCiResults(plan, partial)).toThrow(/execution summary/);
const missingCount = receipts(); missingCount[0].outcome.summary!.testsRan = null;
expect(() => verifyFreeCiResults(plan, missingCount)).toThrow(/execution summary/);
});
test('retains original failures and enforces the five-file retry cap across machines', () => {
const retried = receipts();
const markRetried = (index: number) => {
const result = retried[index];
result.retry = { ...result.outcome, files: [...result.outcome.files], shard: 5 };
result.outcome = { ...result.outcome, status: 'failed', exitCode: 1, failingFiles: [...result.outcome.files] };
};
markRetried(0);
expect(() => verifyFreeCiResults(plan, retried)).not.toThrow();
delete retried[0].retry!.summary;
expect(() => verifyFreeCiResults(plan, retried)).toThrow(/Failed or incomplete/);
retried[0].retry!.summary = { testsRan: 1, filesRan: 1, sawTerminalSummary: true };
expect(() => verifyFreeCiResults(plan, retried)).toThrow(/Failed or incomplete/);
retried[0].retry!.summary = { ...retried[0].outcome.summary! };
retried[0].retry!.files = [];
expect(() => verifyFreeCiResults(plan, retried)).toThrow(/Failed or incomplete/);
retried[0].retry!.files = [...retried[0].outcome.files];
markRetried(1); markRetried(2);
expect(() => verifyFreeCiResults(plan, retried)).toThrow(/five-file limit/);
});
test('a passing retry cannot replace foreign, sibling-shard or duplicate failure attribution', () => {
for (const failures of [['test/unplanned.test.ts'], [plan.shards[1].files[0]],
[plan.shards[0].files[0], plan.shards[0].files[0]]]) {
const results = receipts(), first = results[0];
first.outcome = { ...first.outcome, status: 'failed', exitCode: 1, failingFiles: failures };
first.retry = { ...receipts()[0].outcome, files: [...new Set(failures)],
summary: { testsRan: 1, filesRan: new Set(failures).size, sawTerminalSummary: true } };
expect(eligibleFreeRetryFiles([first.outcome])).toBeNull();
expect(() => verifyFreeCiResults(plan, results)).toThrow(/Failed or incomplete/);
}
});
test('quick feedback includes its deterministic core and known fast free files only', () => {
const candidates = [...QUICK_CORE, ...files, 'test/unknown.test.ts', 'test/codex-e2e.test.ts'];
const measured = { ...durations, [QUICK_CORE[0]]: 99_000, 'test/codex-e2e.test.ts': 1 };
expect(selectQuickFreeFiles(candidates, measured)).toEqual([...QUICK_CORE, ...files.slice(0, 2)]);
expect(QUICK_CORE.every(file => collectFreeTestFiles(ROOT).includes(file))).toBe(true);
});
test('CLI emits a shared plan, accounts for an empty shard, and rejects missing receipts', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'free-ci-contract-'));
const script = path.join(ROOT, 'scripts/test-free-shards.ts');
const planPath = path.join(dir, 'plan.json');
const resultDir = path.join(dir, 'results');
try {
const planned = Bun.spawnSync([process.execPath, script, '--ci-plan', planPath, '--shards', '2000'], { timeout: 10_000 });
expect(planned.exitCode, planned.stderr.toString()).toBe(0);
const emitted = JSON.parse(fs.readFileSync(planPath, 'utf8'));
expect(JSON.parse(planned.stdout.toString()).shard).toHaveLength(2000);
const empty = emitted.shards.find((shard: { files: string[] }) => shard.files.length === 0);
const ran = Bun.spawnSync([process.execPath, script, '--ci-run', planPath, '--shard', String(empty.shard),
'--result', path.join(resultDir, 'empty.json')], { timeout: 10_000 });
expect(ran.exitCode, ran.stderr.toString()).toBe(0);
const emptyOutcome = JSON.parse(fs.readFileSync(path.join(resultDir, 'empty.json'), 'utf8')).outcome;
expect(emptyOutcome.files).toEqual([]);
expect(emptyOutcome.summary).toEqual({ testsRan: 0, filesRan: 0, sawTerminalSummary: false });
const sample = emitted.shards.find((shard: { files: string[] }) => shard.files.includes('test/strict-output.test.ts'));
const nonempty = Bun.spawnSync([process.execPath, script, '--ci-run', planPath, '--shard', String(sample.shard),
'--result', path.join(resultDir, 'sample.json')], { timeout: 10_000 });
expect(nonempty.exitCode, nonempty.stderr.toString()).toBe(0);
const summary = JSON.parse(fs.readFileSync(path.join(resultDir, 'sample.json'), 'utf8')).outcome.summary;
expect(summary.sawTerminalSummary).toBe(true);
expect(summary.filesRan).toBe(sample.files.length);
expect(summary.testsRan).toBeGreaterThan(0);
const aggregate = Bun.spawnSync([process.execPath, script, '--ci-verify', planPath, '--results', resultDir], { timeout: 10_000 });
expect(aggregate.exitCode).toBe(1);
expect(aggregate.stderr.toString()).toContain('Missing or duplicate CI shard results');
const quick = Bun.spawnSync([process.execPath, script, '--quick', '--list'], { timeout: 10_000 });
expect(quick.exitCode, quick.stderr.toString()).toBe(0);
expect(quick.stdout.toString()).toContain('not release acceptance');
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
});
describe('test-free-shards: enumeration', () => {
test('isFreeTestFile rejects non-test files', () => {
expect(isFreeTestFile('test/foo.ts')).toBe(false);
expect(isFreeTestFile('test/foo.test.ts')).toBe(true);
expect(isFreeTestFile('test/foo.test.tsx')).toBe(true);
expect(isFreeTestFile('test/foo.test.mjs')).toBe(true);
});
test('isFreeTestFile rejects paid eval tests', () => {
expect(isFreeTestFile('test/skill-e2e-foo.test.ts')).toBe(false);
expect(isFreeTestFile('test/skill-llm-eval.test.ts')).toBe(false);
expect(isFreeTestFile('test/codex-e2e.test.ts')).toBe(false);
expect(isFreeTestFile('test/codex-e2e-sol-scope.test.ts')).toBe(false);
expect(isFreeTestFile('test/gemini-e2e.test.ts')).toBe(false);
});
test('collectFreeTestFiles returns sorted, deduped, only-free list', () => {
const files = collectFreeTestFiles(ROOT);
expect(files.length).toBeGreaterThan(10);
expect(files).toEqual([...files].sort());
expect(new Set(files).size).toBe(files.length);
for (const f of files) {
expect(isFreeTestFile(f)).toBe(true);
}
});
test('normalizeRelativePath converts Windows backslashes to forward slashes', () => {
expect(normalizeRelativePath('test\\foo\\bar.test.ts')).toBe('test/foo/bar.test.ts');
expect(normalizeRelativePath('test/foo/bar.test.ts')).toBe('test/foo/bar.test.ts');
});
});
describe('test-free-shards: Windows curation', () => {
function withTempFile(content: string, fn: (filePath: string) => void): void {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'curation-test-'));
const file = path.join(dir, 'sample.test.ts');
fs.writeFileSync(file, content);
try {
fn(file);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
test('detects /bin/bash hardcode', () => {
withTempFile(`spawn('/bin/bash', ['-c', 'echo hi']);`, (f) => {
expect(detectWindowsFragility(f)?.reason).toBe('hardcoded /bin/sh or /bin/bash');
});
});
test('detects spawn("sh", ...)', () => {
// tripwire-exempt: string fixture fed to detectWindowsFragility, not a call
withTempFile(`spawnSync('sh', ['-c', 'command -v claude']);`, (f) => {
expect(detectWindowsFragility(f)?.reason).toBe('spawn("sh", ...)');
});
});
test('detects raw /tmp/ paths', () => {
withTempFile(`const TMPERR = '/tmp/codex-err.txt';`, (f) => {
expect(detectWindowsFragility(f)?.reason).toBe('raw /tmp/ path (use os.tmpdir())');
});
});
test('detects which claude shell command', () => {
// tripwire-exempt: string fixture fed to detectWindowsFragility, not a call
withTempFile(`execSync('which claude').trim();`, (f) => {
expect(detectWindowsFragility(f)?.reason).toBe('which claude (use Bun.which)');
});
});
test('Windows-safe code passes the filter', () => {
withTempFile(`import { spawn } from 'child_process'; spawn(claude.command, args);`, (f) => {
expect(detectWindowsFragility(f)).toBeNull();
});
});
test('still detects a direct bin shebang launch', () => {
withTempFile(`spawnSync(path.join(ROOT, 'bin', 'tool'), [], { timeout: 1000 });`, (f) => {
expect(detectWindowsFragility(f)?.reason).toBe('spawns bin/ shebang script (Windows CreateProcess does not parse shebangs)');
});
});
test('curateWindowsSafe partitions files into safe + excluded', () => {
const files = collectFreeTestFiles(ROOT);
const result = curateWindowsSafe(files, ROOT);
expect(result.safe.length + result.excluded.length).toBe(files.length);
// Its bin/ reference is passed to Bun argv, so it must exercise native
// Windows taskkill supervision instead of disappearing behind curation.
expect(result.safe).toContain('test/claude-code-runner.test.ts');
expect(result.safe).toContain('test/claude-code-windows-job.test.ts');
// These replay real callbacks with injected subprocess/SDK boundaries.
// Fixture-only bin paths must not hide the native PATH/supervision checks.
expect(result.safe).toContain('test/setup-gbrain-remote-caller.test.ts');
expect(result.safe).toContain('test/cso-windows-build-contract.test.ts');
// Sanity: at least one excluded entry, since we know test/ship-version-sync.test.ts uses /bin/bash
expect(result.excluded.length).toBeGreaterThan(0);
// Every excluded entry has a non-empty reason
for (const { reason } of result.excluded) {
expect(reason.length).toBeGreaterThan(0);
}
});
test('excludes POSIX CSO helper suites while retaining portable image metadata coverage', () => {
const posixOnly = [
'test/cso-preparation-adversarial.test.ts',
'test/cso-preparation-container.test.ts',
'test/cso-preparation-executor.test.ts',
'test/cso-scanner-cli.test.ts',
'test/cso-verification-cleanup.test.ts',
'test/cso-witness.test.ts',
];
const portable = ['test/cso-image-provisioning.test.ts', 'test/cso-public-ghcr.test.ts'];
const result = curateWindowsSafe([...posixOnly, ...portable], ROOT);
expect(result.safe).toEqual(portable);
expect(result.excluded.map(({ file }) => file).sort()).toEqual(posixOnly.sort());
for (const { reason } of result.excluded) expect(reason).toMatch(/Linux|POSIX|Windows/);
});
});
describe('test-free-shards: sharding', () => {
test('stableHash is deterministic', () => {
expect(stableHash('foo.test.ts')).toBe(stableHash('foo.test.ts'));
expect(stableHash('foo.test.ts')).not.toBe(stableHash('bar.test.ts'));
});
test('assignFilesToShards partitions every file across exactly shardCount shards', () => {
const files = ['a.test.ts', 'b.test.ts', 'c.test.ts', 'd.test.ts', 'e.test.ts'];
const shards = assignFilesToShards(files, 3);
expect(shards.length).toBe(3);
expect(shards.flat().sort()).toEqual([...files].sort());
});
test('empty shards are preserved so indices stay stable for a CI matrix', () => {
// 2 files can never occupy 10 shards — the rest MUST be present and empty,
// not filtered out (filtering renumbered every later shard by occupancy).
const files = ['a.test.ts', 'b.test.ts'];
const shards = assignFilesToShards(files, 10);
expect(shards.length).toBe(10);
expect(shards.flat().sort()).toEqual([...files].sort());
expect(shards.some((s) => s.length === 0)).toBe(true);
});
test("a file's shard index depends only on its own path — other files never renumber it", () => {
const target = 'test/target.test.ts';
const expected = stableHash(target) % 7;
const alone = assignFilesToShards([target], 7);
const crowded = assignFilesToShards(
[target, 'test/a.test.ts', 'test/b.test.ts', 'test/c.test.ts', 'test/d.test.ts', 'browse/test/e.test.ts'],
7,
);
expect(alone.findIndex((s) => s.includes(target))).toBe(expected);
expect(crowded.findIndex((s) => s.includes(target))).toBe(expected);
});
test('assignFilesToShards rejects invalid shard counts', () => {
expect(() => assignFilesToShards(['a.test.ts'], 0)).toThrow();
expect(() => assignFilesToShards(['a.test.ts'], -1)).toThrow();
});
test('shards are stable across runs (same files always land in same shard)', () => {
const files = ['x.test.ts', 'y.test.ts', 'z.test.ts'];
const a = assignFilesToShards(files, 5);
const b = assignFilesToShards(files, 5);
expect(a).toEqual(b);
});
});
describe('test-free-shards: shard args', () => {
test('resolves exact absolute selectors (no substring shard bleed) and pins the per-test timeout', () => {
const args = buildShardArgs(['test/foo.test.ts'], { rootDir: ROOT });
expect(args[0]).toBe('test');
expect(args[1]).toBe(path.resolve(ROOT, 'test/foo.test.ts'));
expect(args).toContain(`--timeout=${FREE_TEST_TIMEOUT_MS}`);
expect(args).toContain('--max-concurrency=1');
expect(args).not.toContain('--parallel');
});
test('parallel mode swaps serial max-concurrency for --parallel', () => {
const args = buildShardArgs(['test/foo.test.ts'], { rootDir: ROOT, parallel: true });
expect(args).toContain('--parallel');
expect(args).not.toContain('--max-concurrency=1');
});
test('per-test timeout matches the 30s the package.json test script used before the repoint', () => {
expect(FREE_TEST_TIMEOUT_MS).toBe(30_000);
});
});
describe('test-free-shards: strict shard execution', () => {
// Fake command seam, same pattern as test/paid-shards.test.ts: each "file"
// label selects a child command. Unlike the paid runner, runFreeShard
// enforces the terminal-summary file count on injected commands too, so
// fake PASSING commands must print a synthetic bun summary line.
const SUMMARY_1 = 'Ran 3 tests across 1 files. [12.00ms]';
const BUSY_LOOP = 'const end = Date.now() + 600000; while (Date.now() < end) {}';
const FAIL_LINE = '(fa' + 'il) planted failure [0.10ms]'; // split so this source file never contains a raw bun fail line
const commandFor = (files: string[]) => {
const mode = files[0];
if (mode === 'spin') return { command: process.execPath, args: ['-e', BUSY_LOOP] };
if (mode === 'no-summary') return { command: process.execPath, args: ['-e', 'console.log("ok")'] };
if (mode === 'fail-exit') {
return { command: process.execPath, args: ['-e', `console.log(${JSON.stringify(SUMMARY_1)}); process.exit(3)`] };
}
if (mode === 'fail-line-exit-zero') {
return { command: process.execPath, args: ['-e', `console.log(${JSON.stringify(FAIL_LINE)}); console.log(${JSON.stringify(SUMMARY_1)})`] };
}
if (mode === 'wrong-file-count') {
return { command: process.execPath, args: ['-e', 'console.log("Ran 3 tests across 4 files. [12.00ms]")'] };
}
return { command: process.execPath, args: ['-e', `console.log(${JSON.stringify(SUMMARY_1)})`] };
};
test('exit 0 WITHOUT bun\'s terminal summary is a FAILURE (anti-truncation backstop)', async () => {
const outcome = await runFreeShard(['no-summary'], 1, 1, { commandFor, quiet: true, log: () => {} });
expect(outcome.status).toBe('failed');
expect(outcome.exitCode).toBe(0);
});
test('exit 0 WITH the terminal summary passes, and the per-shard epilogue line is printed', async () => {
const lines: string[] = [];
const outcome = await runFreeShard(['pass'], 1, 1, { commandFor, quiet: true, log: (l) => lines.push(l) });
expect(outcome.status).toBe('passed');
expect(lines.some((l) => /^\[test:free\] shard 1\/1: 1 files, \d+s, pass$/.test(l))).toBe(true);
});
test('a non-zero exit stays a failure even when the summary is present', async () => {
const outcome = await runFreeShard(['fail-exit'], 1, 1, { commandFor, quiet: true, log: () => {} });
expect(outcome.status).toBe('failed');
expect(outcome.exitCode).toBe(3);
});
test('a printed (fail) result line is a failure even on exit 0 (bun exit-code bug class)', async () => {
const outcome = await runFreeShard(['fail-line-exit-zero'], 1, 1, { commandFor, quiet: true, log: () => {} });
expect(outcome.status).toBe('failed');
expect(outcome.exitCode).toBe(0);
});
test('a summary reporting the wrong file count is a failure (partial execution)', async () => {
const outcome = await runFreeShard(['wrong-file-count'], 1, 1, { commandFor, quiet: true, log: () => {} });
expect(outcome.status).toBe('failed');
});
test('a spinning shard is killed at the wall-clock deadline and reported timed-out, distinct from failed', async () => {
const lines: string[] = [];
const outcome = await runFreeShard(['spin'], 1, 1, {
commandFor, quiet: true, wallTimeoutMs: 1_200, log: (l) => lines.push(l),
});
expect(outcome.status).toBe('timed-out');
expect(outcome.status).not.toBe('failed');
// Killed at the deadline, not left to burn the full 600s busy loop.
expect(outcome.elapsedMs).toBeLessThan(30_000);
expect(outcome.groupPid).toBeGreaterThan(0);
if (process.platform !== 'win32') {
expect(() => process.kill(outcome.groupPid as number, 0)).toThrow();
}
expect(lines.some((l) => /^\[test:free\] shard 1\/1: 1 files, \d+s, timed-out$/.test(l))).toBe(true);
}, 30_000);
test('an empty shard is a fast no-op success and never spawns (stable CI-matrix indices)', async () => {
const lines: string[] = [];
const outcome = await runFreeShard([], 7, 20, {
commandFor: () => { throw new Error('an empty shard must not spawn a child'); },
log: (l) => lines.push(l),
});
expect(outcome.status).toBe('passed');
// Mutation-caught gap: bun strips types at runtime, so a missing
// failingFiles here feeds undefined into the flaky-retry flatMap.
expect(outcome.failingFiles).toEqual([]);
expect(outcome.unattributedFailures).toBe(0);
expect(lines.some((l) => /^\[test:free\] shard 7\/20: 0 files, 0s, pass$/.test(l))).toBe(true);
});
test('the log-file path is announced once at start and the PASS epilogue repeats it', async () => {
const lines: string[] = [];
const outcome = await runFreeShard(['pass'], 1, 1, { commandFor, quiet: true, log: (l) => lines.push(l) });
expect(outcome.status).toBe('passed');
const announced = lines.filter((l) => /^\[test:free\] full log: .+gstack-free-test-.+\.log$/.test(l));
expect(announced.length).toBe(1);
// PASS epilogue carries the counts from the terminal summary + the log path.
expect(lines.some((l) => /^\[test:free\] PASS — 3 tests, 1 files, \d+s\. Full log: .+\.log$/.test(l))).toBe(true);
});
test('spawned shard gets throwaway TMPDIR but NEVER an injected GSTACK_HOME', async () => {
// GSTACK_HOME injection was tried and reverted: one shared scratch home
// per invocation made 6,900 tests share MUTABLE state — config tests
// wrote keys that relink/update-check tests then read (12 measured
// cross-contamination failures). This pin keeps the regression out.
const captureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'free-shard-env-'));
const dump = path.join(captureDir, 'env.json');
try {
const script =
`const fs = require("fs");`
+ `fs.writeFileSync(${JSON.stringify(dump)}, JSON.stringify({`
+ ` home: process.env.GSTACK_HOME ?? null, tmp: process.env.TMPDIR,`
+ ` tmpExists: fs.existsSync(process.env.TMPDIR || "") }));`
+ `console.log(${JSON.stringify(SUMMARY_1)});`;
const outcome = await runFreeShard(['env-dump'], 1, 1, {
commandFor: () => ({ command: process.execPath, args: ['-e', script] }),
quiet: true,
log: () => {},
});
expect(outcome.status).toBe('passed');
const seen = JSON.parse(fs.readFileSync(dump, 'utf8'));
// GSTACK_HOME passes through untouched (whatever the parent had, incl. unset).
expect(seen.home).toBe(process.env.GSTACK_HOME ?? null);
// TMPDIR is a per-shard throwaway, cleaned up once the shard finishes.
expect(seen.tmp).toContain('gstack-free-shard-');
expect(seen.tmpExists).toBe(true);
expect(seen.tmp).not.toBe(process.env.TMPDIR ?? '');
expect(fs.existsSync(seen.tmp)).toBe(false);
} finally {
fs.rmSync(captureDir, { recursive: true, force: true });
}
});
test('concurrent shards isolate browser state and remove it on success or failure', async () => {
const captureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'free-shard-browse-'));
const inheritedState = path.join(captureDir, 'host-browse.json');
const parentState = process.env.BROWSE_STATE_FILE;
fs.writeFileSync(inheritedState, 'host daemon state');
try {
const outcomes = await Promise.all([0, 3].map((exitCode, index) => {
const dump = path.join(captureDir, `shard-${index}.json`);
const script = `
const fs = require('fs');
const path = require('path');
const { resolveConfig } = require(${JSON.stringify(path.join(ROOT, 'browse/src/config.ts'))});
const config = resolveConfig();
fs.mkdirSync(config.stateDir, { recursive: true });
fs.writeFileSync(config.stateFile, ${JSON.stringify(String(index))});
fs.writeFileSync(${JSON.stringify(dump)}, JSON.stringify({
state: process.env.BROWSE_STATE_FILE,
resolvedState: config.stateFile,
tmp: process.env.TMPDIR,
profile: process.env.CHROMIUM_PROFILE,
written: fs.readFileSync(config.stateFile, 'utf8'),
}));
console.log(${JSON.stringify(SUMMARY_1)});
process.exit(${exitCode});
`;
return runFreeShard(['browser-state'], index + 1, 2, {
env: { ...process.env, BROWSE_STATE_FILE: inheritedState },
commandFor: () => ({ command: process.execPath, args: ['-e', script] }),
quiet: true,
log: () => {},
});
}));
expect(outcomes.map((outcome) => outcome.status)).toEqual(['passed', 'failed']);
const seen = [0, 1].map((index) => JSON.parse(fs.readFileSync(path.join(captureDir, `shard-${index}.json`), 'utf8')));
expect(seen[0].state).not.toBe(seen[1].state);
expect(seen[0].profile).not.toBe(seen[1].profile);
for (const [index, shard] of seen.entries()) {
expect(shard.state).not.toBe(inheritedState);
expect(shard.resolvedState).toBe(shard.state);
expect(shard.written).toBe(String(index));
const ownedRoot = path.dirname(shard.tmp);
expect(path.relative(ownedRoot, shard.state)).toBe(path.join('.gstack', 'browse.json'));
expect(path.dirname(shard.profile)).toBe(ownedRoot);
expect(fs.existsSync(ownedRoot)).toBe(false);
expect(fs.existsSync(shard.state)).toBe(false);
}
expect(fs.readFileSync(inheritedState, 'utf8')).toBe('host daemon state');
expect(process.env.BROWSE_STATE_FILE).toBe(parentState);
} finally {
fs.rmSync(captureDir, { recursive: true, force: true });
}
});
});
describe('test-free-shards: output contract (log capture, quiet console, failure epilogue)', () => {
// Convention from the block above: never write a raw bun fail line into this
// source file — build it at runtime so a printed source excerpt can't trip
// the strict classifier.
const FAIL_WORD = '(fa' + 'il)';
const failLine = (name: string) => `${FAIL_WORD} ${name} [0.10ms]`;
const SUMMARY_1 = 'Ran 3 tests across 1 files. [12.00ms]';
/** Fake child that prints the given lines (stdout, then stderr) and exits. */
const commandPrinting = (stdoutLines: string[], stderrLines: string[] = [], exitCode = 0) => () => ({
command: process.execPath,
args: ['-e',
stdoutLines.map((l) => `console.log(${JSON.stringify(l)});`).join('')
+ stderrLines.map((l) => `console.error(${JSON.stringify(l)});`).join('')
+ (exitCode !== 0 ? `process.exit(${exitCode});` : ''),
],
});
test('failure epilogue names the failing test, attributed to its file-chunk header', async () => {
const lines: string[] = [];
const commandFor = commandPrinting(['test/planted.test.ts:', failLine('planted failure'), SUMMARY_1]);
const outcome = await runFreeShard(['planted'], 1, 1, { commandFor, quiet: true, log: (l) => lines.push(l) });
expect(outcome.status).toBe('failed');
expect(lines.some((l) =>
/^\[test:free\] FAIL — 1 failing test\(s\) in 1 file\(s\), 0 crashed worker\(s\)\. Full log: .+\.log$/.test(l),
)).toBe(true);
expect(lines).toContain(' ✗ test/planted.test.ts — planted failure');
});
test('crash markers surface in the epilogue as crashed+retried workers', async () => {
const lines: string[] = [];
const commandFor = commandPrinting([
'test/crashy.test.ts:',
'⟳ crashed running test/crashy.test.ts, retrying',
'test/crashy.test.ts:',
'✗ test/crashy.test.ts (crashed: exited)',
'Ran 0 tests across 1 files. [12.00ms]',
], [], 1);
const outcome = await runFreeShard(['crashy'], 1, 1, { commandFor, quiet: true, log: (l) => lines.push(l) });
expect(outcome.status).toBe('failed');
expect(lines.some((l) =>
/^\[test:free\] FAIL — 0 failing test\(s\) in 0 file\(s\), 1 crashed worker\(s\)\. Full log: /.test(l),
)).toBe(true);
expect(lines).toContain(' ⚠ crashed+retried: test/crashy.test.ts');
});
test('default console is quiet: noise stays in the log; fail/error/summary lines pass through', async () => {
const consoleOut: string[] = [];
const commandFor = commandPrinting([
'PASSING-NOISE gitleaks ascii art',
'test/noisy.test.ts:',
failLine('quiet mode failure'),
'error: expect(received).toBe(expected)',
'Ran 1 tests across 1 files. [1.00ms]',
], ['telemetry stderr spam']);
const outcome = await runFreeShard(['noisy'], 1, 1, {
commandFor, consoleWrite: (t) => consoleOut.push(t), log: () => {},
});
expect(outcome.status).toBe('failed');
const joined = consoleOut.join('');
expect(joined).toContain(failLine('quiet mode failure'));
expect(joined).toContain('error: expect(received).toBe(expected)');
expect(joined).toContain('Ran 1 tests across 1 files.');
expect(joined).not.toContain('PASSING-NOISE');
expect(joined).not.toContain('telemetry stderr spam');
expect(joined).not.toContain('test/noisy.test.ts:'); // headers feed the epilogue, not the console
});
test('--verbose restores the full firehose to the console', async () => {
const consoleOut: string[] = [];
const commandFor = commandPrinting(
['PASSING-NOISE gitleaks ascii art', SUMMARY_1],
['telemetry stderr spam'],
);
const outcome = await runFreeShard(['pass'], 1, 1, {
commandFor, verbose: true, consoleWrite: (t) => consoleOut.push(t), log: () => {},
});
expect(outcome.status).toBe('passed');
const joined = consoleOut.join('');
expect(joined).toContain('PASSING-NOISE gitleaks ascii art');
expect(joined).toContain('telemetry stderr spam');
});
test('quiet suppresses the console entirely, even with an injected sink', async () => {
const consoleOut: string[] = [];
const commandFor = commandPrinting(['PASSING-NOISE', failLine('hidden'), SUMMARY_1]);
await runFreeShard(['pass'], 1, 1, {
commandFor, quiet: true, consoleWrite: (t) => consoleOut.push(t), log: () => {},
});
expect(consoleOut).toEqual([]);
});
test('the full child stream lands in the per-run log file, including console-filtered noise', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'free-log-'));
const logFilePath = path.join(dir, 'run.log');
try {
const lines: string[] = [];
const commandFor = commandPrinting(['stdout NOISE-A', SUMMARY_1], ['stderr NOISE-B']);
const outcome = await runFreeShard(['pass'], 1, 1, { commandFor, quiet: true, logFilePath, log: (l) => lines.push(l) });
expect(outcome.status).toBe('passed');
expect(lines).toContain(`[test:free] full log: ${logFilePath}`);
const logged = fs.readFileSync(logFilePath, 'utf8');
expect(logged).toContain('stdout NOISE-A');
expect(logged).toContain('stderr NOISE-B');
expect(logged).toContain('Ran 3 tests across 1 files.');
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('colored fail lines are attributed after ANSI stripping (a prior grep missed them)', async () => {
const lines: string[] = [];
const colored = `\u001B[31m${failLine('colored failure')}\u001B[0m`;
const commandFor = commandPrinting(['test/colored.test.ts:', colored, 'Ran 1 tests across 1 files. [1.00ms]']);
const outcome = await runFreeShard(['colored'], 1, 1, { commandFor, quiet: true, log: (l) => lines.push(l) });
expect(outcome.status).toBe('failed');
expect(lines).toContain(' ✗ test/colored.test.ts — colored failure');
});
test('wall-timeout epilogue lists wedge suspects: header seen, no results, no summary', async () => {
const lines: string[] = [];
const commandFor = () => ({
command: process.execPath,
args: ['-e', 'console.log("test/wedged.test.ts:");console.log("wedged noise");setTimeout(() => {}, 600000);'],
});
const outcome = await runFreeShard(['wedged'], 1, 1, {
commandFor, quiet: true, wallTimeoutMs: 1_500, log: (l) => lines.push(l),
});
expect(outcome.status).toBe('timed-out');
expect(lines).toContain(' ⏱ in flight at kill: test/wedged.test.ts');
// The epilogue headline shape stays stable across statuses.
expect(lines.some((l) => l.startsWith('[test:free] FAIL — '))).toBe(true);
}, 30_000);
test('timeout with no observable header falls back to the buffered-parallel explanation', () => {
const reporter = new FreeRunReporter(['test/a.test.ts', 'test/b.test.ts']);
reporter.end();
const lines = buildRunEpilogue('timed-out', reporter.report(), 5_000, '/tmp/x.log');
expect(lines.some((l) => l.includes('in flight at kill: unknown'))).toBe(true);
expect(lines.some((l) => l.includes('2 planned file(s) produced no output'))).toBe(true);
});
test('duplicate fail lines dedupe; pre-header failures are labeled unattributed', () => {
const reporter = new FreeRunReporter(['test/a.test.ts']);
reporter.write(`${failLine('early unattributed')}\n`, 'stderr');
reporter.write('test/a.test.ts:\n', 'stderr');
reporter.write(`${failLine('dup')}\n${failLine('dup')}\n`, 'stderr');
reporter.end();
const report = reporter.report();
expect(report.failures).toEqual([
{ file: null, testName: 'early unattributed' },
{ file: 'test/a.test.ts', testName: 'dup' },
]);
const lines = buildRunEpilogue('failed', report, 1_000, '/tmp/x.log');
expect(lines).toContain(' ✗ (unattributed) — early unattributed');
expect(lines).toContain(' ✗ test/a.test.ts — dup');
expect(lines.some((l) => l.includes('2 failing test(s) in 2 file(s)'))).toBe(true);
});
test("a later file's header ends the previous chunk — completed noisy files are not wedge suspects", () => {
const reporter = new FreeRunReporter(['test/done.test.ts', 'test/hung.test.ts']);
reporter.write('test/done.test.ts:\n', 'stderr');
reporter.write('noise from the completed file\n', 'stderr');
reporter.write('test/hung.test.ts:\n', 'stderr');
reporter.write('noise before the hang\n', 'stderr');
reporter.end();
// No terminal summary: only the still-open chunk is in flight.
expect(reporter.report().inFlight).toEqual(['test/hung.test.ts']);
});
test('../-prefixed printed paths canonicalize to planned relative paths (symlinked cwd)', () => {
const reporter = new FreeRunReporter(['browse/test/x.test.ts']);
reporter.write('../../../work/repo/browse/test/x.test.ts:\n', 'stderr');
reporter.write(`${failLine('boom')}\n`, 'stderr');
reporter.end();
expect(reporter.report().failures[0]).toEqual({ file: 'browse/test/x.test.ts', testName: 'boom' });
});
});
describe('test-free-shards: GitHub Actions log-group attribution', () => {
const failLine = (name: string) => `(fail) ${name} [1.00ms]`;
// On GHA (GITHUB_ACTIONS=1) bun wraps each file's section in ::group::.
// Unstripped, the real header fails FILE_HEADER_RE, failures attribute to
// the PREVIOUS file, and the terminal recap's re-printed (fail) lines land
// under a phantom second file — the first Linux run reported 5 real
// failures as 10 across 2 files.
test('::group::-wrapped headers attribute failures to the right file, once', () => {
const reporter = new FreeRunReporter(['test/a.test.ts', 'test/b.test.ts']);
reporter.write('::group::test/a.test.ts:\n', 'stderr');
reporter.write('::endgroup::\n', 'stderr');
reporter.write('::group::test/b.test.ts:\n', 'stderr');
reporter.write(`${failLine('planted')}\n`, 'stderr');
reporter.write('::endgroup::\n', 'stderr');
// Terminal recap re-prints the failing file header + result line.
reporter.write('1 tests failed:\n', 'stderr');
reporter.write('::group::test/b.test.ts:\n', 'stderr');
reporter.write(`${failLine('planted')}\n`, 'stderr');
reporter.end();
expect(reporter.report().failures).toEqual([{ file: 'test/b.test.ts', testName: 'planted' }]);
});
test('headerless recap re-prints do not invent a phantom failing file', () => {
// Round-3 CI shape: bun's recap prints "N tests failed:" then the (fail)
// lines with NO file headers — the stale currentFile (an innocent file)
// was charged with the previous file's failures.
const reporter = new FreeRunReporter(['test/a.test.ts', 'test/b.test.ts']);
reporter.write('::group::test/a.test.ts:\n', 'stderr');
reporter.write(`${failLine('planted')}\n`, 'stderr');
reporter.write('::endgroup::\n', 'stderr');
reporter.write('::group::test/b.test.ts:\n', 'stderr');
reporter.write('(pass-ish output, no failures here)\n', 'stderr');
reporter.write('2 tests failed:\n', 'stderr');
reporter.write(`${failLine('planted')}\n`, 'stderr');
reporter.write(`${failLine('planted')}\n`, 'stderr');
reporter.end();
expect(reporter.report().failures).toEqual([{ file: 'test/a.test.ts', testName: 'planted' }]);
});
});
describe('test-free-shards: curated-list census pins', () => {
// A renamed test file must FAIL here, not silently drop its serialization
// (a phantom TREE_MUTATING key means the reader races regenerating shards
// again) or its serial-child quarantine (WORKER_HOSTILE).
test('every TREE_MUTATING and WORKER_HOSTILE key names a real free test file', () => {
const census = new Set(collectFreeTestFiles(ROOT));
const stale = [...Object.keys(TREE_MUTATING), ...Object.keys(WORKER_HOSTILE)]
.filter((key) => !census.has(key));
expect(stale).toEqual([]);
});
test('every KNOWN_WINDOWS_INCOMPATIBLE entry names a real free test file', () => {
const census = new Set(collectFreeTestFiles(ROOT));
const stale = KNOWN_WINDOWS_INCOMPATIBLE.map((e) => e.file).filter((f) => !census.has(f));
expect(stale).toEqual([]);
});
test('every TEST_ROOTS entry exists on disk and contributes at least one test file', () => {
const files = collectFreeTestFiles(ROOT);
for (const root of TEST_ROOTS) {
expect(fs.existsSync(path.join(ROOT, root))).toBe(true);
expect(files.some((f) => f.startsWith(`${root}/`))).toBe(true);
}
});
});
describe('test-free-shards: wall-timeout scaling', () => {
test('typical local shard keeps the 6-minute floor', () => {
expect(wallTimeoutForShard(70)).toBe(DEFAULT_WALL_TIMEOUT_MS);
});
test('oversized shards (jobs=1 machines, Windows lane) scale linearly past the floor', () => {
expect(wallTimeoutForShard(130)).toBe(130 * PER_FILE_WALL_MS);
expect(wallTimeoutForShard(420)).toBe(420 * PER_FILE_WALL_MS);
});
test('an explicit base above the scaled value wins', () => {
expect(wallTimeoutForShard(10, 10 * 60_000)).toBe(10 * 60_000);
});
});
describe('test-free-shards: duration-aware packing (full-suite LPT)', () => {
const files = ['test/a.test.ts', 'test/b.test.ts', 'test/c.test.ts', 'test/d.test.ts'];
test('LPT balances by cost, not count', () => {
const durations = {
'test/a.test.ts': 90_000, // one giant file
'test/b.test.ts': 30_000,
'test/c.test.ts': 30_000,
'test/d.test.ts': 30_000,
};
const { shards, predictedMs } = packShardsByDuration(files, 2, durations);
// The giant file gets its own shard; the three smalls share the other.
expect(shards.map((s) => s.length).sort()).toEqual([1, 3]);
expect(Math.max(...predictedMs)).toBe(90_000);
});
test('deterministic for identical inputs', () => {
const durations = { 'test/a.test.ts': 5, 'test/b.test.ts': 5, 'test/c.test.ts': 5, 'test/d.test.ts': 5 };
const one = packShardsByDuration(files, 3, durations);
const two = packShardsByDuration([...files].reverse(), 3, durations);
expect(one.shards).toEqual(two.shards);
});
test('unknown files get 75th-percentile pessimism (placed early, never the tail)', () => {
const durations = {
'test/a.test.ts': 1_000,
'test/b.test.ts': 2_000,
'test/c.test.ts': 100_000,
// test/d.test.ts unrecorded → p75 of known = 100_000 (pessimistic)
};
const { shards } = packShardsByDuration(files, 2, durations);
// The unknown must NOT be packed as if free: it lands opposite the
// 100s file, not stacked onto it.
const shardOfC = shards.findIndex((s) => s.includes('test/c.test.ts'));
const shardOfD = shards.findIndex((s) => s.includes('test/d.test.ts'));
expect(shardOfC).not.toBe(shardOfD);
});
test('every file lands in exactly one shard', () => {
const { shards } = packShardsByDuration(files, 3, {});
expect(shards.flat().sort()).toEqual([...files].sort());
});
test('invalid shard count throws', () => {
expect(() => packShardsByDuration(files, 0, {})).toThrow();
});
test('corrupt seed falls back to null (hash sharding), never throws', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'durations-seed-'));
const seedPath = path.join(dir, 'seed.json');
fs.writeFileSync(seedPath, '{ definitely not json');
const prev = process.env.GSTACK_FREE_TEST_DURATIONS;
process.env.GSTACK_FREE_TEST_DURATIONS = seedPath;
try {
expect(loadFreeTestDurations()).toBeNull();
// Missing file: silent null (fresh checkouts are normal).
process.env.GSTACK_FREE_TEST_DURATIONS = path.join(dir, 'missing.json');
expect(loadFreeTestDurations()).toBeNull();
// Valid seed round-trips, non-numeric entries dropped.
fs.writeFileSync(seedPath, JSON.stringify({ version: 1, durations: { 'test/a.test.ts': 42, bad: 'nope' } }));
process.env.GSTACK_FREE_TEST_DURATIONS = seedPath;
expect(loadFreeTestDurations()).toEqual({ 'test/a.test.ts': 42 });
} finally {
if (prev === undefined) delete process.env.GSTACK_FREE_TEST_DURATIONS;
else process.env.GSTACK_FREE_TEST_DURATIONS = prev;
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('packed shards get duration-aware walls (count heuristic is wrong under LPT)', () => {
// A packed shard predicted at 120s must get a 360s wall even though its
// file COUNT would produce only the 6-minute base under the old formula.
expect(wallTimeoutForPackedShard(120_000)).toBe(Math.max(WALL_BASE_MS, 360_000));
// Tiny prediction: base still floors it.
expect(wallTimeoutForPackedShard(1_000)).toBe(WALL_BASE_MS);
});
test('packed walls never undercut the per-file floor (predictions do not transfer across machines)', () => {
// The duration seed is recorded on fast CI; a syscall-supervised sandbox
// replays the same files 2-4x slower. A 253-file shard predicted at ~242s
// got wall-killed at predicted×3 = 725s while genuinely progressing —
// the count-based floor (253 × 5s = 1265s) the runner always guaranteed
// must survive duration packing. Looser is allowed, tighter is not.
expect(wallTimeoutForPackedShard(242_000, WALL_BASE_MS, 253)).toBe(253 * 5_000);
// When the prediction is the larger bound, it still wins.
expect(wallTimeoutForPackedShard(600_000, WALL_BASE_MS, 10)).toBe(1_800_000);
});
});