perf(ci): start source feedback early and diagnose stalled runs (#3013)

* perf(ci): start source feedback early and diagnose stalled runs

* fix(ci): verify workflow identities before main comparison limits

* fix(ci): preserve diagnostics across passing checks and install failures

* fix(ci): preserve ambiguous workflow run ordering

* fix(ci): preserve failure-report candidate and request budgets

* fix(ci): retain candidate errors while checking later main evidence

* fix(ci): retain partial reports and require complete health scans

* test(ci): prune stale fixtures and duplicated assumptions
This commit is contained in:
morluto
2026-10-14 06:07:08 +08:00
committed by GitHub
parent aa6f74af04
commit 6510d0d57f
43 changed files with 4661 additions and 192 deletions
@@ -45,6 +45,7 @@ const fixture = async () => {
for (const path of [
"scripts/run-development-tests.mjs",
"scripts/lib/development-tests.mjs",
"scripts/lib/test-projects.mjs",
])
await copyFile(join(process.cwd(), path), join(root, path));
await symlink(
@@ -0,0 +1,419 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { normalizeWorkflowRun } from "../../../scripts/ci/workflow-run.mjs";
import {
readStaticCheckArtifact,
selectStaticCheckArtifact,
} from "../../../scripts/ci/artifacts.mjs";
import {
classifyFailure,
createGitHubApi,
reportCiFailures,
type CiRun,
type CiJob,
type FailureReportApi,
} from "../../../scripts/ci/failure-report.mjs";
const sha = (digit: string) => digit.repeat(40);
const diagnostic = {
kind: "lint",
path: "src/example.ts",
code: "no-debugger",
message: "Unexpected debugger statement.",
severity: "error",
} as const;
const context = (
sourceSha: string,
taskHash = "a".repeat(16),
prHeadSha?: string,
) => ({
version: 1 as const,
sourceSha,
...(prHeadSha ? { prHeadSha } : {}),
sourceClean: true,
nodeVersion: "v24.18.0",
npmVersion: "11.16.0",
turboVersion: "2.11.7",
platform: "linux",
architecture: "x64",
taskHashes: { "lint:built": taskHash },
});
const run = (overrides: Partial<CiRun> = {}) =>
normalizeWorkflowRun({
id: 10,
run_attempt: 1,
status: "completed",
conclusion: "failure",
event: "pull_request",
path: ".github/workflows/ci.yml@main",
head_sha: sha("a"),
head_branch: "feature",
repository: { full_name: "owner/rea" },
pull_requests: [
{ base: { sha: sha("b"), repo: { full_name: "owner/rea" } } },
],
...overrides,
});
const job = (overrides: Partial<CiJob> = {}) => ({
name: "Static checks",
status: "completed",
conclusion: "failure",
...overrides,
});
const comparison = (): Parameters<typeof classifyFailure>[0] => ({
repository: "owner/rea",
defaultBranch: "main",
run: run(),
job: job(),
diagnostics: [diagnostic],
context: context(sha("a")),
mainRun: run({
id: 20,
event: "push",
head_sha: sha("c"),
head_branch: "main",
pull_requests: [],
}),
mainJob: job(),
mainDiagnostics: [diagnostic],
mainContext: context(sha("c")),
executionSourcesVerified: true,
ancestry: { status: "ahead", mergeBaseSha: sha("c") },
blobs: { "src/example.ts": true },
});
it("attributes only an identical structured lint failure with matching task, context, ancestry, and source blob", () => {
const result = classifyFailure(comparison());
expect(result).toEqual({
classification: "matching-main-diagnostics",
reason:
"supported_diagnostics_match_failed_task_and_source_on_verified_main_ancestor",
});
});
it.each([
["task hash", { mainContext: context(sha("c"), "b".repeat(16)) }],
["dirty source", { context: { ...context(sha("a")), sourceClean: false } }],
[
"toolchain",
{ mainContext: { ...context(sha("c")), turboVersion: "other" } },
],
[
"source sha",
{ context: context(sha("d")), executionSourcesVerified: false },
],
[
"diagnostic",
{ mainDiagnostics: [{ ...diagnostic, message: "different message" }] },
],
["content", { blobs: { "src/example.ts": false } }],
["ancestry", { ancestry: { status: "diverged", mergeBaseSha: sha("e") } }],
["canceled job", { job: job({ conclusion: "cancelled" }) }],
["not a static job", { job: job({ name: "Test shard (1)" }) }],
] as const)("does not attribute on mismatched %s", (_label, overrides) => {
const result = classifyFailure({ ...comparison(), ...overrides });
expect(result.classification).toBe("unknown");
});
it("writes informational JSON and Markdown from the supplied manifest using only read API calls", async () => {
const directory = await createTestTempDirectory("rea-ci-failure-test-");
const calls: string[] = [];
const manifest = {
repository: "owner/rea",
truncation: [],
coverage: { exhaustive: false },
runs: [
{
id: 10,
runAttempt: 1,
workflow: "CI",
event: "pull_request",
conclusion: "failure",
status: "collected",
},
{
id: 11,
runAttempt: 1,
workflow: "CI",
event: "pull_request",
conclusion: "success",
status: "collected",
},
],
};
const failedRun = run();
const api: FailureReportApi = {
async getRun(_repository, id) {
calls.push(`run:${id}`);
return failedRun;
},
async getJobs(_repository, id) {
calls.push(`jobs:${id}`);
return [{ ...job(), run_id: Number(id), run_attempt: 1 }];
},
async getStaticEvidence() {
calls.push("artifact");
return null;
},
async getAncestry() {
throw new Error("must not compare without evidence");
},
async verifyExecutionSource() {
throw new Error("must not verify source without evidence");
},
async getBlobIdentity() {
throw new Error("must not inspect blobs without evidence");
},
};
const report = await reportCiFailures({
repository: "owner/rea",
defaultBranch: "main",
batchManifest: manifest,
api,
outputDirectory: directory,
});
expect(calls).toEqual(["run:10", "jobs:10", "artifact"]);
expect(report).toMatchObject({
informationalOnly: true,
gateEffect: "none; this report never changes CI conclusions",
counts: { unknown: 1 },
});
const json = JSON.parse(
await readFile(join(directory, "report.json"), "utf8"),
);
const markdown = await readFile(join(directory, "report.md"), "utf8");
expect(json.failures[0]).toMatchObject({
classification: "unknown",
reason: "no_matching_verified_main_failure",
});
expect(markdown).toContain("Informational only");
expect(markdown).toContain("Unknown means evidence was incomplete");
});
it.each([
[22, false],
[6, true],
] as const)(
"finds verified main evidence after %s newer PR runs (extra incorrect main hint: %s)",
async (prCount, incorrectMainHints) => {
const directory = await createTestTempDirectory("rea-ci-main-proof-");
const mainSha = sha("c");
const prHeadSha = sha("a");
const mergeSha = sha("d");
const mainRun = run({
id: 20,
event: "push",
head_sha: mainSha,
head_branch: "main",
pull_requests: [],
});
const prRun = run({
head_sha: prHeadSha,
pull_requests: [
{ base: { sha: mainSha, repo: { full_name: "owner/rea" } } },
],
});
const evidence = (sourceSha: string, prHead?: string) => ({
context: context(sourceSha, undefined, prHead),
diagnostics: [diagnostic],
});
const lookups: number[] = [];
const api: FailureReportApi = {
async getRun(_repository, id) {
lookups.push(Number(id));
return Number(id) === 20 ? mainRun : { ...prRun, id };
},
async getJobs(_repository, id) {
return [{ ...job(), run_id: Number(id), run_attempt: 1 }];
},
async getStaticEvidence(_repository, selectedRun) {
return Number(selectedRun.id) === 20
? evidence(mainSha)
: evidence(mergeSha, prHeadSha);
},
async verifyExecutionSource(_repository, selectedRun, sourceContext) {
return selectedRun.event === "pull_request"
? sourceContext.sourceSha === mergeSha &&
sourceContext.prHeadSha === selectedRun.head_sha
: sourceContext.sourceSha === selectedRun.head_sha;
},
async getAncestry() {
return { status: "ahead", mergeBaseSha: mainSha };
},
async getBlobIdentity() {
return { "src/example.ts": true };
},
};
const result = await reportCiFailures({
repository: "owner/rea",
defaultBranch: "main",
batchManifest: {
repository: "owner/rea",
runs: [
...(incorrectMainHints
? [
{
id: 30,
runAttempt: 1,
workflow: "CI",
event: "push",
headBranch: "main",
conclusion: "failure",
status: "collected",
},
]
: []),
...Array.from({ length: prCount }, (_, index) => ({
id: 100 + index,
runAttempt: 1,
workflow: "CI",
event: "pull_request",
headBranch: "feature",
conclusion: "failure",
status: "collected",
})),
{
id: 20,
runAttempt: 1,
workflow: "CI",
event: "push",
headBranch: "main",
conclusion: "failure",
status: "collected",
},
],
},
api,
outputDirectory: directory,
});
expect(result.failures[0]).toMatchObject({
runId: 100,
classification: "matching-main-diagnostics",
reason:
"supported_diagnostics_match_failed_task_and_source_on_verified_main_ancestor",
});
expect(lookups).toHaveLength(
Math.min(prCount, 20) + 1 + Number(incorrectMainHints),
);
expect(lookups[0]).toBe(incorrectMainHints ? 30 : 20);
expect(new Set(lookups).size).toBe(lookups.length);
expect(result.boundedInput.mainCandidateRuns).toBe(1);
expect(result.failures).toHaveLength(Math.min(prCount, 20));
},
);
it("proves checkout merge parents in base-then-PR-head order and rejects false identities", async () => {
const baseSha = sha("b");
const headSha = sha("a");
const mergeSha = sha("c");
const prRun = run({
head_sha: headSha,
pull_requests: [
{ base: { sha: baseSha, repo: { full_name: "owner/rea" } } },
],
});
let parents = [baseSha, headSha];
const calls: string[] = [];
const api = createGitHubApi({
token: "fixture-token",
apiRequest: async (_method, endpoint) => {
calls.push(endpoint);
return {
sha: mergeSha,
parents: parents.map((parentSha) => ({ sha: parentSha })),
};
},
});
const mergeContext = context(mergeSha, undefined, headSha);
expect(
await api.verifyExecutionSource("owner/rea", prRun, mergeContext),
).toBe(true);
expect(calls).toEqual([`repos/owner/rea/commits/${mergeSha}`]);
parents = [headSha, baseSha];
expect(
await api.verifyExecutionSource("owner/rea", prRun, mergeContext),
).toBe(false);
expect(
await api.verifyExecutionSource("owner/rea", prRun, {
...mergeContext,
prHeadSha: sha("e"),
}),
).toBe(false);
});
it("uses static artifacts only when listing is complete, unique, and tied to this run attempt", () => {
const artifact = {
id: 12,
name: "static-check-reports",
expired: false,
workflow_run: { id: 10, head_sha: sha("a") },
};
const runRecord = { id: 10, head_sha: sha("a") };
expect(
selectStaticCheckArtifact(
{ total_count: 1, artifacts: [artifact] },
runRecord,
1,
),
).toBe(artifact);
expect(
selectStaticCheckArtifact(
{ total_count: 2, artifacts: [artifact] },
runRecord,
1,
),
).toBeNull();
expect(
selectStaticCheckArtifact(
{ total_count: 2, artifacts: [artifact, artifact] },
runRecord,
1,
),
).toBeNull();
expect(
selectStaticCheckArtifact(
{
total_count: 1,
artifacts: [
{ ...artifact, workflow_run: { id: 11, head_sha: sha("a") } },
],
},
runRecord,
1,
),
).toBeNull();
expect(
selectStaticCheckArtifact(
{ total_count: 1, artifacts: [artifact] },
runRecord,
2,
),
).toBeNull();
});
it("rejects artifact redirects that could send the bearer token to a non-HTTPS host", async () => {
const calls: string[] = [];
await expect(
readStaticCheckArtifact({
repository: "owner/rea",
artifactId: 12,
token: "fixture-token",
fetchImpl: (async (url: string | URL | Request) => {
calls.push(String(url));
return new Response(null, {
status: 302,
headers: { location: "http://untrusted.example/artifact.zip" },
});
}) as typeof fetch,
}),
).rejects.toThrow("static_artifact_redirect_invalid");
expect(calls).toEqual([
"https://api.github.com/repos/owner/rea/actions/artifacts/12/zip",
]);
});
@@ -0,0 +1,290 @@
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
reportCiFailures,
type CiRun,
type FailureReportApi,
type StaticDiagnostic,
type StaticEvidence,
} from "../../../scripts/ci/failure-report.mjs";
const repository = "owner/rea";
const mainSha = "c".repeat(40);
const prSha = "a".repeat(40);
const diagnostic: StaticDiagnostic = {
kind: "lint",
path: "src/example.ts",
code: "no-debugger",
message: "Unexpected debugger statement.",
severity: "error",
};
const evidence = (
run: CiRun,
diagnostics: readonly StaticDiagnostic[],
): StaticEvidence => ({
context: {
version: 1,
sourceSha: run.head_sha!,
sourceClean: true,
nodeVersion: "v24.18.0",
npmVersion: "11.16.0",
turboVersion: "2.11.7",
platform: "linux",
architecture: "x64",
taskHashes: { "lint:built": "a".repeat(16) },
},
diagnostics,
});
const entry = (id: number, event = "pull_request", runAttempt = 1) => ({
id,
runAttempt,
workflow: "CI",
event,
headBranch: event === "pull_request" ? "feature" : "main",
status: "collected",
conclusion: "failure",
});
function fixture(mainIds: readonly number[], prCount: number) {
const jobs: number[] = [];
const artifacts: number[] = [];
const paths: (readonly string[])[] = [];
const runs: Array<
Omit<ReturnType<typeof entry>, "event"> & { event?: string }
> = [
...mainIds.map((id) => entry(id, "schedule")),
...Array.from({ length: prCount }, (_, index) => entry(100 + index)),
];
const api: FailureReportApi = {
async getRun(_repository, id) {
const selected = runs.find((run) => run.id === Number(id))!;
return {
id,
run_attempt: selected.runAttempt,
status: "completed",
conclusion: "failure",
...(selected.event ? { event: selected.event } : {}),
head_branch: selected.headBranch,
path: ".github/workflows/ci.yml@main",
head_sha: mainIds.includes(Number(id)) ? mainSha : prSha,
repository: { full_name: repository },
pull_requests:
selected.event === "pull_request"
? [{ base: { sha: mainSha, repo: { full_name: repository } } }]
: [],
};
},
async getJobs(_repository, id, attempt) {
jobs.push(Number(id));
return [
{
name: "Static checks",
status: "completed",
conclusion: "failure",
run_id: Number(id),
run_attempt: attempt,
},
];
},
async getStaticEvidence(_repository, run) {
artifacts.push(Number(run.id));
return evidence(run, [diagnostic]);
},
async getAncestry() {
return { status: "identical", mergeBaseSha: mainSha };
},
async getBlobIdentity(_repository, _ancestor, _descendant, requested) {
paths.push(requested);
return Object.fromEntries(requested.map((path) => [path, true]));
},
async verifyExecutionSource() {
return true;
},
};
return { api, runs, jobs, artifacts, paths };
}
async function report(input: ReturnType<typeof fixture>) {
return await reportCiFailures({
repository,
defaultBranch: "main",
batchManifest: { repository, runs: input.runs },
api: input.api,
outputDirectory: await createTestTempDirectory("rea-ci-budget-"),
});
}
it("selects PR failures before the cap even after a day of scheduled main failures", async () => {
const input = fixture(
Array.from({ length: 24 }, (_, index) => 20 + index),
1,
);
input.runs.push({
id: 200,
runAttempt: 1,
workflow: "CI",
headBranch: "feature",
status: "collected",
conclusion: "failure",
});
const result = await report(input);
expect(result.failures).toMatchObject([
{ runId: 100, classification: "matching-main-diagnostics" },
]);
expect(result.boundedInput).toMatchObject({
candidateRuns: 1,
mainCandidateRuns: 5,
manifestTruncated: false,
});
expect(input.jobs).toEqual([100, 20]);
});
it("reuses five main job/artifact observations across twenty completed PR comparisons", async () => {
const input = fixture([20, 21, 22, 23, 24], 20);
const load = input.api.getStaticEvidence;
input.api.getStaticEvidence = async (...args) => {
const result = await load(...args);
return Number(args[1].id) < 24
? evidence(args[1], [{ ...diagnostic, message: "different" }])
: result;
};
const result = await report(input);
expect(result.counts).toEqual({
"matching-main-diagnostics": 20,
unknown: 0,
});
expect(input.paths).toHaveLength(100);
expect(input.jobs).toHaveLength(25);
expect(input.artifacts).toHaveLength(25);
for (const id of [20, 21, 22, 23, 24]) {
expect(input.jobs.filter((item) => item === id)).toHaveLength(1);
expect(input.artifacts.filter((item) => item === id)).toHaveLength(1);
}
});
it.each(["missing", "artifact error", "job error", "wrong job attempt"])(
"reuses unavailable main evidence without retries: %s",
async (failure) => {
const input = fixture([20], 3);
const load = input.api.getStaticEvidence;
const jobs = input.api.getJobs;
input.api.getJobs = async (...args) => {
const result = await jobs(...args);
if (Number(args[1]) !== 20) return result;
if (failure === "job error") throw new Error("job_snapshot_unavailable");
return failure === "wrong job attempt"
? result.map((job) => ({ ...job, run_attempt: 2 }))
: result;
};
input.api.getStaticEvidence = async (...args) => {
const result = await load(...args);
if (Number(args[1].id) !== 20) return result;
if (failure === "artifact error") throw new Error("artifact_unavailable");
return null;
};
const result = await report(input);
expect(result.counts.unknown).toBe(3);
expect(input.jobs.filter((id) => id === 20)).toHaveLength(1);
expect(input.artifacts.filter((id) => id === 20)).toHaveLength(
failure === "job error" || failure === "wrong job attempt" ? 0 : 1,
);
},
);
it.each([1, 2])(
"refreshes unavailable main evidence in the next report (attempt %s)",
async (attempt) => {
const input = fixture([20], 1);
expect((await report(input)).counts["matching-main-diagnostics"]).toBe(1);
input.runs[0]!.runAttempt = attempt;
const load = input.api.getStaticEvidence;
input.api.getStaticEvidence = async (...args) => {
const result = await load(...args);
return Number(args[1].id) === 20 ? null : result;
};
expect((await report(input)).counts.unknown).toBe(1);
expect(input.jobs.filter((id) => id === 20)).toHaveLength(2);
expect(input.artifacts.filter((id) => id === 20)).toHaveLength(2);
},
);
it.each([1, 51])(
"fetches only PR paths with %s PR diagnostics and noisy main evidence",
async (count) => {
const input = fixture([20], 1);
const load = input.api.getStaticEvidence;
const diagnostics = Array.from({ length: count }, (_, index) => ({
...diagnostic,
path: `src/pr-${index}.ts`,
}));
input.api.getStaticEvidence = async (...args) => {
await load(...args);
const noise =
Number(args[1].id) === 20
? Array.from({ length: 60 }, (_, index) => ({
...diagnostic,
path: `src/main-${index}.ts`,
}))
: [];
return evidence(args[1], [...noise, ...diagnostics]);
};
const result = await report(input);
expect(input.paths).toEqual([
diagnostics.slice(0, 50).map((item) => item.path),
]);
expect(result.failures[0]!.classification).toBe(
count === 1 ? "matching-main-diagnostics" : "unknown",
);
},
);
it.each(["jobs", "artifact", "comparison"])(
"continues after an isolated main %s failure and preserves its provenance",
async (failure) => {
const input = fixture([20, 21], 3);
const jobs = input.api.getJobs;
const load = input.api.getStaticEvidence;
input.api.getJobs = async (...args) => {
const result = await jobs(...args);
if (Number(args[1]) === 20 && failure === "jobs")
throw new Error("main_jobs_unavailable");
return result;
};
input.api.getStaticEvidence = async (...args) => {
const result = await load(...args);
if (Number(args[1].id) === 20 && failure === "artifact")
throw new Error("main_artifact_unavailable");
return Number(args[1].id) === 20 && failure === "comparison"
? {
...result!,
context: { ...result!.context, sourceSha: "d".repeat(40) },
}
: result;
};
input.api.verifyExecutionSource = async (_repository, run, context) => {
if (Number(run.id) === 20 && context.sourceSha !== run.head_sha)
throw new Error("main_comparison_unavailable");
return true;
};
const result = await report(input);
expect(result.counts).toEqual({
"matching-main-diagnostics": 3,
unknown: 0,
});
for (const item of result.failures) {
expect(item.candidateFailures).toEqual([
{
runId: 20,
runAttempt: 1,
reason: `main_${failure}_unavailable`,
},
]);
}
expect(input.jobs.filter((id) => id === 20)).toHaveLength(1);
expect(input.jobs.filter((id) => id === 21)).toHaveLength(1);
expect(input.artifacts.filter((id) => id === 20)).toHaveLength(
failure === "jobs" ? 0 : 1,
);
expect(input.artifacts.filter((id) => id === 21)).toHaveLength(1);
},
);
@@ -0,0 +1,313 @@
import { execFile } from "node:child_process";
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { runInNewContext } from "node:vm";
import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import {
parseStaticTaskContext,
recordStaticTaskContext,
} from "../../../scripts/ci/static-task-context.mjs";
import { createGhApiRequest } from "../../../scripts/ci/github-api.mjs";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const scopeFlags = async () =>
z
.object({ CI_FLAGS: z.array(z.string()) })
.parse(
await import(
new URL("../../../scripts/ci/scopes.mjs", import.meta.url).href
),
).CI_FLAGS;
const workflow = async () =>
z
.object({
jobs: z.record(
z.string(),
z
.object({
needs: z.union([z.string(), z.array(z.string())]).optional(),
if: z.string().optional(),
steps: z
.array(
z
.object({
run: z.string().optional(),
env: z.record(z.string(), z.string()).optional(),
})
.passthrough(),
)
.optional(),
})
.passthrough(),
),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
),
),
).jobs;
it("starts source feedback before build and requires both groups without waiving missing jobs", async () => {
const jobs = await workflow();
expect(
jobs.static?.steps?.find(
(step) => step.run === "npm run ci:static-context",
)?.["continue-on-error"],
).toBe(true);
expect(jobs["test-source"]?.needs).toBe("changes");
expect(jobs["test-shard"]?.needs).toEqual(["changes", "build"]);
expect(
jobs["test-source"]?.steps?.some(
(step) =>
step.run === "npm run test:fast -- --reporter=default --reporter=blob",
),
).toBe(true);
const required = fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
);
const flags = await scopeFlags();
for (const tier of ["fast", "full"]) {
for (const result of [
"success",
"failure",
"cancelled",
"skipped",
"missing",
]) {
const needs = Object.fromEntries(
Object.keys(jobs)
.filter((name) => name !== "required")
.map((name) => [name, { result: "success" }]),
);
const outputs = {
...Object.fromEntries(
flags.map((flag) => [flag, tier === "full" ? "true" : "false"]),
),
tier,
code: "true",
};
const context: Record<
string,
{ result: string; outputs?: Record<string, string> }
> = { ...needs, changes: { result: "success", outputs } };
if (result === "missing") delete context["test-source"];
else context["test-source"] = { result };
const run = execute(process.execPath, [required], {
env: {
...process.env,
CI_JOBS: JSON.stringify(context),
CI_QUALIFICATION_DIRECTORY: "",
},
});
if (
result === "success" ||
(tier === "full" && ["skipped", "missing"].includes(result))
)
await expect(run).resolves.toMatchObject({ stderr: "" });
else
await expect(run).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("test-source"),
});
}
}
});
it("records the actual static task graph with explicit source identity and no ambient environment", async () => {
const directory = await createTestTempDirectory("rea-ci-context-");
const context = await recordStaticTaskContext({ outputDirectory: directory });
const head = await execute("git", ["rev-parse", "HEAD"]);
expect(context.sourceSha).toBe(head.stdout.trim());
expect(context.taskHashes["lint:built"]).toMatch(/^[a-f0-9]{16}$/u);
expect(context.taskHashes.jscpd).toMatch(/^[a-f0-9]{16}$/u);
expect(context).not.toHaveProperty("environmentVariables");
expect(context).not.toHaveProperty("env");
expect(
JSON.parse(await readFile(`${directory}/static-task-context.json`, "utf8")),
).toEqual(context);
for (const invalid of [
undefined,
{},
{ ...context, sourceSha: "bad" },
{ ...context, prHeadSha: "bad" },
{ ...context, taskHashes: { jscpd: "stale" } },
])
expect(() => parseStaticTaskContext(invalid)).toThrow();
});
it("rejects mutation methods at the shared GitHub transport before invoking the CLI", async () => {
const request = createGhApiRequest({ env: { PATH: "" } });
await expect(
request("POST", "repos/owner/repo/actions/runs/1/rerun", {
requests: 0,
startedAt: Date.now(),
limitMs: 1000,
}),
).rejects.toThrow("read-only GET");
});
it("collects basic CI telemetry before optional dependency installation can fail", async () => {
const { jobs } = z
.object({
jobs: z.object({
report: z.object({
steps: z.array(
z.object({
id: z.string().optional(),
run: z.string().optional(),
if: z.string().optional(),
"continue-on-error": z.boolean().optional(),
}),
),
}),
}),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/ci-timings.yml", import.meta.url),
"utf8",
),
),
);
const steps = jobs.report.steps;
const installation = steps.findIndex((step) => step.id === "failure-deps");
for (const script of ["pr-ci-health.mjs", "job-timings-batch.mjs"]) {
const collection = steps.findIndex(
(step) => step.run === `node scripts/ci/${script}`,
);
expect(collection).toBeGreaterThanOrEqual(0);
expect(installation).toBeGreaterThan(collection);
}
expect(steps[installation]).toMatchObject({
run: "npm ci",
"continue-on-error": true,
});
expect(
steps.find((step) => step.id === "npm-cache")?.["continue-on-error"],
).toBe(true);
expect(
steps.find((step) => step.run === "node scripts/ci/failure-report.mjs")?.if,
).toContain("steps.failure-deps.outcome == 'success'");
});
it("merges source and built reports exactly once using the workflow's shard matrix", async () => {
const jobs = await workflow();
const matrix = z
.object({
matrix: z.object({ shard: z.string().regex(/^\$\{\{.*\}\}$/u) }),
})
.parse(jobs["test-shard"]?.strategy).matrix.shard;
const shards = z
.array(z.string().regex(/^\d+\/\d+$/u))
.min(1)
.parse(
runInNewContext(
matrix.slice(3, -2),
{
fromJSON: JSON.parse,
needs: { changes: { outputs: { tier: "fast" } } },
},
{ timeout: 1_000 },
),
);
const labels = Object.fromEntries(
["source", "built"].map((group) => [
group,
z
.string()
.min(1)
.parse(
jobs[group === "source" ? "test-source" : "test-shard"]?.steps?.find(
(step) => step.env?.VITEST_BLOB_LABEL,
)?.env?.VITEST_BLOB_LABEL,
),
]),
);
const root = await createTestTempDirectory("rea-ci-group-merge-");
const config = join(root, "vitest.config.mjs");
await writeFile(
config,
`export default { test: { maxWorkers: 1, projects: [${["source", "built"].map((name) => `{ test: { name: "${name}", globals: true, include: ["${name}*.test.js"] } }`).join(",")}] } };`,
);
const files = [
"source.test.js",
...Array.from(
{ length: shards.length },
(_, index) => `built-${index}.test.js`,
),
];
for (const file of files)
await writeFile(
join(root, file),
'it("runs its selected group", () => expect(true).toBe(true));',
);
const vitest = fileURLToPath(
new URL("../../../node_modules/vitest/vitest.mjs", import.meta.url),
);
const blobs = new Map<string, Buffer>();
const runs = [
{ group: "source", shard: [] },
...shards.map((shard) => ({ group: "built", shard: [`--shard=${shard}`] })),
];
for (const { group, shard } of runs) {
await execute(
process.execPath,
[
vitest,
"run",
"--config",
config,
"--project",
group,
"--reporter=blob",
...shard,
],
{
cwd: root,
env: { ...process.env, VITEST_BLOB_LABEL: labels[group]! },
timeout: 20_000,
},
);
for (const filename of await readdir(join(root, ".vitest/blob"))) {
expect(blobs.has(filename)).toBe(false);
blobs.set(filename, await readFile(join(root, ".vitest/blob", filename)));
}
// Separate hosted jobs start with independent report directories.
await rm(join(root, ".vitest/blob"), { recursive: true });
}
expect(blobs.size).toBe(runs.length);
await mkdir(join(root, ".vitest/blob"), { recursive: true });
for (const [filename, bytes] of blobs)
await writeFile(join(root, ".vitest/blob", filename), bytes);
await execute(
process.execPath,
[
vitest,
"--config",
config,
"--merge-reports",
"--reporter=json",
"--outputFile.json=merged.json",
],
{ cwd: root, timeout: 20_000 },
);
const merged = z
.object({
success: z.literal(true),
testResults: z.array(z.object({ name: z.string() })),
})
.parse(JSON.parse(await readFile(join(root, "merged.json"), "utf8")));
expect(
merged.testResults.map(({ name }) => name.split("/").at(-1)).sort(),
).toEqual(files.toSorted());
});
@@ -18,6 +18,8 @@ it("collects the latest attempt for recent completed CI and Release runs into a
workflow_runs: [
{
id: 42,
event: "push",
head_branch: "main",
run_attempt: 3,
status: "completed",
conclusion: "failure",
@@ -43,51 +45,9 @@ it("collects the latest attempt for recent completed CI and Release runs into a
},
],
},
[
{
jobs: [
{
name: "Release lane",
status: "completed",
conclusion: "success",
created_at: recent,
started_at: recent,
completed_at: new Date(Date.parse(recent) + 50_000).toISOString(),
steps: [],
},
],
},
],
[
{
jobs: [
{
name: "Failed lane",
status: "completed",
conclusion: "failure",
created_at: recent,
started_at: recent,
completed_at: new Date(Date.parse(recent) + 55_000).toISOString(),
steps: [],
},
],
},
],
[
{
jobs: [
{
name: "Cancelled lane",
status: "completed",
conclusion: "cancelled",
created_at: recent,
started_at: recent,
completed_at: new Date(Date.parse(recent) + 30_000).toISOString(),
steps: [],
},
],
},
],
completedJobs("Release lane", "success", recent, 50),
completedJobs("Failed lane", "failure", recent, 55),
completedJobs("Cancelled lane", "cancelled", recent, 30),
]);
const result = await runBatch(fixture);
const manifest = JSON.parse(
@@ -116,8 +76,20 @@ it("collects the latest attempt for recent completed CI and Release runs into a
expect(manifest.errors).toEqual([]);
expect(manifest.runs).toMatchObject([
{ id: 43, runAttempt: 2, conclusion: "success" },
{ id: 42, runAttempt: 3, conclusion: "failure" },
{ id: 41, runAttempt: 1, conclusion: "cancelled" },
{
id: 42,
runAttempt: 3,
conclusion: "failure",
event: "push",
headBranch: "main",
},
{
id: 41,
runAttempt: 1,
conclusion: "cancelled",
event: null,
headBranch: null,
},
]);
expect(manifest.runs).toEqual(
expect.arrayContaining([
@@ -234,6 +206,31 @@ it("retains a partial manifest when its collection budget is exhausted", async (
expect(manifest.truncation.join(" ")).toContain("Time budget");
});
function completedJobs(
name: string,
conclusion: string,
startedAt: string,
seconds: number,
) {
return [
{
jobs: [
{
name,
status: "completed",
conclusion,
created_at: startedAt,
started_at: startedAt,
completed_at: new Date(
Date.parse(startedAt) + seconds * 1000,
).toISOString(),
steps: [],
},
],
},
];
}
async function createFixture(responses: unknown[]) {
const directory = await createTestTempDirectory("rea-ci-job-timings-batch-");
const fakeBin = join(directory, "bin");
@@ -0,0 +1,617 @@
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
classifyPrCi,
collectPrCiHealth,
matchRunToPullRequest,
writePrCiHealthReport,
} from "../../../scripts/ci/pr-ci-health.mjs";
import { createGhApiRequest } from "../../../scripts/ci/github-api.mjs";
import type {
PrCiPullRequest,
PrCiWorkflowRun,
} from "../../../scripts/ci/pr-ci-health.mjs";
import { executeWorkflowFixture } from "../../support/workflowGit.js";
const reporter = fileURLToPath(
new URL("../../../scripts/ci/pr-ci-health.mjs", import.meta.url),
);
const observedAt = Date.parse("2026-10-14T00:00:00Z");
const headSha = "a".repeat(40);
const mergeSha = "b".repeat(40);
it("classifies workflow states without confusing absent, pending, and completed CI", () => {
const pull = validPull();
const cases = [
[
"startup_failure",
run({ status: "completed", conclusion: "startup_failure" }),
],
[
"queued_pending_executing",
run({ status: "in_progress", conclusion: null }),
],
["approval_required", run({ status: "waiting", conclusion: null })],
["completed_failure", run({ status: "completed", conclusion: "failure" })],
[
"completed_canceled",
run({ status: "completed", conclusion: "cancelled" }),
],
["completed_success", run({ status: "completed", conclusion: "success" })],
["completed_other", run({ status: "completed", conclusion: "neutral" })],
[
"completed_other",
run({ status: "completed", conclusion: "constructor" }),
],
] as const;
for (const [category, evidence] of cases) {
for (const runsComplete of [true, false]) {
const result = classifyPrCi({
pull,
runs: [
{
run: { ...evidence, run_attempt: 1 },
basis: "event_pr_number_and_head_sha",
},
],
runsComplete,
pullRequestInventoryComplete: true,
ambiguousRuns: [],
});
expect(result).toMatchObject({
category: runsComplete ? category : "unknown",
...(runsComplete
? {}
: { reason: "workflow_run_inventory_incomplete" }),
runs: [
{
id: 77,
attempt: 1,
status: evidence.status,
conclusion: evidence.conclusion,
},
],
});
}
}
for (const runsComplete of [true, false]) {
expect(
classifyPrCi({
pull: { ...pull, mergeable: false },
runs: [],
runsComplete,
pullRequestInventoryComplete: true,
ambiguousRuns: [],
}).category,
).toBe("merge_conflict");
}
});
it("requires complete inventories, known mergeability, and immutable head identity to report missing", () => {
const pull = validPull({ mergeable: true });
const classify = (overrides = {}) =>
classifyPrCi({
pull,
runs: [],
runsComplete: true,
pullRequestInventoryComplete: true,
ambiguousRuns: [],
...overrides,
});
expect(classify().category).toBe("missing");
expect(classify({ runsComplete: false })).toMatchObject({
category: "deferred",
reason: "lookup_inventory_incomplete",
});
expect(classify({ pullRequestInventoryComplete: false }).category).toBe(
"deferred",
);
expect(
classify({
ambiguousRuns: [{ run: run(), basis: "ambiguous_head_identity" }],
}).category,
).toBe("unknown");
expect(classify({ pull: { ...pull, mergeable: undefined } }).category).toBe(
"unknown",
);
expect(classify({ pull: { ...pull, identityValid: false } }).category).toBe(
"unknown",
);
});
it("accepts event PR/head evidence for merge-SHA runs and refuses ambiguous branch identities", () => {
const pull = validPull();
const associatedMergeRun = run({
head_sha: mergeSha,
pull_requests: [
{
number: pull.number!,
head: { sha: headSha, repo: { id: pull.head.repositoryId } },
},
],
});
expect(
matchRunToPullRequest({
run: associatedMergeRun,
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}),
).toEqual({ kind: "match", basis: "event_pr_number_and_head_sha" });
expect(
matchRunToPullRequest({
run: run({
pull_requests: [
{ number: pull.number!, head: { sha: "c".repeat(40) } },
],
}),
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}).kind,
).toBe("none");
const branchRun = run({ pull_requests: [] });
expect(
matchRunToPullRequest({
run: branchRun,
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
inventoryComplete: false,
}).kind,
).toBe("ambiguous");
expect(
matchRunToPullRequest({
run: branchRun,
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}),
).toEqual({
kind: "match",
basis: "event_unique_head_ref_and_repository_id",
});
expect(
matchRunToPullRequest({
run: run({ head_sha: mergeSha, pull_requests: [] }),
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}).kind,
).toBe("none");
expect(
matchRunToPullRequest({
run: run({
pull_requests: [{ number: pull.number!, head: { sha: headSha } }],
}),
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}).kind,
).toBe("ambiguous");
expect(
matchRunToPullRequest({
run: branchRun,
pull,
identityCounts: new Map([["73\u0000feature", 2]]),
}).kind,
).toBe("ambiguous");
expect(
matchRunToPullRequest({
run: run({ event: "workflow_dispatch" }),
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}).kind,
).toBe("none");
});
it("scans target-branch PRs through public gh GET requests and writes JSON and Markdown", async () => {
const fixture = await createFixture();
const calls: string[] = [];
const apiRequest: NonNullable<
Parameters<typeof collectPrCiHealth>[0]["apiRequest"]
> = async (method, endpoint) => {
calls.push(`${method} ${endpoint}`);
if (method !== "GET") throw new Error("fixture rejected a non-GET request");
if (endpoint.includes("/pulls?"))
return [
rawPull(42, { mergeable: true }),
rawPull(43, { mergeable: false }),
rawPull(44, {
base: { ref: "release", repo: { id: 11 } },
mergeable: true,
}),
rawPull(45, { draft: true, mergeable: true }),
];
if (endpoint.includes("/actions/workflows/ci.yml/runs?"))
return {
total_count: 1,
workflow_runs: [
run({
id: 9001,
event: "pull_request",
status: "completed",
conclusion: "failure",
head_sha: mergeSha,
pull_requests: [
{
number: 42,
head: { sha: headSha, repo: { id: 73 } },
},
],
}),
],
};
throw new Error(`unexpected GET endpoint: ${endpoint}`);
};
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest,
});
expect(calls).toHaveLength(2);
expect(calls.every((call) => call.startsWith("GET "))).toBe(true);
expect(calls[0]).toContain("state=open");
expect(calls[0]).not.toContain("base=");
expect(calls[1]).toContain("event=pull_request");
expect(report.pullRequests).toHaveLength(2);
expect(report.pullRequests.map(({ number }) => number)).toEqual([42, 43]);
expect(report.pullRequests.map(({ ci }) => ci.category)).toEqual([
"completed_failure",
"merge_conflict",
]);
expect(report.scan).toMatchObject({
status: "complete",
pullRequestInventoryComplete: true,
workflowRunInventoryComplete: true,
apiRequests: 2,
});
const output = join(fixture.directory, ".cache", "ci-pr-health");
const paths = await writePrCiHealthReport(report, output);
const written = JSON.parse(await readFile(paths.jsonPath, "utf8"));
const markdown = await readFile(paths.markdownPath, "utf8");
expect(written.counts.completed_failure).toBe(1);
expect(markdown).toContain("# Pull request CI health snapshot");
expect(markdown).toContain("#42");
expect(markdown).toContain("completed_failure");
});
it("counts older open PRs when deciding whether a branch/ref fallback is unique", async () => {
const olderPull = rawPull(63, {
created_at: "2026-09-01T00:00:00Z",
head: { ...rawPull(63).head, ref: "shared-feature" },
});
const currentPull = rawPull(64, {
mergeable: true,
head: { ...olderPull.head },
});
const apiRequest: NonNullable<
Parameters<typeof collectPrCiHealth>[0]["apiRequest"]
> = async (_method, endpoint) => {
if (endpoint.includes("/pulls?")) return [currentPull, olderPull];
if (endpoint.includes("/actions/workflows/ci.yml/runs?"))
return {
workflow_runs: [
run({
head_branch: "shared-feature",
pull_requests: [],
}),
],
};
throw new Error(`unexpected GET endpoint: ${endpoint}`);
};
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest,
});
expect(report.scan.pullRequestInventoryComplete).toBe(true);
expect(report.pullRequests.map(({ number }) => number)).toEqual([64]);
expect(report.pullRequests[0]?.ci).toMatchObject({
category: "unknown",
reason: "workflow_run_identity_ambiguous",
});
});
it.each([false, true])(
"keeps page-capped scans uncertain (observed success: %s)",
async (observedSuccess) => {
const pull = rawPull(62, { mergeable: true });
const apiRequest: NonNullable<
Parameters<typeof collectPrCiHealth>[0]["apiRequest"]
> = async (_method, endpoint) => {
if (endpoint.includes("/pulls?")) return [pull];
const page = Number(
new URL(`https://fixture.invalid/${endpoint}`).searchParams.get("page"),
);
return {
workflow_runs: Array.from({ length: 100 }, (_item, index) =>
observedSuccess && page === 1 && index === 0
? run({
run_attempt: 1,
pull_requests: [
{ number: 62, head: { sha: headSha, repo: { id: 73 } } },
],
})
: run({
id: page * 100 + index,
head_branch: "different-branch",
head_repository: { id: 999 },
pull_requests: [],
}),
),
};
};
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest,
});
expect(report.scan.workflowRunPages).toBe(5);
expect(report.scan.workflowRunInventoryComplete).toBe(false);
const firstPull = report.pullRequests[0];
if (firstPull === undefined) throw new Error("fixture PR was not scanned");
expect(firstPull.ci).toMatchObject({
category: observedSuccess ? "unknown" : "deferred",
reason: observedSuccess
? "workflow_run_inventory_incomplete"
: "lookup_inventory_incomplete",
});
expect(firstPull.ci.runs).toHaveLength(observedSuccess ? 1 : 0);
},
);
it("keeps the result unknown when the head changes between API snapshots", async () => {
const apiRequest: NonNullable<
Parameters<typeof collectPrCiHealth>[0]["apiRequest"]
> = async (_method, endpoint) => {
if (endpoint.includes("/pulls?")) return [rawPull(63)];
if (endpoint.includes("/actions/workflows/ci.yml/runs?"))
return { workflow_runs: [] };
return {
...rawPull(63, { mergeable: true }),
head: {
...rawPull(63).head,
sha: mergeSha,
},
};
};
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest,
});
expect(report.pullRequests[0]).toMatchObject({
identityChangedDuringScan: true,
ci: { category: "unknown", reason: "pull_request_head_identity_invalid" },
});
expect(report.scan).toMatchObject({
status: "partial",
errors: ["pull_request_identity_changed_during_scan"],
});
});
it("public CLI uses only GET and produces a report from fixture GitHub responses", async () => {
const fixture = await createFixture();
const ghCalls = join(fixture.directory, "gh-calls.jsonl");
const ghResponse = join(fixture.directory, "gh-response.json");
const fakeGh = join(fixture.fakeBin, "gh");
await writeFile(
ghResponse,
JSON.stringify([
[rawPull(51, { mergeable: true })],
{ total_count: 0, workflow_runs: [] },
]),
);
await writeFile(
fakeGh,
`#!/usr/bin/env node\nconst fs=require("node:fs");\nconst args=process.argv.slice(2);\nfs.appendFileSync(process.env.CI_GH_CALLS, JSON.stringify(args)+"\\n");\nif(args[0]!=="api"||args[1]!=="--method"||args[2]!=="GET")process.exit(41);\nconst page=Number(new URL("https://fixture.invalid/"+args.at(-1)).searchParams.get("page"));\nconst responses=JSON.parse(fs.readFileSync(process.env.CI_GH_RESPONSE,"utf8"));\nprocess.stdout.write(JSON.stringify(responses[page===1&&args.at(-1).includes("/pulls?")?0:1]));\n`,
);
await chmod(fakeGh, 0o755);
const outputDirectory = join(fixture.directory, ".cache", "ci-pr-health");
await executeWorkflowFixture(process.execPath, [reporter], {
cwd: fixture.directory,
env: {
...process.env,
PATH: `${fixture.fakeBin}${delimiter}${process.env.PATH ?? ""}`,
CI_REPOSITORY: "owner/rea",
CI_REPOSITORY_ID: "11",
CI_DEFAULT_BRANCH: "main",
CI_PR_HEALTH_DIRECTORY: outputDirectory,
CI_GH_CALLS: ghCalls,
CI_GH_RESPONSE: ghResponse,
},
});
const calls = (await readFile(ghCalls, "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line));
expect(calls).toHaveLength(2);
expect(
calls.every(
(args: string[]) => args[1] === "--method" && args[2] === "GET",
),
).toBe(true);
const report = JSON.parse(
await readFile(join(outputDirectory, "report.json"), "utf8"),
);
expect(report.pullRequests[0].ci.category).toBe("missing");
await expect(
readFile(join(outputDirectory, "summary.md"), "utf8"),
).resolves.toContain("missing");
});
it("rejects non-GET methods before launching the GitHub client", async () => {
const fixture = await createFixture();
const request = createGhApiRequest({
env: {
...process.env,
PATH: `${fixture.fakeBin}${delimiter}${process.env.PATH ?? ""}`,
CI_GH_CALLS: join(fixture.directory, "should-not-exist"),
},
});
await expect(
request("POST", "repos/owner/rea/pulls", {
requests: 0,
startedAt: observedAt,
limitMs: 1_000,
}),
).rejects.toThrow("read-only GET");
await expect(
readFile(join(fixture.directory, "should-not-exist")),
).rejects.toMatchObject({ code: "ENOENT" });
});
function validPull(overrides: Partial<PrCiPullRequest> = {}): PrCiPullRequest {
return {
number: 42,
identityValid: true,
mergeable: true,
head: { repositoryId: 73, ref: "feature", sha: headSha },
...overrides,
};
}
it.each([
["newer run", { id: 78, created_at: "2026-10-13T01:00:00Z" }, "unknown"],
[
"older run",
{ id: 78, created_at: "2026-10-12T23:00:00Z" },
"completed_success",
],
["equal timestamps", { id: 78 }, "unknown"],
[
"retry of an older run",
{ id: 78, created_at: "2026-10-12T23:00:00Z", run_attempt: 2 },
"unknown",
],
["unknown timestamp", { id: 78, created_at: "invalid" }, "unknown"],
["newer attempt", { run_attempt: 3 }, "unknown"],
["older attempt", { run_attempt: 1 }, "completed_success"],
] as const)(
"retains ambiguity evidence for a %s without reporting a stale completion",
(_label, overrides, category) => {
const currentAttempt = "id" in overrides ? 1 : 2;
const result = classifyPrCi({
pull: validPull(),
runs: [
{
run: run({ run_attempt: currentAttempt }),
basis: "event_pr_number_and_head_sha",
},
],
ambiguousRuns: [
{
run: run({ run_attempt: currentAttempt, ...overrides }),
basis: "ambiguous_head_identity",
},
],
runsComplete: true,
pullRequestInventoryComplete: true,
});
expect(result.category).toBe(category);
expect(result.runs).toHaveLength(2);
},
);
it("does not let an older proven run hide a newer run with an unverified repository ID", async () => {
const pull = rawPull(42);
const older = run({
id: 70,
created_at: "2026-10-13T00:00:00Z",
pull_requests: [{ number: 42, head: { sha: headSha, repo: { id: 73 } } }],
});
const newer = run({
id: 71,
created_at: "2026-10-13T01:00:00Z",
status: "in_progress",
conclusion: null,
pull_requests: [{ number: 42, head: { sha: headSha } }],
});
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest: async (_method, endpoint) => {
if (endpoint.includes("/pulls?")) return [pull];
if (endpoint.endsWith("/pulls/42")) return { ...pull, mergeable: true };
return { workflow_runs: [newer, older] };
},
});
expect(report.pullRequests[0]?.ci).toMatchObject({
category: "unknown",
reason: "workflow_run_identity_ambiguous",
});
expect(report.pullRequests[0]?.ci.runs).toHaveLength(2);
});
it("keeps a proven newest run even when two older matched runs have equal timestamps", () => {
const result = classifyPrCi({
pull: validPull(),
runs: [
run({ id: 70, run_attempt: 1 }),
run({ id: 71, run_attempt: 1, conclusion: "failure" }),
run({
id: 72,
run_attempt: 1,
created_at: "2026-10-13T01:00:00Z",
status: "in_progress",
conclusion: null,
}),
].map((run) => ({ run, basis: "event_pr_number_and_head_sha" })),
ambiguousRuns: [],
runsComplete: true,
pullRequestInventoryComplete: true,
});
expect(result.category).toBe("queued_pending_executing");
expect(result.runs).toHaveLength(3);
});
function run(overrides: Partial<PrCiWorkflowRun> = {}): PrCiWorkflowRun {
return {
id: 77,
event: "pull_request",
head_branch: "feature",
head_repository: { id: 73 },
head_sha: headSha,
status: "completed",
conclusion: "success",
created_at: "2026-10-13T00:00:00Z",
pull_requests: [],
...overrides,
};
}
function rawPull(number: number, overrides: Record<string, unknown> = {}) {
return {
number,
draft: false,
created_at: "2026-10-13T00:00:00Z",
html_url: `https://github.com/owner/rea/pull/${String(number)}`,
base: { ref: "main", repo: { id: 11 } },
head: {
ref: `feature-${String(number)}`,
sha: headSha,
repo: { id: 73, full_name: "contributor/rea" },
},
...overrides,
};
}
async function createFixture() {
const directory = await createTestTempDirectory("rea-ci-pr-health-");
const fakeBin = join(directory, "bin");
await mkdir(fakeBin);
return { directory, fakeBin };
}
@@ -44,7 +44,7 @@ function run(overrides: Record<string, unknown> = {}) {
id: 7,
status: "completed",
conclusion: "success",
path: ".github/workflows/ci.yml",
path: ".github/workflows/ci.yml@main",
event: "schedule",
created_at: new Date(now - 120_000).toISOString(),
head_sha: validSha,
@@ -121,7 +121,11 @@ it("exports every canonical scope with read authority for admission and keeps te
);
expect(timings.on.workflow_run).toBeUndefined();
expect(timings.on.schedule).toHaveLength(1);
expect(timings.permissions).toEqual({ contents: "read", actions: "read" });
expect(timings.permissions).toEqual({
contents: "read",
actions: "read",
"pull-requests": "read",
});
const checkout = timings.jobs.report.steps.find((step) =>
step.uses?.startsWith("actions/checkout@"),
);
@@ -154,6 +158,7 @@ it("holds native and provider fan-out behind static validation while portable fe
"static",
"build",
"test-shard",
"test-source",
"test",
"docs",
"required",
@@ -369,7 +374,7 @@ it("keeps fast feedback separate from complete qualification and release proof",
// release their concurrency slot without waiting for another runner.
expect(ci.jobs.required?.if).toBe("${{ !cancelled() }}");
const shards = ci.jobs["test-shard"]?.steps ?? [];
const fast = shards.find((step) => step.run?.includes("npm run test:run"));
const fast = shards.find((step) => step.run?.includes("npm run test:built"));
const full = shards.find((step) => step.run?.includes("test:ci:shard:run"));
expect(fast?.if).toBe("needs.changes.outputs.tier == 'fast'");
expect(fast?.run).toContain("--reporter=blob");
@@ -0,0 +1,99 @@
import { execFile } from "node:child_process";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { parseStaticArchive } from "../../../scripts/ci/artifacts.mjs";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const producer = fileURLToPath(
new URL("../../../scripts/ci/static-check-report.mjs", import.meta.url),
);
it.each([3.5, 100, 0])(
"retains real lint failures when the duplication threshold is %s",
async (threshold) => {
const root = await createTestTempDirectory("rea-ci-static-archive-");
await mkdir(join(root, "src"));
await mkdir(join(root, "tests"));
await writeFile(
join(root, ".oxlintrc.json"),
JSON.stringify({ rules: { "no-debugger": "error" } }),
);
await writeFile(
join(root, ".jscpd.json"),
JSON.stringify({ threshold, minLines: 5, minTokens: 50 }),
);
await writeFile(
join(root, "src/example.ts"),
"debugger;\nexport const example = true;\n",
);
const duplicate =
"export function compute(value: number) {\n" +
Array.from({ length: 20 }, (_, index) => ` value += ${index};\n`).join(
"",
) +
" return value;\n}\n";
for (const name of threshold === 3.5 ? [] : ["first", "second"])
await writeFile(join(root, `src/${name}.ts`), duplicate);
await expect(
execute(process.execPath, [producer, "lint", "src/example.ts"], {
cwd: root,
}),
).rejects.toMatchObject({ code: 1 });
const duplication = execute(process.execPath, [producer, "duplicates"], {
cwd: root,
});
if (threshold === 0)
await expect(duplication).rejects.toMatchObject({ code: 1 });
else await duplication;
const reports = join(root, ".cache/static-checks");
expect(
JSON.parse(
await readFile(join(reports, "jscpd/jscpd-report.json"), "utf8"),
),
).toMatchObject({ reaCheck: { exitCode: threshold === 0 ? 1 : 0 } });
await writeFile(
join(reports, "static-task-context.json"),
JSON.stringify({
version: 1,
sourceSha: "a".repeat(40),
sourceClean: true,
nodeVersion: process.version,
npmVersion: "11.16.0",
turboVersion: "2.11.7",
platform: process.platform,
architecture: process.arch,
taskHashes: { "lint:built": "a".repeat(16), jscpd: "b".repeat(16) },
}),
);
const archive = join(root, "reports.zip");
await execute(
"zip",
[
"-q",
archive,
"oxlint.json",
"jscpd/jscpd-report.json",
"static-task-context.json",
],
{ cwd: reports },
);
const evidence = await parseStaticArchive(archive);
expect(evidence.diagnostics.filter(({ kind }) => kind === "lint")).toEqual([
expect.objectContaining({
kind: "lint",
path: "src/example.ts",
severity: "error",
}),
]);
const duplicates = evidence.diagnostics.filter(
({ kind }) => kind === "jscpd",
);
if (threshold === 0) expect(duplicates.length).toBeGreaterThan(0);
else expect(duplicates).toEqual([]);
},
);
@@ -35,7 +35,7 @@ function run(id: number, overrides: Record<string, unknown> = {}) {
id,
status: "completed",
conclusion: "success",
path: ".github/workflows/ci.yml",
path: ".github/workflows/ci.yml@main",
event: "schedule",
created_at: new Date(now - 120_000).toISOString(),
head_branch: "main",
@@ -0,0 +1,75 @@
import { execFileSync } from "node:child_process";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
BUILT_TEST_PROJECTS,
SOURCE_TEST_PROJECTS,
projectForTest,
} from "../../../scripts/lib/test-projects.mjs";
import {
developmentTestPlan,
parseDevelopmentTestRequest,
} from "../../../scripts/lib/development-tests.mjs";
const repository = process.cwd();
describe("canonical test-project ownership", () => {
it("assigns every tracked test file exactly once to source or built", () => {
const files = execFileSync("git", ["ls-files", "*.test.ts"], {
cwd: repository,
encoding: "utf8",
})
.trim()
.split("\n")
.filter(Boolean);
const grouped = new Map<string, string[]>();
for (const file of files) {
const project = projectForTest(file);
grouped.set(project.group, [...(grouped.get(project.group) ?? []), file]);
}
expect(grouped.get("source")).not.toBeUndefined();
expect(grouped.get("built")).not.toBeUndefined();
expect(
(grouped.get("source")?.length ?? 0) +
(grouped.get("built")?.length ?? 0),
).toBe(files.length);
expect(
SOURCE_TEST_PROJECTS.reduce(
(count, project) => count + project.include.length,
0,
),
).toBeGreaterThan(0);
expect(
BUILT_TEST_PROJECTS.every((project) => project.group === "built"),
).toBe(true);
expect(() => projectForTest("tests/unowned/example.test.ts")).toThrow(
"No test project owns",
);
});
it("owns the Hopper real-provider conformance test as built and requires preparation", () => {
const testPath =
"tests/conformance/providers/hopper/realHopperSearch.test.ts";
expect(projectForTest(testPath)).toMatchObject({
name: "boundary",
group: "built",
});
expect(() => parseDevelopmentTestRequest("local", [testPath])).toThrow(
`Use test:focused for built test projects: ${testPath}`,
);
const request = parseDevelopmentTestRequest("focused", [testPath]);
expect(developmentTestPlan(request)).toMatchObject({ needsBuild: true });
});
it("uses canonical selectors in Vitest while retaining independent runner policy", async () => {
const config = await readFile(join(repository, "vitest.config.ts"), "utf8");
expect(config).toContain(
"[...SOURCE_TEST_PROJECTS, ...BUILT_TEST_PROJECTS]",
);
expect(config).toContain("PROJECT_POLICIES");
expect(config).not.toContain('"src/{contracts,domain}/**/*.test.ts"');
});
});
+140 -15
View File
@@ -3,6 +3,7 @@ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { runInNewContext } from "node:vm";
import { expect, it } from "vitest";
import { parse } from "yaml";
@@ -48,9 +49,7 @@ const workflow = async () =>
it("merges available failed-shard diagnostics and skips unavailable shard reports", async () => {
const steps = (await workflow()).test!.steps;
const download = steps.find(
(step) =>
step.uses?.includes("actions/download-artifact") &&
step.with?.pattern === "vitest-report-*",
(step) => step.with?.pattern === "vitest-report-*",
);
const merge = steps.findIndex((step) => step.run?.includes("test:ci:merge"));
const upload = steps.findIndex((step) => step.with?.name === "test-results");
@@ -59,8 +58,7 @@ it("merges available failed-shard diagnostics and skips unavailable shard report
);
expect(merge).toBeGreaterThan(0);
expect(download?.if).toContain("!cancelled()");
expect(download?.if).toContain("needs.test-shard.result == 'success'");
expect(download?.if).toContain("needs.test-shard.result == 'failure'");
expect(upload).toBeGreaterThan(merge);
expect(gate).toBeGreaterThan(upload);
const merges = steps.filter((step) => step.run?.includes("--reporter=json"));
@@ -70,8 +68,6 @@ it("merges available failed-shard diagnostics and skips unavailable shard report
"--reporter=./scripts/ci/test-timing-reporter.mjs",
);
expect(step.if).toContain("!cancelled()");
expect(step.if).toContain("needs.test-shard.result == 'success'");
expect(step.if).toContain("needs.test-shard.result == 'failure'");
}
expect(steps[upload]?.with?.path).toContain("test-timings.json");
expect(steps[upload]?.with).toMatchObject({ "include-hidden-files": true });
@@ -86,12 +82,23 @@ it("merges available failed-shard diagnostics and skips unavailable shard report
);
const command = steps[gate]?.run;
if (command === undefined) throw new Error("Missing shard result gate");
for (const result of ["failure", "cancelled", "skipped", ""]) {
await expect(
execute("bash", ["-c", command], {
env: { ...process.env, CODE_REQUIRED: "true", SHARD_RESULT: result },
}),
).rejects.toMatchObject({ code: 1 });
for (const tier of ["fast", "full"]) {
for (const shard of ["success", "failure", "cancelled", "skipped", ""]) {
for (const source of ["success", "failure", "cancelled", "skipped", ""]) {
const check = execute("bash", ["-c", command], {
env: {
...process.env,
CODE_REQUIRED: "true",
SHARD_RESULT: shard,
SOURCE_REQUIRED: String(tier === "fast"),
SOURCE_RESULT: source,
},
});
if (shard === "success" && (tier !== "fast" || source === "success"))
await expect(check).resolves.toMatchObject({ stderr: "" });
else await expect(check).rejects.toMatchObject({ code: 1 });
}
}
}
await expect(
execute("bash", ["-c", command], {
@@ -100,6 +107,80 @@ it("merges available failed-shard diagnostics and skips unavailable shard report
).resolves.toMatchObject({ stderr: "" });
});
// These workflow conditions use the shared boolean/string expression subset.
// Evaluate the checked-in expressions so failure-state coverage cannot drift
// into a separate test implementation of the collection policy.
function conditionValue(
condition: string | undefined,
needs: Record<string, unknown>,
canceled: boolean,
) {
if (!condition) throw new Error("Missing report collection condition");
return runInNewContext(
condition
.replaceAll("needs.test-shard", 'needs["test-shard"]')
.replaceAll("needs.test-source", 'needs["test-source"]'),
{ needs, cancelled: () => canceled },
{ timeout: 1_000 },
);
}
it("collects either fast test group while keeping full reports tied to full shards", async () => {
const steps = (await workflow()).test.steps;
const download = steps.find(
(step) => step.with?.pattern === "vitest-report-*",
);
const fast = steps.find(
(step) => step.name === "Merge fast-suite JUnit and timing reports",
);
const full = steps.find(
(step) => step.name === "Merge coverage, JUnit, and timing reports",
);
for (const tier of ["fast", "full"]) {
for (const shard of ["success", "failure", "cancelled", "skipped", ""]) {
for (const source of ["success", "failure", "cancelled", "skipped", ""]) {
for (const [code, canceled] of [
["true", false],
["true", true],
["false", false],
["false", true],
] as const) {
const needs = {
changes: { outputs: { code, tier } },
"test-shard": { result: shard },
"test-source": { result: source },
};
const builtAvailable = ["success", "failure"].includes(shard);
const sourceAvailable = ["success", "failure"].includes(source);
const enabled = code === "true" && !canceled;
const available =
builtAvailable || (tier === "fast" && sourceAvailable);
const expected = enabled
? {
download: available,
fast: tier === "fast" && available,
full: tier === "full" && builtAvailable,
}
: { download: false, fast: false, full: false };
expect(conditionValue(download?.if, needs, canceled)).toBe(
expected.download,
);
expect(conditionValue(fast?.if, needs, canceled)).toBe(expected.fast);
expect(conditionValue(full?.if, needs, canceled)).toBe(expected.full);
}
}
}
}
const summary = steps.find((step) =>
step.run?.includes("scripts/ci/test-report.mjs"),
);
expect(summary?.env?.SHARD_RESULT).toBe("${{ needs.test-shard.result }}");
expect(summary?.env?.SOURCE_RESULT).toBe("${{ needs.test-source.result }}");
expect(summary?.env?.SOURCE_REQUIRED).toBe(
"${{ needs.changes.outputs.tier == 'fast' }}",
);
});
it("keeps diagnosis available after merge failure and publishes only complete successful history", async () => {
const steps = (await workflow()).test!.steps;
const diagnosis = steps.find((step) => step.with?.name === "test-results");
@@ -220,7 +301,12 @@ it("exports portable timing history and removes it on a failed, partial, or inva
{ name: join(root, "tests/fast.test.ts"), durationMs: 10 },
],
};
const run = async (value: unknown, shards = "success", merge = "success") => {
const run = async (
value: unknown,
shards = "success",
merge = "success",
source?: string,
) => {
await writeFile(join(root, "test-timings.json"), JSON.stringify(value));
await writeFile(summary, "");
return execute(process.execPath, [fileURLToPath(script)], {
@@ -229,6 +315,8 @@ it("exports portable timing history and removes it on a failed, partial, or inva
...process.env,
GITHUB_STEP_SUMMARY: summary,
SHARD_RESULT: shards,
SOURCE_REQUIRED: String(source !== undefined),
SOURCE_RESULT: source ?? "",
MERGE_RESULT: merge,
},
});
@@ -256,6 +344,24 @@ it("exports portable timing history and removes it on a failed, partial, or inva
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(summary, "utf8")).toContain("diagnostic only");
}
await run(report, "success", "success", "success");
expect(await readFile(history, "utf8")).toContain('"success":true');
for (const [shards, source] of [
["skipped", "success"],
["success", "skipped"],
["success", "cancelled"],
["success", "failure"],
["success", ""],
]) {
await run(report);
await run(report, shards, "success", source);
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
const text = await readFile(summary, "utf8");
expect(text).toContain(`Source result: ${source}.`);
expect(text).toContain("diagnostic only");
if (shards === "skipped" || source !== "failure")
expect(text).toContain("Partial test diagnostics");
}
await run(report);
await expect(
run({
@@ -352,6 +458,21 @@ it("recovers complete module costs from real blob reports without executing test
expect(file.durationMs).toBeCloseTo(
Object.values(file.phases).reduce((sum, value) => sum + value, 0),
);
const partial = await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
SHARD_RESULT: "skipped",
SOURCE_REQUIRED: "true",
SOURCE_RESULT: "success",
MERGE_RESULT: "success",
},
});
expect(partial.stdout).toContain("Partial test diagnostics");
expect(partial.stdout).toContain("sample.test.js");
await expect(
readFile(join(root, ".cache/ci-test-history/test-results.json")),
).rejects.toMatchObject({ code: "ENOENT" });
await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" },
@@ -420,13 +541,15 @@ it("records failed omissions from full reports without treating partial or unhan
state: index === 1 ? "failed" : "passed",
})),
};
const run = async (report: unknown) => {
const run = async (report: unknown, source = "failure") => {
await writeFile(join(root, "test-timings.json"), JSON.stringify(report));
await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
SHARD_RESULT: "failure",
SOURCE_REQUIRED: "true",
SOURCE_RESULT: source,
MERGE_RESULT: "failure",
CI_VERIFY_TEST_INVENTORY: "true",
CI_TEST_SELECTION: JSON.stringify(
@@ -458,6 +581,8 @@ it("records failed omissions from full reports without treating partial or unhan
{ ...timing, reason: "interrupted" },
])
expect(await run(report)).toMatchObject({ complete: false });
for (const source of ["skipped", "cancelled", ""])
expect(await run(timing, source)).toMatchObject({ complete: false });
await expect(run({ ...timing, files: "invalid" })).rejects.toMatchObject({
code: 1,
});
@@ -0,0 +1,54 @@
import { expect, it } from "vitest";
import { normalizeWorkflowRun } from "../../../scripts/ci/workflow-run.mjs";
it.each([
[".github/workflows/ci.yml", ".github/workflows/ci.yml", null],
[".github/workflows/ci.yml@main", ".github/workflows/ci.yml", "main"],
[
".github/workflows/ci.yml@refs/heads/release/v1",
".github/workflows/ci.yml",
"refs/heads/release/v1",
],
[
".github/workflows/ci.yml@feature@v1",
".github/workflows/ci.yml",
"feature@v1",
],
[
".github/workflows/release.yaml@main",
".github/workflows/release.yaml",
"main",
],
])(
"preserves API path %s while separating its file identity and ref",
(path, file, ref) => {
const raw = { id: 10, path, head_sha: "a".repeat(40) };
const parsed = normalizeWorkflowRun(raw);
expect(parsed).toEqual({ ...raw, workflowPath: { file, ref } });
expect(raw).not.toHaveProperty("workflowPath");
},
);
it.each([
undefined,
null,
42,
"",
".github/workflows/ci.yml@",
".github/workflows/ci.yml@main\n",
".github/workflows/ci.yml@main\0",
"../.github/workflows/ci.yml",
".github/workflows/../ci.yml@main",
".github/workflows/ci.yml-extra@main",
"https://example.test/ci.yml@main",
])(
"keeps malformed workflow path %s unknown instead of inventing a file identity",
(path) => {
const parsed = normalizeWorkflowRun({
path,
workflowPath: { file: ".github/workflows/ci.yml", ref: "main" },
});
expect(parsed.path).toBe(path);
expect(parsed.workflowPath).toBeNull();
},
);