fix(plugins): resolve review findings and integrate main

This commit is contained in:
morluto
2026-10-14 07:51:46 +08:00
565 changed files with 101110 additions and 46071 deletions
@@ -228,7 +228,7 @@ describe("case-distinct APK resource names", () => {
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
@@ -238,11 +238,11 @@ describe("case-distinct APK resource names", () => {
);
expect(projection.root_format).toBe("apk");
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
expect(projection.components.manifests).toHaveLength(1);
expect(projection.components.dex).toHaveLength(1);
@@ -75,7 +75,7 @@ async function createCompleteAppleProjection() {
}
describe("Apple application projection", () => {
it("keeps a case-colliding real IPA inventory partial", async () => {
it("retains complete traversal and case-collision limits for a real IPA", async () => {
const root = await createTestTempDirectory("rea-apple-case-collision-");
const path = join(root, "CaseCollision.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
@@ -93,7 +93,7 @@ describe("Apple application projection", () => {
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const result = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
@@ -103,11 +103,11 @@ describe("Apple application projection", () => {
);
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
});
@@ -2,6 +2,7 @@ import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { fragmentInventoryEvidence } from "../../fixtures/artifactEvidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -77,7 +78,11 @@ describe("leaf artifact comparison", () => {
// Persisted inventory Evidence predates coverage_status. The known leaf
// notice remains complete when normalized at the inventory boundary.
const parsed = artifactInventoryResultSchema.parse(left.normalized_result);
const { coverage_status: _coverageStatus, ...legacyInventory } = parsed;
const {
coverage: _coverage,
coverage_status: _coverageStatus,
...legacyInventory
} = parsed;
const legacy = createEvidence(
{
path: left.subject!.local_path,
@@ -157,7 +162,7 @@ describe("artifact inventory coverage", () => {
const graph = artifactInventoryResultSchema.parse(
complete.normalized_result,
);
const partial = createEvidence(
const contradictory = createEvidence(
{
path: complete.subject!.local_path,
sha256: complete.subject!.digest.sha256,
@@ -168,6 +173,29 @@ describe("artifact inventory coverage", () => {
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({ ...graph, coverage_status: "partial" }),
confidence: "derived",
authority: "shipped-artifact",
},
);
expect(() => parseArtifactInventoryEvidence(contradictory)).toThrow(
"Artifact inventory has conflicting coverage declarations",
);
const { coverage: _coverage, ...legacyStatusGraph } = graph;
const partial = createEvidence(
{
path: complete.subject!.local_path,
sha256: complete.subject!.digest.sha256,
format: complete.subject!.format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...legacyStatusGraph,
coverage_status: "partial",
}),
confidence: "observed",
authority: "shipped-artifact",
},
@@ -180,7 +208,8 @@ describe("artifact inventory coverage", () => {
summary: { unchanged: 0, unknown: 1 },
});
const { coverage_status: _coverageStatus, ...legacyGraph } = graph;
const { coverage_status: _coverageStatus, ...legacyGraph } =
legacyStatusGraph;
const unknownLegacy = createEvidence(
{
path: complete.subject!.local_path,
@@ -219,6 +248,7 @@ describe("artifact inventory coverage", () => {
const fragmentGraph = artifactInventoryResultSchema.parse(
fragment.normalized_result,
);
const { coverage: _coverage, ...legacyFragmentGraph } = fragmentGraph;
const mixed = createEvidence(
{
path: fragment.subject!.local_path,
@@ -230,7 +260,7 @@ describe("artifact inventory coverage", () => {
operation: "inventory_artifact",
parameters: fragment.parameters,
result: jsonValueSchema.parse({
...fragmentGraph,
...legacyFragmentGraph,
coverage_status: "partial",
}),
confidence: "derived",
@@ -239,7 +269,7 @@ describe("artifact inventory coverage", () => {
);
expect(() =>
parseArtifactInventoryEvidence([firstFragment, mixed]),
).toThrow("Artifact inventory pages disagree on coverage status");
).toThrow("Artifact inventory pages do not share one coverage declaration");
});
});
@@ -314,6 +344,61 @@ describe("artifact comparison", () => {
});
describe("artifact comparison completeness", () => {
it("does not infer child changes from root-only coverage", async () => {
const root = await createTestTempDirectory("rea-artifact-root-coverage-");
const leftPath = join(root, "left.app");
const rightPath = join(root, "right.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "left-only.txt"), "left"),
writeFile(join(rightPath, "right-only.txt"), "right"),
]);
const [left, right] = await Promise.all([
observe(leftPath),
observe(rightPath),
]);
const rootOnly = (evidence: Awaited<ReturnType<typeof observe>>) => {
const inventory = artifactInventoryResultSchema.parse(
evidence.normalized_result,
);
return createEvidence(
{
path: evidence.subject?.local_path ?? "",
sha256: inventory.manifest.root_sha256,
format: inventory.manifest.root_format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...inventory,
coverage: { scope: "root", status: "complete" },
}),
confidence: "derived",
authority: "shipped-artifact",
},
);
};
const compared = compareArtifacts(rootOnly(left), rootOnly(right));
expect(compared.status).toBe("unknown");
expect(compared.summary).toMatchObject({ added: 0, removed: 0 });
expect(
compared.changes
.filter(({ logical_path }) => logical_path !== ".")
.map(({ logical_path, classification }) => ({
logical_path,
classification,
})),
).toEqual([
{ logical_path: "left-only.txt", classification: "unknown" },
{ logical_path: "right-only.txt", classification: "unknown" },
]);
expect(compared.limitations).toContain(
"Container entry coverage is unavailable for child paths.",
);
});
it("compares every graph member for inventories larger than 500 entries", async () => {
const root = await createTestTempDirectory("rea-artifact-pages-");
const entryCount = 501;
@@ -358,7 +443,9 @@ describe("artifact comparison completeness", () => {
changes: [],
});
}, 15_000);
});
describe("artifact comparison fragment integrity", () => {
it("assembles real inventory fragments and retains every citation", async () => {
const parent = await createTestTempDirectory("rea-artifact-fragments-");
const leftPath = join(parent, "left.app");
@@ -415,6 +502,30 @@ describe("artifact comparison completeness", () => {
evidence_links: citations,
})),
});
const fragment = leftFragments[0];
if (fragment === undefined) throw new Error("Expected inventory fragments");
const conflictingScope = createEvidence(
{
path: leftPath,
sha256: left.subject?.digest.sha256 ?? "",
format: "directory",
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...artifactInventoryResultSchema.parse(fragment.normalized_result),
coverage: { scope: "root", status: "complete" },
}),
},
);
expect(() =>
compareArtifacts(
[conflictingScope, ...leftFragments.slice(1)],
rightFragments,
),
).toThrow(/coverage declaration/u);
}, 15_000);
it("rejects non-inventory and tampered Evidence", async () => {
@@ -445,3 +556,90 @@ describe("artifact comparison completeness", () => {
);
});
});
describe("ZIP non-entry coverage", () => {
it("retains pre-directory APK block changes and compares historical scope descriptions", async () => {
const root = await createTestTempDirectory("rea-apk-block-compare-");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("classes.dex", new TextReader("unchanged entry"));
const zip = Buffer.from(await writer.close());
const eocd = zip.length - 22;
expect(zip.readUInt32LE(eocd)).toBe(0x06054b50);
const directory = zip.readUInt32LE(eocd + 16);
// APK Signing Block framing with one opaque padding pair, not a verified signature.
// https://source.android.com/docs/security/features/apksigning/v2#apk-signing-block
const block = Buffer.alloc(48);
block.writeBigUInt64LE(40n, 0);
block.writeBigUInt64LE(8n, 8);
block.writeUInt32LE(0x42726577, 16);
block.writeBigUInt64LE(40n, 24);
block.write("APK Sig Block 42", 32, "ascii");
const paths = [join(root, "before.apk"), join(root, "after.apk")];
for (const [index, path] of paths.entries()) {
block.writeUInt32LE(index, 20);
const apk = Buffer.concat([
zip.subarray(0, directory),
block,
zip.subarray(directory),
]);
apk.writeUInt32LE(directory + block.length, eocd + block.length + 16);
await writeFile(path, apk);
}
const left = await observe(paths[0]!);
const right = await observe(paths[1]!);
const inventory = artifactInventoryResultSchema.parse(
left.normalized_result,
);
expect(inventory.limitations).toContain(
"ZIP inventory lists central-directory entries only. Non-entry bytes, including an APK Signing Block before the central directory or a ZIP comment after it, are not occurrences.",
);
expect(
inventory.occurrences.map(({ logical_path }) => logical_path).sort(),
).toEqual([".", "classes.dex"]);
expect(compareArtifacts(left, right)).toMatchObject({
status: "changed",
summary: { changed: 1, unchanged: 1, unknown: 0 },
changes: [
expect.objectContaining({ logical_path: ".", dimensions: ["content"] }),
],
});
const {
coverage: _coverage,
coverage_status: _coverageStatus,
...legacyInventory
} = inventory;
const withLimitation = (limitation: string) =>
createEvidence(
{
path: paths[0]!,
sha256: inventory.manifest.root_sha256,
format: "apk",
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...legacyInventory,
limitations: [limitation],
}),
confidence: "observed",
authority: "shipped-artifact",
},
);
const historical = withLimitation(
"ZIP inventory lists central-directory entries only. Bytes after the central directory, including an APK Signing Block or a ZIP comment, are not occurrences.",
);
expect(compareArtifacts(historical, left)).toMatchObject({
status: "unchanged",
summary: { unchanged: 2, unknown: 0 },
changes: [],
});
expect(
compareArtifacts(
withLimitation("ZIP entry bytes could not be read."),
left,
).status,
).toBe("unknown");
});
});
@@ -52,3 +52,22 @@ it("rejects a root path replaced between its initial stat and open", async () =>
message: `Root artifact changed before inventory: ${path}`,
});
});
it("keeps unavailable container traversal distinct from observed root bytes", async () => {
const root = await createTestTempDirectory("rea-artifact-root-scope-");
const path = join(root, "fixture.pkg");
// The recognized XAR prefix selects PKG inventory; no child decoder is installed.
await writeFile(path, Buffer.from("xar!fixture"));
const inventory = await inventoryArtifact(path);
expect(inventory.manifest).toMatchObject({
root_format: "pkg",
node_count: 1,
occurrence_count: 1,
edge_count: 0,
});
expect(inventory.occurrences[0]?.hash_status).toBe("verified");
expect(inventory.coverage).toEqual({
scope: "container-entries",
status: "unknown",
});
});
@@ -26,6 +26,7 @@ import {
thinMach,
} from "../../../src/domain/binaryTarget.fixture.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { parseExecutableHeader } from "../../../src/domain/binaryTarget.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -424,6 +425,65 @@ describe("binary target I/O: explicit kinds and executable headers", () => {
});
});
it("extracts CodeView RSDS debug metadata from a PE target", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "symbols.exe");
await writeFile(
path,
pe(0x8664, 64, 0x0002, false, {
type: "RSDS",
pdbPath: "C:\\build\\test.pdb",
guid: "12345678-abcd-ef01-2345-6789abcdef01",
age: 3,
}),
);
const result = await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "x64",
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
format: "pe",
architecture: "x86_64",
codeView: {
pdbPath: "C:\\build\\test.pdb",
pdbFileName: "test.pdb",
guid: "12345678-abcd-ef01-2345-6789abcdef01",
age: 3,
},
});
});
it("extracts CodeView NB10 debug metadata from a PE target", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "legacy.exe");
await writeFile(
path,
pe(0x014c, 64, 0x0002, false, {
type: "NB10",
pdbPath: "D:\\old\\legacy.pdb",
age: 1,
}),
);
const result = await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "ia32",
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
format: "pe",
architecture: "x86",
codeView: {
pdbPath: "D:\\old\\legacy.pdb",
pdbFileName: "legacy.pdb",
guid: null,
age: 1,
},
});
});
it("refuses a truncated Mach-O header before any provider sees it", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "truncated");
@@ -884,3 +944,43 @@ it.each([
});
},
);
describe("binary target I/O: PE CodeView header ranges", () => {
it.each(["RSDS", "NB10"] as const)(
"reads bounded %s header debug records and rejects unfinished names",
async (type) => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "header-symbols.exe");
const bytes = pe(0x8664, 64, 0x0002, false, {
type,
pdbPath: "header.pdb",
});
const optionalHeader = 64 + 24;
bytes.writeUInt32LE(512, optionalHeader + 60);
bytes.copy(bytes, 384, 512);
bytes.writeUInt32LE(384, optionalHeader + 112 + 6 * 8);
bytes.writeUInt32LE(412, 384 + 20);
bytes.writeUInt32LE(0, 384 + 24);
for (const complete of [true, false]) {
if (!complete) {
const dataSize = bytes.readUInt32LE(384 + 16);
bytes[412 + dataSize - 1] = 0x61;
}
await writeFile(path, bytes);
const resolved = await parseBinaryTarget(path, {
hostArchitecture: "x64",
});
const buffered = parseExecutableHeader(bytes, "x64");
if (!resolved.ok) throw resolved.error;
if (!buffered.ok) throw new Error(buffered.error);
for (const value of [resolved.value, buffered.value]) {
if (complete)
expect(value).toMatchObject({
codeView: { pdbPath: "header.pdb" },
});
else expect(value).not.toHaveProperty("codeView");
}
}
},
);
});
@@ -0,0 +1,247 @@
import { execFileSync } from "node:child_process";
import { chmod, readFile, readdir, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { describe, expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const repository = process.cwd();
const actionPath = join(repository, ".github/actions/npm-cache/action.yml");
const readAction = async () =>
z
.object({
outputs: z.record(z.string(), z.object({ value: z.string() })),
runs: z.object({
steps: z.array(
z.object({
id: z.string().optional(),
if: z.string().optional(),
uses: z.string().optional(),
with: z.record(z.string(), z.string()).optional(),
run: z.string().optional(),
env: z.record(z.string(), z.string()).optional(),
}),
),
}),
})
.parse(parse(await readFile(actionPath, "utf8")));
const readWorkflows = async () => {
const directory = join(repository, ".github/workflows");
const files = (await readdir(directory)).filter((file) =>
/\.ya?ml$/u.test(file),
);
return Promise.all(
files.map(async (file) => ({
file,
workflow: z
.object({
jobs: z
.record(
z.string(),
z.object({
steps: z.array(z.record(z.string(), z.unknown())).optional(),
}),
)
.optional(),
})
.parse(parse(await readFile(join(directory, file), "utf8"))),
})),
);
};
describe("hosted npm download-cache policy", () => {
it("only allows shared writes for trusted original default-branch events", async () => {
const action = await readAction();
const policy = action.runs.steps.find((step) => step.id === "context");
const command = z.string().parse(policy?.run);
const outputDirectory = await createTestTempDirectory(
"rea-ci-cache-policy-",
);
const npmStub = join(outputDirectory, "npm");
await writeFile(
npmStub,
String.raw`#!/bin/sh
printf '%s\n' 'C:\Users\runner with spaces\AppData\Local\npm-cache'
`,
);
await chmod(npmStub, 0o755);
for (const [event, ref, defaultBranch, expected] of [
["push", "refs/heads/main", "main", "true"],
["schedule", "refs/heads/main", "main", "true"],
["workflow_dispatch", "refs/heads/main", "main", "true"],
["push", "refs/heads/stable", "stable", "true"],
["pull_request", "refs/heads/main", "main", "false"],
["pull_request_target", "refs/heads/main", "main", "false"],
["workflow_call", "refs/heads/main", "main", "false"],
["push", "refs/heads/feature/cache", "main", "false"],
["push", "refs/heads/main", "stable", "false"],
["push", "refs/heads/main", "", "false"],
]) {
const outputPath = join(
outputDirectory,
`policy-${Date.now()}-${Math.random()}`,
);
execFileSync("bash", ["-euo", "pipefail", "-c", command], {
env: {
...process.env,
PATH: `${outputDirectory}${delimiter}${process.env.PATH ?? ""}`,
GITHUB_EVENT_NAME: event,
GITHUB_REF: ref,
GITHUB_OUTPUT: outputPath,
DEFAULT_BRANCH: defaultBranch,
LOCKFILES_HASH: "lock-hash",
RUNNER_OS: "Windows",
},
});
const output = await readFile(outputPath, "utf8");
expect(output).toContain(`can-save=${expected}\n`);
expect(output).toContain(
`path=${String.raw`C:\Users\runner with spaces\AppData\Local\npm-cache`}\n`,
);
expect(output).toContain(
`key=npm-download-Windows-${process.arch}-lock-hash\n`,
);
}
});
it("uses a lockfile-, npmrc-, OS-, and runtime-architecture-scoped download cache", async () => {
const action = await readAction();
const policy = action.runs.steps.find((step) => step.id === "context");
const restoreAndSave = action.runs.steps.find((step) =>
step.uses?.startsWith("actions/cache@"),
);
const restoreOnly = action.runs.steps.find((step) =>
step.uses?.startsWith("actions/cache/restore@"),
);
expect(action.outputs["can-save"]?.value).toBe(
"${{ steps.context.outputs.can-save }}",
);
expect(action.outputs.path?.value).toBe(
"${{ steps.context.outputs.path }}",
);
expect(policy?.env?.DEFAULT_BRANCH).toBe(
"${{ github.event.repository.default_branch }}",
);
expect(policy?.env?.LOCKFILES_HASH).toBe(
"${{ hashFiles('npm-shrinkwrap.json', '.npmrc') }}",
);
expect(policy?.run).toContain(
'cache_key="npm-download-${RUNNER_OS}-${runtime_arch}-${LOCKFILES_HASH}"',
);
expect(restoreAndSave?.uses).toBe(
"actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830",
);
expect(restoreAndSave?.if).toBe("steps.context.outputs.can-save == 'true'");
expect(restoreOnly?.uses).toBe(
"actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830",
);
expect(restoreOnly?.if).toBe("steps.context.outputs.can-save != 'true'");
expect(restoreAndSave?.with?.path).toBe(
"${{ steps.context.outputs.path }}",
);
expect(restoreOnly?.with?.path).toBe(restoreAndSave?.with?.path);
expect(restoreAndSave?.with?.key).toBe("${{ steps.context.outputs.key }}");
expect(restoreOnly?.with?.key).toBe(restoreAndSave?.with?.key);
expect(restoreAndSave?.with).not.toHaveProperty("restore-keys");
expect(restoreOnly?.with).not.toHaveProperty("restore-keys");
});
it("replaces every inline setup-node npm cache immediately and preserves conditions", async () => {
const workflows = await readWorkflows();
let npmCacheSteps = 0;
for (const { file, workflow } of workflows) {
const source = await readFile(
join(repository, ".github/workflows", file),
"utf8",
);
expect(source).not.toMatch(/^\s+cache:\s*npm\s*$/mu);
for (const [jobName, job] of Object.entries(workflow.jobs ?? {})) {
const steps = job.steps ?? [];
for (let index = 0; index < steps.length; index++) {
const step = steps[index];
if (step?.uses !== "./.github/actions/npm-cache") continue;
npmCacheSteps++;
expect(step.id).toBe("npm-cache");
const setup = steps[index - 1];
expect(
typeof setup?.uses === "string" &&
setup.uses.startsWith("actions/setup-node@"),
`${file}:${jobName} npm cache action must immediately follow setup-node`,
).toBe(true);
expect(step.if).toBe(setup?.if);
expect(setup?.with).not.toHaveProperty("cache", "npm");
const npmCiIndex = steps.findIndex(
(candidate, candidateIndex) =>
candidateIndex > index && candidate.run === "npm ci",
);
expect(
npmCiIndex,
`${file}:${jobName} retains npm ci after cache`,
).toBeGreaterThan(index);
}
}
}
expect(npmCacheSteps).toBeGreaterThan(0);
});
});
it("shares static task snapshots only after validation using the npm cache owner's write authority", async () => {
const workflows = await readWorkflows();
const ci = workflows.find(({ file }) => file === "ci.yml");
const steps = ci?.workflow.jobs?.static?.steps ?? [];
const restore = steps.find((step) => step.id === "static-cache");
const save = steps.find(
(step) => step.name === "Save validated static task cache",
);
expect(restore?.uses).toBe(
"actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830",
);
expect(restore?.if).toBe("needs.changes.outputs.code == 'true'");
expect(restore?.with).toMatchObject({ path: ".turbo/cache/" });
expect(save?.uses).toBe(
"actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830",
);
expect(save?.if).toContain("success()");
expect(save?.if).toContain("steps.npm-cache.outputs.can-save == 'true'");
expect(save?.with).toEqual({
path: ".turbo/cache/",
key: "${{ steps.static-cache.outputs.cache-primary-key }}",
});
expect(steps.indexOf(save!)).toBeGreaterThan(
steps.findIndex((step) => step.run === "npm run test:python"),
);
});
it("bounds the rolling static snapshot with Turbo age and size eviction", async () => {
const turbo = z
.object({
cacheMaxAge: z.string(),
cacheMaxSize: z.string(),
})
.parse(JSON.parse(await readFile(join(repository, "turbo.json"), "utf8")));
// The static job restores the previous snapshot by prefix and saves the
// whole .turbo/cache directory again. Without local eviction every main
// commit carries all historical entries into a new immutable GitHub cache,
// growing transfers toward the 10 GB repository limit.
expect(turbo.cacheMaxAge).toMatch(/^[1-9]\d*(s|m|h|d|w)$/u);
expect(turbo.cacheMaxAge).not.toBe("0");
const size = /^(\d+(?:\.\d+)?)(MB|GB|TB)$/iu.exec(turbo.cacheMaxSize);
expect(size, "cacheMaxSize must use an explicit MB/GB/TB budget").not.toBe(
null,
);
const value = Number(size?.[1] ?? "0");
const unit = (size?.[2] ?? "MB").toUpperCase();
const megabytes =
unit === "TB" ? value * 1024 * 1024 : unit === "GB" ? value * 1024 : value;
expect(megabytes).toBeGreaterThan(0);
expect(megabytes).toBeLessThanOrEqual(1024);
});
+141 -1
View File
@@ -215,6 +215,146 @@ it("does not charge a documentation PR for unrelated implementation updates on m
});
});
it.each([
"src/gdb/GdbSessionManager.ts",
"src/rizin/RizinDebugSessionManager.ts",
"src/cutter/CutterBridgeClient.ts",
"src/objdump/ObjdumpCommand.ts",
"tests/boundary/providers/GdbSessionManagerCoverage.test.ts",
"tests/boundary/providers/GdbCommandQueue.test.ts",
"tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts",
"tests/boundary/providers/RizinCommandTimeout.test.ts",
"tests/boundary/providers/RizinTimeoutEvidence.test.ts",
"tests/boundary/providers/GdbSessionReviewRegressions.test.ts",
"tests/boundary/providers/gdbTestHelpers.ts",
"tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts",
"tests/boundary/mcp/gdbCancellationMcp.test.ts",
"tests/boundary/mcp/rizinDebuggerCancellationMcp.test.ts",
"tests/composition/reverseEngineeringAdmission.test.ts",
"tests/support/reverseEngineeringMcpHarness.ts",
"tests/support/reverseEngineeringCompositionEdgeCases.ts",
"tests/support/reverseEngineeringCompositionFixtures.ts",
"tests/support/reverseEngineeringService.ts",
"tests/support/ownedRizinCommandEvidenceTests.ts",
"tests/support/reverseDebuggerMcpTestHelpers.ts",
"tests/boundary/cli/gdbStartupCleanupCli.test.ts",
"vitest.reverse-tools.config.ts",
"vitest.reverse-tools-semantics.config.ts",
"stryker.config.mjs",
"stryker.semantics.config.mjs",
"tsconfig.reverse-tools-mutation.json",
"scripts/prepare-reverse-tools-mutation.mjs",
"scripts/lib/reverse-tools-mutation-targets.mjs",
])(
"selects the reverse-tool coverage and mutation gate for %s",
async (path) => {
const { directory, base } = await fixture();
const head = await change(directory, [path]);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
reverse_tools: true,
});
},
);
const reverseToolsVitestConfig = await readFile(
new URL("../../../vitest.reverse-tools.config.ts", import.meta.url),
"utf8",
);
const reverseToolsVitestInputs = [
...reverseToolsVitestConfig.matchAll(/"((?:\.\/)?(?:src|tests)\/[^"]+)"/gu),
].flatMap((match) =>
match[1] === undefined ? [] : [match[1].replace(/^\.\//u, "")],
);
const reverseToolsMutationConfig = JSON.parse(
await readFile(
new URL("../../../tsconfig.reverse-tools-mutation.json", import.meta.url),
"utf8",
),
) as { include: string[] };
const reverseToolsInputs = [
...new Set([
...reverseToolsVitestInputs,
...reverseToolsMutationConfig.include.map((path) =>
path.replace(/^\.\//u, ""),
),
]),
];
it.each(reverseToolsInputs)(
"selects the reverse-tool quality gate for configured input %s",
async (path) => {
const { directory, base } = await fixture();
const head = await change(directory, [path]);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
reverse_tools: true,
});
},
);
it("requires the reverse-tool gate when its scope is selected", async () => {
const workflow = parse(
await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
),
);
expect(workflow.jobs["reverse-tools-quality"].if).toBe(
"needs.changes.outputs.reverse_tools == 'true'",
);
expect(workflow.jobs.required.needs).toContain("reverse-tools-quality");
const { CI_FLAGS } = await loadScopes();
const outputs = {
...Object.fromEntries(CI_FLAGS.map((flag) => [flag, "false"])),
tier: "fast",
reverse_tools: "true",
};
const command = new URL("../../../scripts/ci/required.mjs", import.meta.url)
.pathname;
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "skipped" },
}),
},
}),
).rejects.toMatchObject({ code: 1 });
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "failure" },
}),
},
}),
).rejects.toMatchObject({ code: 1 });
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "success" },
}),
},
}),
).resolves.toMatchObject({
stdout: expect.stringContaining("Every selected CI lane passed"),
});
});
it.each([
"src/README.md",
"README.md.ts",
@@ -494,7 +634,7 @@ it.each([
{ code: true, package: true, evm: true, browser: true },
],
[
"package-lock.json",
"npm-shrinkwrap.json",
{ code: true, package: true, evm: true, browser: true },
],
[
@@ -0,0 +1,435 @@
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.each([
[{}, "diagnostic_source_blob_identity_unavailable"],
[
{ "src/example.ts": false },
"diagnostic_source_content_not_identical_at_main_and_tested_base",
],
] as const)(
"distinguishes unavailable blob identity from verified differences (%s)",
(blobs, reason) => {
expect(classifyFailure({ ...comparison(), blobs })).toEqual({
classification: "unknown",
reason,
});
},
);
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,407 @@
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
reportCiFailures,
createGitHubApi,
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",
);
if (count > 50)
expect(result.failures[0]!.reason).toBe(
"diagnostic_source_blob_identity_unavailable",
);
},
);
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);
},
);
it.each([0, 1, 2])(
"preserves every failed job when artifact analysis fails at position %s",
async (position) => {
const input = fixture([20], 1);
const jobs = [
{ name: "Python producer", conclusion: "failure" },
{ name: "Test shard (1)", conclusion: "timed_out" },
];
jobs.splice(position, 0, { name: "Static checks", conclusion: "failure" });
input.api.getJobs = async (_repository, id, attempt) =>
jobs.map((job) => ({
...job,
status: "completed",
run_id: Number(id),
run_attempt: attempt,
}));
input.api.getStaticEvidence = async (_repository, _run, job) => {
if (job.name === "Static checks")
throw new Error("static_artifact_unavailable");
return null;
};
const result = await report(input);
expect(result.counts.unknown).toBe(3);
expect(result.failures).toEqual(
jobs.map((job) => ({
runId: 100,
runAttempt: 1,
runHead: prSha,
event: "pull_request",
job: job.name,
conclusion: job.conclusion,
classification: "unknown",
reason:
job.name === "Static checks"
? "static_artifact_unavailable"
: "no_matching_verified_main_failure",
})),
);
},
);
it("keeps unavailable job inventories at run scope", async () => {
const input = fixture([], 1);
input.api.getJobs = async () => {
throw new Error("job_inventory_unavailable");
};
expect((await report(input)).failures).toEqual([
{
runId: 100,
runAttempt: 1,
classification: "unknown",
reason: "job_inventory_unavailable",
},
]);
});
it.each([
["request", "github_api_temporarily_unavailable"],
["budget", "github_api_request_budget_exhausted"],
["missing sha", "github_content_blob_identity_unavailable"],
["invalid sha", "github_content_blob_identity_unavailable"],
["directory", "github_content_blob_identity_unavailable"],
] as const)(
"retains unavailable blob evidence as a comparison error: %s",
async (failure, reason) => {
const input = fixture([20], 1);
const contentApi = createGitHubApi({
token: "fixture-token",
apiRequest: async () => {
if (failure === "request") throw new Error(reason);
if (failure === "missing sha") return { type: "file" };
if (failure === "invalid sha")
return { type: "file", sha: "not-a-sha" };
if (failure === "directory") return [];
return { type: "file", sha: "e".repeat(40) };
},
});
if (failure === "budget") {
for (let id = 1; id <= 250; id++) await contentApi.getRun(repository, id);
}
input.api.getBlobIdentity = contentApi.getBlobIdentity;
const result = await report(input);
expect(result.failures).toMatchObject([
{
job: "Static checks",
classification: "unknown",
reason: "no_matching_verified_main_failure",
candidateFailures: [{ runId: 20, runAttempt: 1, reason }],
},
]);
},
);
it.each([true, false])(
"reports blob equality only from verified file SHAs (equal: %s)",
async (equal) => {
const api = createGitHubApi({
token: "fixture-token",
apiRequest: async (_method, endpoint) => ({
type: "file",
sha:
equal || endpoint.includes(`ref=${mainSha}`)
? "e".repeat(40)
: "f".repeat(40),
}),
});
expect(
await api.getBlobIdentity(repository, mainSha, prSha, ["src/example.ts"]),
).toEqual({ "src/example.ts": equal });
},
);
@@ -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");
@@ -506,3 +511,44 @@ it("rejects incomplete or malformed classification even when available jobs succ
});
}
});
it("fails fast only for ordinary PR matrices and rejects partial portable feedback", async () => {
const { jobs } = await workflow();
expect(jobs["test-shard"]?.strategy).toMatchObject({
"fail-fast":
"${{ github.event_name == 'pull_request' && needs.changes.outputs.tier == 'fast' }}",
});
expect(jobs["package-e2e"]?.strategy).toMatchObject({ "fail-fast": false });
const flags = await scopeFlags();
for (const result of ["failure", "cancelled", "skipped", "missing"]) {
// Even an incorrectly successful report merge cannot hide matrix failure.
const needs: Record<string, unknown> = {
changes: {
result: "success",
outputs: {
...Object.fromEntries(flags.map((flag) => [flag, "false"])),
tier: "fast",
code: "true",
},
},
static: { result: "success" },
build: { result: "success" },
test: { result: "success" },
...(result === "missing" ? {} : { "test-shard": { result } }),
};
await expect(
executeWorkflowFixture(
process.execPath,
[
fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
),
],
{ env: { ...process.env, CI_JOBS: JSON.stringify(needs) } },
),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("test-shard"),
});
}
});
@@ -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"');
});
});
+176 -52
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";
@@ -16,6 +17,32 @@ import { workflowGit } from "../../support/workflowGit.js";
const execute = promisify(execFile);
const script = new URL("../../../scripts/ci/test-report.mjs", import.meta.url);
// Each report invocation owns its CI state and summary destination. Inherited
// workflow flags must not change fixture outcomes or append to the real job.
const executeTimingReport = async (
root: string,
environment: NodeJS.ProcessEnv = {},
) => {
const summary = join(root, "summary.md");
await writeFile(summary, "");
const output = await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
SHARD_RESULT: "success",
MERGE_RESULT: "success",
SOURCE_REQUIRED: "false",
SOURCE_RESULT: "",
CI_VERIFY_TEST_INVENTORY: "false",
CI_TEST_SELECTION: "",
...environment,
GITHUB_STEP_SUMMARY: summary,
},
});
return { ...output, summary: await readFile(summary, "utf8") };
};
const stepsSchema = z.array(
z.object({
name: z.string().optional(),
@@ -48,9 +75,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 +84,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 +94,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 +108,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 +133,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");
@@ -144,14 +251,8 @@ it("rejects successful shard reports with missing or duplicate portable files",
files: names.map((name) => ({ name, durationMs: 1 })),
}),
);
return execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
SHARD_RESULT: "success",
MERGE_RESULT: "success",
CI_VERIFY_TEST_INVENTORY: "true",
},
return executeTimingReport(root, {
CI_VERIFY_TEST_INVENTORY: "true",
});
};
await expect(
@@ -220,17 +321,18 @@ 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)], {
cwd: root,
env: {
...process.env,
GITHUB_STEP_SUMMARY: summary,
SHARD_RESULT: shards,
MERGE_RESULT: merge,
},
return executeTimingReport(root, {
SHARD_RESULT: shards,
SOURCE_REQUIRED: String(source !== undefined),
SOURCE_RESULT: source ?? "",
MERGE_RESULT: merge,
});
};
await run(report);
@@ -256,6 +358,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,10 +472,17 @@ 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),
);
await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" },
const partial = await executeTimingReport(root, {
SHARD_RESULT: "skipped",
SOURCE_REQUIRED: "true",
SOURCE_RESULT: "success",
});
expect(partial.summary).toContain("Partial test diagnostics");
expect(partial.summary).toContain("sample.test.js");
await expect(
readFile(join(root, ".cache/ci-test-history/test-results.json")),
).rejects.toMatchObject({ code: "ENOENT" });
await executeTimingReport(root);
expect(
parseTestDurations(
await readFile(
@@ -387,10 +514,7 @@ it("recovers complete module costs from real blob reports without executing test
files: [{ state: "failed" }],
});
// Even a caller accidentally marking the merge successful cannot publish this report.
await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" },
});
await executeTimingReport(root);
await expect(
readFile(join(root, ".cache/ci-test-history/test-results.json")),
).rejects.toMatchObject({ code: "ENOENT" });
@@ -420,21 +544,19 @@ 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",
MERGE_RESULT: "failure",
CI_VERIFY_TEST_INVENTORY: "true",
CI_TEST_SELECTION: JSON.stringify(
planTestSelection(["src/sqlite/Provider.ts"], "pull_request", "fast"),
),
GITHUB_SHA: "merge-sha",
CI_PR_HEAD_SHA: "pr-head-sha",
},
await executeTimingReport(root, {
SHARD_RESULT: "failure",
SOURCE_REQUIRED: "true",
SOURCE_RESULT: source,
MERGE_RESULT: "failure",
CI_VERIFY_TEST_INVENTORY: "true",
CI_TEST_SELECTION: JSON.stringify(
planTestSelection(["src/sqlite/Provider.ts"], "pull_request", "fast"),
),
GITHUB_SHA: "merge-sha",
CI_PR_HEAD_SHA: "pr-head-sha",
});
return JSON.parse(
await readFile(
@@ -458,6 +580,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();
},
);
@@ -23,7 +23,7 @@ const fixture = async (
const root = await createTestTempDirectory("rea-deps-");
await mkdir(join(root, "node_modules"));
await writeFile(
join(root, "package-lock.json"),
join(root, "npm-shrinkwrap.json"),
JSON.stringify({
packages: {
"": {
@@ -103,7 +103,7 @@ describe("dependency install freshness", () => {
expect(seeded.status, `${seeded.stdout}${seeded.stderr}`).toBe(0);
const rootLock = asRecord(
JSON.parse(await readFile(join(root, "package-lock.json"), "utf8")),
JSON.parse(await readFile(join(root, "npm-shrinkwrap.json"), "utf8")),
);
const lockPackages = asRecord(rootLock?.packages);
const rootPackage = asRecord(lockPackages?.[""]);
@@ -191,7 +191,7 @@ const createBuildCacheFixture = async (): Promise<string> => {
throw new Error("package is missing its cached build command");
const paths = [
".nvmrc",
"package-lock.json",
"npm-shrinkwrap.json",
"turbo.json",
"tsconfig.json",
"tsconfig.build.json",
@@ -23,10 +23,27 @@ it("threads the selected host and environment into system diagnostics", async ()
environment,
execFileOutput: async (command, arguments_, options) => {
calls.push({ command, arguments: arguments_, environment: options?.env });
if (command === "sw_vers") return { stdout: "15.0\n", stderr: "" };
if (command === "ldd") return { stdout: "linux-vdso.so.1", stderr: "" };
if (command === "sw_vers")
return {
stdout: "15.0\n",
stderr: "",
stdoutBytes: 5,
stderrBytes: 0,
};
if (command === "ldd")
return {
stdout: "linux-vdso.so.1",
stderr: "",
stdoutBytes: Buffer.byteLength("linux-vdso.so.1"),
stderrBytes: 0,
};
if (command === "which")
return { stdout: "/selected/bin/rea\n", stderr: "" };
return {
stdout: "/selected/bin/rea\n",
stderr: "",
stdoutBytes: 18,
stderrBytes: 0,
};
throw new Error(`Unexpected diagnostic command: ${command}`);
},
});
@@ -88,7 +105,12 @@ it.each([
environment: { HOME: join(root, "home") },
execFileOutput: async (_command, arguments_) => {
calls.push(arguments_);
return { stdout: `${caskroom}\n`, stderr: "" };
return {
stdout: `${caskroom}\n`,
stderr: "",
stdoutBytes: Buffer.byteLength(`${caskroom}\n`),
stderrBytes: 0,
};
},
});
@@ -111,7 +133,12 @@ it("reports no Homebrew Hopper when the cask has no receipt", async () => {
environment: { HOME: caskroom },
execFileOutput: async (_command, arguments_) => {
calls.push(arguments_);
return { stdout: `${caskroom}\n`, stderr: "" };
return {
stdout: `${caskroom}\n`,
stderr: "",
stdoutBytes: Buffer.byteLength(`${caskroom}\n`),
stderrBytes: 0,
};
},
});
@@ -55,6 +55,8 @@ const host: GhidraInstallationHost = {
readText: () => "application.version=12.1.3\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
osArch: "amd64",
osName: "Linux",
version: "21.0.12",
major: 21,
home: "/jdk-21",
@@ -20,7 +20,7 @@ import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGr
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import {
ZIP_PACKAGE_FORMATS,
ZIP_NON_ENTRY_TAIL_LIMITATION,
ZIP_NON_ENTRY_LIMITATION,
} from "../../../../src/domain/zipPackageFormat.js";
const { runProviderAnalysis } = createDirectAnalysis({});
@@ -214,7 +214,7 @@ describe("HarmonyOS packaging boundaries", () => {
});
describe("HarmonyOS inventory coverage", () => {
it("keeps a case-colliding inventory partial in the application projection", async () => {
it("retains complete traversal and case-collision limits in the application projection", async () => {
const path = await writeApplicationZip(
"rea-harmony-case-collision-",
"Fixture.hap",
@@ -225,7 +225,7 @@ describe("HarmonyOS inventory coverage", () => {
);
const inventory = await inventoryApplicationPackage(path);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const projection = requireDeterministicProjection(
@@ -234,11 +234,11 @@ describe("HarmonyOS inventory coverage", () => {
harmonyApplicationProjectionResultSchema,
);
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
});
@@ -264,7 +264,7 @@ describe("HarmonyOS inventory coverage", () => {
artifact_kind: "container",
artifact_format: format,
});
expect(inventory.limitations).toContain(ZIP_NON_ENTRY_TAIL_LIMITATION);
expect(inventory.limitations).toContain(ZIP_NON_ENTRY_LIMITATION);
},
);
@@ -114,18 +114,34 @@ describe("Hermes YAML shape diagnostics", () => {
"!!omap [{rea: {command: rea, args: [mcp]}}]",
"!!timestamp 2001-12-15",
"!!binary cmVh",
].flatMap((value) => [
{
original: `${value}\n`,
problem: "The configuration root must be an object",
},
{
original: `mcp_servers: ${value}\n`,
problem: '"mcp_servers" must be an object',
},
]),
]
.flatMap((value) => [
{
original: `${value}\n`,
problem: "The configuration root must be an object",
},
{
original: `mcp_servers: ${value}\n`,
problem: '"mcp_servers" must be an object',
},
])
.concat(
// An explicit null root is a value, not an empty file.
[
"null\n",
"~\n",
"# Hermes configuration\nnull\n",
"--- ~\n",
"--- !!null\n",
'!!null ""\n',
"--- &empty\n",
].map((original) => ({
original,
problem: "The configuration root must be an object",
})),
),
)(
"blocks setup and uninstall before changes for tagged non-record YAML: $original",
"blocks setup and uninstall before changes for tagged or null non-record YAML: $original",
async ({ original, problem }) => {
const { home, client } = await hermesClient();
const cursor = join(home, ".cursor", "mcp.json");
@@ -281,7 +297,36 @@ mcp_servers:
});
});
it.each(["", "\n"])(
// Comments and a bare document marker parse to a null document, like an
// empty file, and are kept ahead of the new registration.
});
describe("Hermes YAML empty configurations", () => {
it("rejects multiple YAML documents before treating an empty first root as absent", async () => {
const { client } = await hermesClient();
const original =
"---\n---\nmcp_servers:\n rea:\n command: rea\n args: [mcp]\n";
await writeFile(client.configPath, original);
expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
{ status: "invalid" },
);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "failed",
reason: "readback",
});
expect(await readFile(client.configPath, "utf8")).toBe(original);
await expect(
readFile(`${client.configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it.each([
"",
"\n",
"# Hermes configuration\n",
"---\n",
"---\n# Hermes configuration\n",
])(
"configures an empty config.yaml %j as a new document",
async (original) => {
const { home, client } = await hermesClient();
@@ -289,7 +334,10 @@ mcp_servers:
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual({
const text = await readFile(client.configPath, "utf8");
const kept = original.trimEnd();
expect(text.slice(0, kept.length)).toBe(kept);
expect(parseYaml(text)).toEqual({
mcp_servers: {
rea: { command: command[0], args: command.slice(1), enabled: true },
},
@@ -67,6 +67,11 @@ describe("static Electron application analysis", () => {
});
});
it(
"keeps Electron runtime entrypoints on their declared filenames",
exactRuntimeEntrypointFixture,
);
it("keeps computed identifier member keys unknown", async () => {
const root = await computedMemberFixtureDirectory();
@@ -153,9 +158,210 @@ describe("static Electron application analysis", () => {
});
});
const exactRuntimeEntrypointFixture = async (): Promise<void> => {
const root = await createTestTempDirectory("rea-electron-exact-entrypoints-");
await mkdir(join(root, "renderer/page"), { recursive: true });
await Promise.all([
writeFile(
join(root, "main.cjs"),
String.raw`
const { BrowserWindow, utilityProcess } = require("electron");
const path = require("node:path");
new BrowserWindow({ webPreferences: { preload: "./entry" } });
new BrowserWindow().loadURL("file:///renderer/index.html");
new BrowserWindow().loadURL("renderer/bare.html");
new BrowserWindow().loadURL("#home");
new BrowserWindow().loadURL("");
new BrowserWindow().loadURL("./renderer/other.html?theme=dark#home");
new BrowserWindow().loadURL("./renderer/missing.html");
new BrowserWindow().loadFile("./renderer/page");
new BrowserWindow({ webPreferences: { preload: path.join(__dirname, "preload") } });
new BrowserWindow({ webPreferences: { preload: "./explicit-preload.js" } });
utilityProcess.fork("./worker");
utilityProcess.fork("./worker#v1.js");
utilityProcess.fork("./service.js");
`,
),
writeFile(join(root, "entry.html"), "<title>sibling</title>"),
writeFile(join(root, "preload.html"), "<title>sibling</title>"),
writeFile(join(root, "worker.js"), "module.exports = {};"),
writeFile(join(root, "renderer/index.html"), "<title>renderer</title>"),
writeFile(
join(root, "renderer/bare.html"),
"<title>bare renderer URL</title>",
),
writeFile(join(root, "renderer/other.html"), "<title>other</title>"),
writeFile(join(root, "renderer/missing.html.js"), "module.exports = {};"),
writeFile(
join(root, "renderer/page/index.html"),
"<title>directory</title>",
),
writeFile(join(root, "explicit-preload.js"), "module.exports = {};"),
writeFile(join(root, "service.js"), "module.exports = {};"),
]);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const graph = parseJavaScriptApplicationGraph(result.graph);
expectSuffixOnlyRenderersUnresolved(graph);
expectExactRendererPaths(graph);
const roles = graph.nodes.filter(({ kind }) => kind === "electron-preload");
const roleByDeclaration = new Map(
roles.map((role) => [role.observations[0]?.properties.declared_path, role]),
);
expect(result.electron_summary.resolved_utility_entrypoints).toBe(2);
for (const [declaredPath, candidatePath] of [
["./entry", "entry"],
["preload", "preload"],
]) {
const role = roleByDeclaration.get(declaredPath);
expect(role?.observations[0]?.properties).toMatchObject({
declared_path: declaredPath,
resolved_path: null,
resolution_status: "not-found",
candidate_path: candidatePath,
limitations: [
expect.stringContaining(
"extension and directory fallback were not attempted",
),
],
});
expect(
graph.edges.some(
(edge) =>
edge.source_node_id === role?.node_id && edge.relation === "maps_to",
),
).toBe(false);
}
expect(
roleByDeclaration.get("./explicit-preload.js")?.observations[0]?.properties,
).toMatchObject({
resolved_path: "explicit-preload.js",
resolution_status: "resolved",
});
const utilityLaunches = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "map-utility-process-launch",
);
const resolvedWorker = utilityLaunches.find(
(edge) => edge.properties.declared_path === "./worker",
);
expect(resolvedWorker?.evidence).toMatchObject({
authority: "static-relationship-inference",
state: "inferred",
limitations: expect.arrayContaining([
"Static syntax does not prove that this relationship executes at runtime.",
]),
});
expect(utilityLaunches).toEqual(
expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
declared_path: "./worker",
resolved_path: "worker.js",
resolution_status: "resolved",
}),
}),
expect.objectContaining({
properties: expect.objectContaining({
declared_path: "./worker#v1.js",
resolved_path: null,
resolution_status: "not-found",
}),
}),
expect.objectContaining({
properties: expect.objectContaining({
declared_path: "./service.js",
resolved_path: "service.js",
resolution_status: "resolved",
}),
}),
]),
);
expect(
graph.edges.some(
(edge) =>
edge.evidence.extractor.operation ===
"resolve-utility-process-entrypoint" &&
edge.properties.resolved_path === "worker.html",
),
).toBe(false);
};
type Reconstruction = Awaited<ReturnType<typeof reconstructJavaScriptArtifact>>;
type ApplicationGraph = ReturnType<typeof parseJavaScriptApplicationGraph>;
const expectSuffixOnlyRenderersUnresolved = (graph: ApplicationGraph): void => {
const renderers = new Map(
graph.nodes
.filter(({ kind }) => kind === "electron-renderer")
.map((renderer) => [
renderer.observations[0]?.properties.declared_path,
renderer,
]),
);
expect(
renderers.get("file:///renderer/index.html")?.observations[0]?.properties,
).toMatchObject({
resolved_path: "renderer/index.html",
resolution_status: "resolved",
});
for (const declaredPath of [
"./renderer/other.html?theme=dark#home",
"renderer/bare.html",
"./renderer/missing.html",
"#home",
"",
]) {
const renderer = renderers.get(declaredPath);
expect(renderer?.observations[0]?.properties).toMatchObject({
resolved_path: null,
resolution_status: "unavailable",
});
expect(renderer?.observations[0]?.properties.limitations).toEqual(
expect.arrayContaining([
expect.stringContaining("requires a URL protocol"),
]),
);
expect(
graph.edges.some(
(edge) =>
edge.source_node_id === renderer?.node_id &&
edge.relation === "maps_to",
),
).toBe(false);
}
};
const expectExactRendererPaths = (graph: ApplicationGraph): void => {
const renderers = new Map(
graph.nodes
.filter(({ kind }) => kind === "electron-renderer")
.map((renderer) => [
renderer.observations[0]?.properties.declared_path,
renderer,
]),
);
for (const [declaredPath, candidatePath] of [
["./renderer/page", "renderer/page"],
]) {
const renderer = renderers.get(declaredPath);
expect(renderer?.observations[0]?.properties).toMatchObject({
resolved_path: null,
resolution_status: "not-found",
candidate_path: candidatePath,
});
expect(
graph.edges.some(
(edge) =>
edge.source_node_id === renderer?.node_id &&
edge.relation === "maps_to",
),
).toBe(false);
}
};
const expectElectronSummary = (result: Reconstruction): void => {
expect(result.electron_summary).toMatchObject({
browser_windows: 3,
@@ -1,6 +1,6 @@
import { writeFile } from "node:fs/promises";
import { mkdir, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { join, relative, sep } from "node:path";
import { dirname, join, relative, sep } from "node:path";
import { describe, expect, it } from "vitest";
@@ -133,3 +133,66 @@ describe("literal CommonJS paths in application graphs", () => {
},
);
});
describe("literal CommonJS percent bytes in application graphs", () => {
it("agrees with Node for requests whose literal names contain %2e or %2F", async () => {
const root = await createTestTempDirectory("rea-literal-percent-require-");
const files = {
"app/lit%2eb.js": "module.exports = 'lit%2eb.js';",
"app/x%2Fy.js": "module.exports = 'x%2Fy.js';",
"app/sub/%2e%2e/x.js": "module.exports = 'sub/%2e%2e/x.js';",
"app/x.js": "module.exports = 'decoy for a decoded parent';",
"app/pkg/package.json": JSON.stringify({ main: "lit%2eb" }),
"app/pkg/lit%2eb.js": "module.exports = 'pkg/lit%2eb.js';",
"app/node_modules/dep/package.json": JSON.stringify({ name: "dep" }),
"app/node_modules/dep/lit%2eb.js": "module.exports = 'dep/lit%2eb.js';",
"escape.js": "module.exports = 'decoy outside the request directory';",
};
const specifiers = [
"./lit%2eb",
"./x%2Fy",
"./sub/%2e%2e/x",
"./pkg",
"dep/lit%2eb",
];
// CommonJS reads %2e%2e as a directory name, never as a parent segment.
const literalSegment = "./%2e%2e/escape";
for (const [path, text] of Object.entries(files)) {
await mkdir(dirname(join(root, path)), { recursive: true });
await writeFile(join(root, path), text);
}
const main = join(root, "app", "main.cjs");
await writeFile(
main,
[...specifiers, literalSegment]
.map((specifier) => `require(${JSON.stringify(specifier)});`)
.join("\n"),
);
const nodeRequire = createRequire(main);
const nodePath = (specifier: string) =>
relative(root, nodeRequire.resolve(specifier)).split(sep).join("/");
expect(() => nodeRequire.resolve(literalSegment)).toThrow(
/Cannot find module/u,
);
const { graph } = await analyze(root);
const requests = (specifier: string) =>
graph.edges.filter(
(edge) =>
edge.relation === "imports" &&
edge.properties.specifier === specifier,
);
for (const specifier of specifiers) {
const edges = requests(specifier);
expect(edges.length, specifier).toBeGreaterThan(0);
for (const edge of edges)
expect(edge.properties.resolved_path, specifier).toBe(
nodePath(specifier),
);
}
const unresolved = requests(literalSegment);
expect(unresolved.length).toBeGreaterThan(0);
for (const edge of unresolved)
expect(edge.properties.resolved_path).toBeNull();
});
});
@@ -19,6 +19,9 @@ import {
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_OPERATIONS,
} from "../../../src/ghidra/GhidraProviderCapabilities.js";
import { OBJDUMP_PROVIDER_IDENTITY } from "../../../src/objdump/ObjdumpCommand.js";
import { RIZIN_PROVIDER_IDENTITY } from "../../../src/rizin/RizinCommand.js";
import { GDB_PROVIDER_IDENTITY } from "../../../src/gdb/GdbSessionManager.js";
import {
documentationFactIssues,
skillReferenceIssues,
@@ -118,6 +121,16 @@ describe("canonical product catalog", () => {
expect(catalog.setup_clients.map(({ id }) => id)).toEqual(
SUPPORTED_CLIENT_DEFINITIONS.map(({ name }) => name),
);
expect(catalog.cli.commands).toHaveLength(CLI_COMMAND_NAMES.length);
expect(catalog.providers.map(({ id }) => id)).toEqual(
expect.arrayContaining(
[
OBJDUMP_PROVIDER_IDENTITY,
RIZIN_PROVIDER_IDENTITY,
GDB_PROVIDER_IDENTITY,
].map(({ id }) => id),
),
);
expect(
catalog.providers.find(({ id }) => id === HOPPER_PROVIDER_IDENTITY.id)
?.capabilities,
@@ -63,7 +63,7 @@ async function metadata(
},
".mcp.json": codexServerConfig(version),
"package.json": { name: "rea-agents", version },
"package-lock.json": { version, packages: { "": { version } } },
"npm-shrinkwrap.json": { version, packages: { "": { version } } },
".release-please-manifest.json": { ".": version },
"server.json": {
version,
@@ -568,7 +568,7 @@ it("validates candidate options before inspecting the working directory", async
});
it.each([
"package-lock.json",
"npm-shrinkwrap.json",
"server.json",
"src/generatedPackageMetadata.ts",
])("rejects inconsistent version metadata in %s", async (path) => {
@@ -579,7 +579,7 @@ it.each([
path.endsWith(".ts")
? 'export const METADATA = {\n version: "5.1.0",\n};\n'
: JSON.stringify(
path === "package-lock.json"
path === "npm-shrinkwrap.json"
? { version: "6.0.0", packages: { "": { version: "5.1.0" } } }
: path === "server.json"
? {
@@ -0,0 +1,78 @@
import { execFileSync } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const root = fileURLToPath(new URL("../../../", import.meta.url));
const runNode = (source: string, ...arguments_: string[]): string =>
execFileSync(
process.execPath,
["--input-type=module", "-e", source, ...arguments_],
{ cwd: root, encoding: "utf8" },
);
describe("reverse-tools mutation configuration", () => {
it("loads nonempty targets from both actual Stryker configs", () => {
const result = runNode(
`const [mainUrl, semanticsUrl] = process.argv.slice(1);
const main = await import(mainUrl);
const semantics = await import(semanticsUrl);
process.stdout.write(JSON.stringify({
main: main.default.mutate.length,
semantics: semantics.default.mutate.length,
}));`,
pathToFileURL(join(root, "stryker.config.mjs")).href,
pathToFileURL(join(root, "stryker.semantics.config.mjs")).href,
);
const targets = JSON.parse(result) as {
main: number;
semantics: number;
};
expect(targets.main).toBeGreaterThan(0);
expect(targets.semantics).toBeGreaterThan(0);
});
it("fails closed when an owned mutation method is missing", async () => {
const directory = await createTestTempDirectory("rea-mutation-selector-");
const source = join(directory, "source.ts");
await writeFile(source, "class Present { run() {} }\n");
const result = runNode(
`import { mutationRanges } from "./scripts/lib/reverse-tools-mutation-targets.mjs";
const [source] = process.argv.slice(1);
try {
mutationRanges(source, [{ kind: "method", owner: "Missing", name: "run" }]);
throw new Error("missing owner unexpectedly selected");
} catch (error) {
if (!(error instanceof Error) || !error.message.includes("found 0")) throw error;
process.stdout.write(error.message);
}`,
source,
);
expect(result).toMatch(/found 0/u);
});
it("fails closed when an owned mutation method is ambiguous", async () => {
const directory = await createTestTempDirectory("rea-mutation-selector-");
const source = join(directory, "source.ts");
await writeFile(source, "class Owner { run() {} run(value: string) {} }\n");
const result = runNode(
`import { mutationRanges } from "./scripts/lib/reverse-tools-mutation-targets.mjs";
const [source] = process.argv.slice(1);
try {
mutationRanges(source, [{ kind: "method", owner: "Owner", name: "run" }]);
throw new Error("ambiguous target unexpectedly selected");
} catch (error) {
if (!(error instanceof Error) || !error.message.includes("found 2")) throw error;
process.stdout.write(error.message);
}`,
source,
);
expect(result).toMatch(/found 2/u);
});
});
@@ -49,7 +49,7 @@ const lintDiagnostics = async (root: string) =>
),
).diagnostics;
it("includes every actually linted file in both cached lint task inputs", () => {
it("covers the lint inventory and root tool configs in resolved cache inputs", () => {
const scan = spawnSync(
process.execPath,
[join(repository, "node_modules/oxlint/bin/oxlint"), "--debug=files"],
@@ -69,6 +69,7 @@ it("includes every actually linted file in both cached lint task inputs", () =>
"run",
"lint",
"lint:built",
"knip",
"--dry=json",
],
{
@@ -99,6 +100,14 @@ it("includes every actually linted file in both cached lint task inputs", () =>
files.filter((file) => !Object.hasOwn(task.inputs, file)),
`${task.task} omits actual checker inputs`,
).toEqual([]);
const knip = tasks.find(({ task }) => task === "knip");
expect(knip).toBeDefined();
expect(
files.filter(
(file) => !file.includes("/") && !Object.hasOwn(knip!.inputs, file),
),
"knip omits root tool configuration inputs",
).toEqual([]);
});
it("summarizes warnings without losing their complete diagnostic records", async () => {
@@ -0,0 +1,325 @@
import { spawnSync } from "node:child_process";
import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { workflowGit } from "../../support/workflowGit.js";
const repository = fileURLToPath(new URL("../../../", import.meta.url));
const turbo = join(repository, "node_modules/turbo/bin/turbo");
const reportScript = join(repository, "scripts/ci/static-check-report.mjs");
const rootConfigSchema = z.object({
globalDependencies: z.array(z.string()).optional(),
globalPassThroughEnv: z.array(z.string()).optional(),
tasks: z.record(z.string(), z.record(z.string(), z.unknown())),
});
const dryRunSchema = z.object({
tasks: z.array(z.object({ taskId: z.string(), hash: z.string() })),
});
const execute = (command: string, args: string[], cwd: string) =>
spawnSync(process.execPath, [command, ...args], {
cwd,
encoding: "utf8",
timeout: 30_000,
maxBuffer: 16 * 1024 * 1024,
env: process.env,
});
const readRootConfig = async () =>
rootConfigSchema.parse(
JSON.parse(await readFile(join(repository, "turbo.json"), "utf8")),
);
const writeTaskFixture = async (
root: string,
taskNames: string[],
scripts: Record<string, string>,
) => {
const config = await readRootConfig();
const tasks = Object.fromEntries(
taskNames.map((name) => {
const task = config.tasks[name];
if (task === undefined) throw new Error(`Missing Turbo task ${name}`);
// These tests measure a task's own inputs. Drop dependency edges so the
// unrelated compile task cannot add fixture-specific inputs or outputs.
const { dependsOn: _dependsOn, ...definition } = task;
return [name, definition];
}),
);
await writeFile(
join(root, "turbo.json"),
JSON.stringify(
{
...(config.globalDependencies === undefined
? {}
: { globalDependencies: config.globalDependencies }),
...(config.globalPassThroughEnv === undefined
? {}
: { globalPassThroughEnv: config.globalPassThroughEnv }),
tasks,
},
null,
2,
),
);
await writeFile(
join(root, "package.json"),
JSON.stringify({
name: "rea-static-task-cache-fixture",
version: "1.0.0",
private: true,
packageManager: "npm@11.16.0",
scripts,
}),
);
await writeFile(
join(root, "npm-shrinkwrap.json"),
JSON.stringify({
name: "rea-static-task-cache-fixture",
version: "1.0.0",
lockfileVersion: 3,
packages: {
"": { name: "rea-static-task-cache-fixture", version: "1.0.0" },
},
}),
);
};
const runTurbo = (
root: string,
task: string,
cacheDirectory: string,
dryRun = false,
) =>
execute(
turbo,
[
"run",
task,
...(dryRun ? ["--dry=json"] : ["--output-logs=errors-only"]),
"--cache=local:rw,remote:r",
"--cache-dir",
cacheDirectory,
],
root,
);
const taskHash = (root: string, task: string, cacheDirectory: string) => {
const result = runTurbo(root, task, cacheDirectory, true);
expect(result.error).toBeUndefined();
expect(result.status, result.stderr).toBe(0);
const { tasks } = dryRunSchema.parse(JSON.parse(result.stdout));
const entry = tasks.find(({ taskId }) => taskId === task);
if (entry === undefined) throw new Error(`Turbo omitted task ${task}`);
return entry.hash;
};
it("restores a real lint report across cold, warm, and fresh consumer checkouts", async () => {
const producer = await createTestTempDirectory("rea-static-cache-producer-");
const consumer = await createTestTempDirectory("rea-static-cache-consumer-");
const cache = await createTestTempDirectory("rea-static-cache-store-");
const script = "node scripts/ci/static-check-report.mjs lint";
for (const root of [producer, consumer]) {
await mkdir(join(root, "scripts/ci"), { recursive: true });
await mkdir(join(root, "src"), { recursive: true });
await symlink(
join(repository, "node_modules"),
join(root, "node_modules"),
"junction",
);
await writeTaskFixture(root, ["lint"], { lint: script });
await writeFile(
join(root, ".nvmrc"),
await readFile(join(repository, ".nvmrc")),
);
await writeFile(join(root, ".gitignore"), ".cache/\nnode_modules/\n");
await writeFile(
join(root, ".oxlintrc.json"),
JSON.stringify({ rules: { "no-debugger": "error" } }),
);
await writeFile(join(root, "src/check.js"), "export const ready = true;\n");
await writeFile(
join(root, "scripts/ci/static-check-report.mjs"),
await readFile(reportScript, "utf8"),
);
await workflowGit(root, ["init", "--initial-branch=main"]);
await workflowGit(root, ["add", "."]);
await workflowGit(root, ["commit", "-m", "test: seed static task cache"]);
}
const cold = runTurbo(producer, "lint", cache);
expect(cold.error).toBeUndefined();
expect(cold.status, cold.stderr).toBe(0);
expect(cold.stdout).toMatch(/Cached:\s+0 cached/u);
const report = join(producer, ".cache/static-checks/oxlint.json");
const cleanReport = await readFile(report, "utf8");
await rm(join(producer, ".cache"), { recursive: true });
const warm = runTurbo(producer, "lint", cache);
expect(warm.error).toBeUndefined();
expect(warm.status, warm.stderr).toBe(0);
expect(warm.stdout).toMatch(/Cached:\s+1 cached/u);
expect(await readFile(report, "utf8")).toBe(cleanReport);
const freshConsumer = runTurbo(consumer, "lint", cache);
expect(freshConsumer.error).toBeUndefined();
expect(freshConsumer.status, freshConsumer.stderr).toBe(0);
expect(freshConsumer.stdout).toMatch(/Cached:\s+1 cached/u);
expect(
await readFile(join(consumer, ".cache/static-checks/oxlint.json"), "utf8"),
).toBe(cleanReport);
await writeFile(join(consumer, "src/check.js"), "debugger;\n");
const invalid = runTurbo(consumer, "lint", cache);
expect(invalid.error).toBeUndefined();
expect(invalid.status).not.toBe(0);
expect(invalid.stdout).toMatch(/Cached:\s+0 cached/u);
const { diagnostics } = z
.object({
diagnostics: z.array(
z.object({ code: z.string().optional(), severity: z.string() }),
),
})
.parse(
JSON.parse(
await readFile(
join(consumer, ".cache/static-checks/oxlint.json"),
"utf8",
),
),
);
expect(diagnostics).toContainEqual(
expect.objectContaining({
code: "eslint(no-debugger)",
severity: "error",
}),
);
});
it("invalidates checker task hashes for Node, ignore, and VitePress config changes", async () => {
const root = await createTestTempDirectory("rea-static-cache-inputs-");
const cache = await createTestTempDirectory("rea-static-cache-hashes-");
await mkdir(join(root, "docs/.vitepress"), { recursive: true });
await mkdir(join(root, "src"), { recursive: true });
await mkdir(join(root, "tests"), { recursive: true });
await writeTaskFixture(
root,
["jscpd", "knip", "metadata:check", "scan:todos"],
// This fixture probes only Turbo's real task hash; the checker commands
// are intentionally inert so the hash test cannot invoke large suites.
{
jscpd: 'node -e "process.exit(0)"',
knip: 'node -e "process.exit(0)"',
"metadata:check": 'node -e "process.exit(0)"',
"scan:todos": 'node -e "process.exit(0)"',
},
);
await writeFile(join(root, ".nvmrc"), "24.18.0\n");
await writeFile(join(root, ".npmrc"), "engine-strict=true\n");
await writeFile(join(root, ".gitignore"), ".cache/\n");
await writeFile(join(root, ".jscpd.json"), "{}\n");
await writeFile(join(root, "docs/.vitepress/config.ts"), "export {};\n");
await writeFile(
join(root, "vitest.config.ts"),
'import { CiTestSequencer } from "./tests/ciTestSequencer.js";\nexport const sequencer = CiTestSequencer;\n',
);
await writeFile(join(root, "src/input.ts"), "export {};\n");
await writeFile(join(root, "tests/input.ts"), "export {};\n");
const initial = new Map<string, string>();
for (const task of ["jscpd", "knip", "metadata:check", "scan:todos"])
initial.set(task, taskHash(root, task, cache));
await writeFile(join(root, ".nvmrc"), "24.19.0\n");
for (const task of ["jscpd", "metadata:check", "scan:todos"])
expect(
taskHash(root, task, cache),
`${task} must hash the Node pin`,
).not.toBe(initial.get(task));
await writeFile(join(root, ".nvmrc"), "24.18.0\n");
await writeFile(join(root, ".npmrc"), "engine-strict=false\n");
for (const task of ["jscpd", "knip", "metadata:check", "scan:todos"])
expect(
taskHash(root, task, cache),
`${task} must hash npm settings`,
).not.toBe(initial.get(task));
await writeFile(join(root, ".npmrc"), "engine-strict=true\n");
for (const task of ["jscpd", "metadata:check", "scan:todos"])
expect(taskHash(root, task, cache), `${task} restores after Node pin`).toBe(
initial.get(task),
);
await writeFile(join(root, ".gitignore"), ".cache/\ncoverage/\n");
for (const task of ["jscpd", "knip"])
expect(taskHash(root, task, cache), `${task} must hash gitignore`).not.toBe(
initial.get(task),
);
await writeFile(join(root, ".gitignore"), ".cache/\n");
for (const task of ["jscpd", "knip"])
expect(
taskHash(root, task, cache),
`${task} restores after gitignore`,
).toBe(initial.get(task));
await writeFile(
join(root, "docs/.vitepress/config.ts"),
"export const configRevision = 2;\n",
);
expect(
taskHash(root, "knip", cache),
"knip must hash its configured VitePress entry",
).not.toBe(initial.get("knip"));
await writeFile(join(root, "docs/.vitepress/config.ts"), "export {};\n");
await writeFile(join(root, "vitest.config.ts"), "export {};\n");
expect(
taskHash(root, "knip", cache),
"knip must hash vitest.config.ts so unused sequencer imports invalidate the cache",
).not.toBe(initial.get("knip"));
for (const task of ["jscpd", "metadata:check", "scan:todos"])
expect(
taskHash(root, task, cache),
`${task} must ignore vitest.config.ts`,
).toBe(initial.get(task));
});
it.each(["compile", "typecheck"])(
"invalidates %s for JavaScript owners, declarations, and the authoritative lock",
async (task) => {
const root = await createTestTempDirectory("rea-mjs-cache-inputs-");
const cache = await createTestTempDirectory("rea-mjs-cache-store-");
await mkdir(join(root, "src/application"), { recursive: true });
await writeTaskFixture(root, [task], {
[task]: 'node -e "process.exit(0)"',
});
const owner = join(root, "src/application/PackageRunnerCommand.mjs");
const declaration = join(
root,
"src/application/PackageRunnerCommand.d.mts",
);
await writeFile(owner, "export const command = 1;\n");
await writeFile(declaration, "export declare const command: number;\n");
await workflowGit(root, ["init", "--quiet"]);
await workflowGit(root, ["add", "."]);
const initial = taskHash(root, task, cache);
expect(taskHash(root, task, cache)).toBe(initial);
await writeFile(owner, "export const command = 2;\n");
expect(taskHash(root, task, cache)).not.toBe(initial);
await writeFile(owner, "export const command = 1;\n");
await writeFile(declaration, "export declare const command: string;\n");
expect(taskHash(root, task, cache)).not.toBe(initial);
await writeFile(declaration, "export declare const command: number;\n");
expect(taskHash(root, task, cache)).toBe(initial);
const lockPath = join(root, "npm-shrinkwrap.json");
const lock = JSON.parse(await readFile(lockPath, "utf8"));
lock.packages["node_modules/fixture"] = { version: "1.0.0" };
await writeFile(lockPath, JSON.stringify(lock));
expect(taskHash(root, task, cache)).not.toBe(initial);
},
);
@@ -28,7 +28,7 @@ test("generates locked inventory and rejects stale notice metadata or preserved
optional: true,
};
await writeFile(
resolve(root, "package-lock.json"),
resolve(root, "npm-shrinkwrap.json"),
JSON.stringify({
packages: {
"": { name: "fixture", version: "1.0.0" },