chore: reconcile captured main with PR #2801

This commit is contained in:
morluto
2026-10-13 21:43:32 +08:00
808 changed files with 74776 additions and 5305 deletions
@@ -29,6 +29,14 @@ const createModuleLookupFixture = async () => {
'import "ancestor-empty";',
'import "ancestor-blocked";',
'import "ancestor-sub/parser";',
'import "./.hidden.js";',
'import "./..pkg.js";',
'import "./exact.js/.";',
'import "./exact.js/child/..";',
'import ".hidden.js";',
'import "..pkg.js";',
'import ".";',
'import "..";',
"void fallback;",
].join("\n"),
"esm/extensionless.js": "module.exports = 1;",
@@ -36,6 +44,10 @@ const createModuleLookupFixture = async () => {
"esm/explicit.js.js": "module.exports = 3;",
"esm/exact.js": "module.exports = 4;",
"esm/actual.cjs": "module.exports = 5;",
"esm/.hidden.js": "module.exports = 'local hidden';",
"esm/..pkg.js": "module.exports = 'local dot package';",
"node_modules/.hidden.js/index.js": "module.exports = 'hidden package';",
"node_modules/..pkg.js/index.js": "module.exports = 'dot package';",
"esm/typed.mts": 'import value from "./typed-dep.js"; void value;',
"esm/typed-dep.ts": "export default 42;",
"cjs/entry.cjs": [
@@ -54,8 +66,15 @@ const createModuleLookupFixture = async () => {
'require("ancestor-empty");',
'require("ancestor-blocked");',
'require("ancestor-sub/parser");',
'require(".hidden.js");',
'require("./.hidden.js");',
'require(".");',
'require("..");',
].join("\n"),
"cjs/directory/index.cjs": "module.exports = 6;",
"cjs/index.js": "module.exports = 'current directory';",
"index.js": "module.exports = 'parent directory';",
"cjs/.hidden.js": "module.exports = 'local hidden';",
"cjs/extensionless.cjs": "module.exports = 1;",
"cjs/feature.cjs": "module.exports = 2;",
"cjs/module-only.mjs": "export default 42;",
@@ -79,7 +98,7 @@ const createModuleLookupFixture = async () => {
"node_modules/ancestor-blocked/index.js": "module.exports = 9;",
"node_modules/ancestor-sub/parser.js": "module.exports = 10;",
"esm/runtime-control.mjs": [
'const specifiers = ["./extensionless", "./directory", "./explicit.js", "./exact.js", "./actual.cjs?cache=1", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
'const specifiers = ["./extensionless", "./directory", "./explicit.js", "./exact.js", "./actual.cjs?cache=1", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser", "./.hidden.js", "./..pkg.js", "./exact.js/.", "./exact.js/child/..", ".hidden.js", "..pkg.js", ".", ".."];',
"const results = [];",
"for (const specifier of specifiers) {",
" try { const value = (await import(specifier)).default; results.push({ specifier, ok: true, value }); }",
@@ -88,7 +107,7 @@ const createModuleLookupFixture = async () => {
"console.log(JSON.stringify(results));",
].join("\n"),
"cjs/runtime-control.cjs": [
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./module-only", "./valid-directory", "./default-js", "./default-json", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./module-only", "./valid-directory", "./default-js", "./default-json", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser", ".hidden.js", "./.hidden.js", ".", ".."];',
"const results = [];",
"for (const specifier of specifiers) {",
" try { const value = require(specifier); results.push({ specifier, ok: true, value }); }",
@@ -109,6 +128,110 @@ const createModuleLookupFixture = async () => {
return root;
};
type RuntimeControlResult = {
readonly specifier: string;
readonly ok: boolean;
readonly code?: string;
readonly value?: unknown;
};
const expectNodeRuntimeControls = (
esmOutput: string,
cjsOutput: string,
): void => {
const esmResults = JSON.parse(esmOutput) as RuntimeControlResult[];
const cjsResults = JSON.parse(cjsOutput) as RuntimeControlResult[];
expect(esmResults).toEqual([
{
specifier: "./extensionless",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{
specifier: "./directory",
ok: false,
code: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "./explicit.js",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{ specifier: "./exact.js", ok: true, value: 4 },
{ specifier: "./actual.cjs?cache=1", ok: true, value: 5 },
{ specifier: "empty-main", ok: true, value: 42 },
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{ specifier: "file-only", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{ specifier: "ancestor-empty", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{
specifier: "ancestor-blocked",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{
specifier: "ancestor-sub/parser",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{ specifier: "./.hidden.js", ok: true, value: "local hidden" },
{ specifier: "./..pkg.js", ok: true, value: "local dot package" },
{
specifier: "./exact.js/.",
ok: false,
code: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "./exact.js/child/..",
ok: false,
code: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: ".hidden.js",
ok: false,
code: "ERR_INVALID_MODULE_SPECIFIER",
},
{
specifier: "..pkg.js",
ok: false,
code: "ERR_INVALID_MODULE_SPECIFIER",
},
{ specifier: ".", ok: false, code: "ERR_UNSUPPORTED_DIR_IMPORT" },
{ specifier: "..", ok: false, code: "ERR_UNSUPPORTED_DIR_IMPORT" },
]);
expect(cjsResults).toEqual([
{
specifier: "./extensionless",
ok: false,
code: "MODULE_NOT_FOUND",
},
{
specifier: "./directory",
ok: false,
code: "MODULE_NOT_FOUND",
},
{
specifier: "./feature",
ok: false,
code: "MODULE_NOT_FOUND",
},
{ specifier: "./feature.cjs", ok: true, value: 2 },
{ specifier: "./module-only", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "./valid-directory", ok: true, value: 42 },
{ specifier: "./default-js", ok: true, value: 3 },
{ specifier: "./default-json", ok: true, value: { value: 4 } },
{ specifier: "empty-main", ok: true, value: 42 },
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "file-only", ok: true, value: 7 },
{ specifier: "ancestor-empty", ok: true, value: 8 },
{ specifier: "ancestor-blocked", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "ancestor-sub/parser", ok: true, value: 10 },
{ specifier: ".hidden.js", ok: true, value: "hidden package" },
{ specifier: "./.hidden.js", ok: true, value: "local hidden" },
{ specifier: ".", ok: true, value: "current directory" },
{ specifier: "..", ok: true, value: "parent directory" },
]);
};
cliTest.for(["CLI", "stdio MCP"] as const)(
"matches Node module lookup for ESM and CommonJS through %s",
async (surface, { cli }) => {
@@ -123,79 +246,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
timeout: 5_000,
}),
]);
const esmResults = JSON.parse(esmControl.stdout) as Array<{
readonly specifier: string;
readonly ok: boolean;
readonly code?: string;
readonly value?: unknown;
}>;
const cjsResults = JSON.parse(cjsControl.stdout) as Array<{
readonly specifier: string;
readonly ok: boolean;
readonly code?: string;
readonly value?: unknown;
}>;
expect(esmResults).toEqual([
{
specifier: "./extensionless",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{
specifier: "./directory",
ok: false,
code: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "./explicit.js",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{ specifier: "./exact.js", ok: true, value: 4 },
{ specifier: "./actual.cjs?cache=1", ok: true, value: 5 },
{ specifier: "empty-main", ok: true, value: 42 },
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{ specifier: "file-only", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{ specifier: "ancestor-empty", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{
specifier: "ancestor-blocked",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{
specifier: "ancestor-sub/parser",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
]);
expect(cjsResults).toEqual([
{
specifier: "./extensionless",
ok: false,
code: "MODULE_NOT_FOUND",
},
{
specifier: "./directory",
ok: false,
code: "MODULE_NOT_FOUND",
},
{
specifier: "./feature",
ok: false,
code: "MODULE_NOT_FOUND",
},
{ specifier: "./feature.cjs", ok: true, value: 2 },
{ specifier: "./module-only", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "./valid-directory", ok: true, value: 42 },
{ specifier: "./default-js", ok: true, value: 3 },
{ specifier: "./default-json", ok: true, value: { value: 4 } },
{ specifier: "empty-main", ok: true, value: 42 },
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "file-only", ok: true, value: 7 },
{ specifier: "ancestor-empty", ok: true, value: 8 },
{ specifier: "ancestor-blocked", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "ancestor-sub/parser", ok: true, value: 10 },
]);
expectNodeRuntimeControls(esmControl.stdout, cjsControl.stdout);
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
const expectations = [
@@ -211,6 +262,14 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
["import", "ancestor-empty", null, "not-found"],
["import", "ancestor-blocked", null, "not-found"],
["import", "ancestor-sub/parser", null, "not-found"],
["import", "./.hidden.js", "esm/.hidden.js", "resolved"],
["import", "./..pkg.js", "esm/..pkg.js", "resolved"],
["import", ".hidden.js", null, "rejected"],
["import", "..pkg.js", null, "rejected"],
["import", ".", null, "not-found"],
["import", "..", null, "not-found"],
["import", "./exact.js/.", null, "not-found"],
["import", "./exact.js/child/..", null, "not-found"],
["require", "./extensionless", null, "not-found"],
["require", "./directory", null, "not-found"],
["require", "./feature", null, "not-found"],
@@ -242,19 +301,30 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
"node_modules/ancestor-sub/parser.js",
"resolved",
],
["require", ".hidden.js", "node_modules/.hidden.js/index.js", "resolved"],
["require", "./.hidden.js", "cjs/.hidden.js", "resolved"],
["require", ".", "cjs/index.js", "resolved"],
["require", "..", "index.js", "resolved"],
] as const;
for (const [kind, specifier, resolvedPath, status] of expectations)
expect(graph.edges).toContainEqual(
for (const [kind, specifier, resolvedPath, status] of expectations) {
const matchingProperties = graph.edges
.filter((edge) => edge.relation === "imports")
.map((edge) => edge.properties)
.filter(
(properties) =>
"module_link_kind" in properties &&
properties.module_link_kind === kind &&
properties.specifier === specifier,
);
expect(matchingProperties).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: kind,
specifier,
resolved_path: resolvedPath,
resolution_status: status,
}),
module_link_kind: kind,
specifier,
resolved_path: resolvedPath,
resolution_status: status,
}),
);
}
},
);
@@ -0,0 +1,61 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
cliTest.for(["CLI", "stdio MCP"] as const)(
"retains both repeated chunk callback observations through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-bundler-callbacks-");
const source = [
'(globalThis.webpackChunkFixture = globalThis.webpackChunkFixture || []).push([[1], {a: function() {}}, function(r) { r(7); r.e("chunk-a"); }]);',
'(globalThis.webpackChunkFixture = globalThis.webpackChunkFixture || []).push([[1], {a: function() {}}, function(r) { r(8); r.e("chunk-b"); }]);',
].join("\n");
await writeFile(join(root, "bundle.js"), source);
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
const chunk = graph.nodes.find(({ kind }) => kind === "javascript-chunk");
for (const [index, entry, asyncChunk] of [
[0, "7", "chunk-a"],
[1, "8", "chunk-b"],
] as const) {
expect(chunk?.observations).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
entry_module_keys: [entry],
async_chunk_keys: [asyncChunk],
}),
evidence: expect.objectContaining({
location: expect.objectContaining({
value: expect.objectContaining({
source: "bundle.js",
start: { line: index + 1, column: 0 },
}),
}),
}),
}),
);
expect(graph.edges).toContainEqual(
expect.objectContaining({
source_node_id: chunk?.node_id,
properties: expect.objectContaining({
kind: "bundler-entry-module",
module_key: entry,
resolution_status: "not-found",
}),
}),
);
expect(graph.edges).toContainEqual(
expect.objectContaining({
source_node_id: chunk?.node_id,
properties: expect.objectContaining({
kind: "bundler-async-chunk",
chunk_key: asyncChunk,
resolution_status: "not-found",
}),
}),
);
}
},
);
@@ -0,0 +1,85 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
cliTest.for(["CLI", "stdio MCP"] as const)(
"retains getter-local alias mutations in exported Evidence through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-getter-local-aliases-");
const cases = [
["initialized", "const self = this; return self.s;", true],
["assigned", "let self; self = this; return self.s;", true],
["destructured", "const { s: value } = this; return value;", true],
["readOnly", "const self = this; return self.s;", false],
[
"cyclic",
"let self = this.start; while (flag) self = self.child; return self;",
true,
"start: { child: { child: shared } }",
],
] as const;
const privateCases = [
["privateProjection", "shared", true, "unknown"],
["privateUnrelated", "{ peer: shared }", true, "literal"],
["privateReadOnly", "shared", false, "literal"],
] as const;
await writeFile(
join(root, "app.mjs"),
cases
.map(
([
name,
getter,
write,
members = "s: shared",
]) => `export function ${name}() {
const shared = { x: 1 };
const box = { ${members}, get v() { ${getter} } };
${write ? "box.v.x = 2;" : "const saved = box.v;"}
return shared.x;
}`,
)
.join("\n") +
privateCases
.map(
([name, value, write]) => `export function ${name}() {
const shared = { x: 1 };
class Box {
#s = ${value};
peer = this;
get v() { const { peer: self } = this; return self.#s; }
}
const box = new Box();
${write ? "box.v.x = 2;" : "const saved = box.v;"}
return shared.x;
}`,
)
.join("\n"),
);
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
for (const [name, status] of [
...cases.map(([name, , write]) => [name, write ? "unknown" : "literal"]),
...privateCases.map(([name, , , status]) => [name, status]),
]) {
const observation = graph.nodes
.flatMap(({ observations }) => observations)
.find(
({ properties }) =>
properties.semantic_role === "export-return-shapes" &&
properties.exported_name === name,
);
expect(observation, name).toBeDefined();
expect(observation?.properties.static_return_shapes).toMatchObject([
{
value_status: status,
fields: [
{ path: "", state: status, value: status === "unknown" ? null : 1 },
],
},
]);
}
},
);
@@ -39,6 +39,47 @@ export function superclass() {
new B().v.x = 2;
return shared.x;
}
export function arrayReceiver() {
const arr = [{ x: 1, get self() { return this; } }];
arr[0].self.x = 2;
return arr[0].x;
}
export function nestedArrayReceiver() {
const outer = { arr: [{ x: 1, get self() { return this; } }] };
outer.arr[0].self.x = 2;
return outer.arr[0].x;
}
export function assignedReceiver() {
let box;
box = { x: 1, get self() { return this; } };
box.self.x = 2;
return box.x;
}
export function savedArrayReceiver() {
const arr = [{ x: 1, get self() { return this; } }];
const saved = arr[0].self;
saved.x = 2;
return arr[0].x;
}
export function arrayReadOnly() {
const arr = [{ x: 1, get self() { return this; } }];
const saved = arr[0].self;
return arr[0].x;
}
export function replacementKeepsOldObject() {
const old = { x: 1 };
let box = old;
box = { x: 1, old: box, get self() { return this; } };
box.self.x = 2;
return old.x;
}
export function replacementMutatesCapturedObject() {
const old = { x: 1 };
let box = old;
box = { old: box, get self() { return this; } };
box.self.old.x = 2;
return old.x;
}
export function untouched() {
const box = { x: 1, y: 1, get self() { return this; } };
box.self.y = 2;
@@ -66,13 +107,20 @@ export function untouched() {
const { graph } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(document).normalized_result;
for (const name of [
"self",
"property",
"privateField",
"superclass",
"untouched",
]) {
for (const [name, status] of [
["self", "unknown"],
["property", "unknown"],
["privateField", "unknown"],
["superclass", "unknown"],
["arrayReceiver", "unknown"],
["nestedArrayReceiver", "unknown"],
["assignedReceiver", "unknown"],
["savedArrayReceiver", "unknown"],
["arrayReadOnly", "literal"],
["replacementKeepsOldObject", "literal"],
["replacementMutatesCapturedObject", "unknown"],
["untouched", "literal"],
] as const) {
const projection = graph.nodes
.flatMap(({ observations }) => observations)
.find(
@@ -82,7 +130,16 @@ export function untouched() {
);
expect(projection, name).toBeDefined();
expect(projection?.properties.static_return_shapes).toMatchObject([
{ value_status: name === "untouched" ? "literal" : "unknown" },
{
value_status: status,
fields: [
{
path: "",
state: status,
...(status === "literal" ? { value: 1 } : {}),
},
],
},
]);
}
},
@@ -0,0 +1,110 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { expect } from "vitest";
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"preserves literal NIB fields and UTF-8 names through CLI and stdio MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-nib-field-identity-");
const app = join(root, "Fixture.app");
const contents = join(app, "Contents");
await mkdir(join(contents, "Resources"), { recursive: true });
await mkdir(join(contents, "MacOS"));
await writeFile(
join(contents, "MacOS/App"),
thinMach(0xfeedfacf, 0x0100000c),
);
await writeFile(
join(contents, "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>App</string><key>CFBundleIdentifier</key><string>dev.rea.nib-fields</string></dict></plist>",
);
const archive = encodeNibArchiveFixture({
classes: ["UIView", "\uFEFFCustomView"],
objects: [
{
classIndex: 0,
values: {
["__proto__"]: { ref: 1 },
constructor: 7,
enabled: true,
"\uFEFFenabled": false,
},
},
{ classIndex: 1, values: { ["__proto__"]: 23 } },
],
});
const path = join(contents, "Resources/Panel.nib");
await writeFile(path, archive);
const result = await cli.run({
arguments: ["decode-interface-builder", app, "--json"],
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
});
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
const contract = toolContract("decode_interface_builder");
const evidence = contract.outputSchema.parse(result.json);
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
env: {
PATH: process.env.PATH ?? "",
REA_LOG_LEVEL: "silent",
REA_ANALYSIS_PROVIDER: "auto",
},
stderr: "pipe",
});
const client = new Client({ name: "nib-field-identity", version: "1" });
try {
await client.connect(transport);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: app },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const response = await client.callTool({
name: contract.name,
arguments: {},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const mcp = contract.outputSchema.parse(response.structuredContent);
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
} finally {
try {
await client.close();
} finally {
await transport.close();
}
}
const report = interfaceBuilderAnalysisSchema.parse(
evidence.normalized_result,
);
expect(report.documents[0]?.archive_sha256).toBe(
createHash("sha256").update(archive).digest("hex"),
);
const objects = report.graph.nodes.filter(
({ attributes }) => attributes.interface_builder_object_id !== undefined,
);
expect(objects).toHaveLength(2);
expect(objects[0]?.attributes.nibValues).toEqual({
["__proto__"]: { objectID: "1" },
constructor: 7,
enabled: true,
"\uFEFFenabled": false,
});
expect(objects[1]?.attributes).toMatchObject({
class_name: "\uFEFFCustomView",
nibValues: { ["__proto__"]: 23 },
});
expect(await readFile(path)).toEqual(archive);
},
60_000,
);
@@ -141,6 +141,13 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
).toBe("node_modules/fi%xture/actual.cjs");
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
expect(graph.coverage.status).toBe("complete");
const requireFileUrl = graph.edges.find(
({ properties }) =>
properties.module_link_kind === "require" &&
properties.specifier === "file:///src/uri-dep.cjs",
);
expect(requireFileUrl?.evidence.limitations.length).toBeGreaterThan(0);
const imports = graph.edges.filter(
({ properties }) => properties.module_link_kind === "require",
);
@@ -0,0 +1,111 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect } from "vitest";
import {
CPU,
fatImage,
machoImage,
} from "../../src/artifacts/apple/MachoImage.fixture.js";
import { artifactInventoryResultSchema } from "../../src/domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest.for(["jar", "zip"])(
"distinguishes JVM classes from universal Mach-O files in %s inventory",
async (extension, { cli }) => {
const root = await createTestTempDirectory("rea-class-inventory-");
const path = join(root, `mixed.${extension}`);
// The large class can hold the entire 65-entry table suggested by its
// version bytes. Checking only the table length does not distinguish it.
const classes = [
["Hello.class", javaClass()],
["Big.class", javaClass("x".repeat(4_000))],
["renamed.bin", javaClass()],
] as const;
const writer = new ZipWriter(new Uint8ArrayWriter());
for (const [name, bytes] of classes)
await writer.add(name, new Uint8ArrayReader(bytes));
const nativePaths: string[] = [];
for (const wide of [false, true]) {
for (const littleEndian of [false, true]) {
const name = `fat${wide ? 64 : 32}-${littleEndian ? "le" : "be"}`;
nativePaths.push(name);
await writer.add(
name,
new Uint8ArrayReader(
fatImage(
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
wide,
littleEndian,
),
),
);
}
}
await writeFile(path, await writer.close());
const reply = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
});
expect(reply.exitCode, reply.stdout + reply.stderr).toBe(0);
const inspection = artifactInspectionResultSchema.parse(
parseEvidence(reply.json).normalized_result,
);
const inventory = artifactInventoryResultSchema.parse(
inspection.substeps[0]?.evidence.normalized_result,
);
for (const name of nativePaths) {
expect(inventory.occurrences).toContainEqual(
expect.objectContaining({
logical_path: name,
artifact_kind: "executable",
artifact_format: "mach-o-universal",
limitations: [],
}),
);
}
for (const [name, bytes] of classes) {
const occurrence = inventory.occurrences.find(
(item) => item.logical_path === name,
);
expect(occurrence).toBeDefined();
expect.soft(occurrence?.artifact_kind, name).not.toBe("executable");
expect.soft(occurrence?.artifact_format, name).not.toMatch(/^mach-o/u);
const sha256 = createHash("sha256").update(bytes).digest("hex");
const node = inventory.nodes.find((item) => item.sha256 === sha256);
expect(node).toBeDefined();
expect.soft(node?.format, name).not.toMatch(/^mach-o/u);
}
},
);
/** Minimal valid Java 21 class, with an optional unused UTF-8 constant. */
const javaClass = (extra?: string): Buffer => {
const utf8 = (value: string): Buffer => {
const text = Buffer.from(value);
const header = Buffer.alloc(3);
header[0] = 1;
header.writeUInt16BE(text.length, 1);
return Buffer.concat([header, text]);
};
const constants = [
Buffer.from([7, 0, 2]),
utf8("Hello"),
Buffer.from([7, 0, 4]),
utf8("java/lang/Object"),
...(extra === undefined ? [] : [utf8(extra)]),
];
const header = Buffer.from("cafebabe000000410000", "hex");
header.writeUInt16BE(constants.length + 1, 8);
return Buffer.concat([
header,
...constants,
Buffer.from("0021000100030000000000000000", "hex"),
]);
};
+9 -2
View File
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { expect } from "vitest";
import { toolContract } from "../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import { flutterResultSchemas } from "../../src/domain/flutter/flutterBuildAnalysis.js";
import {
aotFixtureImage,
engineFixtureImage,
@@ -59,6 +60,9 @@ cliTest(
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract(name).outputSchema.parse(result.json);
const complete = flutterResultSchemas[name].parse(
evidence.normalized_result,
);
const response = await call(name, {
path,
...(abi === undefined ? {} : { abi }),
@@ -70,7 +74,7 @@ cliTest(
expect(mcp.subject).toMatchObject({
local_path: path,
format: "apk",
digest: { sha256: evidence.normalized_result.target.sha256 },
digest: { sha256: complete.target.sha256 },
});
expect(mcp.evidence_id).toBe(evidence.evidence_id);
if (name === "inspect_dart_aot") {
@@ -134,6 +138,9 @@ cliTest(
const evidence = toolContract("inspect_dart_aot").outputSchema.parse(
result.json,
);
const complete = flutterResultSchemas.inspect_dart_aot.parse(
evidence.normalized_result,
);
const { call } = await connectLocalToolsMcp();
const response = await call("inspect_dart_aot", { path });
expect(response.isError, JSON.stringify(response)).not.toBe(true);
@@ -146,7 +153,7 @@ cliTest(
string_pool: { coverage: "complete" },
});
expect(
evidence.normalized_result.libapp.sections
complete.libapp.sections
.filter((section) => section.name.endsWith("Data"))
.map((section) => section.kind),
).toEqual([4, 4]);
@@ -0,0 +1,135 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect } from "vitest";
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import { harmonyApplicationProjectionResultSchema } from "../../src/domain/harmony/harmonyApplication.js";
import { workspaceCliTest as test } from "../support/cli/workspaceCliFixture.js";
test("preserves Harmony archive formats through the public CLI/MCP lifecycle", async ({
cli,
workspace,
}) => {
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"module.json",
new TextReader('{"module":{"name":"fixture"}}'),
);
await writer.add(
"ets/modules.abc",
new TextReader("opaque bytecode fixture"),
);
const bytes = await writer.close();
const environment = {
PATH: process.env.PATH ?? "",
HOME: workspace.root,
USERPROFILE: workspace.root,
XDG_CONFIG_HOME: workspace.path("config"),
XDG_CACHE_HOME: workspace.path("cache"),
XDG_STATE_HOME: workspace.path("state"),
NODE_OPTIONS: "--max-old-space-size=512",
REA_LOG_LEVEL: "silent",
};
const client = new Client({ name: "rea-harmony-acceptance", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
env: environment,
stderr: "pipe",
});
try {
await client.connect(transport);
await client.listTools();
for (const { suffix, format } of [
{ suffix: "hap", format: "hap" },
{ suffix: "hsp", format: "hsp" },
{ suffix: "app", format: "app-pack" },
]) {
const path = workspace.path(`fixture.${suffix}`);
await writeFile(path, bytes);
const sha256 = createHash("sha256").update(bytes).digest("hex");
const cliReply = await cli.run({
arguments: ["inspect-artifact", path, "--format", "json"],
environment,
});
expect(cliReply.exitCode, cliReply.stderr).toBe(0);
const cliEvidence = parseEvidence(cliReply.json);
const cliInventory = artifactInspectionResultSchema.parse(
cliEvidence.normalized_result,
);
expect(cliInventory.subject).toMatchObject({
root_format: format,
root_sha256: sha256,
});
const opened = await client.callTool({
name: "open_binary",
arguments: { path },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
expect(opened.structuredContent).toMatchObject({
result: { kind: "archive", format, sha256 },
});
const status = await client.callTool({
name: "binary_session",
arguments: {},
});
expect(status.isError, JSON.stringify(status)).not.toBe(true);
expect(status.structuredContent).toMatchObject({
result: { open: true, kind: "archive", format, sha256 },
});
const inspected = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
const inventoryEvidence = parseEvidence(inspected.structuredContent);
expect(
artifactInspectionResultSchema.parse(
inventoryEvidence.normalized_result,
),
).toEqual(cliInventory);
const projected = await client.callTool({
name: "project_harmony_application_graph",
arguments: { inventory_evidence: [inventoryEvidence] },
});
expect(projected.isError, JSON.stringify(projected)).not.toBe(true);
const graph = harmonyApplicationProjectionResultSchema.parse(
parseEvidence(projected.structuredContent).normalized_result,
);
expect(graph).toMatchObject({
root_format: format,
root_sha256: sha256,
coverage: { status: "complete-within-inventory" },
});
expect(
graph.components.manifests.map(({ path: member }) => member),
).toEqual(["module.json"]);
expect(
graph.components.bytecode.map(({ path: member }) => member),
).toEqual(["ets/modules.abc"]);
const closed = await client.callTool({
name: "close_binary",
arguments: {},
});
expect(closed.isError, JSON.stringify(closed)).not.toBe(true);
const empty = await client.callTool({
name: "binary_session",
arguments: {},
});
expect(empty.isError, JSON.stringify(empty)).not.toBe(true);
expect(empty.structuredContent).toMatchObject({
result: { open: false },
});
expect(await readFile(path)).toEqual(Buffer.from(bytes));
}
} finally {
await client.close();
}
}, 120_000);
@@ -6,6 +6,17 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const cases = [
{
client: "cursor",
path: ".cursor/mcp.json",
text: "malformed UTF-8",
bytes: Buffer.concat([
Buffer.from('{"label":"'),
Buffer.from([0xff]),
Buffer.from('"}'),
]),
diagnostic: "not valid UTF-8",
},
{
client: "cursor",
path: ".cursor/mcp.json",
@@ -92,7 +103,9 @@ for (const scenario of cases)
);
const config = join(home, scenario.path);
await mkdir(dirname(config), { recursive: true });
await writeFile(config, scenario.text);
const original =
"bytes" in scenario ? scenario.bytes : Buffer.from(scenario.text);
await writeFile(config, original);
const environment = {
HOME: home,
USERPROFILE: home,
@@ -146,7 +159,7 @@ for (const scenario of cases)
});
if (!("syntax" in scenario))
expect(uninstall.stdout).not.toContain("not valid JSON");
expect(await readFile(config, "utf8")).toBe(scenario.text);
expect(await readFile(config)).toEqual(original);
expect(await readdir(dirname(config))).toEqual([
scenario.path.split("/").at(-1),
]);
+106 -1
View File
@@ -1,5 +1,5 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { expect } from "vitest";
@@ -8,6 +8,111 @@ import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest.for([
{
label: "blank defaults",
harness: "",
agents: " \t ",
dshRoot: "home/.dsh",
agentsRoot: "home/.agents",
},
{
label: "tilde roots",
harness: "~/selected harness",
agents: "~\\shared agents",
dshRoot: "home/selected harness",
agentsRoot: "home/shared agents",
},
{
label: "relative roots",
harness: "./selected harness",
agents: "../shared agents",
dshRoot: "workspace/selected harness",
agentsRoot: "shared agents",
},
])(
"DSH CLI uses Harness path semantics through setup, doctor and uninstall for $label",
async ({ harness, agents, dshRoot, agentsRoot }, { cli }) => {
const root = await createTestTempDirectory("rea-dsh-paths-");
const home = join(root, "home");
const cwd = join(root, "workspace");
const config = join(root, dshRoot, "cordis.patch.yml");
const skillRoot = join(
root,
agentsRoot,
"skills",
"reverse-engineer-anything",
);
const skill = join(skillRoot, "SKILL.md");
await mkdir(home);
await mkdir(cwd);
await mkdir(dirname(config), { recursive: true });
const original =
"# caller patch\n- insert: [{id: caller, name: caller-plugin}]\n";
await writeFile(config, original);
const run = (args: readonly string[]) =>
cli.run({
arguments: [...args, "--json"],
cwd,
environment: {
HOME: home,
USERPROFILE: home,
DSH_HOME: harness,
DSH_AGENTS_HOME: agents,
},
});
const planned = await run(["setup", "--client", "dsh", "--dry-run"]);
expect(planned.exitCode).toBe(0);
expect(planned.json).toMatchObject({
status: "planned",
appliedActions: [],
plannedActions: expect.arrayContaining([
expect.objectContaining({ id: "configure_client:dsh", target: config }),
expect.objectContaining({ kind: "install_skill", target: skillRoot }),
]),
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" });
const configured = await run(["setup", "--client", "dsh", "--yes"]);
expect(configured.exitCode).toBe(0);
expect(configured.json).toMatchObject({
status: "ready",
clients: { dsh: { status: "configured" } },
});
const text = await readFile(config, "utf8");
expect(text).toContain("# caller patch");
expect(text).toContain("rea-mcp");
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(skill, "utf8")).toContain(
"name: reverse-engineer-anything",
);
const doctor = await run(["doctor", "--client", "dsh", "--skill"]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({ healthy: true });
const repeated = await run(["setup", "--client", "dsh", "--yes"]);
expect(repeated.exitCode).toBe(0);
expect(repeated.json).toMatchObject({
status: "ready",
plannedActions: [],
appliedActions: [],
});
expect(await readFile(config, "utf8")).toBe(text);
const removed = await run(["uninstall"]);
expect(removed.exitCode).toBe(0);
expect(removed.json).toMatchObject({
status: "complete",
items: expect.arrayContaining([
expect.objectContaining({ name: "dsh", status: "removed" }),
]),
});
expect(parse(await readFile(config, "utf8"))).toEqual([
{ insert: [{ id: "caller", name: "caller-plugin" }] },
]);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" });
},
);
cliTest(
"DSH CLI previews, approves, repairs, launches MCP, repeats and uninstalls while preserving caller YAML",
async ({ cli }) => {
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES } from "../../../src/browser/history/CaptureRelease.js";
import { NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES } from "../../../src/browser/history/CaptureRelease.js";
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../../src/domain/webNetworkCapture.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
@@ -46,7 +46,7 @@ const capture = (count: number) =>
// Node.js enforces the decoder's V8 heap flags. Bun ignores them; on Windows
// the decoder's Job Object commit limit is the enforced bound instead, and
// Bun elsewhere has no bound this capture can reach.
const jobLimit = HAR_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES;
const jobLimit = NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES;
it.skipIf(process.versions.bun !== undefined && jobLimit === null)(
"reports real HAR memory exhaustion through CLI and MCP and preserves server usability",
async () => {
+457
View File
@@ -0,0 +1,457 @@
import { execFile } from "node:child_process";
import { writeFile, truncate, rm } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it as runtimeTest } from "vitest";
import {
NODE_CAPTURE_HEAP_ENFORCED,
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} from "../../../src/browser/history/CaptureRelease.js";
import { webNetworkCaptureSummaryViewResultSchema } from "../../../src/domain/analysisView/analysisView.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import {
webNetworkCaptureSchema,
WEB_NETWORK_CAPTURE_LIMITS,
} from "../../../src/domain/webNetworkCapture.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const hasMemoryBound =
NODE_CAPTURE_HEAP_ENFORCED ||
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null;
const it = runtimeTest.skipIf(!hasMemoryBound);
const cli = fileURLToPath(new URL("../../../scripts/rea.mjs", import.meta.url));
const event = {
name: "transport:packet_sent",
time: 1791819895000.25,
data: {
header: { packet_type: "1RTT", packet_number: 5 },
frames: [
{ frame_type: "stream", stream_id: 0, offset: 10, length: 5, fin: true },
],
},
};
const qlog = (events: unknown[]) =>
JSON.stringify({
qlog_format: "JSON",
qlog_version: "0.3",
traces: [
{
vantage_point: { name: "aioquic", type: "server" },
common_fields: { ODCID: "trace-local" },
events,
},
],
});
const assertAdditionalQlogFacets = async (
call: Awaited<ReturnType<typeof connectLocalToolsMcp>>["call"],
retained: { kind: string; evidence_id: string },
): Promise<void> => {
for (const [view, expected] of [
[
{ kind: "qlog", facet: "traces", offset: 1, limit: 1 },
[{ trace_index: 1, event_count: 1, stream_count: 1 }],
],
[
{ kind: "qlog", facet: "loss-declarations", trace_index: 0 },
[{ record_ordinal: 1, packet_number: { state: "reported", value: "5" } }],
],
[{ kind: "qlog", facet: "incomplete-records", trace_index: 0 }, []],
[
{
kind: "qlog",
facet: "ranges",
trace_index: 0,
stream_id: "0",
direction: "sent",
},
[{ start: "10", end: "15" }],
],
[
{
kind: "qlog",
facet: "final-sizes",
trace_index: 0,
stream_id: "0",
direction: "sent",
},
["15"],
],
[{ kind: "qlog", facet: "traces", offset: 99 }, []],
] as const) {
const response = await call("inspect_analysis_view", {
source: retained,
view,
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(
parseEvidence(response.structuredContent).normalized_result,
).toMatchObject({
page: { items: expected },
coverage: { exhausted: true },
});
}
};
it("pages original trace-scoped facts after source deletion without conflating selected events or identical stream IDs", async () => {
const root = await createTestTempDirectory("rea-qlog-pages-");
const path = join(root, "input.qlog");
const source = JSON.parse(
qlog([
event,
{
name: "recovery:packet_lost",
time: 1791819895001,
data: { packet_number: 5, type: "1RTT" },
},
]),
);
source.traces.push({
...source.traces[0],
events: [
{
...event,
data: {
frames: [
{
frame_type: "stream",
stream_id: 0,
offset: 100,
length: 3,
fin: true,
},
],
},
},
],
});
await writeFile(path, JSON.stringify(source));
const { call } = await connectLocalToolsMcp();
const response = await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
detail: "summary",
record_ordinals: [2],
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const summary = webNetworkCaptureSummaryViewResultSchema.parse(
parseEvidence(response.structuredContent).normalized_result,
);
expect(summary).toMatchObject({
summary: {
total_records: 3,
retained_records: 1,
qlog: {
trace_count: 2,
retained_stream_count: 2,
loss_declaration_count: 1,
},
},
});
expect(JSON.stringify(summary)).not.toContain('"contributions"');
if (
!("parent_evidence_id" in summary) ||
typeof summary.parent_evidence_id !== "string"
)
throw new Error("Missing retained parent");
const retained = {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
};
const parent = parseEvidence(
(
await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
record_ordinals: [2],
})
).structuredContent,
);
expect(parent.evidence_id).toBe(summary.parent_evidence_id);
const portablePath = join(root, "parent.json");
await rm(path);
const pages = [];
for (const trace_index of [0, 1]) {
const page = await call("inspect_analysis_view", {
source: retained,
view: { kind: "qlog", facet: "streams", trace_index, limit: 1 },
});
expect(page.isError, JSON.stringify(page)).not.toBe(true);
pages.push(parseEvidence(page.structuredContent).normalized_result);
}
expect(pages[0]).toMatchObject({
page: { items: [{ stream_id: "0", unique_bytes: "5" }] },
context: { scope: "all-recorded-events-before-selection" },
});
expect(pages[1]).toMatchObject({
page: { items: [{ stream_id: "0", unique_bytes: "3" }] },
});
await assertAdditionalQlogFacets(call, retained);
const view = {
kind: "qlog",
facet: "contributions",
trace_index: 0,
stream_id: "0",
direction: "sent",
offset: 0,
limit: 1,
};
const contribution = parseEvidence(
(await call("inspect_analysis_view", { source: retained, view }))
.structuredContent,
);
expect(contribution.normalized_result).toMatchObject({
page: {
items: [{ record_ordinal: 0, frame_index: 0, offset: "10", length: "5" }],
},
coverage: { total: 1, exhausted: true },
});
await writeFile(
portablePath,
JSON.stringify({ source: { kind: "inline", evidence: parent }, view }),
);
const cliResult = await execute(process.execPath, [
cli,
"inspect-analysis-view",
portablePath,
"--json",
]);
expect(parseEvidence(JSON.parse(cliResult.stdout)).normalized_result).toEqual(
contribution.normalized_result,
);
for (const invalid of [
{ kind: "qlog", facet: "streams" },
{ kind: "qlog", facet: "streams", trace_index: 99 },
{ ...view, stream_id: "99" },
{ kind: "qlog", facet: "traces", trace_index: 0 },
])
expect(
parseMcpToolError(
await call("inspect_analysis_view", {
source: retained,
view: invalid,
}),
),
).toMatchObject({ error: { code: "invalid_request" } });
}, 60_000);
runtimeTest.runIf(!hasMemoryBound)(
"refuses qlog when this runtime cannot enforce a decoder memory bound",
async () => {
const { call } = await connectLocalToolsMcp();
const root = await createTestTempDirectory("rea-qlog-unbounded-");
const path = join(root, "input.qlog");
await writeFile(path, qlog([event]));
expect(
parseMcpToolError(
await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
}),
),
).toMatchObject({ error: { code: "capability_unavailable" } });
},
);
it("runs built CLI and real stdio SDK with exact evidence parity, selection, retained references and strict schemas", async () => {
const root = await createTestTempDirectory("rea-qlog-public-");
const path = join(root, "input.qlog");
await writeFile(
path,
qlog([
event,
{
name: "recovery:packet_lost",
time: 1791819895001.125,
data: { packet_number: 5, type: "1RTT" },
},
]),
);
const { call, client } = await connectLocalToolsMcp();
const input = { capture_path: path, format: "qlog", record_ordinals: [1, 0] };
const response = await call("inspect_web_network_capture", input);
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const mcp = parseEvidence(response.structuredContent);
const result = await execute(process.execPath, [
cli,
"inspect-web-network-capture",
path,
"qlog",
"--record",
"1",
"--record",
"0",
"--json",
]);
const cliEvidence = parseEvidence(JSON.parse(result.stdout));
expect(cliEvidence.evidence_id).toBe(mcp.evidence_id);
expect(cliEvidence.normalized_result).toEqual(mcp.normalized_result);
expect(mcp.analysis_profile?.parameters).toMatchObject({
qlog_profile: "aioquic-1.5.0-json-0.3",
});
expect(mcp.authority).toBe("historical-reference");
const decoded = webNetworkCaptureSchema.parse(mcp.normalized_result);
expect(decoded.records.map((record) => record.ordinal)).toEqual([1, 0]);
if (decoded.format !== "qlog") throw new Error("qlog format required");
expect(decoded.qlog.traces[0]?.streams[0]).toMatchObject({
unique_bytes: "5",
covered_ranges: [{ start: "10", end: "15" }],
});
const retained = await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: mcp.evidence_id },
view: { kind: "api-surface" },
});
// An unsupported view over an existing retained parent proves lookup without pretending qlog is HAR.
expect(parseMcpToolError(retained)).toMatchObject({
error: { code: "unsupported_target" },
});
await client.ping();
for (const record_ordinals of [[2], [0, 0]]) {
expect(
parseMcpToolError(
await call("inspect_web_network_capture", {
...input,
record_ordinals,
}),
),
).toMatchObject({ error: { code: "invalid_request" } });
}
const hidden = await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
sensitive_values: ["trace-local", "/traces/0", "input.qlog"],
});
expect(JSON.stringify(hidden)).not.toContain("trace-local");
expect(JSON.stringify(hidden)).not.toContain("/traces/0");
expect(JSON.stringify(hidden)).not.toContain("input.qlog");
const hiddenEvidence = parseEvidence(hidden.structuredContent);
expect(
webNetworkCaptureSchema.parse(hiddenEvidence.normalized_result).artifact
.path,
).toBe("");
const invalid = await call("inspect_web_network_capture", {
...input,
mysecret: true,
sensitive_values: ["mysecret"],
});
expect(parseMcpToolError(invalid)).toMatchObject({
error: { code: "invalid_request" },
});
expect(JSON.stringify(invalid)).not.toContain("mysecret");
}, 60_000);
it("fails whole-capture validation before selection and survives malformed, unsupported and oversized qlog", async () => {
const root = await createTestTempDirectory("rea-qlog-errors-");
const path = join(root, "input.qlog");
const { call, client } = await connectLocalToolsMcp();
for (const [text, code] of [
[qlog([event, { ...event, time: "invalid" }]), "invalid_request"],
[qlog([event]).slice(0, -1), "invalid_request"],
[
qlog([event]).replace('"qlog_version":"0.3"', '"qlog_version":"0.4"'),
"capability_unavailable",
],
[
qlog([
{
...event,
extension: JSON.parse("[".repeat(65) + "0" + "]".repeat(65)),
},
]),
"invalid_request",
],
] as const) {
await writeFile(path, text);
expect(
parseMcpToolError(
await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
record_ordinals: [0],
}),
),
).toMatchObject({ error: { code } });
const failed: unknown = await execute(process.execPath, [
cli,
"inspect-web-network-capture",
path,
"qlog",
"--json",
]).catch((cause: unknown) => cause);
expect(failed).toMatchObject({
code: 1,
stdout: expect.stringContaining(`"code":"${code}"`),
});
}
await truncate(path, WEB_NETWORK_CAPTURE_LIMITS.inputBytes + 1);
expect(
parseMcpToolError(
await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
}),
),
).toMatchObject({ error: { code: "invalid_request" } });
await writeFile(path, qlog([event]));
await client.ping();
expect(
(
await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
})
).isError,
).not.toBe(true);
}, 60_000);
runtimeTest.skipIf(process.versions.bun !== undefined || !hasMemoryBound)(
"contains actual qlog decoder heap exhaustion and keeps MCP usable",
async () => {
const root = await createTestTempDirectory("rea-qlog-capacity-");
const path = join(root, "dense.qlog");
const dense = qlog(Array<unknown>(100_000).fill(event));
expect(Buffer.byteLength(dense)).toBeLessThan(
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
);
await writeFile(path, dense);
const { call, client } = await connectLocalToolsMcp();
const response = await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
record_ordinals: [0],
});
expect(parseMcpToolError(response)).toMatchObject({
error: {
code: "resource_constraint",
details: {
resource: "memory",
reported_limits: { old_generation_heap_mib: 192 },
},
},
});
const failed: unknown = await execute(
process.execPath,
[cli, "inspect-web-network-capture", path, "qlog", "--json"],
{ timeout: 40_000, maxBuffer: 1024 * 1024 },
).catch((cause: unknown) => cause);
expect(failed).toMatchObject({
code: 1,
stdout: expect.stringContaining('"code":"resource_constraint"'),
});
await writeFile(path, qlog([event]));
await client.ping();
expect(
(
await call("inspect_web_network_capture", {
capture_path: path,
format: "qlog",
})
).isError,
).not.toBe(true);
},
60_000,
);
+56 -38
View File
@@ -26,6 +26,26 @@ class FixtureProcess extends EventEmitter implements ProviderProcessHandle {
}
}
const fixtureLauncher =
(process: FixtureProcess): JadxLauncher =>
async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
it("joins pending input errors before detaching the owned protocol stream", async () => {
let completeWrite: ((cause: Error) => void) | undefined;
const failure = new Error("owned pipe closed during cancellation");
@@ -70,26 +90,9 @@ it("joins pending input errors before detaching the owned protocol stream", asyn
it("decodes split UTF-8 and newline bytes, then routes multiple complete frames", async () => {
const process = new FixtureProcess();
const launcher: JadxLauncher = async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
launcher,
fixtureLauncher(process),
);
const received: JSONRPCMessage[] = [];
transport.onmessage = (message) => received.push(message);
@@ -98,7 +101,9 @@ it("decodes split UTF-8 and newline bytes, then routes multiple complete frames"
const first = {
jsonrpc: "2.0",
id: 1,
result: { content: [{ type: "text", text: "snow 雪 🦊" }] },
result: {
content: [{ type: "text", text: "snow 雪 🦊 and literal �" }],
},
} satisfies JSONRPCMessage;
const second = {
jsonrpc: "2.0",
@@ -120,28 +125,41 @@ it("decodes split UTF-8 and newline bytes, then routes multiple complete frames"
await transport.close();
});
it("accepts a complete JSON-RPC frame at the 8 MiB boundary", async () => {
it.each([
["invalid UTF-8 byte", Buffer.from([0xff])],
["truncated UTF-8 sequence", Buffer.from([0xe2, 0x82])],
])("rejects %s in a complete JSON-RPC frame", async (_label, invalid) => {
const process = new FixtureProcess();
const launcher: JadxLauncher = async ({ runId }) => ({
process,
ownership: {
runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
cleanup: async () => {
process.emit("exit", 0, null);
process.emit("close", 0, null);
process.stdout.end();
process.stderr.end();
process.stdin.end();
return { cleaned: true, signaled: false };
},
});
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
launcher,
fixtureLauncher(process),
);
const received: JSONRPCMessage[] = [];
const errors: Error[] = [];
transport.onmessage = (message) => received.push(message);
transport.onerror = (cause) => errors.push(cause);
await transport.start();
process.stdout.write(
Buffer.concat([
Buffer.from('{"jsonrpc":"2.0","id":1,"result":{"text":"'),
invalid,
Buffer.from('"}}\n'),
]),
);
await new Promise<void>((resolve) => setImmediate(resolve));
await transport.close();
expect(received).toEqual([]);
expect(errors).toHaveLength(1);
expect(errors[0]?.message).toMatch(/encoded data was not valid/i);
});
it("accepts a complete JSON-RPC frame at the 8 MiB boundary", async () => {
const process = new FixtureProcess();
const transport = new JadxMcpTransport(
{ command: "fixture", arguments: [] },
fixtureLauncher(process),
);
const received: JSONRPCMessage[] = [];
transport.onmessage = (message) => received.push(message);
@@ -0,0 +1,89 @@
import { open } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import { PwntoolsLayoutProvider } from "../../../src/native/pwntools/PwntoolsLayoutProvider.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const unsupportedHost = process.platform !== "linux" || process.arch !== "x64";
const DEFAULT_INPUT_BYTES = 33_554_432;
// One byte above the shipped bound, so the admission decision is the only
// difference between the first two cases.
const ARTIFACT_BYTES = DEFAULT_INPUT_BYTES + 1;
/** Sparse regular file just larger than the shipped input bound. */
const oversizedArtifact = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-pwntools-input-bound-");
const path = join(root, "recorded-core");
const handle = await open(path, "w");
await handle.truncate(ARTIFACT_BYTES);
await handle.close();
return path;
};
/** One admission attempt, reported as the projected caller-visible failure. */
const inspect = async (override?: string) => {
const path = await oversizedArtifact();
const provider = new PwntoolsLayoutProvider(
{
REA_PWNTOOLS_PYTHON: process.execPath,
...(override === undefined
? {}
: { REA_PWNTOOLS_MAX_INPUT_BYTES: override }),
},
async (spawn) =>
spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", "process.stdout.write('no reply')"],
}),
);
onTestFinished(async () => {
await provider.close();
});
const result = await provider.inspect({ path });
if (result.ok) throw new Error("Expected the bounded decoder to fail");
const projected = projectAnalysisError(result.error);
return { projected, text: JSON.stringify(projected) };
};
it.runIf(!unsupportedHost)(
"refuses an artifact above the shipped bound when no override is set",
async () => {
const { projected, text } = await inspect();
expect(projected.code).toBe("invalid_request");
expect(text).toContain(
`Selected artifact exceeds ${String(DEFAULT_INPUT_BYTES)} bytes`,
);
},
);
it.runIf(!unsupportedHost)(
"admits the same artifact once the override widens the bound",
async () => {
const { projected, text } = await inspect(String(ARTIFACT_BYTES));
// Admission passed, so the only remaining failure is that the owned decoder
// never wrote a reply, which also proves the process really ran.
expect(text).not.toContain("Selected artifact exceeds");
expect(projected.code).toBe("unreadable_output");
expect(text).toContain("no reply");
},
);
it.runIf(!unsupportedHost)(
"refuses an unusable override before reading the artifact",
async () => {
const { projected, text } = await inspect("0");
expect(projected.code).toBe("provider_unavailable");
expect(projected.details).toMatchObject({
rejections: [
{ diagnostics: { configuration_key: "REA_PWNTOOLS_MAX_INPUT_BYTES" } },
],
});
expect(text).toContain("REA_PWNTOOLS_MAX_INPUT_BYTES must be a decimal");
expect(text).not.toContain("Selected artifact exceeds");
},
);
@@ -0,0 +1,315 @@
import { describe, expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
type FakeOptions,
} from "../../fixtures/fakeCdpBrowser.js";
import { trackBrowser } from "./cdpBrowserProvider.support.js";
const startBrowser = async (options: FakeOptions = {}) => {
const browser = await startFakeCdpBrowser({
...options,
commandResult(command, origin, frameReads) {
const override = options.commandResult?.(command, origin, frameReads);
if (override !== undefined) return override;
if (command.method === "DOMSnapshot.captureSnapshot") {
const nodes = {
nodeType: [9, 1, 1, 1, 1],
nodeName: [1, 2, 3, 3, 3],
nodeValue: [4, 4, 4, 4, 4],
parentIndex: [-1, 0, 1, 1, 1],
backendNodeId: [1, 2, 3, 4, 5],
attributes: [[], [], [5, 6], [5, 7], [5, 6, 8, 9]],
};
return {
strings: [
`${origin}/app`,
"#document",
"HTML",
"a",
"",
"xlink:href",
"/first",
"/second",
"href",
"/ordinary",
"https://excluded.example/page",
],
documents: [
{ documentURL: 0, nodes },
{
documentURL: 10,
nodes: { ...nodes, backendNodeId: [11, 12, 13, 14, 15] },
},
],
};
}
if (command.method === "DOM.describeNode")
return {
node: {
backendNodeId: command.params.backendNodeId,
nodeType: 1,
nodeName: "a",
isSVG: true,
},
};
return undefined;
},
});
trackBrowser(browser);
return browser;
};
const inspect = (browser: FakeCdpBrowser, signal?: AbortSignal) =>
new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
target_id: "allowed-page",
allowed_origins: [browser.allowedOrigin],
observation_ms: 0,
}),
signal === undefined ? undefined : { signal },
);
describe("CDP SVG identity at the snapshot boundary", () => {
it("describes only in-scope XLink candidates without a winning href", async () => {
const browser = await startBrowser();
const result = await inspect(browser);
if (!result.ok) throw result.error;
expect(result.value.metadata.dom_urls.map(({ url }) => url)).toEqual(
["/first", "/second", "/ordinary"].map(
(path) => browser.allowedOrigin + path,
),
);
expect(
browser.commands
.filter(({ method }) => method === "DOM.describeNode")
.map(({ params }) => params),
).toEqual([
{ backendNodeId: 3, depth: 0 },
{ backendNodeId: 4, depth: 0 },
]);
});
it.each(["removed", "mismatched"])(
"retains partial metadata when a candidate is %s",
async (failure) => {
const browser = await startBrowser({
commandError: (command) =>
failure === "removed" &&
command.method === "DOM.describeNode" &&
command.params.backendNodeId === 3
? { code: -32_000, message: "No node found for given backend id" }
: undefined,
commandResult: (command) =>
failure === "mismatched" &&
command.method === "DOM.describeNode" &&
command.params.backendNodeId === 3
? {
node: {
backendNodeId: 99,
nodeType: 1,
nodeName: "a",
isSVG: true,
},
}
: undefined,
});
const result = await inspect(browser);
if (!result.ok) throw result.error;
expect(result.value.metadata.dom_urls.map(({ url }) => url)).toEqual(
["/second", "/ordinary"].map((path) => browser.allowedOrigin + path),
);
expect(result.value.completeness.excluded).toContainEqual({
section: "metadata",
reason: "provider_unavailable",
count: 1,
});
expect(result.value.limitations).toContain(
"SVG identity was unavailable for 1 snapshotted XLink candidate nodes; their URL destinations remain unknown.",
);
},
);
it("stops querying after the first batch reports an unsupported method", async () => {
const browser = await startBrowser({
commandResult: manyCandidates,
unsupportedMethods: ["DOM.describeNode"],
});
const result = await inspect(browser);
if (!result.ok) throw result.error;
expect(result.value.metadata.dom_urls).toEqual([]);
expect(result.value.completeness.excluded).toContainEqual({
section: "metadata",
reason: "provider_unavailable",
count: 25,
});
expect(descriptions(browser).length).toBeGreaterThan(0);
expect(descriptions(browser).length).toBeLessThanOrEqual(8);
});
it.each([
{ options: { closeOnMethod: "DOM.describeNode" }, reason: "disconnected" },
{
options: {
commandError: (command: { method: string }) =>
command.method === "DOM.describeNode"
? { code: -32_602, message: "Invalid parameters" }
: undefined,
},
reason: "protocol_error",
},
])(
"propagates $reason during node description",
async ({ options, reason }) => {
const browser = await startBrowser(options);
expect(await inspect(browser)).toMatchObject({
ok: false,
error: { _tag: "BrowserObservationError", reason },
});
},
);
it("cancels a pending description and detaches without closing the target", async () => {
const browser = await startBrowser({ hangOnMethod: "DOM.describeNode" });
const controller = new AbortController();
const pending = inspect(browser, controller.signal);
await expect.poll(() => descriptions(browser).length).toBeGreaterThan(1);
controller.abort();
expect(await pending).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", operation: "inspect_web_page" },
});
const methods = browser.commands.map(({ method }) => method);
expect(methods).toContain("Target.detachFromTarget");
expect(methods).not.toContain("Target.closeTarget");
expect(methods).not.toContain("Browser.close");
});
});
const manyCandidates: NonNullable<FakeOptions["commandResult"]> = (
command,
origin,
) => {
if (command.method !== "DOMSnapshot.captureSnapshot") return undefined;
const count = 25;
return {
strings: [
origin,
"#document",
"HTML",
"a",
"",
"xlink:href",
...Array.from({ length: count }, (_, index) => `/link-${String(index)}`),
],
documents: [
{
documentURL: 0,
nodes: {
nodeType: [9, 1, ...Array<number>(count).fill(1)],
nodeName: [1, 2, ...Array<number>(count).fill(3)],
nodeValue: Array<number>(count + 2).fill(4),
parentIndex: [-1, 0, ...Array<number>(count).fill(1)],
backendNodeId: Array.from(
{ length: count + 2 },
(_, index) => index + 1,
),
attributes: [
[],
[],
...Array.from({ length: count }, (_, index) => [5, index + 6]),
],
},
},
],
};
};
const descriptions = (browser: FakeCdpBrowser) =>
browser.commands.filter(({ method }) => method === "DOM.describeNode");
describe("CDP SVG query concurrency", () => {
it("bounds in-flight reads and preserves metadata order across reversed replies", async () => {
const browser = await startBrowser({
commandResult: manyCandidates,
hangOnMethod: "DOM.describeNode",
});
const controller = new AbortController();
const pending = inspect(browser, controller.signal);
try {
await expect.poll(() => descriptions(browser).length).toBeGreaterThan(1);
let replied = 0;
while (replied < 25) {
await expect
.poll(() => descriptions(browser).length)
.toBeGreaterThan(replied);
const batch = descriptions(browser).slice(replied);
expect(batch.length).toBeLessThanOrEqual(8);
for (const command of [...batch].reverse()) {
const id = Number(command.params.backendNodeId);
browser.emitRawMessage(
JSON.stringify({
id: command.id,
result: {
node: {
backendNodeId: id,
nodeType: 1,
nodeName: "a",
isSVG: id % 2 === 1,
},
},
}),
);
}
replied += batch.length;
}
const result = await pending;
if (!result.ok) throw result.error;
expect(result.value.metadata.dom_urls.map(({ url }) => url)).toEqual(
Array.from(
{ length: 13 },
(_, index) => `${browser.allowedOrigin}/link-${String(index * 2)}`,
),
);
expect(descriptions(browser)).toHaveLength(25);
} finally {
controller.abort();
await pending;
}
});
it("cancels sibling reads on a fatal reply without waiting for hung nodes", async () => {
const browser = await startBrowser({
commandResult: manyCandidates,
hangOnMethod: "DOM.describeNode",
});
const controller = new AbortController();
const pending = inspect(browser, controller.signal);
try {
await expect.poll(() => descriptions(browser).length).toBeGreaterThan(1);
const batch = descriptions(browser);
browser.emitRawMessage(
JSON.stringify({
id: batch.at(-1)?.id,
error: { code: -32_602, message: "Invalid parameters" },
}),
);
await expect(pending).resolves.toMatchObject({
ok: false,
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
});
expect(descriptions(browser)).toHaveLength(batch.length);
const methods = browser.commands.map(({ method }) => method);
expect(methods).toContain("Target.detachFromTarget");
expect(methods).not.toContain("Target.closeTarget");
expect(methods).not.toContain("Browser.close");
} finally {
controller.abort();
await pending;
}
});
});
@@ -3,6 +3,37 @@ import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
describe("screenshot committed document identity", () => {
it.each([
{ offset: 8, value: 14 },
{ offset: 16, value: 0x8000_0000 },
{ offset: 20, value: 0x8000_0000 },
])("rejects invalid screenshot IHDR metadata", async ({ offset, value }) => {
const bytes = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
"base64",
);
bytes.writeUInt32BE(value, offset);
const browser = await startFakeCdpBrowser({
commandResult: ({ method }) =>
method === "Page.captureScreenshot"
? { data: bytes.toString("base64") }
: undefined,
});
onTestFinished(async () => {
await browser.close();
});
const result = await new CdpBrowserProvider().captureScreenshot(
captureWebScreenshotInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
}),
);
expect(result).toMatchObject({
ok: false,
error: { reason: "protocol_error" },
});
});
it.each(["loader-main", "loader-reloaded"])(
"distinguishes %s for the same URL",
async (screenshotDocumentLoader) => {
+55 -2
View File
@@ -45,8 +45,38 @@ const pageHtml = `<!doctype html><title>x</title>
<image id="img" xlink:href="/xl-image" />
<use id="use" xlink:href="/xl-use" />
<a id="out" xlink:href="https://cdn.example.test/out"><text>out</text></a>
<a id="move-desc" xlink:href="/xl-moved-desc"><text>move desc</text></a>
<a id="move-title" xlink:href="/xl-moved-title"><text>move title</text></a>
<desc id="desc-container">
<a xlink:href="/xl-html-desc">not an SVG link</a>
<a href="/html-desc">HTML link</a>
<svg><a xlink:href="/xl-nested-desc"><text>nested</text></a></svg>
</desc>
<title id="title-container">
<a xlink:href="/xl-html-title">not an SVG link</a>
<a href="/html-title">HTML link</a>
<svg><a xlink:href="/xl-nested-title"><text>nested</text></a></svg>
</title>
</svg>
<a id="html" xlink:href="/xl-html">html</a>
<script>
for (const kind of ['desc', 'title']) {
const container = document.getElementById(kind + '-container');
container.append(document.getElementById('move-' + kind));
for (const nested of [false, true]) {
const anchor = document.createElementNS('http://www.w3.org/2000/svg', 'a');
anchor.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href',
'/xl-created-' + (nested ? 'nested-' : '') + kind);
const parent = nested
? container.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'g'))
: container;
parent.append(anchor);
}
const math = document.createElementNS('http://www.w3.org/1998/Math/MathML', 'a');
math.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '/xl-math-' + kind);
container.append(math);
}
</script>
`;
it.skipIf(chromeExecutable === undefined)(
@@ -143,17 +173,36 @@ it.skipIf(chromeExecutable === undefined)(
url: null,
destination_scope: "outside_policy",
}),
...[
"/html-desc",
"/html-title",
"/xl-nested-desc",
"/xl-nested-title",
"/xl-moved-desc",
"/xl-moved-title",
"/xl-created-desc",
"/xl-created-title",
"/xl-created-nested-desc",
"/xl-created-nested-title",
].map((path) =>
expect.objectContaining({
attribute: "href",
url: `${origin}${path}`,
destination_scope: "approved",
}),
),
]),
);
expect(
urls.some(
(url) =>
url.url?.endsWith("/xl-html") === true ||
url.url?.includes("/xl-html") === true ||
url.url?.includes("/xl-math") === true ||
url.url?.endsWith("/xlink-loses") === true,
),
).toBe(false);
expect(urls.every((url) => url.attribute === "href")).toBe(true);
expect(urls).toHaveLength(5);
expect(urls).toHaveLength(15);
} finally {
child.kill("SIGTERM");
if (!(await waitForExit(child, 2_000))) child.kill("SIGKILL");
@@ -173,6 +222,8 @@ const xhtmlPage = `<?xml version="1.0" encoding="UTF-8"?>
<svg:svg width="10" height="10">
<svg:a id="pa1" xlink:href="/xl-pa1"><svg:text>p</svg:text></svg:a>
<svg:image id="img" xlink:href="/xl-image"/>
<svg:desc><svg:a xlink:href="/xl-xml-desc"><svg:text>desc</svg:text></svg:a></svg:desc>
<svg:title><svg:a xlink:href="/xl-xml-title"><svg:text>title</svg:text></svg:a></svg:title>
<svg:foreignObject width="10" height="10">
<a id="fo-a" xlink:href="/xl-html-fo">no</a>
<h:a xmlns:h="http://www.w3.org/1999/xhtml" id="fo-h" xlink:href="/xl-h">no</h:a>
@@ -202,6 +253,8 @@ for (const { format, page, contentType, nodeNames, link, destinations } of [
destinations: [
"/xl-pa1",
"/xl-image",
"/xl-xml-desc",
"/xl-xml-title",
"/xl-fo-svg",
"/xl-orphan",
"/xl-custom",
@@ -11,7 +11,7 @@ import {
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import { expect, it, onTestFinished, vi } from "vitest";
import { HistoricalCaptureDecoder } from "../../../src/browser/history/HistoricalCaptureDecoder.js";
import { MitmproxyCaptureAdapter } from "../../../src/browser/history/MitmproxyCaptureAdapter.js";
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "../../../src/browser/history/CaptureRelease.js";
@@ -22,6 +22,7 @@ import {
import { historicalHar } from "../../fixtures/historicalHar.js";
import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
const linux = it.skipIf(process.platform !== "linux");
@@ -138,6 +139,66 @@ it("classifies an oversized selected capture before creating an owned decoder",
});
});
it("retains a failed capture reader and retries it before a fresh load", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-capture-reader-close-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
const path = join(root, "input.har");
await writeFile(path, JSON.stringify(historicalHar()));
const originalClose = OwnedFileHandle.prototype.close;
const close = vi.spyOn(OwnedFileHandle.prototype, "close");
let allowClose = false;
let closeAttempts = 0;
close.mockImplementation(async function (this: OwnedFileHandle) {
closeAttempts += 1;
if (!allowClose) throw new Error("injected capture reader close failure");
await originalClose.call(this);
});
let decoderCalls = 0;
const decoder = new HistoricalCaptureDecoder(
[
{
format: "har",
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
command: async () => {
decoderCalls += 1;
return {
command: process.execPath,
arguments: ["-e", "process.exit(0)"],
};
},
},
],
process.env,
);
const input = inspectWebNetworkCaptureInputSchema.parse({
capture_path: path,
format: "har",
});
try {
const first = await decoder.inspect(input);
expect(first.ok).toBe(false);
if (first.ok) throw new Error("Reader close failure must fail inspection");
expect(first.error.cleanupResources).toContain(path);
expect(decoderCalls).toBe(0);
const refused = await decoder.inspect(input);
expect(refused.ok).toBe(false);
if (refused.ok) throw new Error("Fresh read must wait for owner cleanup");
expect(refused.error.cleanupIncomplete).toBe(true);
expect(refused.error.cleanupResources).toContain(path);
expect(decoderCalls).toBe(0);
expect(closeAttempts).toBe(2);
allowClose = true;
await decoder.close();
expect(closeAttempts).toBe(3);
} finally {
allowClose = true;
await decoder.close().catch(() => undefined);
close.mockRestore();
}
});
it("does not misclassify decoder filesystem failures as missing selected input", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-historical-command-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
@@ -7,6 +7,9 @@ import { execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { webNetworkCaptureSchema } from "../../../src/domain/webNetworkCapture.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const entrypoint = fileURLToPath(
new URL("../../../scripts/rea.mjs", import.meta.url),
);
@@ -41,6 +44,91 @@ const cli = async (
};
import { historicalHar } from "../../fixtures/historicalHar.js";
it("excludes declared binary lengths through CLI, MCP and retained capture pages", async () => {
const root = await createTestTempDirectory("rea-har-byte-length-");
const path = join(root, "capture.har");
const fixture = historicalHar();
const entry = fixture.log.entries[0];
if (entry === undefined) throw new Error("fixture missing");
const body = Buffer.alloc(12_345, "A");
const content = body.toString("base64");
const digest = createHash("sha256").update(body).digest("hex");
await writeFile(
path,
JSON.stringify({
log: {
...fixture.log,
entries: [
{
...entry,
response: {
...entry.response,
content: {
size: 99,
mimeType: "text/plain",
encoding: "base64",
text: content,
},
},
},
],
},
}),
);
const { call } = await connectLocalToolsMcp();
const args = { capture_path: path, format: "har" };
const control = await call("inspect_web_network_capture", args);
expect(control.isError).not.toBe(true);
const retained = parseEvidence(control.structuredContent);
const controlCapture = webNetworkCaptureSchema.parse(
retained.normalized_result,
);
expect(controlCapture.records[0]?.binary_fields[0]).toMatchObject({
state: "retained",
bytes: body.length,
content_base64: content,
sha256: digest,
});
for (const literal of ["12345", "2345"]) {
// Only the derived count matches, so this cannot pass via another exclusion.
expect(content).not.toContain(literal);
expect(digest).not.toContain(literal);
const fromCli = await cli(path, "har", ["--sensitive-value", literal]);
expect(fromCli.ok, fromCli.stdout).toBe(true);
const evidence = parseEvidence(JSON.parse(fromCli.stdout));
const response = await call("inspect_web_network_capture", {
...args,
sensitive_values: [literal],
});
expect(response.isError).not.toBe(true);
const fromMcp = parseEvidence(response.structuredContent);
expect(fromMcp.normalized_result).toEqual(evidence.normalized_result);
const capture = webNetworkCaptureSchema.parse(evidence.normalized_result);
expect(capture.records[0]?.reported).toMatchObject({
response: { content: { size: 99, text: null } },
});
expect(capture.records[0]?.binary_fields[0]).toEqual({
pointer: "/response/content/text",
representation: "har-base64-content",
state: "redacted",
bytes: null,
content_base64: null,
sha256: null,
});
for (const detail of ["preview", "complete"]) {
const page = await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: fromMcp.evidence_id },
view: { kind: "capture", detail },
});
expect(page.isError).not.toBe(true);
const result = parseEvidence(page.structuredContent);
expect(result.normalized_result).toMatchObject({
items: [{ binary_fields: [{ state: "redacted", bytes: null }] }],
});
}
}
}, 60_000);
it("reads actual upstream HAR packages in an owned process and retains selected producer order", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-history-har-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
@@ -0,0 +1,499 @@
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { readFile, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { gzipSync } from "node:zlib";
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it as runtimeTest } from "vitest";
import { z } from "zod";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { webNetworkCaptureSchema } from "../../../src/domain/webNetworkCapture.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
NODE_CAPTURE_HEAP_ENFORCED,
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES,
} from "../../../src/browser/history/CaptureRelease.js";
const hasMemoryBound =
NODE_CAPTURE_HEAP_ENFORCED ||
NODE_CAPTURE_PROCESS_MEMORY_LIMIT_BYTES !== null;
const it = runtimeTest.skipIf(!hasMemoryBound);
// Synthetic member fixtures based on Telerik's SAZ layout; not a real-producer golden.
const compressedBody = gzipSync(Buffer.from("stored compressed body"));
const members = (): [string, Buffer][] => [
[
"raw/0042_s.txt",
Buffer.concat([
Buffer.from(
"HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\nSet-Cookie: server-credential\r\n\r\n",
),
compressedBody,
]),
],
[
"raw/7_c.txt",
Buffer.concat([
Buffer.from("POST /bytes HTTP/2.0\r\n:authority: example.test\r\n\r\n"),
Buffer.from([0xff, 0, 0x80]),
]),
],
[
"raw/0042_c.txt",
Buffer.from(
"GET https://user:password@example.test/a HTTP/1.1\r\nAuthorization: Bearer client-credential\r\nCookie: cookie-credential\r\nX-Duplicate: one\r\nX-Duplicate: two\r\nX-Text: unicode-\u03b2\r\n\r\n",
),
],
[
"raw/0042_m.xml",
Buffer.from(
'<Session SID="0042"><SessionTimers ClientConnected="2026-10-13T00:00:00Z"/><SessionFlags><SessionFlag N="x-processinfo" V="fixture:1"/></SessionFlags><Unknown value="01"><![CDATA[retained metadata]]></Unknown></Session>',
),
],
["raw/0042_w.txt", Buffer.from("opaque websocket message file")],
["raw/7_g.txt", Buffer.from([0, 1, 2])],
["[Content_Types].xml", Buffer.from("<Types/>")],
];
const archive = async (entries = members(), password?: string, level = 6) => {
const writer = new ZipWriter(new Uint8ArrayWriter(), {
useWebWorkers: false,
level,
...(password === undefined ? {} : { password }),
});
for (const [name, bytes] of entries)
await writer.add(name, new Uint8ArrayReader(bytes));
return Buffer.from(await writer.close());
};
const fixture = async (bytes: Buffer) => {
const root = await createTestTempDirectory("rea-saz-capture-");
const path = join(root, "capture.saz");
await writeFile(path, bytes);
return path;
};
const entrypoint = fileURLToPath(
new URL("../../../scripts/rea.mjs", import.meta.url),
);
const cliResponse = async (path: string, extra: string[] = []) => {
try {
const { stdout } = await promisify(execFile)(
process.execPath,
[
entrypoint,
"inspect-web-network-capture",
path,
"saz",
"--json",
...extra,
],
{ timeout: 40_000, maxBuffer: 4 * 1024 * 1024 },
);
return { ok: true, stdout };
} catch (cause: unknown) {
if (
cause instanceof Error &&
"stdout" in cause &&
typeof cause.stdout === "string"
)
return { ok: false, stdout: cause.stdout };
throw cause;
}
};
const cli = async (path: string, extra: string[] = []) => {
const result = await cliResponse(path, extra);
expect(result.ok, result.stdout).toBe(true);
return parseEvidence(JSON.parse(result.stdout));
};
it("inspects native SAZ through the public CLI and MCP with equal evidence, bytes and archive coordinates", async () => {
const bytes = await archive();
const path = await fixture(bytes);
const evidence = await cli(path, ["--record", "1", "--record", "0"]);
const capture = webNetworkCaptureSchema.parse(evidence.normalized_result);
expect(capture).toMatchObject({
format: "saz",
total_records: 2,
runtime_attribution: "unknown",
records: [
{ ordinal: 1, reported: { session_id: "7", response: null } },
{
ordinal: 0,
reported: {
session_id: "0042",
request: { url: "https://example.test/a" },
response: { status: "200" },
},
},
],
});
expect(capture.records[1]?.location).toEqual({
kind: "archive-members",
members: [
"raw/0042_s.txt",
"raw/0042_c.txt",
"raw/0042_m.xml",
"raw/0042_w.txt",
],
});
expect(capture.records[1]?.binary_fields).toContainEqual({
pointer: "/response/body",
representation: "producer-bytes",
state: "retained",
content_base64: compressedBody.toString("base64"),
bytes: compressedBody.length,
sha256: createHash("sha256").update(compressedBody).digest("hex"),
});
expect(capture.records[0]?.binary_fields).toContainEqual(
expect.objectContaining({
pointer: "/request/body",
content_base64: "/wCA",
}),
);
expect(capture.records[1]?.binary_fields).toContainEqual(
expect.objectContaining({
pointer: "/request/body",
bytes: 0,
content_base64: "",
}),
);
expect(capture.records[1]?.reported).toMatchObject({
request: {
headers: [
{ name: "Authorization", value: null },
{ name: "Cookie", value: null },
{ name: "X-Duplicate", value: " one" },
{ name: "X-Duplicate", value: " two" },
{ name: "X-Text" },
],
},
});
expect(JSON.stringify(capture)).toContain("retained metadata");
for (const secret of [
"user:password",
"client-credential",
"server-credential",
"cookie-credential",
])
expect(JSON.stringify(capture)).not.toContain(secret);
expect(capture.artifact.sha256).toBe(
createHash("sha256").update(bytes).digest("hex"),
);
expect(await readFile(path)).toEqual(bytes);
const { client, call } = await connectLocalToolsMcp();
const tool = (await client.listTools()).tools.find(
(item) => item.name === "inspect_web_network_capture",
);
if (tool?.outputSchema === undefined)
throw new Error("Missing capture schema");
const args = { capture_path: path, format: "saz", record_ordinals: [1, 0] };
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validate(tool.inputSchema, args)).toBe(true);
const response = await call("inspect_web_network_capture", args);
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const fromMcp = parseEvidence(response.structuredContent);
expect(fromMcp.normalized_result).toEqual(evidence.normalized_result);
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: { detail: "complete" },
});
const records = z
.object({ result: z.object({ records: z.array(z.unknown()) }) })
.parse(bundle.structuredContent)
.result.records.map(parseEvidence);
expect(
records.find((record) => record.evidence_id === fromMcp.evidence_id),
).toEqual(fromMcp);
}, 60_000);
it("pages retained SAZ Evidence through public MCP and portable CLI after source deletion", async () => {
const path = await fixture(await archive());
const { call } = await connectLocalToolsMcp();
const args = { capture_path: path, format: "saz", record_ordinals: [1, 0] };
const full = await call("inspect_web_network_capture", args);
const fromMcp = parseEvidence(full.structuredContent);
const capture = webNetworkCaptureSchema.parse(fromMcp.normalized_result);
const summaryArgs = { ...args, detail: "summary" };
const summaryResponse = await call(
"inspect_web_network_capture",
summaryArgs,
);
expect(summaryResponse.isError, JSON.stringify(summaryResponse)).not.toBe(
true,
);
const summary = parseEvidence(summaryResponse.structuredContent);
expect(summary.normalized_result).toMatchObject({
kind: "summary",
parent_evidence_id: fromMcp.evidence_id,
summary: { format: "saz", total_records: 2, retained_records: 2 },
});
expect(JSON.stringify(summary)).not.toContain(
compressedBody.toString("base64"),
);
// Retained pages must keep their snapshot semantics after the input disappears.
await unlink(path);
const source = {
kind: "retained-evidence",
evidence_id: fromMcp.evidence_id,
};
const previewArgs = {
source,
view: { kind: "capture", offset: 0, limit: 1 },
};
const previewResponse = await call("inspect_analysis_view", previewArgs);
expect(previewResponse.isError, JSON.stringify(previewResponse)).not.toBe(
true,
);
const preview = parseEvidence(previewResponse.structuredContent);
expect(preview.normalized_result).toMatchObject({
items: [
{
ordinal: 1,
reported: {
session_id: "7",
request: { method: "POST", url: "/bytes" },
},
},
],
coverage: { examined: 1, total: 2, next_offset: 1, exhausted: false },
});
expect(JSON.stringify(preview)).not.toContain("content_base64");
const completeResponse = await call("inspect_analysis_view", {
source,
view: { kind: "capture", detail: "complete", offset: 1, limit: 1 },
});
expect(completeResponse.isError, JSON.stringify(completeResponse)).not.toBe(
true,
);
const complete = parseEvidence(completeResponse.structuredContent);
expect(complete.normalized_result).toMatchObject({
items: [capture.records[1]],
coverage: { next_offset: null, exhausted: true },
});
const workflow = join(path, "..", "summary-view.json");
await writeFile(
workflow,
JSON.stringify({
source: { kind: "inline", evidence: fromMcp },
view: { kind: "summary" },
}),
);
const standalone = await promisify(execFile)(process.execPath, [
entrypoint,
"inspect-analysis-view",
workflow,
"--json",
]);
expect(
parseEvidence(JSON.parse(standalone.stdout)).normalized_result,
).toEqual(summary.normalized_result);
}, 60_000);
it("keeps CRLF separators inside a body after LF-only HTTP headers", async () => {
const body = Buffer.from("\ufefffirst\r\n\r\nsecond\n\nthird");
const bytes = await archive([
[
"raw/1_c.txt",
Buffer.concat([
Buffer.from("POST https://example.test/ HTTP/1.1\nX-Test: request\n\n"),
body,
]),
],
[
"raw/1_s.txt",
Buffer.concat([
Buffer.from("HTTP/1.1 200 OK\nX-Test: response\n\n"),
body,
]),
],
]);
const path = await fixture(bytes);
const capture = webNetworkCaptureSchema.parse(
(await cli(path)).normalized_result,
);
expect(capture.records[0]?.reported).toMatchObject({
request: {
headers: [{ name: "X-Test", value: " request" }],
body: body.toString("utf8"),
},
response: {
headers: [{ name: "X-Test", value: " response" }],
body: body.toString("utf8"),
},
});
for (const pointer of ["/request/body", "/response/body"])
expect(capture.records[0]?.binary_fields).toContainEqual({
pointer,
representation: "producer-bytes",
state: "retained",
content_base64: body.toString("base64"),
bytes: body.length,
sha256: createHash("sha256").update(body).digest("hex"),
});
expect(await readFile(path)).toEqual(bytes);
});
it("excludes explicit literals from XML, HTTP byte views, member coordinates and binary sidecars", async () => {
const path = await fixture(await archive());
const result = await cli(path, [
"--sensitive-value",
"0042",
"--sensitive-value",
"unicode-\u03b2",
"--sensitive-value",
compressedBody.toString("base64"),
"--sensitive-value",
"retained metadata",
]);
const capture = webNetworkCaptureSchema.parse(result.normalized_result);
expect(capture.records[0]?.location).toEqual({
kind: "unknown",
reason: "explicit-sensitive-value",
});
expect(capture.records[0]?.binary_fields).toContainEqual({
pointer: "/response/body",
representation: "producer-bytes",
state: "redacted",
bytes: null,
sha256: null,
content_base64: null,
});
const text = JSON.stringify(result);
for (const secret of [
"0042",
"unicode-",
"retained metadata",
compressedBody.toString("base64"),
createHash("sha256").update(compressedBody).digest("hex"),
])
expect(text).not.toContain(secret);
});
it("retains folded headers, stored chunk framing and BOM-marked UTF-16 metadata", async () => {
const body = "3\r\none\r\n0\r\n\r\n";
const path = await fixture(
await archive([
[
"raw/1_s.txt",
Buffer.from(
`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nX-Folded: first\r\n second\r\n\r\n${body}`,
),
],
[
"raw/1_m.xml",
Buffer.from(
'\ufeff<?xml version="1.0" encoding="utf-16"?><Session><Note>\u03b2</Note><Source><![CDATA[<!DOCTYPE html>]]></Source></Session>',
"utf16le",
),
],
[
"raw/2_c.txt",
Buffer.from(
"CONNECT example.test:443 HTTP/1.1\nHost: example.test:443\n\n",
),
],
]),
);
const evidence = await cli(path);
const capture = webNetworkCaptureSchema.parse(evidence.normalized_result);
expect(capture.records[0]?.reported).toMatchObject({
request: null,
response: {
body,
headers: [
{ name: "Transfer-Encoding", value: " chunked" },
{ name: "X-Folded", value: " first\r\n second" },
],
},
});
expect(capture.records[0]?.binary_fields).toContainEqual(
expect.objectContaining({
pointer: "/response/body",
content_base64: Buffer.from(body).toString("base64"),
}),
);
expect(JSON.stringify(capture.records[0]?.reported)).toContain("\u03b2");
expect(capture.records[1]?.reported).toMatchObject({
request: { method: "CONNECT", url: "example.test:443", body: "" },
});
});
it.each([
"bad-http",
"bad-xml",
"dtd",
"unknown-member",
"encrypted",
"duplicate",
"crc",
"expanded-limit",
])("rejects %s before returning a selected subset", async (variant) => {
let entries = members();
if (variant === "bad-http")
entries.push(["raw/8_c.txt", Buffer.from("malformed-private-input")]);
if (variant === "bad-xml")
entries.push(["raw/8_m.xml", Buffer.from("<Session><Broken></Session>")]);
if (variant === "dtd")
entries.push([
"raw/8_m.xml",
Buffer.from(
'<!DOCTYPE Session [<!ENTITY external SYSTEM "file:///private-input">]><Session>&external;</Session>',
),
]);
if (variant === "unknown-member")
entries.push(["raw/8_unknown.txt", Buffer.from("unknown extension")]);
if (variant === "duplicate")
entries = [
["raw/8_c.txt", Buffer.from("GET /a HTTP/1.1\r\n\r\n")],
["raw/9_c.txt", Buffer.from("GET /b HTTP/1.1\r\n\r\n")],
];
let bytes = await archive(
entries,
variant === "encrypted" ? "fixture-password" : undefined,
variant === "crc" ? 0 : 6,
);
if (variant === "duplicate")
bytes = Buffer.from(
bytes.toString("latin1").replaceAll("raw/9_c.txt", "raw/8_c.txt"),
"latin1",
);
if (variant === "crc") {
const offset = bytes.indexOf(Buffer.from("HTTP/1.1 200 OK"));
expect(offset).toBeGreaterThan(0);
bytes[offset + 9] = 0x35;
}
if (variant === "expanded-limit") {
const central = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]));
bytes.writeUInt32LE(33 * 1024 * 1024, central + 24);
}
const path = await fixture(bytes);
const result = await cliResponse(path, ["--record", "0"]);
expect(result.ok, result.stdout).toBe(false);
expect(JSON.parse(result.stdout).category).toBe(
["encrypted", "unknown-member", "dtd"].includes(variant)
? "unsupported_provider"
: variant === "expanded-limit"
? "execution_failure"
: "invalid_input",
);
if (variant === "expanded-limit")
expect(JSON.parse(result.stdout).code).toBe("unreadable_output");
expect(JSON.stringify(result)).not.toContain("malformed-private-input");
});
runtimeTest.runIf(!hasMemoryBound)(
"reports SAZ unavailable when its runtime cannot enforce decoder memory",
async () => {
const response = await cliResponse(await fixture(await archive()));
expect(response.ok).toBe(false);
expect(JSON.parse(response.stdout)).toMatchObject({
code: "capability_unavailable",
});
},
);
+162 -2
View File
@@ -1,3 +1,4 @@
import { packetFieldsCatalogSchema } from "../../../src/domain/captures/packetFields.js";
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
import { it, expect, onTestFinished } from "vitest";
import { writeFile, readdir, chmod, symlink } from "node:fs/promises";
@@ -20,14 +21,15 @@ const fixture = async (mode = "ok", failCleanup = false) => {
await writeFile(
script,
`import {readFileSync, writeFileSync, chmodSync, truncateSync} from 'node:fs';
if (process.argv.includes('--version')) { console.log('TShark (Wireshark) 4.6.9 (fixture)'); console.error('version warning'); }
if (process.argv.includes('--version')) { console.log(${JSON.stringify(mode)} === 'bad-version' ? 'TShark (Wireshark) 3.0.0' : 'TShark (Wireshark) 4.6.9 (fixture)'); console.error('version warning'); }
else if (${JSON.stringify(mode)} === 'nonzero') { console.error('invalid decoder'); process.exitCode = 1; }
else if (${JSON.stringify(mode)} === 'malformed-copy') { chmodSync('capture', 0o600); writeFileSync('capture', 'changed'); }
else if (${JSON.stringify(mode)} === 'oversized-copy') { chmodSync('capture', 0o600); truncateSync('capture', 32 * 1024 * 1024 + 1); console.log('[]'); }
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat(5 * 1024 * 1024));
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat((process.argv.includes('-G') ? 33 : 5) * 1024 * 1024));
else if (${JSON.stringify(mode)} === 'wait') { console.log('ready'); setInterval(() => {}, 1000); }
else if (${JSON.stringify(mode)} === 'invalid-json') console.log('not json');
else if (${JSON.stringify(mode)} === 'many') console.log(JSON.stringify(Array.from({length:90},(_,i)=>({_source:{layers:{"frame.number":[String(i+1)],"ip.addr":["192.0.2.1"]}}}))));
else if (process.argv.includes('-G')) { console.log('P\\tUniversal Serial Bus\\tusb\\nF\\tVendor ID\\tusb.idVendor\\tFT_UINT16\\tusb\\tBASE_HEX\\t0x0\\t\\nF\\tOther Vendor\\tusb.idVendor\\tFT_UINT32\\tusb\\tBASE_HEX\\t0x0\\tSecond registration\\nP\\tInternet Protocol\\tip\\nF\\tAddress\\tip.addr\\tFT_IPv4\\tip\\t\\t0x0\\tSource or destination'); console.error('glossary warning'); }
else { if(readFileSync('capture', 'utf8') !== 'recording bytes') throw Error('wrong copy'); console.log(JSON.stringify([{_source:{layers:{"frame.number":["1"],"ip.addr":["192.0.2.1","192.0.2.2"]}}}])); console.error('producer warning'); }
`,
);
@@ -301,6 +303,9 @@ it("retains a completed observation when cancellation arrives at the service bou
const execution = await f.service.provider.inspect(input);
if (!execution.ok) throw execution.error;
const service = new PacketCaptureService({
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
f.controller.abort();
return execution;
@@ -465,3 +470,158 @@ it("rejects oversized selector lists and UTF-8 argv expansion before provider wo
}
expect(f.calls()).toBe(0);
});
it("discovers installed protocols and field definitions without a capture", async () => {
const f = await fixture();
for (const [input, expected] of [
[
{ query: "USB" },
{
records: [{ abbreviation: "usb", kind: "protocol", field_type: null }],
output_window: { examined: 2, matching: 1, returned: 1 },
},
],
[
{ kind: "fields", protocol: "usb", limit: 1 },
{
records: [
{
abbreviation: "usb.idVendor",
field_type: "FT_UINT16",
source_line: 2,
},
],
output_window: {
examined: 3,
matching: 2,
returned: 1,
has_more: true,
},
},
],
[
{ kind: "fields", protocol: "usb", offset: 1, limit: null },
{
records: [
{
abbreviation: "usb.idVendor",
field_type: "FT_UINT32",
source_line: 3,
},
],
output_window: { matching: 2, returned: 1, has_more: false },
},
],
[
{ kind: "fields", query: "destination" },
{
records: [
{
abbreviation: "ip.addr",
description: "Source or destination",
display_base: "",
},
],
},
],
[
{ query: "no-such-protocol" },
{ records: [], output_window: { matching: 0, returned: 0 } },
],
] as const) {
const result = await f.service.inspectFields(input);
if (!result.ok) throw result.error;
const report = packetFieldsCatalogSchema.parse(
result.value.normalized_result,
);
expect(report).toMatchObject(expected);
expect(report.tool.arguments).toEqual(["-G", "fields"]);
expect(report.tool.version_diagnostics).toBe("version warning\n");
expect(report.diagnostics).toBe("glossary warning\n");
expect(report.limits.output_bytes).toBe(32 * 1024 * 1024);
}
expect(
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
).toEqual([]);
});
it("shares discovery admission with inspection and refuses work after shutdown", async () => {
const f = await fixture("gated");
const active = f.service.inspect({ path: f.path, fields: ["ip.addr"] });
await f.acquired;
const busy = await f.service.inspectFields({});
f.release();
if (!(await active).ok) throw new Error("Inspection failed");
expect(busy).toMatchObject({
ok: false,
error: { operation: "inspect_packet_fields", resource: "capacity" },
});
await f.service.close();
expect(await f.service.inspectFields({})).toMatchObject({
ok: false,
error: {
operation: "inspect_packet_fields",
_tag: "AnalysisCancelledError",
},
});
});
it.each([
"bad-version",
"nonzero",
"overflow",
"wait",
"oversized-tool",
"invalid-json",
])("retains field discovery failure facts: %s", async (mode) => {
const f = await fixture(mode);
const result = await f.service.inspectFields(
{},
{ signal: f.controller.signal },
);
if (result.ok) throw new Error("Expected failure");
expect(result.error).toMatchObject({ operation: "inspect_packet_fields" });
if (mode === "bad-version")
expect(result.error.capturedOutput).toMatchObject({
stdout: "TShark (Wireshark) 3.0.0\n",
stderr: "version warning\n",
});
if (mode === "invalid-json")
expect(result.error.capturedOutput?.stdout).toBe("not json\n");
if (mode === "overflow")
expect(result.error).toMatchObject({
resource: "memory",
reportedLimits: { output_bytes: 32 * 1024 * 1024 },
});
});
it("retains completed discovery on late cancellation and cleanup failure", async () => {
for (const mode of ["post-run-abort", "cleanup"]) {
const f = await fixture(mode, mode === "cleanup");
const result = await f.service.inspectFields(
{ query: "usb" },
{ signal: f.controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: {
partialObservation: {
operation: "inspect_packet_fields",
normalized_result: { records: [{ abbreviation: "usb" }] },
},
},
});
if (mode === "cleanup") {
await f.service.inspectFields({});
await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
expect(f.calls()).toBe(2);
for (let attempt = 0; attempt < 2; attempt++)
await expect(f.service.close()).rejects.toMatchObject({
operation: "inspect_packet_fields",
cleanupIncomplete: true,
});
}
f.allowCleanup();
await f.service.close();
}
});
@@ -0,0 +1,67 @@
import { expect, it } from "vitest";
import { inspectPacketFieldsInputSchema } from "../../../src/domain/captures/packetFields.js";
import { parseFieldDiscovery } from "../../../src/captures/parseFieldDiscovery.js";
it("keeps duplicate registrations and source ordinals instead of overwriting abbreviations", () => {
const text =
"P\tUSB\tusb\r\nF\tVendor\tusb.idVendor\tFT_UINT16\tusb\tBASE_HEX\t0x0\t\r\nF\tVendor\tusb.idVendor\tFT_UINT32\tusb\tBASE_HEX\t0x0\t";
const result = parseFieldDiscovery(
text,
inspectPacketFieldsInputSchema.parse({
kind: "fields",
query: "idVendor",
offset: 1,
}),
);
expect(result.records).toMatchObject([
{
source_line: 3,
abbreviation: "usb.idVendor",
field_type: "FT_UINT32",
description: "",
},
]);
expect(result.output_window).toEqual({
examined: 2,
matching: 2,
returned: 1,
has_more: false,
});
});
it("rejects damaged records even outside the selected page", () => {
for (const text of [
"",
"P\tmissing",
"F\tname\tabbr",
"P\tname\t",
"P\tUSB\tusb\nBAD",
])
expect(() =>
parseFieldDiscovery(
text,
inspectPacketFieldsInputSchema.parse({ limit: 1 }),
),
).toThrow();
});
it("bounds explicit full-result expansion while allowing a page from the same large glossary", () => {
const text = "P\t" + "Long name ".repeat(30) + "\tabbr\n";
const glossary = text.repeat(6000);
expect(() =>
parseFieldDiscovery(
glossary,
inspectPacketFieldsInputSchema.parse({ limit: null }),
),
).toThrow("representation budget");
const result = parseFieldDiscovery(
glossary,
inspectPacketFieldsInputSchema.parse({ offset: 5999, limit: 1 }),
);
expect(result.output_window).toEqual({
examined: 6000,
matching: 6000,
returned: 1,
has_more: false,
});
});
@@ -12,6 +12,38 @@ const selectors = [
] as const;
describe("CLI analysis selector boundaries", () => {
cliTest(
"accepts file offsets and rejects mixed coordinate selectors before opening a target",
async ({ cli }) => {
const selected = await cli.run({
arguments: [
"decompile",
"does-not-exist",
"--file-offset=0x210",
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(selected.json).toMatchObject({ code: "target_unavailable" });
const conflicting = await cli.run({
arguments: [
"decompile",
"does-not-exist",
"0x140001010",
"--file-offset=0x210",
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(conflicting.json).toMatchObject({
code: "invalid_request",
details: {
operation: "procedure_pseudo_code",
issues: [{ path: ["file-offset"], reason: "invalid_value" }],
},
});
},
);
cliTest(
"rejects missing and conflicting selectors before opening a target",
async ({ cli }) => {
@@ -0,0 +1,85 @@
import { expect, it } from "vitest";
import { Cli } from "incur";
import pino from "pino";
import type { ApktoolResourceAnalysisPort } from "../../../src/application/apktool/ApktoolResourceAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { registerApktoolCommands } from "../../../src/cli/apktoolCommands.js";
import { presentOmittableDefaults } from "../../../src/cli/omittableDefaults.js";
import type { ApktoolRequest } from "../../../src/domain/apktool/apktoolResourceAnalysis.js";
import { ok } from "../../../src/domain/result.js";
const invoke = async (argv: readonly string[]) => {
const requests: ApktoolRequest[] = [];
const provider: ApktoolResourceAnalysisPort = {
async inspectAvailability() {
throw new Error("unexpected provider probe");
},
async close() {},
async execute(request) {
requests.push(request);
return ok(
createAnalysisExecution(
{ strings: [] },
{ id: "apktool", name: "Apktool", version: null },
),
);
},
};
const cli = Cli.create("rea", { sync: false });
registerApktoolCommands(cli, pino({ level: "silent" }), {}, provider);
presentOmittableDefaults(cli);
let stdout = "";
let exitCode = 0;
await cli.serve([...argv], {
env: {},
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
});
return { exitCode, stdout, requests };
};
it("dispatches --no-strings as include_strings false", async () => {
const result = await invoke([
"decode-android-resources",
"/targets/app.apk",
"--no-strings",
"--json",
]);
expect(result.exitCode).toBe(0);
expect(result.requests).toEqual([
{
operation: "decode_android_resources",
input: { path: "/targets/app.apk", include_strings: false },
},
]);
});
it("keeps string projection enabled when the flag is omitted", async () => {
const result = await invoke([
"decode-android-resources",
"/targets/app.apk",
"--json",
]);
expect(result.exitCode).toBe(0);
expect(result.requests).toEqual([
{
operation: "decode_android_resources",
input: { path: "/targets/app.apk", include_strings: true },
},
]);
});
it("documents the supported negative flag in command help", async () => {
const result = await invoke(["decode-android-resources", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("--no-strings");
});
+115
View File
@@ -5,6 +5,7 @@ import { silentLogger } from "../../../src/logger.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { err } from "../../../src/domain/result.js";
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
it.each([false, true])(
"awaits cleanup retry and preserves completed output when retry failure is %s",
@@ -32,6 +33,9 @@ it.each([false, true])(
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => err(original),
close: async () => {
await Promise.resolve();
@@ -79,6 +83,111 @@ it.each([false, true])(
},
);
it("keeps the primary CLI failure when close throws an untyped error", async () => {
const cli = Cli.create("capture-cleanup-primary-test", { sync: false });
registerCaptureCommands(
cli,
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () =>
err(
new AnalysisInputError("inspect_packet_capture", {
userMessage: "The selected capture input was rejected.",
}),
),
close: async () => {
throw new Error("raw close failure");
},
},
);
let stdout = "";
await cli.serve(
[
"inspect-packet-capture",
"recording.pcap",
"--fields",
"ip.addr",
"--format",
"json",
],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(JSON.parse(stdout)).toMatchObject({
code: "cleanup_incomplete",
message: "The selected capture input was rejected.",
details: {
diagnostics: {
primary_error: { code: "invalid_request" },
},
resources: [],
},
});
});
it("closes the service and retains an unexpected producer rejection", async () => {
const cli = Cli.create("capture-producer-rejection-test", { sync: false });
let closed = false;
registerCaptureCommands(
cli,
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
throw new Error("raw producer failure");
},
close: async () => {
closed = true;
throw new Error("raw close failure");
},
},
);
let stdout = "";
await cli.serve(
[
"inspect-packet-capture",
"recording.pcap",
"--fields",
"ip.addr",
"--format",
"json",
],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(closed).toBe(true);
expect(JSON.parse(stdout)).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: {
primary_error: {
code: "execution_failure",
details: {
operation: "inspect_packet_capture",
provider_id: "tshark-capture",
},
},
cleanup_error: { code: "cleanup_incomplete" },
},
},
});
});
it("rejects an oversized selector budget before the CLI invokes its service", async () => {
const cli = Cli.create("capture-selector-test", { sync: false });
let called = false;
@@ -87,6 +196,9 @@ it("rejects an oversized selector budget before the CLI invokes its service", as
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
called = true;
throw new Error("Must not inspect");
@@ -125,6 +237,9 @@ it("rejects conflicting output options before the CLI invokes its service", asyn
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
called = true;
throw new Error("Must not inspect");
+89
View File
@@ -58,6 +58,95 @@ describe("CLI output argument boundary", () => {
});
});
describe("unclosed CLI output filter slices", () => {
it.each([
"providers[",
"providers[0,1].name[",
"name,providers[",
"][,]",
"providers],name[0,1]",
])("rejects %s before the filter parser runs", (filter) => {
expect(
validateCliOutputArguments([
"providers",
"--json",
"--filter-output",
filter,
]),
).toMatchObject({ ok: false, code: "INVALID_OUTPUT_FILTER" });
});
it("preserves effective-filter and earlier flag-error precedence", () => {
for (const arguments_ of [
[
"--filter-output",
"providers[",
"--filter-output",
"capabilities[0,1].provider.id,open",
],
["--filter-output", "capabilities[-1,].provider.id"],
["--filter-output", "capabilities[[0,1]"],
["--format", "invalid", "--filter-output", "providers["],
["--token-limit", "invalid", "--filter-output", "providers["],
])
expect(validateCliOutputArguments(arguments_)).toEqual({ ok: true });
});
workspaceCliTest(
"fails promptly across output formats without invoking the command",
async ({ cli }) => {
for (const format of ["json", "jsonl", "yaml", "toon", "md"]) {
const result = await cli.run({
arguments: [
"analyze",
"/absent/target",
"--format",
format,
"--filter-output",
"result[0,1].name[",
],
timeoutMs: 3000,
});
expect(result.exitCode).toBe(1);
expect(result.stdout).toContain("INVALID_OUTPUT_FILTER");
expect(result.stdout).toContain("closing ]");
expect(result.stderr).toBe("");
}
const splitPath = await cli.run({
arguments: ["providers", "--json", "--filter-output", "][,]"],
timeoutMs: 3000,
});
expect(splitPath.exitCode).toBe(1);
expect(splitPath.json).toMatchObject({
ok: false,
error: { code: "INVALID_OUTPUT_FILTER" },
});
},
CLI_INTEGRATION_TIMEOUT_MS,
);
workspaceCliTest(
"retains closed slices and multiple filter paths",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"providers",
"--json",
"--filter-output",
"capabilities[0,1].provider.id,open",
],
timeoutMs: 3000,
});
expect(result.exitCode).toBe(0);
expect(result.json).toEqual({
capabilities: [{ provider: { id: expect.any(String) } }],
open: false,
});
},
CLI_INTEGRATION_TIMEOUT_MS,
);
});
describe("CLI output valued-flag parsing", () => {
workspaceCliTest(
"preserves complete JSON errors when native builtin flags follow unusual arguments",
+159 -84
View File
@@ -1,100 +1,175 @@
import { execFile } from "node:child_process";
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { promisify } from "node:util";
import {
copyFile,
mkdir,
readFile,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const runner = resolve("scripts/run-development-tests.mjs");
describe("development test runner", () => {
it("rejects nonexistent explicit paths instead of returning a zero-test success", async () => {
await expect(
execute(process.execPath, [
runner,
"focused",
"src/missing.test.ts",
"--dry-run",
]),
).rejects.toMatchObject({ code: 1 });
const run = (root: string, command: string, arguments_: readonly string[]) =>
execFileOutput(command, arguments_, {
cwd: root,
stopSignal: "SIGTERM",
timeout: 30_000,
maxBuffer: 1024 * 1024,
});
it("reports actionable remediation when the comparison base is unavailable", async () => {
await expect(
execute(process.execPath, [
runner,
"changed",
"--base",
"missing-test-base",
"--dry-run",
const git = (root: string, ...arguments_: string[]) =>
run(root, "git", arguments_);
const commit = (root: string, message: string) =>
git(
root,
"-c",
"user.name=REA fixture",
"-c",
"user.email=fixture@example.test",
"-c",
"commit.gpgSign=false",
"commit",
"--quiet",
"-m",
message,
);
const fixture = async () => {
const root = await createTestTempDirectory("rea-development-tests-");
await mkdir(join(root, "scripts", "lib"), { recursive: true });
await mkdir(join(root, "src"));
for (const path of [
"scripts/run-development-tests.mjs",
"scripts/lib/development-tests.mjs",
])
await copyFile(join(process.cwd(), path), join(root, path));
await symlink(
join(process.cwd(), "node_modules"),
join(root, "node_modules"),
process.platform === "win32" ? "junction" : undefined,
);
await writeFile(join(root, "package.json"), '{"type":"module"}\n');
await writeFile(join(root, ".gitignore"), "node_modules\nselected.txt\n");
await writeFile(
join(root, "vitest.config.mjs"),
'export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };\n',
);
await writeFile(join(root, "src/value.ts"), "export const value = 1;\n");
await writeFile(
join(root, "src/value.test.ts"),
'import { expect, it } from "vitest"; import { writeFileSync } from "node:fs"; import { value } from "./value.js"; it("checks the selected source", () => { expect(value).toBe(1); writeFileSync("selected.txt", String(value)); });\n',
);
await git(root, "init", "--quiet", "-b", "main");
await git(root, "add", ".");
await commit(root, "fixture");
return root;
};
const testCommand = (root: string, ...arguments_: string[]) =>
run(root, process.execPath, [
"scripts/run-development-tests.mjs",
...arguments_,
]);
describe("development test runner public CLI", () => {
it("runs an explicitly selected source test on a clean tree without build artifacts", async () => {
const root = await fixture();
const { stdout: status } = await git(root, "status", "--porcelain");
expect(status).toBe("");
await testCommand(root, "local", "src/value.test.ts");
expect(await readFile(join(root, "selected.txt"), "utf8")).toBe("1");
});
it("plans an exact local test without building", async () => {
const root = await fixture();
const { stdout } = await testCommand(
root,
"local",
"src/value.test.ts",
"--dry-run",
);
expect(JSON.parse(stdout)).toMatchObject({
needsBuild: false,
artifactTasks: [],
vitestArguments: expect.arrayContaining([
"run",
"--project",
"domain",
"--project",
"services",
"--project",
"adapters",
"--project",
"composition",
"--project",
"conformance",
"--project",
"evaluation",
"src/value.test.ts",
]),
});
});
it("uses committed dependency changes to select source tests and reports failures", async () => {
const root = await fixture();
const { stdout: base } = await git(root, "rev-parse", "HEAD");
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
await git(root, "add", "src/value.ts");
await commit(root, "change dependency");
await expect(
testCommand(root, "changed", "--base", base.trim()),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("src/value.test.ts"),
stderr: expect.stringContaining("expected 2 to be 1"),
});
});
it("runs changed and focused tests from a committed branch regression", async () => {
const root = await fixture();
const { stdout: baseline } = await git(root, "rev-parse", "HEAD");
await git(root, "update-ref", "refs/remotes/origin/main", baseline.trim());
await git(root, "switch", "--quiet", "-c", "regression");
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
await writeFile(
join(root, "src/value.test.ts"),
'import { expect, it } from "vitest"; import { value } from "./value.js"; it("checks current source", () => expect(value).toBe(2));\n',
);
await git(root, "add", "src");
await commit(root, "regression fix");
expect((await git(root, "status", "--porcelain")).stdout).toBe("");
const changed = await testCommand(root, "changed");
expect(changed.stdout).toContain("1 passed");
const focused = await testCommand(root, "focused", "src/value.test.ts");
expect(focused.stdout).toContain("1 passed");
}, 60_000);
it("reports a missing comparison base and rejects missing or compiled-boundary paths", async () => {
const root = await fixture();
await expect(
testCommand(root, "changed", "--base", "missing-test-base", "--dry-run"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining(
"Fetch origin/main or pass --base REVISION",
),
});
});
it("runs a committed branch regression through real Git and Vitest without dist", async () => {
const root = await createTestTempDirectory("rea-development-tests-");
await mkdir(join(root, "src"));
await symlink(
resolve("node_modules"),
join(root, "node_modules"),
"junction",
);
await writeFile(
join(root, "package.json"),
JSON.stringify({ type: "module" }),
);
await writeFile(join(root, ".gitignore"), "node_modules\n");
await writeFile(
join(root, "vitest.config.ts"),
`export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };`,
);
await writeFile(join(root, "src/value.ts"), "export const value = 1;\n");
await writeFile(
join(root, "src/value.test.ts"),
`import { it, expect } from "vitest"; import { value } from "./value"; it("checks current source", () => expect(value).toBe(1));\n`,
);
const git = (arguments_: string[]) =>
execute("git", arguments_, { cwd: root });
await git(["init", "-b", "main"]);
await git(["add", ".gitignore", "package.json", "vitest.config.ts", "src"]);
const commit = [
"-c",
"user.name=REA fixture",
"-c",
"user.email=fixture@example.test",
"commit",
"-m",
"fixture",
];
await git(commit);
const { stdout: baseline } = await git(["rev-parse", "HEAD"]);
await git(["update-ref", "refs/remotes/origin/main", baseline.trim()]);
await git(["switch", "-c", "regression"]);
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
await writeFile(
join(root, "src/value.test.ts"),
`import { it, expect } from "vitest"; import { value } from "./value"; it("checks current source", () => expect(value).toBe(2));\n`,
);
await git(["add", "src"]);
await git(commit);
expect((await git(["status", "--porcelain"])).stdout).toBe("");
const { stdout } = await execute(process.execPath, [runner, "changed"], {
cwd: root,
await expect(
testCommand(root, "focused", "src/missing.test.ts"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("ENOENT"),
});
expect(stdout).toContain("1 passed");
const explicit = await execute(
process.execPath,
[runner, "focused", "src/value.test.ts"],
{ cwd: root },
);
expect(explicit.stdout).toContain("1 passed");
}, 30_000);
await expect(
testCommand(root, "local", "tests/acceptance/runtime.test.ts"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("Use test:focused"),
});
});
});
+67 -3
View File
@@ -4,11 +4,13 @@ import { dirname, join } from "node:path";
import { describe, expect } from "vitest";
import {
CPU,
FILE_TYPE,
LC,
buildVersionCommand,
dylibCommand,
dyldEnvironmentCommand,
fatImage,
machoImage,
rpathCommand,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
@@ -178,14 +180,17 @@ describe("trace-dylib-resolution CLI", () => {
// A root below a symlinked directory that points outside the bundle.
const outside = await createTestTempDirectory("rea-dylib-outside-");
await writeFiles(outside, { Tool: machoImage({}) });
await symlink(outside, join(app, "Contents/Linked"));
await symlink(outside, join(app, "Contents/Linked"), "dir");
for (const [root, reason, message] of [
["../outside", "invalid_format", "Use a normalized path"],
["Contents/Info.plist", "invalid_value", "is not a Mach-O image"],
[
"Contents/Linked/Tool",
"invalid_value",
"resolves outside the analyzed root",
// Windows link text is outside the POSIX dyld path representation.
process.platform === "win32"
? "is not a regular file in the analyzed root"
: "resolves outside the analyzed root",
],
] as const) {
await expectRootInputError(cli, { app, root, reason, message });
@@ -376,7 +381,8 @@ cliTest(
},
);
describe.skipIf(process.getuid?.() === 0)(
// This permission fixture requires POSIX mode bits and a non-root caller.
describe.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"trace-dylib-resolution permissions",
() => {
cliTest(
@@ -471,6 +477,64 @@ cliTest(
},
);
cliTest(
"reports each same-named slice's own embedded dyld environment",
async ({ cli }) => {
// arm64e and arm64e.x1 slices both report the architecture name arm64e.
// A plain x86_64 slice keeps the bundle openable on x64 hosts.
for (const [settings, expected] of [
[[null, "DYLD_PRINT_RPATHS=1"], ["DYLD_PRINT_RPATHS=1"]],
[
["DYLD_PRINT_LIBRARIES=1", "DYLD_PRINT_RPATHS=1"],
["DYLD_PRINT_LIBRARIES=1", "DYLD_PRINT_RPATHS=1"],
],
] as const) {
const app = await fixtureApp();
await writeFiles(app, {
"Contents/MacOS/App": fatImage([
...[CPU.arm64e, CPU.arm64eX1].map((cpu, index) => {
const setting = settings[index];
return {
cpu,
bytes: machoImage({
cpu,
commands:
setting === null || setting === undefined
? []
: [dyldEnvironmentCommand(setting)],
}),
};
}),
{ cpu: CPU.x86_64, bytes: machoImage({ cpu: CPU.x86_64 }) },
]),
});
const result = await cli.run({
arguments: [
"trace-dylib-resolution",
app,
"--root",
"Contents/MacOS/App",
"--architecture",
"arm64e",
"--json",
],
environment: ENVIRONMENT,
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const trace = dylibResolutionResultSchema.parse(
parseEvidence(result.json).normalized_result,
);
expect(trace.roots).toHaveLength(2);
const environments = trace.findings
.filter(({ kind }) => kind === "dyld-environment-present")
.map(({ explanation }) =>
expected.filter((setting) => explanation.includes(setting)),
);
expect(environments).toEqual(expected.map((setting) => [setting]));
}
},
);
cliTest(
"retains definitive load findings for an explicitly selected app library root",
async ({ cli }) => {
@@ -0,0 +1,92 @@
import { describe, expect } from "vitest";
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
import { elf } from "../../../src/domain/binaryTarget.fixture.js";
/**
* A headless IDA supervisor that completes the MCP handshake and then leaves
* every tool call unanswered, as an `idb_open` still running auto-analysis
* would. It exits when REA closes its input.
*/
const UNRESPONSIVE_SUPERVISOR = `import { createInterface } from "node:readline";
const tools = ["idb_open", "idb_list", "idb_close", "server_health", "list_funcs",
"lookup_funcs", "find_regex", "decompile", "disasm", "callees", "xrefs_to"];
const send = (message) =>
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
for await (const line of createInterface({ input: process.stdin })) {
const request = JSON.parse(line);
if (request.method === "initialize")
send({ id: request.id, result: {
protocolVersion: request.params.protocolVersion,
capabilities: { tools: {} },
serverInfo: { name: "unresponsive-ida-fixture", version: "1" },
} });
else if (request.method === "tools/list")
send({ id: request.id, result: {
tools: tools.map((name) => ({ name, inputSchema: { type: "object" } })),
} });
}
`;
describe("headless IDA timeout through the one-shot CLI", () => {
workspaceCliTest(
"exits after a retained-cleanup failure instead of waiting on the supervisor",
async ({ cli, workspace }) => {
const supervisor = await workspace.write(
"supervisor.mjs",
UNRESPONSIVE_SUPERVISOR,
);
const workspaceRoot = await workspace.mkdir("ida-workspaces");
const registration = await workspace.write(
"ida-mcp.json",
JSON.stringify({
command: process.execPath,
args: [supervisor],
mode: "headless",
timeoutMs: 500,
workspaceRoot,
}),
);
const target = await workspace.write("target.elf", elf(2, 1, 62));
const result = await cli.run({
arguments: ["decompile", target, "main", "--json"],
environment: {
...workspace.environment,
REA_ANALYSIS_PROVIDER: "ida",
REA_IDA_MCP_CONFIG: registration,
REA_LOG_LEVEL: "silent",
},
timeoutMs: 30_000,
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "cleanup_incomplete",
details: {
provider_id: "ida",
cleanup: "incomplete",
resources: [expect.stringContaining(workspaceRoot)],
cleanup_error: {
details: {
diagnostics: {
upstream_sessions: {
state: "unverified",
sessions: [
{
session_id: expect.stringMatching(/^rea-/),
backend: "worker",
owned: null,
input_path: null,
},
],
},
},
},
},
},
});
},
);
});
+32
View File
@@ -561,3 +561,35 @@ describe("CLI result output surface", () => {
});
}, 60_000);
});
describe("streamed CLI filtered selections", () => {
it.each([
["raw_result", "json", "null\n"],
["raw_result", "jsonl", "null\n"],
["nested.value", "json", '{"nested":{"value":null}}\n'],
["missing", "json", "{}\n"],
["count", "json", "0\n"],
["enabled", "json", "false\n"],
] as const)(
"keeps the selected value of --filter-output %s in %s",
async (filter, format, expected) => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(chunk);
callback();
},
});
const output = createCliResultOutput(
["--format", format, "--filter-output", filter],
destination,
);
if (output === undefined) throw new Error("Missing JSON output surface");
await output.write(
{ raw_result: null, nested: { value: null }, count: 0, enabled: false },
{ command: "fixture", duration: "1ms", format },
);
expect(Buffer.concat(chunks).toString("utf8")).toBe(expected);
},
);
});
@@ -1,9 +1,13 @@
import { copyFile } from "node:fs/promises";
import { join } from "node:path";
import { join, resolve } from "node:path";
import { describe, expect } from "vitest";
import { z } from "zod";
import {
inspectMachoSchema,
listArchitecturesSchema,
} from "../../../src/domain/native/nativeInspection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -34,27 +38,68 @@ const resultSchema = z.object({
describe.skipIf(process.platform !== "darwin")(
"native Mach-O CLI with echoed path text",
() => {
cliTest(
"does not read load commands or symbols from the file name",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-macho-echo-");
const inspect = async (name: string) => {
const path = join(directory, name);
await copyFile("/usr/bin/true", path);
const result = await cli.run({
arguments: ["inspect-macho", path, "--json"],
environment,
});
expect(result.exitCode).toBe(0);
const { provenance: _provenance, ...facts } = resultSchema.parse(
result.json,
).normalized_result;
return facts;
};
const forged = await inspect(FORGED_NAME);
expect(forged).toEqual(await inspect("tool"));
expect(JSON.stringify(forged)).not.toMatch(/forged|4242/u);
},
);
const lipoName = "tool\narchitecture forged\n offset 123\n size 32";
for (const [facts, command, filename] of [
["load commands or symbols", "inspect-macho", FORGED_NAME],
["FAT architecture records", "inspect-macho", lipoName],
["FAT architecture inventory", "list-architectures", lipoName],
["thin-file framing", "inspect-macho", "tool\nNon-fat file: forged"],
] as const) {
cliTest(
`does not read ${facts} from the file name`,
async ({ cli, processes }) => {
const directory = await createTestTempDirectory(
"rea-native-cli-echo-",
);
const fixture = join(directory, "fat-fixture");
const compiled = await processes.run(
"/usr/bin/xcrun",
[
"clang",
"-arch",
"arm64",
"-arch",
"x86_64",
resolve("tests/conformance/c/fixture.c"),
"-o",
fixture,
],
{ timeoutMs: 30_000 },
);
expect(compiled.exitCode, compiled.stderr).toBe(0);
const inspect = async (name: string) => {
const path = join(directory, name);
await copyFile(fixture, path);
const result = await cli.run({
arguments: [command, path, "--json"],
environment,
});
expect(result.exitCode).toBe(0);
const { provenance: _provenance, ...facts } = resultSchema.parse(
result.json,
).normalized_result;
return facts;
};
const ordinary = await inspect("tool");
// Prove this comparison exercised FAT framing, independent of host binaries.
const architectures =
listArchitecturesSchema.shape.architectures.parse(
ordinary.architectures,
);
expect(architectures.total).toBeGreaterThan(1);
if (command === "inspect-macho") {
const selected =
inspectMachoSchema.shape.selected_architecture.parse(
ordinary.selected_architecture,
);
expect(selected.container_file_offset).toBeGreaterThan(0);
}
const forged = await inspect(filename);
expect(forged).toEqual(ordinary);
expect(JSON.stringify(forged)).not.toMatch(/forged|4242/u);
},
60_000,
);
}
},
);
@@ -21,14 +21,14 @@ const adHocProgram = async (directory: string, name: string) => {
describe.skipIf(process.platform !== "darwin")(
"native signature CLI with echoed path text",
() => {
cliTest(
"does not read signature fields from the file name codesign echoes",
async ({ cli }) => {
cliTest.for(["\n", "\r\n"])(
"does not read signature fields from the file name codesign echoes (%j)",
async (newline, { cli }) => {
const directory = await createTestTempDirectory("rea-signature-");
const forged = "Developer ID Application: Example (ABCDE12345)";
const program = await adHocProgram(
directory,
`tool\nAuthority=${forged}\nTeamIdentifier=ABCDE12345`,
`tool${newline}Authority=${forged}${newline}Identifier=forged${newline}TeamIdentifier=ABCDE12345`,
);
const unsignedName = await adHocProgram(
directory,
@@ -75,7 +75,7 @@ describe.skipIf(process.platform !== "darwin")(
normalized_result: {
identifier: expect.stringMatching(
new RegExp(
`^tool\\nAuthority=${forged.replace(/[()]/gu, "\\$&")}\\nTeamIdentifier=ABCDE12345-`,
`^tool${newline}Authority=${forged.replace(/[()]/gu, "\\$&")}${newline}Identifier=forged${newline}TeamIdentifier=ABCDE12345-`,
"u",
),
),
+37
View File
@@ -0,0 +1,37 @@
import { expect, it } from "vitest";
import { expectConfigurationRefusal, serveCli } from "./cliServeHarness.js";
it.each(["inspect-pcap-client", "inspect-pcap-capture"])(
"%s advertises a schema through the public CLI",
async (command) => {
const result = await serveCli([command, "--schema", "--json"]);
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout)).toBeTruthy();
},
);
it.each([
["inspect-pcap-client"],
["inspect-pcap-capture", "/nonexistent/capture.pcap"],
])("%s names the missing Wireshark tool to configure", async (...argv) => {
const result = await serveCli([...argv, "--json"], {
REA_TSHARK_COMMAND: "/nonexistent/tshark",
REA_CAPINFOS_COMMAND: "/nonexistent/capinfos",
});
expectConfigurationRefusal(
result,
"Cannot run selected tool /nonexistent/tshark",
);
expectConfigurationRefusal(result, "through absolute REA_TSHARK_COMMAND");
});
it("names a relative tool selection as configuration to fix", async () => {
const result = await serveCli(["inspect-pcap-client", "--json"], {
REA_TSHARK_COMMAND: "tshark",
});
expectConfigurationRefusal(
result,
"REA_TSHARK_COMMAND must be an absolute path to the tshark binary",
);
});
+30
View File
@@ -38,6 +38,36 @@ cliTest(
},
);
cliTest(
"rejects a 6502 image crossing the 16-bit boundary before provider startup",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-6502-cli-overflow-");
const path = join(root, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
const result = await cli.run({
arguments: [
"inspect",
path,
"--target-format",
"raw-binary",
"--architecture",
"6502",
"--entry-point",
"0xffff",
"--provider",
"ghidra",
"--json",
],
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { reason: expect.stringContaining("6502 address width") },
});
},
);
cliTest(
"rejects an unaligned AArch64 entry before provider startup",
async ({ cli }) => {
@@ -0,0 +1,118 @@
import { mkdir, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { describe, expect } from "vitest";
import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
// Reference-source reads require no-follow opens; Windows reports unsupported.
describe.skipIf(process.platform === "win32")(
"compiled reference-source directory imports",
() => {
cliTest(
"resolves directory spellings without selecting similarly named files",
async ({ cli }) => {
const workspace = await createTestTempDirectory(
"rea-reference-directory-imports-",
);
const root = join(workspace, "source");
const imports = [
["slash.cjs", "./lib/", "lib/index.js"],
["dot.cjs", "./lib/.", "lib/index.js"],
["self.cjs", ".", "index.js"],
["self-slash.cjs", "./", "index.js"],
["nested/parent.cjs", "..", "index.js"],
["nested/parent-slash.cjs", "../", "index.js"],
["direct.cjs", "./lib.js", "lib.js"],
["fallback.cjs", "./fallback", "fallback/index.js"],
["legacy-order.cjs", "./dep", "dep/index.js"],
] as const;
const unresolved = [
["missing.cjs", "./missing/", "missing/"],
["escape.cjs", "../outside/", "../outside/"],
["main.ts", "./folder.js/.", "folder.js"],
] as const;
const files = new Map<string, string>([
["index.js", 'module.exports = "root index";\n'],
["lib/index.js", 'module.exports = "library index";\n'],
["lib.js", 'module.exports = "sibling JavaScript file";\n'],
["lib.ts", 'export const value = "sibling TypeScript file";\n'],
["fallback/index.js", 'module.exports = "fallback index";\n'],
["dep/index.js", 'module.exports = "existing index priority";\n'],
["dep.cjs", 'module.exports = "later CommonJS candidate";\n'],
[
"folder.ts",
'export const value = "emitted filename counterpart";\n',
],
["missing.js", 'module.exports = "not a directory";\n'],
...[...imports, ...unresolved].map(
([path, specifier]) =>
[path, `require(${JSON.stringify(specifier)});\n`] as const,
),
]);
await Promise.all(
[...files].map(async ([path, contents]) => {
const target = join(root, path);
await mkdir(dirname(target), { recursive: true });
await writeFile(target, contents);
}),
);
const outside = join(workspace, "outside", "index.js");
await mkdir(dirname(outside), { recursive: true });
await writeFile(outside, 'module.exports = "outside import root";\n');
// Node's loader establishes each fixture's meaning independently.
for (const [path, specifier, target] of imports)
expect(createRequire(join(root, path)).resolve(specifier)).toBe(
join(root, target),
);
expect(() =>
createRequire(join(root, "missing.cjs")).resolve("./missing/"),
).toThrow();
expect(() =>
createRequire(join(root, "main.ts")).resolve("./folder.js/."),
).toThrow();
expect(
createRequire(join(root, "escape.cjs")).resolve("../outside/"),
).toBe(outside);
const result = await cli.run({
arguments: ["import-reference-source", root, "--json"],
environment: {
HOME: workspace,
XDG_CONFIG_HOME: workspace,
XDG_CACHE_HOME: workspace,
},
});
expect(result.exitCode).toBe(0);
const graph = historicalSourceGraphSchema.parse(result.json);
expect(graph.parse_failures).toEqual([]);
expect(graph.relationships).toHaveLength(
imports.length + unresolved.length,
);
for (const [from, , to] of imports)
expect.soft(graph.relationships, from).toContainEqual({
from_path: from,
to,
kind: "requires",
resolution: "internal",
parse_state: "parsed",
});
for (const [from, , to] of unresolved)
expect.soft(graph.relationships, from).toContainEqual({
from_path: from,
to,
kind: "requires",
resolution: "unresolved",
parse_state: "parsed",
});
expect(
graph.entries.some((entry) => entry.path.includes("outside")),
).toBe(false);
},
);
},
);
@@ -1,3 +1,5 @@
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { describe, expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -62,3 +64,42 @@ describe("scenario CLI schema diagnostics", () => {
});
});
});
for (const field of [
"executable_path",
"application_path",
"application_root",
] as const) {
cliTest(`names the unresolved Electron ${field}`, async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-path-");
const missing = join(root, "missing");
const result = await cli.run({
arguments: [
"capture-electron-scenario",
JSON.stringify({
executable_path: process.execPath,
application_path: root,
application_root: root,
actions: [],
[field]: missing,
}),
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: [field],
reason: "invalid_value",
message: expect.stringContaining("ENOENT"),
},
],
},
});
expect(JSON.stringify(result.json)).toContain(missing);
});
}
+6
View File
@@ -30,6 +30,9 @@ it.each([
silentLogger,
{},
{
inspectDecoders: async () => {
throw new Error("Unexpected discovery call");
},
decode: async () => {
called = true;
throw new Error("Must not decode");
@@ -84,6 +87,9 @@ it.each([false, true])(
silentLogger,
{},
{
inspectDecoders: async () => {
throw new Error("Unexpected discovery call");
},
decode: async () => err(original),
close: async () => {
await Promise.resolve();
@@ -0,0 +1,88 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import {
snapshotBinding,
snapshotTarget,
} from "../../../src/domain/analysisSnapshot.js";
import {
ANALYSIS_SNAPSHOT_PROFILE,
ANALYSIS_SNAPSHOT_TARGET,
} from "../../../src/domain/analysisSnapshot.fixture.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe.each([
{ mode: "native", paddingBytes: 0 },
{ mode: "streamed", paddingBytes: 9 * 1024 * 1024 },
])("analysis snapshot input ($mode)", ({ paddingBytes }) => {
it.each(["[]", "null", "5", '"x"', "true"])(
"classifies a readable %s root as invalid content, not an I/O failure",
async (document) => {
const root = await createTestTempDirectory("rea-snapshot-root-");
const path = join(root, "snapshot.json");
const encoded = `${" ".repeat(paddingBytes)}${document}`;
await writeFile(path, encoded);
const loaded = await readAnalysisSnapshot(path);
if (loaded.ok) throw new Error("Expected a non-object root rejection");
const projected = projectAnalysisError(loaded.error);
expect(projected).toMatchObject({
code: "evidence_integrity_mismatch",
details: { reason: "invalid-json" },
});
expect(projected.message).toContain("Repair or recreate");
expect(loaded.error.cause).toMatchObject({
message: "JSON document root must be an object",
});
expect(await readFile(path, "utf8")).toBe(encoded);
},
);
it("retains syntax and snapshot-member validation and loads valid objects", async () => {
const root = await createTestTempDirectory("rea-snapshot-validation-");
const path = join(root, "snapshot.json");
const prefix = " ".repeat(paddingBytes);
await writeFile(path, `${prefix}[`);
expect(await readAnalysisSnapshot(path)).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "invalid-json" },
});
await writeFile(path, `${prefix}{}`);
expect(await readAnalysisSnapshot(path)).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
const snapshot = {
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
binding: snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE),
entries: [],
workflow_entries: [],
evidence_bundle: createEvidenceBundle([]),
};
await writeFile(path, `${prefix}${JSON.stringify(snapshot)}`);
expect(await readAnalysisSnapshot(path)).toEqual({
ok: true,
value: snapshot,
});
});
});
it("keeps file-selection failures distinct from invalid snapshot contents", async () => {
const root = await createTestTempDirectory("rea-snapshot-selection-");
for (const [path, reason] of [
[join(root, "missing.json"), "missing"],
[root, "not-file"],
] as const) {
const loaded = await readAnalysisSnapshot(path);
if (loaded.ok) throw new Error("Expected a file-selection failure");
expect(projectAnalysisError(loaded.error)).toMatchObject({
code: "invalid_request",
details: { reason },
});
}
});
@@ -38,8 +38,19 @@ it("completes an empty ZIP extraction with an empty identity", async () => {
expect(await readdir(output)).toEqual([]);
});
const legacyControlNames = [
["legacy ASCII control", Buffer.from("Icon\r"), false, "Icon\r"],
[
"legacy CP437 control",
Buffer.from([0x82, 0x09, 0x7f, 0x2e, 0x61]),
false,
"é\t\u007F.a",
],
] as const;
it.each([
["legacy CP437", Buffer.from([0x82, 0x2e, 0x74, 0x78, 0x74]), false, "é.txt"],
...legacyControlNames,
[
"EFS with leading U+FEFF",
Buffer.from([0xef, 0xbb, 0xbf, 0x61, 0x62]),
@@ -68,6 +79,38 @@ it.each([
},
);
it.skipIf(process.platform === "win32").each(legacyControlNames)(
"extracts %s ZIP members under their stored names",
async (_label, rawName, utf8Flag, logicalPath) => {
const root = await createTestTempDirectory("rea-zip-extracted-name-");
const path = join(root, "names.zip");
await writeSingleEntryZip(path, "x.txt");
const archive = await readFile(path);
await writeFile(
path,
rewriteSingleEntryName(archive, "x.txt", rawName, utf8Flag),
);
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const output = join(root, "output");
const result = await withArtifactClient(target.value, (client) =>
client.execute("extract_artifact", { output_root: output }),
);
if (!result.ok) throw result.error;
const extraction = artifactExtractionResultSchema.parse(
result.value.result,
);
expect(
extraction.artifacts.map(({ relative_path }) => relative_path),
).toEqual([logicalPath]);
expect(await readdir(output)).toEqual([logicalPath]);
expect(await readFile(join(output, logicalPath), "utf8")).toBe(
"member bytes",
);
},
);
it("preserves valid Info-ZIP Unicode Path overrides", async () => {
const root = await createTestTempDirectory("rea-zip-unicode-path-");
const path = join(root, "unicode-path.zip");
@@ -323,16 +366,11 @@ it("rejects overlapping ZIP member data ranges through artifact inventory", asyn
bytes.writeUInt32LE(firstLocalOffset, second + 42);
await writeFile(path, bytes);
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const result = await withArtifactClient(target.value, (client) =>
client.execute("inventory_artifact", {}),
await expectInventoryFailure(
path,
"format",
"ZIP archive is malformed: Overlapping entry found",
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
});
});
it("preserves encrypted-member and corrupt-CRC observations", async () => {
@@ -395,16 +433,11 @@ it("preserves encrypted-member and corrupt-CRC observations", async () => {
bytes[dataOffset] = firstByte ^ 1;
await writeFile(corruptPath, bytes);
const corruptTarget = await parseBinaryTarget(corruptPath);
if (!corruptTarget.ok) throw corruptTarget.error;
const corruptResult = await withArtifactClient(
corruptTarget.value,
(client) => client.execute("inventory_artifact", {}),
await expectInventoryFailure(
corruptPath,
"format",
"ZIP archive is malformed: Invalid compressed data",
);
expect(corruptResult).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
});
});
it("rejects a truncated ZIP through artifact inventory", async () => {
@@ -412,17 +445,51 @@ it("rejects a truncated ZIP through artifact inventory", async () => {
const path = join(root, "truncated.zip");
await writeFile(path, Buffer.from([0x50, 0x4b, 0x03, 0x04]));
await expectInventoryFailure(
path,
"format",
"ZIP archive is malformed: File format is not recognized",
);
});
it("reports an unsupported ZIP compression method as unavailable", async () => {
const root = await createTestTempDirectory("rea-zip-method-");
const path = join(root, "lzma.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("data.txt", new TextReader("member bytes"), { level: 0 });
const bytes = Buffer.from(await writer.close());
// Declare LZMA (14) in both headers; REA reads only stored and Deflate data.
const localHeader = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
const centralHeader = bytes.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]));
if (localHeader < 0 || centralHeader < 0)
throw new Error("Expected ZIP local and central headers");
bytes.writeUInt16LE(14, localHeader + 8);
bytes.writeUInt16LE(14, centralHeader + 10);
await writeFile(path, bytes);
await expectInventoryFailure(
path,
"unavailable",
"ZIP archive uses an unsupported feature: Compression method not supported",
);
});
/** Inventory one archive through the provider and expect a typed failure. */
const expectInventoryFailure = async (
path: string,
reason: string,
detail: string,
): Promise<void> => {
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const result = await withArtifactClient(target.value, (client) =>
client.execute("inventory_artifact", {}),
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
error: { _tag: "ArtifactOperationError", reason, detail },
});
});
};
const writeSingleEntryZip = async (
path: string,
+339 -12
View File
@@ -1,4 +1,5 @@
import {
chmod,
cp,
mkdir,
readFile,
@@ -7,6 +8,7 @@ import {
writeFile,
} from "node:fs/promises";
import { dirname, join, matchesGlob } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, expect, it } from "vitest";
import { parse } from "yaml";
@@ -78,12 +80,13 @@ async function classify(
head: string,
event = "pull_request",
full = false,
skipFull = false,
) {
const output = join(directory, "scope-output");
await writeFile(output, "");
const result = await execFileAsync(
process.execPath,
[new URL("../../../scripts/ci/plan.mjs", import.meta.url).pathname],
[fileURLToPath(new URL("../../../scripts/ci/plan.mjs", import.meta.url))],
{
cwd: directory,
env: {
@@ -92,6 +95,7 @@ async function classify(
HEAD_SHA: head,
GITHUB_EVENT_NAME: event,
CI_FULL: String(full),
CI_SKIP_FULL: String(skipFull),
GITHUB_OUTPUT: output,
},
},
@@ -99,6 +103,21 @@ async function classify(
return z.record(z.string(), z.unknown()).parse(JSON.parse(result.stdout));
}
it("reuses only scheduled qualification and preserves every explicit full request", async () => {
const { directory, base } = await fixture();
const reused = await classify(directory, base, base, "schedule", false, true);
expect(reused.tier).toBe("reused");
const { CI_FLAGS } = await loadScopes();
for (const flag of CI_FLAGS) expect(reused[flag]).toBe(false);
for (const event of ["workflow_dispatch", "pull_request", "schedule"])
expect(
(await classify(directory, base, base, event, true, true)).tier,
).toBe("full");
expect(
(await classify(directory, base, base, "push", false, true)).tier,
).toBe("fast");
});
it("keeps every translated root README and authored guide on the documentation lane", async () => {
const { directory, base } = await fixture();
const readmes = (await readdir(new URL("../../../", import.meta.url))).filter(
@@ -118,6 +137,64 @@ it("keeps every translated root README and authored guide on the documentation l
});
});
it.each([
"job-timings.mjs",
"job-timings-batch.mjs",
"test-report.mjs",
"test-timing-reporter.mjs",
"test-history.mjs",
])(
"keeps portable CI reporter %s on static checks and portable tests",
async (name) => {
const { directory, base } = await fixture();
const head = await change(directory, [`scripts/ci/${name}`]);
const plan = await classify(directory, base, head);
const { CI_FLAGS } = await loadScopes();
expect(plan.code).toBe(true);
for (const flag of CI_FLAGS)
if (flag !== "code") expect(plan[flag]).toBe(false);
},
);
it("preserves a provider lane when a portable CI reporter changes with provider source", async () => {
const { directory, base } = await fixture();
const head = await change(directory, [
"scripts/ci/test-report.mjs",
"src/evm/Example.ts",
]);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
evm: true,
browser: false,
package: false,
});
});
it("keeps unknown CI scripts on complete qualification", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["scripts/ci/new-qualification.mjs"]);
const plan = await classify(directory, base, head);
const { CI_FLAGS } = await loadScopes();
for (const flag of CI_FLAGS) expect(plan[flag]).toBe(true);
});
it("emits an observational owner proposal without changing ordinary or full portable execution", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["src/evm/Example.ts"]);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
testSelection: { mode: "candidate", owners: ["evm"] },
});
expect(
await classify(directory, base, head, "pull_request", true),
).toMatchObject({
code: true,
testSelection: { mode: "full", owners: [] },
});
const output = await readFile(join(directory, "scope-output"), "utf8");
expect(output).toContain('test_selection={"version":1,"mode":"full"');
});
it("does not charge a documentation PR for unrelated implementation updates on main", async () => {
const { directory, base } = await fixture();
await git(directory, ["switch", "-c", "docs/change"]);
@@ -161,13 +238,148 @@ it("retains complete checks when implementation is renamed into documentation",
});
});
it("retains the complete main-push baseline even for documentation", async () => {
it("keeps main pushes scoped when a successful ancestor baseline is available", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["README_ja.md"]);
expect(await classify(directory, base, head, "push")).toMatchObject({
tier: "fast",
code: false,
package: false,
docs: true,
matrix: {
include: [
{ os: "ubuntu-latest", platform: "linux", architecture: "x64" },
],
},
});
});
it("includes changes from earlier cancelled pushes since the last successful baseline", async () => {
const { directory, base } = await fixture();
await change(directory, ["src/evm/client.ts"]);
const head = await change(directory, ["README.md"]);
expect(await classify(directory, base, head, "push")).toMatchObject({
tier: "fast",
code: true,
evm: true,
runtime: true,
package: false,
});
});
it.each(["", "not-a-commit"])(
"fails closed to all lanes for a missing or invalid push baseline (%s)",
async (base) => {
const { directory } = await fixture();
const head = await change(directory, ["README.md"]);
const plan = await classify(directory, base, head, "push");
expect(plan).toMatchObject({
tier: "fast",
code: true,
package: true,
evm: true,
browser: true,
reasons: expect.arrayContaining([expect.stringContaining("baseline")]),
});
const { CI_FLAGS } = await loadScopes();
for (const flag of CI_FLAGS) expect(plan[flag]).toBe(true);
},
);
it("selects only a trusted successful ancestor from recent CI push runs", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["src/evm/client.ts"]);
const bin = join(directory, "fake-bin");
await mkdir(bin);
const gh = join(bin, "gh");
await writeFile(gh, '#!/bin/sh\ncat "$GH_FIXTURE_RESPONSE"\n');
await chmod(gh, 0o755);
const response = join(directory, "runs.json");
await writeFile(
response,
JSON.stringify({
workflow_runs: [
{
event: "push",
conclusion: "success",
head_branch: "main",
head_repository: { full_name: "untrusted/fork" },
head_sha: base,
},
{
event: "push",
conclusion: "success",
head_branch: "main",
head_repository: { full_name: "owner/repo" },
head_sha: base,
},
],
}),
);
const output = join(directory, "baseline-output");
const result = await execFileAsync(
process.execPath,
[new URL("../../../scripts/ci/baseline.mjs", import.meta.url).pathname],
{
cwd: directory,
env: {
...process.env,
PATH: `${bin}:${process.env.PATH}`,
GH_FIXTURE_RESPONSE: response,
CI_REPOSITORY: "owner/repo",
CI_DEFAULT_BRANCH: "main",
HEAD_SHA: head,
GITHUB_OUTPUT: output,
},
},
);
expect(JSON.parse(result.stdout)).toEqual({ base, reason: "" });
expect(await readFile(output, "utf8")).toBe(`base=${base}\nreason=\n`);
});
it("returns an empty baseline when GitHub lookup fails", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["src/evm/client.ts"]);
const bin = join(directory, "fake-bin");
await mkdir(bin);
const gh = join(bin, "gh");
await writeFile(gh, "#!/bin/sh\nexit 1\n");
await chmod(gh, 0o755);
const result = await execFileAsync(
process.execPath,
[new URL("../../../scripts/ci/baseline.mjs", import.meta.url).pathname],
{
cwd: directory,
env: {
...process.env,
PATH: `${bin}:${process.env.PATH}`,
CI_REPOSITORY: "owner/repo",
CI_DEFAULT_BRANCH: "main",
HEAD_SHA: head,
},
},
);
expect(JSON.parse(result.stdout)).toMatchObject({
base: "",
reason: expect.stringContaining("Could not read"),
});
expect(head).not.toBe(base);
});
it("fails closed when the successful push baseline is not an ancestor", async () => {
const { directory, base } = await fixture();
await git(directory, ["switch", "-c", "unrelated"]);
const unrelated = await change(directory, ["other.txt"]);
await git(directory, ["switch", "main"]);
const head = await change(directory, ["README.md"]);
expect(await classify(directory, unrelated, head, "push")).toMatchObject({
tier: "fast",
code: true,
package: true,
evm: true,
browser: true,
});
expect(head).not.toBe(base);
});
it("fails classification rather than treating an invalid Git comparison as a scope", async () => {
@@ -207,7 +419,8 @@ it("retains native Inspector verification on every documented package host", asy
);
expect(packageInspector.if).toBeUndefined();
expect(
(await classify((await fixture()).directory, "", "", "push")).matrix,
(await classify((await fixture()).directory, "", "", "workflow_dispatch"))
.matrix,
).toEqual({
include: [
{ os: "ubuntu-latest", platform: "linux", architecture: "x64" },
@@ -227,7 +440,14 @@ it("retains native Inspector verification on every documented package host", asy
it.each([
[
"src/evm/client.ts",
{ code: true, runtime: true, evm: true, browser: false, package: false },
{
code: true,
runtime: true,
evm: true,
browser: false,
package: false,
sqlite: false,
},
],
[
"src/browser/execution/evaluate.ts",
@@ -299,6 +519,10 @@ it.each([
"src/windows/Example.ts",
{ code: true, runtime: true, package: true, apple: false, evm: false },
],
[
"src/domain/javascript/javascriptRuntimeStaticCandidates.ts",
{ code: true, runtime: true, package: true, javascript_recovery: true },
],
["install.sh", { code: true, runtime: true, package: true, evm: false }],
[
".agents/skills/reverse-engineer-anything/SKILL.md",
@@ -328,6 +552,38 @@ it.each([
"src/process/ProcessOwnership.test.ts",
{ code: true, package: true, apple: false, evm: false, browser: false },
],
[
"src/sqlite/SqliteDatabaseProvider.ts",
{ code: true, sqlite: true, runtime: true, package: false },
],
[
"src/application/sqlite/SqliteDatabaseService.test.ts",
{ code: true, sqlite: true, runtime: false },
],
[
"tests/boundary/sqlite/sqliteDatabaseProvider.test.ts",
{ code: true, sqlite: true, runtime: false },
],
[
"tests/fixtures/sqlite/database.ts",
{ code: true, sqlite: true, runtime: false },
],
["tests/acceptance/sqliteDatabaseCli.test.ts", { code: true, sqlite: true }],
[
"tests/boundary/mcp/serverLifecycleMcp.test.ts",
{ code: true, sqlite: true },
],
["src/process/OwnedCommand.ts", { code: true, sqlite: true, runtime: true }],
["src/server/createServer.ts", { code: true, sqlite: true, runtime: true }],
[
"src/contracts/toolContracts.ts",
{ code: true, sqlite: true, runtime: true },
],
[
"src/domain/analysisErrorProjection.ts",
{ code: true, sqlite: true, runtime: true },
],
["src/domain/javascript/example.ts", { code: true, sqlite: false }],
])("selects the appropriate lanes for %s", async (path, expected) => {
const { directory, base } = await fixture();
const head = await change(directory, [path]);
@@ -370,6 +626,52 @@ it("scopes package script edits while retaining broad dependency checks", async
});
});
it.each(["test:sqlite", "test:sqlite:run"])(
"routes %s script changes to the SQLite runtime matrix",
async (script) => {
const { directory } = await fixture();
const base = await change(
directory,
["package.json"],
JSON.stringify({ scripts: { [script]: "vitest run" } }),
);
const head = await change(
directory,
["package.json"],
JSON.stringify({
scripts: { [script]: "vitest run --reporter=default" },
}),
);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
sqlite: true,
evm: false,
package: false,
});
},
);
it("keeps unrelated test script changes off the SQLite runtime matrix", async () => {
const { directory } = await fixture();
const base = await change(
directory,
["package.json"],
JSON.stringify({ scripts: { "test:domain": "vitest run src/domain" } }),
);
const head = await change(
directory,
["package.json"],
JSON.stringify({
scripts: { "test:domain": "vitest run src/domain --reporter=default" },
}),
);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
sqlite: false,
evm: false,
});
});
it.each([
["browser", "real-browser"],
["binary_layout", "real-binary-layout"],
@@ -386,7 +688,9 @@ it.each([
async (scope, name) => {
const workflow = z
.object({
on: z.object({ workflow_call: z.null() }).passthrough(),
on: z
.object({ workflow_call: z.object({}).passthrough().nullable() })
.passthrough(),
})
.parse(
parse(
@@ -423,10 +727,19 @@ it.each([
);
it("rejects skipped selected work while allowing unselected lanes to skip", async () => {
const command = new URL("../../../scripts/ci/required.mjs", import.meta.url)
.pathname;
const command = fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
);
const { CI_FLAGS } = await loadScopes();
const jobs = {
changes: { result: "success", outputs: { evm: "true" } },
changes: {
result: "success",
outputs: {
...Object.fromEntries(CI_FLAGS.map((flag) => [flag, "false"])),
tier: "fast",
evm: "true",
},
},
static: { result: "success" },
test: { result: "success" },
evm: { result: "success" },
@@ -462,7 +775,10 @@ it.each([
"src/process/capture/example.test.ts",
{ code: true, runtime: false, browser: false, package: false },
],
[".nvmrc", { code: true, package: true, browser: true, evm: true }],
[
".nvmrc",
{ code: true, package: true, browser: true, evm: true, sqlite: true },
],
[
"tsconfig.build.json",
{ code: true, package: true, browser: true, evm: true },
@@ -599,8 +915,10 @@ it.each(["workflow_dispatch", "schedule"])(
async (event) => {
const { directory, base } = await fixture();
expect(await classify(directory, base, base, event)).toMatchObject({
tier: "full",
code: true,
package: true,
sqlite: true,
evm: true,
browser: true,
});
@@ -614,7 +932,14 @@ it("honors ci:full for successive PR revisions", async () => {
for (const head of [first, second]) {
expect(
await classify(directory, base, head, "pull_request", true),
).toMatchObject({ code: true, package: true, evm: true, browser: true });
).toMatchObject({
tier: "full",
code: true,
package: true,
sqlite: true,
evm: true,
browser: true,
});
}
});
@@ -654,7 +979,7 @@ const INTEL_HOST = {
architecture: "x64",
};
it("keeps macOS x64 package verification for ci:full and non-PR events", async () => {
it("keeps macOS x64 package verification only for full qualification", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["src/windows/Example.ts"]);
const matrix = z.object({ include: z.array(z.unknown()) });
@@ -665,7 +990,8 @@ it("keeps macOS x64 package verification for ci:full and non-PR events", async (
expect(pullRequest).toHaveLength(3);
expect(pullRequest).not.toContainEqual(INTEL_HOST);
expect(await hosts("pull_request", true)).toContainEqual(INTEL_HOST);
for (const event of ["push", "schedule", "workflow_dispatch"])
expect(await hosts("push", false)).not.toContainEqual(INTEL_HOST);
for (const event of ["schedule", "workflow_dispatch"])
expect(await hosts(event, false)).toContainEqual(INTEL_HOST);
});
@@ -678,6 +1004,7 @@ const workflowFile = async (name: string): Promise<unknown> =>
);
const scopesSchema = z.object({
CI_FLAGS: z.array(z.string()),
SCOPES: z.record(z.string(), z.array(z.string())),
MANUAL_VERIFIERS: z.array(z.string()),
});
@@ -0,0 +1,243 @@
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 {
executeWorkflowFixture,
workflowGit,
} from "../../support/workflowGit.js";
const reporter = fileURLToPath(
new URL("../../../scripts/ci/job-timings.mjs", import.meta.url),
);
it("merges paginated jobs, reports elapsed metrics, and preserves raw responses", async () => {
const fixture = await createFixture([
{
total_count: 4,
jobs: [
{
name: "Build package",
workflow_name: "CI",
status: "completed",
conclusion: "success",
created_at: "2026-10-13T00:00:00Z",
started_at: "2026-10-13T00:00:10Z",
completed_at: "2026-10-13T00:01:10Z",
steps: [
{
name: "Install dependencies (npm ci)",
started_at: "2026-10-13T00:00:10Z",
completed_at: "2026-10-13T00:00:40Z",
},
{
name: "Upload artifact",
started_at: "2026-10-13T00:00:40Z",
completed_at: "2026-10-13T00:00:41Z",
},
],
},
],
},
{
total_count: 4,
jobs: [
{
name: "Queued lane",
status: "queued",
created_at: "2026-10-13T00:00:00Z",
started_at: "2026-10-13T00:00:00Z",
completed_at: null,
steps: [],
},
{
name: "Running lane",
status: "in_progress",
created_at: "2026-10-13T00:00:00Z",
started_at: "2026-10-13T00:00:15Z",
completed_at: null,
steps: [
{
name: "Download artifacts",
started_at: "2026-10-13T00:00:20Z",
completed_at: "2026-10-13T00:00:22Z",
},
],
},
{
name: "Skipped lane",
status: "completed",
conclusion: "skipped",
created_at: "2026-10-13T00:00:00Z",
started_at: "2026-10-13T00:00:00Z",
completed_at: "2026-10-13T00:00:00Z",
steps: [],
},
],
},
]);
const result = await runReporter(fixture);
const report = JSON.parse(
await readFile(join(fixture.outputDirectory, "report.json"), "utf8"),
);
expect(report.run.snapshot).toContain("partial");
expect(report.counts).toMatchObject({
jobs: 4,
completed: 2,
skipped: 1,
queueUnknown: 2,
executionUnknown: 3,
completedExecutionUnknown: 0,
});
expect(report.aggregates.queueSeconds).toMatchObject({
count: 2,
p50: 10,
p95: 15,
});
expect(report.aggregates.completedExecutionSeconds).toMatchObject({
count: 1,
p50: 60,
p95: 60,
});
expect(report.aggregates.summedCompletedJobElapsedSeconds).toMatchObject({
value: 60,
knownCount: 1,
unknownCount: 0,
label: expect.stringContaining("not CPU time"),
});
expect(report.jobs[1].queue).toEqual({
seconds: null,
reason: "job start is not established by its status",
});
expect(report.jobs[3].queue).toEqual({
seconds: null,
reason: "job was skipped",
});
expect(report.jobs[3].execution).toEqual({
seconds: null,
reason: "job was skipped",
});
expect(report.stepCosts.npmCi[0].duration.seconds).toBe(30);
expect(report.stepCosts.artifactUpload[0].duration.seconds).toBe(1);
expect(report.stepCosts.artifactDownload[0].duration.seconds).toBe(2);
expect(report.stepCostInterpretation).toContain(
"not total artifact transfer costs",
);
expect(report.cpuSeconds).toBeUndefined();
expect(result.stdout).toContain("4 job timing records");
expect(
await readFile(join(fixture.outputDirectory, "jobs.json"), "utf8"),
).toBe(fixture.raw);
const summary = await readFile(fixture.summary, "utf8");
expect(summary).toContain("point-in-time snapshot");
expect(summary).toContain("unknown");
expect(summary).toContain("not CPU time");
expect(summary).toContain("60 s");
expect(summary).toContain("not total artifact transfer costs");
const args = JSON.parse(await readFile(fixture.args, "utf8"));
expect(args).toEqual([
"api",
"--paginate",
"--slurp",
"repos/example/rea/actions/runs/42/attempts/2/jobs?per_page=100",
]);
});
it("marks invalid and out-of-order timestamps unknown instead of emitting negative durations", async () => {
const fixture = await createFixture([
{
jobs: [
{
name: "Invalid dates",
status: "completed",
created_at: "not-a-date",
started_at: "2026-10-13T00:00:10Z",
completed_at: "2026-10-13T00:00:05Z",
steps: [],
},
],
},
]);
await runReporter(fixture);
const report = JSON.parse(
await readFile(join(fixture.outputDirectory, "report.json"), "utf8"),
);
expect(report.jobs[0].queue).toEqual({
seconds: null,
reason: "invalid timestamp",
});
expect(report.jobs[0].execution).toEqual({
seconds: null,
reason: "timestamps out of order",
});
expect(report.counts.completedExecutionUnknown).toBe(1);
expect(report.aggregates.summedCompletedJobElapsedSeconds).toMatchObject({
value: null,
unknownCount: 1,
});
});
it("fails on malformed pages or a failed GitHub API request", async () => {
const malformed = await createFixture([{ jobs: "not-an-array" }]);
await expect(runReporter(malformed)).rejects.toThrow();
await expect(
readFile(join(malformed.outputDirectory, "jobs.json"), "utf8"),
).resolves.toBe(malformed.raw);
const failedApi = await createFixture([], { exitCode: 1 });
await expect(runReporter(failedApi)).rejects.toThrow();
});
async function createFixture(
pages: unknown[],
{ exitCode = 0 }: { exitCode?: number } = {},
) {
const directory = await createTestTempDirectory("rea-ci-job-timings-");
await workflowGit(directory, ["init", "--initial-branch=main"]);
const fakeBin = join(directory, "bin");
await mkdir(fakeBin);
const raw = JSON.stringify(pages);
const rawPath = join(directory, "gh-response.json");
const args = join(directory, "gh-args.json");
await writeFile(rawPath, raw);
const fakeGh = join(fakeBin, "gh");
await writeFile(
fakeGh,
`#!/usr/bin/env node\nconst fs = require("node:fs");\nfs.writeFileSync(process.env.CI_GH_ARGS, JSON.stringify(process.argv.slice(2)));\nprocess.stdout.write(fs.readFileSync(process.env.CI_GH_RESPONSE, "utf8"));\nprocess.exitCode = ${String(exitCode)};\n`,
);
await chmod(fakeGh, 0o755);
const outputDirectory = join(directory, ".cache", "ci-job-timings");
const summary = join(directory, "summary.md");
await writeFile(summary, "");
return {
directory,
fakeBin,
raw,
rawPath,
args,
outputDirectory,
summary,
};
}
function runReporter(fixture: Awaited<ReturnType<typeof createFixture>>) {
return executeWorkflowFixture(process.execPath, [reporter], {
cwd: fixture.directory,
env: {
...process.env,
PATH: `${fixture.fakeBin}${delimiter}${process.env.PATH ?? ""}`,
CI_REPOSITORY: "example/rea",
CI_JOB_TIMINGS_DIRECTORY: fixture.outputDirectory,
CI_GH_ARGS: fixture.args,
CI_GH_RESPONSE: fixture.rawPath,
CI_TIMING_RUN_ID: "42",
CI_TIMING_RUN_ATTEMPT: "2",
GITHUB_STEP_SUMMARY: fixture.summary,
},
});
}
@@ -0,0 +1,288 @@
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { executeWorkflowFixture } from "../../support/workflowGit.js";
const batchScript = fileURLToPath(
new URL("../../../scripts/ci/job-timings-batch.mjs", import.meta.url),
);
it("collects the latest attempt for recent completed CI and Release runs into a bounded manifest", async () => {
const recent = new Date().toISOString();
const fixture = await createFixture([
{
workflow_runs: [
{
id: 42,
run_attempt: 3,
status: "completed",
conclusion: "failure",
created_at: new Date(Date.parse(recent) + 1_000).toISOString(),
},
{
id: 41,
run_attempt: 1,
status: "completed",
conclusion: "cancelled",
created_at: recent,
},
],
},
{
workflow_runs: [
{
id: 43,
run_attempt: 2,
status: "completed",
conclusion: "success",
created_at: new Date(Date.parse(recent) + 2_000).toISOString(),
},
],
},
[
{
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: [],
},
],
},
],
]);
const result = await runBatch(fixture);
const manifest = JSON.parse(
await readFile(
join(fixture.outputDirectory, "batch-manifest.json"),
"utf8",
),
);
const calls = JSON.parse(await readFile(fixture.calls, "utf8"));
expect(result.stdout).toContain("3 collected runs");
expect(
await readFile(join(fixture.directory, "summary.md"), "utf8"),
).toContain("collected 3 of 3");
expect(manifest.selection).toMatchObject({
lookbackHours: 24,
maxRunsPerWorkflow: 100,
exhaustive: false,
});
expect(manifest.coverage).toMatchObject({
workflowsQueried: ["CI", "Release"],
selectedRuns: 3,
collectedRuns: 3,
});
expect(manifest.truncation).toEqual([]);
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" },
]);
expect(manifest.runs).toEqual(
expect.arrayContaining([
expect.objectContaining({
status: "collected",
rawPath: expect.any(String),
reportPath: expect.any(String),
}),
]),
);
expect(calls).toContainEqual([
"api",
"--paginate",
"--slurp",
"repos/example/rea/actions/runs/42/attempts/3/jobs?per_page=100",
]);
expect(calls).toContainEqual([
"api",
"--paginate",
"--slurp",
"repos/example/rea/actions/runs/41/attempts/1/jobs?per_page=100",
]);
const failedReport = JSON.parse(
await readFile(
join(fixture.outputDirectory, "runs/42-3/report.json"),
"utf8",
),
);
expect(failedReport.jobs[0].conclusion).toBe("failure");
expect(failedReport.jobs[0].execution.seconds).toBe(55);
});
it("records listing and per-run errors without claiming complete coverage", async () => {
const recent = new Date().toISOString();
const fixture = await createFixture([
{
workflow_runs: [
{
id: 7,
run_attempt: 2,
status: "completed",
conclusion: "success",
created_at: recent,
},
],
},
{ error: true },
{ jobs: "malformed" },
]);
await runBatch(fixture);
const manifest = JSON.parse(
await readFile(
join(fixture.outputDirectory, "batch-manifest.json"),
"utf8",
),
);
expect(manifest.selection.exhaustive).toBe(false);
expect(manifest.errors).toMatchObject([
{ scope: "workflow:Release" },
{ scope: "run" },
]);
expect(manifest.runs[0]).toMatchObject({
id: 7,
runAttempt: 2,
status: "error",
});
});
it("retains a partial manifest when its collection budget is exhausted", async () => {
const fixture = await createFixture([
{
workflow_runs: [8, 9].map((id) => ({
id,
run_attempt: 1,
status: "completed",
created_at: new Date().toISOString(),
})),
},
{ workflow_runs: [] },
]);
await executeWorkflowFixture(
process.execPath,
[
"--input-type=module",
"-e",
`
const { collectJobTimingsBatch } = await import(${JSON.stringify(pathToFileURL(batchScript).href)});
let clock = Date.now();
await collectJobTimingsBatch({
repository: "example/rea",
outputDirectory: process.env.CI_JOB_TIMINGS_DIRECTORY,
now: () => clock,
collect: async () => {
clock += 240001;
throw new Error("fixture request exhausted the remaining budget");
},
});
`,
],
{ cwd: fixture.directory, env: fixtureEnvironment(fixture) },
);
const manifest = JSON.parse(
await readFile(
join(fixture.outputDirectory, "batch-manifest.json"),
"utf8",
),
);
expect(manifest.coverage).toMatchObject({
selectedRuns: 2,
collectedRuns: 0,
});
expect(manifest.runs).toHaveLength(1);
expect(manifest.runs[0]).toMatchObject({ status: "error" });
expect(manifest.truncation.join(" ")).toContain("Time budget");
});
async function createFixture(responses: unknown[]) {
const directory = await createTestTempDirectory("rea-ci-job-timings-batch-");
const fakeBin = join(directory, "bin");
await mkdir(fakeBin);
const responsePath = join(directory, "responses.json");
const calls = join(directory, "calls.json");
await writeFile(responsePath, JSON.stringify(responses));
await writeFile(calls, "[]");
const fakeGh = join(fakeBin, "gh");
await writeFile(
fakeGh,
`#!/usr/bin/env node
const fs = require("node:fs");
const calls = JSON.parse(fs.readFileSync(process.env.CI_GH_CALLS, "utf8"));
calls.push(process.argv.slice(2));
fs.writeFileSync(process.env.CI_GH_CALLS, JSON.stringify(calls));
const responses = JSON.parse(fs.readFileSync(process.env.CI_GH_RESPONSES, "utf8"));
const response = responses[calls.length - 1];
if (response && response.error) { process.stderr.write("fixture API error"); process.exitCode = 1; }
else process.stdout.write(JSON.stringify(response));
`,
);
await chmod(fakeGh, 0o755);
return {
directory,
fakeBin,
responses: responsePath,
calls,
outputDirectory: join(directory, ".cache", "ci-job-timings"),
};
}
function runBatch(fixture: Awaited<ReturnType<typeof createFixture>>) {
return executeWorkflowFixture(process.execPath, [batchScript], {
cwd: fixture.directory,
env: fixtureEnvironment(fixture),
});
}
function fixtureEnvironment(
fixture: Awaited<ReturnType<typeof createFixture>>,
) {
return {
...process.env,
PATH: `${fixture.fakeBin}${delimiter}${process.env.PATH ?? ""}`,
CI_REPOSITORY: "example/rea",
CI_JOB_TIMINGS_DIRECTORY: fixture.outputDirectory,
CI_GH_CALLS: fixture.calls,
CI_GH_RESPONSES: fixture.responses,
GITHUB_STEP_SUMMARY: join(fixture.directory, "summary.md"),
};
}
@@ -0,0 +1,98 @@
import { readFile } from "node:fs/promises";
import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { executeWorkflowFixture } from "../../support/workflowGit.js";
async function workflow(name: string) {
return z
.object({
on: z.record(z.string(), z.unknown()),
permissions: z.record(z.string(), z.string()),
concurrency: z.object({ group: z.string() }).optional(),
jobs: z.record(
z.string(),
z.object({
name: z.string().optional(),
if: z.string().optional(),
uses: z.string().optional(),
with: z.record(z.string(), z.string()).optional(),
steps: z
.array(
z.object({
run: z.string().optional(),
uses: z.string().optional(),
env: z.record(z.string(), z.string()).optional(),
}),
)
.optional(),
}),
),
})
.parse(
parse(
await readFile(
new URL(`../../../.github/workflows/${name}`, import.meta.url),
"utf8",
),
),
);
}
it("refreshes title validation on edits without checking out PR code or cancelling CI", async () => {
const title = await workflow("pr-title.yml");
expect(title.on.pull_request).toMatchObject({
types: ["opened", "synchronize", "reopened", "edited"],
});
expect(title.permissions).toEqual({});
expect(title.concurrency?.group).not.toBe(
(await workflow("ci.yml")).concurrency?.group,
);
const jobs = Object.values(title.jobs);
expect(jobs).toHaveLength(1);
expect(jobs[0]?.name).toBe("Conventional PR title");
expect(jobs[0]?.if).toBeUndefined(); // A skipped check must not green-light an invalid title on body edits.
const steps = jobs[0]?.steps ?? [];
expect(steps).toHaveLength(1);
expect(steps[0]?.uses).toBeUndefined();
expect(steps[0]?.env).toEqual({
PR_TITLE: "${{ github.event.pull_request.title }}",
});
const command = z.string().parse(steps[0]?.run);
for (const title of [
"fix(ci): repair workflow",
"feat!: changed contract",
"docs: literal $(exit 91) `exit 92` text",
]) {
await expect(
executeWorkflowFixture("bash", ["-c", command], {
env: { ...process.env, PR_TITLE: title },
}),
).resolves.toMatchObject({ stderr: "" });
}
for (const title of ["", "Fix CI", "feat: "]) {
await expect(
executeWorkflowFixture("bash", ["-c", command], {
env: { ...process.env, PR_TITLE: title },
}),
).rejects.toMatchObject({ code: 1 });
}
expect((await workflow("ci.yml")).jobs["pr-title"]).toBeUndefined();
});
it("qualifies only ci:full label additions at the caller's merge revision", async () => {
const full = await workflow("ci-full-pr.yml");
expect(full.on.pull_request).toMatchObject({ types: ["labeled"] });
expect(full.permissions).toEqual({ contents: "read", actions: "read" });
expect(Object.values(full.jobs)).toEqual([
{
name: "Qualify labeled PR revision",
if: "github.event.label.name == 'ci:full'",
uses: "./.github/workflows/ci.yml",
with: { source_sha: "${{ github.sha }}" },
},
]);
// Metadata events must not create skipped replacements for the main CI checks.
expect(full.jobs.required).toBeUndefined();
expect(full.concurrency).toBeUndefined();
});
@@ -0,0 +1,375 @@
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
executeWorkflowFixture,
workflowGit,
} from "../../support/workflowGit.js";
const qualificationScript = fileURLToPath(
new URL("../../../scripts/ci/qualification.mjs", import.meta.url),
);
const requiredScript = fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
);
const now = Date.now();
const validSha = "a".repeat(40);
const repository = "example/rea";
function artifact(overrides: Record<string, unknown> = {}) {
return {
id: 42,
name: "ci-full-qualification-v1",
expired: false,
created_at: new Date(now - 60_000).toISOString(),
workflow_run: {
id: 7,
repository_id: 1,
head_repository_id: 1,
head_branch: "main",
head_sha: validSha,
},
...overrides,
};
}
function run(overrides: Record<string, unknown> = {}) {
return {
id: 7,
status: "completed",
conclusion: "success",
path: ".github/workflows/ci.yml",
event: "schedule",
created_at: new Date(now - 120_000).toISOString(),
head_sha: validSha,
head_branch: "main",
head_repository: { full_name: repository },
...overrides,
};
}
async function admissionFixture(
candidate: Record<string, unknown> = artifact(),
candidateRun: Record<string, unknown> = run(),
options: { apiError?: boolean; malformed?: boolean; force?: boolean } = {},
) {
const directory = await createTestTempDirectory("rea-ci-qualification-");
const bin = join(directory, "bin");
await mkdir(bin);
const fixturePath = join(directory, "api.json");
await writeFile(
fixturePath,
options.malformed
? "not-json"
: JSON.stringify({ artifacts: [candidate], run: candidateRun }),
);
const gh = join(bin, "gh");
await writeFile(
gh,
[
"#!/bin/sh",
'if [ "$GH_API_ERROR" = "true" ]; then exit 1; fi',
'case "$*" in',
' *actions/artifacts*) cat "$GH_FIXTURE_RESPONSE" ;;',
" *actions/runs/7*) node -e 'const x=require(process.env.GH_FIXTURE_RESPONSE); process.stdout.write(JSON.stringify(x.run))' ;;",
" *) exit 2 ;;",
"esac",
"",
].join("\n"),
);
await chmod(gh, 0o755);
const output = join(directory, "github-output");
await writeFile(output, "");
const env = {
...process.env,
PATH: `${bin}:${process.env.PATH ?? ""}`,
GH_FIXTURE_RESPONSE: fixturePath,
GH_API_ERROR: String(options.apiError ?? false),
CI_REPOSITORY: repository,
CI_REPOSITORY_ID: "1",
CI_DEFAULT_BRANCH: "main",
HEAD_SHA: validSha,
GITHUB_RUN_ID: "100",
GITHUB_OUTPUT: output,
...(options.force ? { CI_FORCE_FULL: "true" } : {}),
};
return { directory, output, env };
}
async function decide(
candidate?: Record<string, unknown>,
candidateRun?: Record<string, unknown>,
options?: { apiError?: boolean; malformed?: boolean; force?: boolean },
) {
const fixture = await admissionFixture(candidate, candidateRun, options);
const result = await executeWorkflowFixture(
process.execPath,
[qualificationScript],
{
cwd: fixture.directory,
env: fixture.env,
},
);
return {
...fixture,
decision: z
.record(z.string(), z.unknown())
.parse(JSON.parse(result.stdout)),
outputText: await readFile(fixture.output, "utf8"),
};
}
it("reuses only a recent trusted full qualification for the exact default-branch SHA", async () => {
const { decision, outputText } = await decide();
expect(decision).toMatchObject({ run_full: false, run_id: 7 });
expect(Object.keys(decision).sort()).toEqual([
"reason",
"run_full",
"run_id",
]);
expect(outputText).toContain("run_full=false\n");
expect(outputText).toContain("run_id=7\n");
});
const rejectedCandidates: Array<
[string, () => Record<string, unknown>, () => Record<string, unknown>]
> = [
[
"old",
() =>
artifact({
created_at: new Date(now - 24 * 60 * 60 * 1000 - 1).toISOString(),
}),
run,
],
[
"future",
() => artifact({ created_at: new Date(now + 60_000).toISOString() }),
run,
],
["expired", () => artifact({ expired: true }), run],
[
"foreign repository",
() =>
artifact({
workflow_run: { ...artifact().workflow_run, repository_id: 2 },
}),
run,
],
[
"foreign branch",
() =>
artifact({
workflow_run: { ...artifact().workflow_run, head_branch: "other" },
}),
run,
],
[
"foreign SHA",
() =>
artifact({
workflow_run: { ...artifact().workflow_run, head_sha: "b".repeat(40) },
}),
run,
],
[
"untrusted workflow",
artifact,
() => run({ path: ".github/workflows/release.yml" }),
],
["failed run", artifact, () => run({ conclusion: "failure" })],
[
"old producer rerun with a fresh artifact",
artifact,
() =>
run({ created_at: new Date(now - 25 * 60 * 60 * 1000).toISOString() }),
],
["wrong workflow event", artifact, () => run({ event: "push" })],
];
it.each(rejectedCandidates)(
"runs full qualification for a %s candidate",
async (_name, makeArtifact, makeRun) => {
const { decision } = await decide(makeArtifact(), makeRun());
expect(decision.run_full).toBe(true);
},
);
it.each([
["API error", { apiError: true }],
["malformed query response", { malformed: true }],
] as const)("fails closed on %s", async (_name, options) => {
const { decision } = await decide(undefined, undefined, options);
expect(decision.run_full).toBe(true);
});
it("lets the daily force-full setting bypass the GitHub API", async () => {
const { decision } = await decide(undefined, undefined, {
force: true,
apiError: true,
});
expect(decision).toMatchObject({ run_full: true });
expect(decision.reason).toContain("Forced");
});
async function workflowContract() {
const workflowPath = new URL(
"../../../.github/workflows/ci.yml",
import.meta.url,
);
const parsed = parse(await readFile(workflowPath, "utf8"));
return z
.object({
jobs: z.record(
z.string(),
z.object({ needs: z.unknown().optional() }).passthrough(),
),
})
.parse(parsed).jobs;
}
async function requiredRun(
changes: Record<string, string>,
overrides: { failed?: string; runAttempt?: string; event?: string } = {},
) {
const directory = await createTestTempDirectory("rea-ci-receipt-");
await workflowGit(directory, ["init", "--initial-branch=main"]);
await writeFile(join(directory, "fixture.txt"), "qualified source\n");
await workflowGit(directory, ["add", "."]);
await workflowGit(directory, ["commit", "-m", "fixture source"]);
const head = await workflowGit(directory, ["rev-parse", "HEAD"]);
const jobs = await workflowContract();
const results: Record<
string,
{ result: string; outputs?: Record<string, string> }
> = {};
for (const name of z.array(z.string()).parse(jobs.required?.needs)) {
results[name] = {
result:
name === overrides.failed
? "failure"
: changes.tier === "reused"
? "skipped"
: "success",
};
}
results.changes = { result: "success", outputs: changes };
const receiptDirectory = join(directory, ".cache", "receipt");
const output = join(directory, "github-output");
await writeFile(output, "");
const env = {
...process.env,
CI_JOBS: JSON.stringify(results),
CI_QUALIFICATION_DIRECTORY: receiptDirectory,
GITHUB_EVENT_NAME: overrides.event ?? "schedule",
GITHUB_SHA: head,
GITHUB_RUN_ID: "100",
GITHUB_RUN_ATTEMPT: overrides.runAttempt ?? "1",
GITHUB_REPOSITORY: repository,
GITHUB_OUTPUT: output,
};
const result = executeWorkflowFixture(process.execPath, [requiredScript], {
cwd: directory,
env,
});
return { directory, head, output, result };
}
it("writes a full receipt only after every canonical flag and workflow need pass", async () => {
const scopesPath = new URL("../../../scripts/ci/scopes.mjs", import.meta.url);
const { CI_FLAGS } = await import(scopesPath.href);
const changes = Object.fromEntries(
CI_FLAGS.map((flag: string) => [flag, "true"]),
);
changes.tier = "full";
const { directory, head, output, result } = await requiredRun(changes);
await expect(result).resolves.toMatchObject({ stderr: "" });
const receiptPath = join(directory, ".cache", "receipt", "receipt.json");
const receipt = z
.object({
sourceSha: z.string(),
runId: z.number(),
runAttempt: z.number(),
})
.parse(JSON.parse(await readFile(receiptPath, "utf8")));
expect(receipt).toMatchObject({ sourceSha: head, runId: 100, runAttempt: 1 });
expect(await readFile(output, "utf8")).toContain(
`receipt_path=${receiptPath}\n`,
);
expect(await readFile(output, "utf8")).toContain(
"receipt_name=ci-full-qualification-v1\n",
);
});
it.each([
["failed selected lane", { failed: "sqlite-runtime" }],
["partial full scope", {}],
] as const)(
"does not issue a receipt after %s",
async (caseName, overrides) => {
const scopesPath = new URL(
"../../../scripts/ci/scopes.mjs",
import.meta.url,
);
const { CI_FLAGS } = await import(scopesPath.href);
const changes = Object.fromEntries(
CI_FLAGS.map((flag: string) => [flag, "true"]),
);
changes.tier = "full";
if (caseName === "partial full scope") changes.sqlite = "false";
const outcome = await requiredRun(changes, overrides);
await expect(outcome.result).rejects.toMatchObject({ code: 1 });
await expect(
readFile(join(outcome.directory, ".cache", "receipt", "receipt.json")),
).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(outcome.output, "utf8")).not.toContain("receipt_");
},
);
it("never writes a fresh receipt for a reused scheduled qualification", async () => {
const scopesPath = new URL("../../../scripts/ci/scopes.mjs", import.meta.url);
const { CI_FLAGS } = await import(scopesPath.href);
const changes = Object.fromEntries(
CI_FLAGS.map((flag: string) => [flag, "false"]),
);
changes.tier = "reused";
changes.qualification_run_id = "7";
const outcome = await requiredRun(changes);
const result = await outcome.result;
await expect(
readFile(join(outcome.directory, ".cache", "receipt", "receipt.json")),
).rejects.toMatchObject({ code: "ENOENT" });
expect(result.stdout).toContain("Qualification reused from run 7");
expect(await readFile(outcome.output, "utf8")).not.toContain("receipt_");
});
it.each([
["missing receipt run", { qualification_run_id: "" }, "schedule"],
["selected validation lane", { sqlite: "true" }, "schedule"],
["manual dispatch", {}, "workflow_dispatch"],
] as const)(
"rejects qualification reuse with %s",
async (_name, override, event) => {
const { CI_FLAGS } = await import(
new URL("../../../scripts/ci/scopes.mjs", import.meta.url).href
);
const changes: Record<string, string> = {
...Object.fromEntries(CI_FLAGS.map((flag: string) => [flag, "false"])),
tier: "reused",
qualification_run_id: "7",
...override,
};
const outcome = await requiredRun(changes, { event });
await expect(outcome.result).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("scheduled admission receipt"),
});
expect(await readFile(outcome.output, "utf8")).not.toContain("receipt_");
},
);
+424 -22
View File
@@ -26,7 +26,19 @@ const workflow = async (filename = "ci.yml") =>
),
);
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;
it("binds SQLite compatibility jobs to the build's prepared runtime artifact and root layout", async () => {
expect((await workflow()).jobs["sqlite-runtime"]?.if).toBe(
"needs.changes.outputs.sqlite == 'true'",
);
const steps = z.array(
z.object({
uses: z.string().optional(),
@@ -52,6 +64,77 @@ it("binds SQLite compatibility jobs to the build's prepared runtime artifact and
expect(downloads[0]?.with).toEqual({ name, path: "." });
});
it("exports every canonical scope with read authority for admission and keeps telemetry outside the gate", async () => {
const { jobs } = await workflow();
const CI_FLAGS = await scopeFlags();
const outputs = z.record(z.string(), z.string()).parse(jobs.changes?.outputs);
expect(jobs.changes?.permissions).toEqual({
contents: "read",
actions: "read",
});
expect(jobs.build?.permissions).toEqual({
contents: "read",
actions: "read",
});
for (const flag of CI_FLAGS)
expect(outputs[flag]).toBe(`\${{ steps.plan.outputs.${flag} }}`);
const steps = z
.array(
z.object({
run: z.string().optional(),
if: z.string().optional(),
}),
)
.parse(jobs.required?.steps);
const telemetry = steps.find((step) =>
step.run?.includes("scripts/ci/job-timings.mjs"),
);
expect(telemetry).toBeUndefined();
const timings = z
.object({
on: z.object({
schedule: z.array(z.object({ cron: z.string() })),
workflow_dispatch: z.unknown(),
workflow_run: z.unknown().optional(),
}),
permissions: z.record(z.string(), z.string()),
jobs: z.object({
report: z.object({
steps: z.array(
z.object({
uses: z.string().optional(),
run: z.string().optional(),
with: z.record(z.string(), z.unknown()).optional(),
env: z.record(z.string(), z.unknown()).optional(),
}),
),
}),
}),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/ci-timings.yml", import.meta.url),
"utf8",
),
),
);
expect(timings.on.workflow_run).toBeUndefined();
expect(timings.on.schedule).toHaveLength(1);
expect(timings.permissions).toEqual({ contents: "read", actions: "read" });
const checkout = timings.jobs.report.steps.find((step) =>
step.uses?.startsWith("actions/checkout@"),
);
expect(checkout?.with).toEqual({
ref: "${{ github.event.repository.default_branch }}",
"persist-credentials": false,
});
const report = timings.jobs.report.steps.find((step) =>
step.run?.includes("scripts/ci/job-timings-batch.mjs"),
);
expect(report?.env?.CI_REPOSITORY).toBe("${{ github.repository }}");
});
const requiredNeeds = async () => {
const { jobs } = await workflow();
return { jobs, needs: z.array(z.string()).parse(jobs.required?.needs) };
@@ -64,6 +147,240 @@ it("makes the required gate wait for every CI lane, including future additions",
);
});
it("holds native and provider fan-out behind static validation while portable feedback stays independent", async () => {
const { jobs } = await workflow();
const earlyJobs = new Set([
"changes",
"static",
"build",
"test-shard",
"test",
"docs",
"required",
]);
for (const [name, job] of Object.entries(jobs)) {
if (earlyJobs.has(name)) continue;
expect(job.needs, `${name} must wait for static validation`).toContain(
"static",
);
expect(job.if).not.toMatch(/always\(|cancelled\(/u);
}
expect(jobs["test-shard"]?.needs).not.toContain("static");
});
it("binds provider build reuse to the current run while keeping standalone dispatches independent", async () => {
const { jobs } = await workflow();
const consumers = [
"browser",
"binary_layout",
"evm",
"javascript_recovery",
"recorded_crash",
"web_network",
"web_runtime",
"web_source_map",
];
const buildTerms = z
.string()
.parse(jobs.build?.if)
.split("||")
.map((term) => term.trim());
// Provider workflow edits select their lane without code=true. The build
// producer must still run, without selecting the portable test shards.
expect(new Set(buildTerms)).toEqual(
new Set(
["code", ...consumers].map(
(scope) => `needs.changes.outputs.${scope} == 'true'`,
),
),
);
expect(jobs["test-shard"]?.if).toBe("needs.changes.outputs.code == 'true'");
for (const name of consumers) {
const caller = jobs[name];
expect(caller?.needs).toContain("build");
expect(caller?.with).toEqual({ build_cache_artifact: "rea-build-cache" });
const path = z.string().parse(caller?.uses);
const called = z
.object({
on: z.object({
workflow_call: z.object({
inputs: z.record(z.string(), z.unknown()),
}),
workflow_dispatch: z.unknown(),
}),
jobs: z.record(
z.string(),
z.object({
steps: z.array(
z.object({
uses: z.string().optional(),
with: z.record(z.string(), z.unknown()).optional(),
}),
),
}),
),
})
.parse(
parse(
await readFile(new URL(`../../../${path}`, import.meta.url), "utf8"),
),
);
expect(called.on.workflow_call.inputs.build_cache_artifact).toMatchObject({
type: "string",
default: "",
});
expect(Object.hasOwn(called.on, "workflow_dispatch")).toBe(true);
for (const job of Object.values(called.jobs))
expect(
job.steps.find(
(step) => step.uses === "./.github/actions/portable-build-cache",
)?.with,
).toEqual({ build_cache_artifact: "${{ inputs.build_cache_artifact }}" });
}
const action = z
.object({
runs: z.object({
steps: z.array(
z.object({
id: z.string().optional(),
uses: z.string().optional(),
if: z.string().optional(),
with: z.record(z.string(), z.unknown()).optional(),
"continue-on-error": z.boolean().optional(),
}),
),
}),
})
.parse(
parse(
await readFile(
new URL(
"../../../.github/actions/portable-build-cache/action.yml",
import.meta.url,
),
"utf8",
),
),
);
const download = action.runs.steps.find((step) =>
step.uses?.startsWith("actions/download-artifact@"),
);
expect(download?.with).toEqual({
name: "${{ inputs.build_cache_artifact }}",
path: ".turbo/cache/",
});
expect(download?.if).toBe("inputs.build_cache_artifact != ''");
expect(download?.["continue-on-error"]).not.toBe(true);
for (const step of action.runs.steps.filter(
(step) => step.id === "plan" || step.uses?.startsWith("actions/cache"),
))
expect(step.if).toContain("inputs.build_cache_artifact == ''");
});
it("runs workflow validation inside required static checks when selected", async () => {
const { jobs } = await workflow();
const steps = z
.array(z.object({ run: z.string().optional(), if: z.string().optional() }))
.parse(jobs.static?.steps);
const validation = steps.filter((step) => step.run?.includes("actionlint"));
expect(validation).toHaveLength(1);
expect(validation[0]?.if).toBe("needs.changes.outputs.workflows == 'true'");
expect(jobs.workflows).toBeUndefined();
});
it("leaves cancellation ownership with CI so child lanes cannot cancel another tier", async () => {
const { jobs } = await workflow();
const children = Object.values(jobs).flatMap((job) =>
typeof job.uses === "string" && job.uses.startsWith("./.github/workflows/")
? [job.uses]
: [],
);
expect(children.length).toBeGreaterThan(0);
for (const path of children) {
const child = z
.object({ concurrency: z.unknown().optional() })
.parse(
parse(
await readFile(new URL(`../../../${path}`, import.meta.url), "utf8"),
),
);
expect(
child.concurrency,
`${path} must use caller scheduling`,
).toBeUndefined();
}
});
it("keeps fast feedback separate from complete qualification and release proof", async () => {
const ci = z
.object({
on: z.object({
push: z.unknown(),
pull_request: z.unknown(),
schedule: z.array(z.object({ cron: z.string() })),
workflow_call: z.object({
inputs: z.object({
source_sha: z.object({
required: z.literal(true),
type: z.literal("string"),
}),
}),
}),
}),
concurrency: z.object({
group: z.string(),
"cancel-in-progress": z.string(),
}),
jobs: z.record(
z.string(),
z.object({
if: z.string().optional(),
steps: z
.array(
z.object({
run: z.string().optional(),
if: z.string().optional(),
with: z.record(z.string(), z.unknown()).optional(),
}),
)
.optional(),
}),
),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
),
),
);
expect(ci.on.schedule).toEqual([
{ cron: "23 0-2,4-23 * * *" },
{ cron: "23 3 * * *" },
]);
expect(ci.concurrency.group).toContain("'qualification' || 'feedback'");
expect(ci.concurrency.group).toContain("inputs.source_sha ||");
expect(ci.concurrency.group).toContain("github.ref");
expect(ci.concurrency["cancel-in-progress"]).toBe(
"${{ github.event_name == 'pull_request' && inputs.source_sha == '' && !contains(github.event.pull_request.labels.*.name, 'ci:full') }}",
);
expect(ci.jobs.required?.if).toBe("${{ always() }}");
const shards = ci.jobs["test-shard"]?.steps ?? [];
const fast = shards.find((step) => step.run?.includes("npm run test:run"));
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");
expect(fast?.run).not.toContain("--coverage");
expect(full?.if).toBe("needs.changes.outputs.tier == 'full'");
const proof = ci.jobs["package-e2e"]?.steps?.find(
(step) => step.with?.name === "verified-release-package",
);
expect(proof?.if).toContain("needs.changes.outputs.tier == 'full'");
expect(proof?.if).toContain("matrix.platform == 'linux'");
expect(proof?.if).toContain("matrix.architecture == 'x64'");
});
it.each([
["true", "success", true],
["true", "failure", false],
@@ -71,34 +388,119 @@ it.each([
["true", "skipped", false],
["true", "missing", false],
["false", "skipped", true],
["false", "failure", false],
] as const)(
"enforces the SQLite required gate for code=%s and result=%s",
async (code, result, passes) => {
"enforces mapped required scopes for selected=%s and result=%s",
async (selected, result, passes) => {
const workflow = await requiredNeeds();
// GitHub exposes only direct dependencies in the required job's needs context.
const needs: Record<
string,
{ result: string; outputs?: Record<string, string> }
> = Object.fromEntries(
workflow.needs.map((name) => [name, { result: "success" }]),
);
needs.changes = { result: "success", outputs: { code } };
if (result === "missing") delete needs["sqlite-runtime"];
else if ("sqlite-runtime" in needs) needs["sqlite-runtime"] = { result };
const execution = executeWorkflowFixture(
for (const [scope, lane] of [
["sqlite", "sqlite-runtime"],
["workflows", "static"],
] as const) {
// GitHub exposes only direct dependencies in the required job's needs context.
const needs: Record<
string,
{ result: string; outputs?: Record<string, string> }
> = Object.fromEntries(
workflow.needs.map((name) => [name, { result: "success" }]),
);
needs.changes = {
result: "success",
outputs: {
...Object.fromEntries(
(await scopeFlags()).map((flag) => [flag, "false"]),
),
tier: "fast",
code: "true",
[scope]: selected,
},
};
if (result === "missing") delete needs[lane];
else needs[lane] = { result };
const execution = executeWorkflowFixture(
process.execPath,
[
fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
),
],
{ env: { ...process.env, CI_JOBS: JSON.stringify(needs) } },
);
// Static checks remain required even without workflow edits.
const expected = passes && !(lane === "static" && result !== "success");
if (expected)
await expect(execution).resolves.toMatchObject({ stderr: "" });
else
await expect(execution).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining(lane),
});
}
},
);
it("rejects incomplete or malformed classification even when available jobs succeeded", async () => {
const flags = await scopeFlags();
const valid = {
...Object.fromEntries(flags.map((flag) => [flag, "false"])),
tier: "fast",
};
const run = (outputs: unknown) =>
executeWorkflowFixture(
process.execPath,
[
fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
),
],
{ env: { ...process.env, CI_JOBS: JSON.stringify(needs) } },
{
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
}),
CI_QUALIFICATION_DIRECTORY: "",
},
},
);
if (passes) await expect(execution).resolves.toMatchObject({ stderr: "" });
else
await expect(execution).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("sqlite-runtime"),
});
},
);
await expect(run(valid)).resolves.toMatchObject({ stderr: "" });
// Metadata is not a scope, even when its string happens to be "true".
await expect(
run({ ...valid, qualification_run_id: "true" }),
).resolves.toMatchObject({ stderr: "" });
for (const outputs of [
undefined,
null,
{},
{ ...valid, tier: undefined },
{ ...valid, tier: "" },
{ ...valid, tier: "unknown" },
]) {
await expect(run(outputs)).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("valid tier"),
});
}
for (const flag of flags) {
await expect(run({ ...valid, [flag]: undefined })).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining(`scope outputs: ${flag}`),
});
}
for (const value of ["", "TRUE", "yes", true, false, 0, null, [], {}]) {
await expect(run({ ...valid, sqlite: value })).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("scope outputs: sqlite"),
});
}
for (const tier of ["full", "reused"]) {
await expect(
run({ ...valid, tier, sqlite: undefined }),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("scope outputs: sqlite"),
});
}
});
@@ -0,0 +1,188 @@
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { delimiter, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { executeWorkflowFixture } from "../../support/workflowGit.js";
const script = fileURLToPath(
new URL("../../../scripts/ci/test-history.mjs", import.meta.url),
);
const repository = "example/rea";
const repositoryId = 1;
const now = Date.now();
function artifact(id: number, overrides: Record<string, unknown> = {}) {
return {
id: id + 100,
name: "test-timings",
expired: false,
created_at: new Date(now - 60_000).toISOString(),
workflow_run: {
id,
repository_id: repositoryId,
head_repository_id: repositoryId,
head_branch: "main",
},
...overrides,
};
}
function run(id: number, overrides: Record<string, unknown> = {}) {
return {
id,
status: "completed",
conclusion: "success",
path: ".github/workflows/ci.yml",
event: "schedule",
created_at: new Date(now - 120_000).toISOString(),
head_branch: "main",
head_repository: { full_name: repository },
...overrides,
};
}
async function invoke(
artifacts: unknown[],
runs: Record<number, unknown>,
options: {
apiError?: boolean;
repository?: string;
repositoryId?: string;
} = {},
) {
const directory = await createTestTempDirectory("rea-ci-test-history-");
const fakeBin = join(directory, "bin");
await mkdir(fakeBin);
const fixture = join(directory, "api.json");
const calls = join(directory, "api-calls");
const output = join(directory, "github-output");
await writeFile(fixture, JSON.stringify({ artifacts, runs }));
await writeFile(output, "");
await writeFile(calls, "");
const fakeGh = join(fakeBin, "gh");
await writeFile(
fakeGh,
[
"#!/bin/sh",
'printf \'%s\\n\' "$*" >> "$GH_API_CALLS"',
'if [ "$GH_API_ERROR" = "true" ]; then exit 1; fi',
'if [ "$4" = "repos/example/rea/actions/artifacts" ]; then',
' node -e \'const fs=require("node:fs"); const x=JSON.parse(fs.readFileSync(process.env.GH_FIXTURE_RESPONSE,"utf8")); process.stdout.write(JSON.stringify({artifacts:x.artifacts}));\'',
"else",
' run_id="${4##*/}"',
' node -e \'const fs=require("node:fs"); const x=JSON.parse(fs.readFileSync(process.env.GH_FIXTURE_RESPONSE,"utf8")); process.stdout.write(JSON.stringify(x.runs[Number(process.argv[1])] ?? {}));\' "$run_id"',
"fi",
"",
].join("\n"),
);
await chmod(fakeGh, 0o755);
const node24 = dirname(process.execPath);
const result = await executeWorkflowFixture(process.execPath, [script], {
cwd: directory,
env: {
...process.env,
PATH: [fakeBin, node24, process.env.PATH ?? ""].join(delimiter),
GH_FIXTURE_RESPONSE: fixture,
GH_API_CALLS: calls,
GH_API_ERROR: String(options.apiError ?? false),
GH_TOKEN: "fixture-token",
CI_REPOSITORY: options.repository ?? repository,
CI_REPOSITORY_ID: options.repositoryId ?? String(repositoryId),
CI_DEFAULT_BRANCH: "main",
GITHUB_OUTPUT: output,
},
});
return {
result,
output: await readFile(output, "utf8"),
calls: await readFile(calls, "utf8"),
};
}
it("selects the latest trusted full run that actually published timing history", async () => {
const { result, output, calls } = await invoke(
[
artifact(15),
artifact(14),
artifact(13, {
workflow_run: { ...artifact(13).workflow_run, head_repository_id: 2 },
}),
artifact(12, {
workflow_run: { ...artifact(12).workflow_run, head_branch: "feature" },
}),
artifact(11),
],
{
15: run(15, { conclusion: "failure" }),
14: run(14, { path: ".github/workflows/release.yml" }),
11: run(11, { event: "workflow_dispatch" }),
},
);
expect(JSON.parse(result.stdout)).toEqual({ run_id: "11" });
expect(output).toBe("run-id=11\n");
expect(calls).toContain("name=test-timings");
expect(calls).toContain("per_page=100");
expect(calls.match(/actions\/runs\//gu)).toHaveLength(3);
expect(calls).not.toContain("actions/workflows");
});
it("rejects expired, foreign, old, and non-full run candidates", async () => {
const { result, output } = await invoke(
[
artifact(15, { expired: true }),
artifact(14, {
workflow_run: { ...artifact(14).workflow_run, head_repository_id: 2 },
}),
artifact(13, {
created_at: new Date(now - 31 * 24 * 60 * 60 * 1000).toISOString(),
}),
artifact(12),
],
{
12: run(12, { event: "pull_request" }),
},
);
expect(JSON.parse(result.stdout)).toEqual({ run_id: "" });
expect(output).toBe("run-id=\n");
});
it("writes an empty run id when GitHub history is unavailable", async () => {
const { result, output } = await invoke([], {}, { apiError: true });
expect(JSON.parse(result.stdout)).toEqual({ run_id: "" });
expect(output).toBe("run-id=\n");
});
it("bounds run lookups to five artifacts even when inventory has more", async () => {
const ids = [25, 24, 23, 22, 21, 20, 19];
const { result, calls } = await invoke(
ids.map((id) => artifact(id)),
Object.fromEntries(
ids.map((id, index) => [
id,
run(id, index < 5 ? { conclusion: "failure" } : {}),
]),
),
);
expect(JSON.parse(result.stdout)).toEqual({ run_id: "" });
expect(calls.match(/actions\/runs\//gu)).toHaveLength(5);
});
it("returns empty history without querying for an invalid repository identity", async () => {
const { result, output, calls } = await invoke(
[],
{},
{
repository: "owner/repo?per_page=100",
repositoryId: "not-an-id",
},
);
expect(JSON.parse(result.stdout)).toEqual({ run_id: "" });
expect(output).toBe("run-id=\n");
expect(calls).toBe("");
});
+297 -12
View File
@@ -1,5 +1,5 @@
import { execFile } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
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";
@@ -8,8 +8,11 @@ import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { planTestSelection } from "../../../scripts/ci/test-selection.mjs";
import { parseTestDurations } from "../../ciTestSequencer.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { workflowGit } from "../../support/workflowGit.js";
const execute = promisify(execFile);
const script = new URL("../../../scripts/ci/test-report.mjs", import.meta.url);
@@ -53,6 +56,23 @@ it("collects failed-shard diagnostics before enforcing the shard result", async
expect(upload).toBeGreaterThan(merge);
expect(gate).toBeGreaterThan(upload);
expect(steps[merge]?.if).not.toContain("needs.test-shard.result");
const merges = steps.filter((step) => step.run?.includes("--reporter=json"));
expect(merges).toHaveLength(2);
for (const step of merges)
expect(step.run).toContain(
"--reporter=./scripts/ci/test-timing-reporter.mjs",
);
expect(steps[upload]?.with?.path).toContain("test-timings.json");
expect(steps[upload]?.with).toMatchObject({ "include-hidden-files": true });
expect(steps[upload]?.with?.path).toContain(
".cache/ci-test-selection/report.json",
);
const summary = steps.find((step) =>
step.run?.includes("scripts/ci/test-report.mjs"),
);
expect(summary?.env?.CI_TEST_SELECTION).toBe(
"${{ needs.changes.outputs.test_selection }}",
);
const command = steps[gate]?.run;
if (command === undefined) throw new Error("Missing shard result gate");
for (const result of ["failure", "cancelled", "skipped", ""]) {
@@ -77,11 +97,67 @@ it("keeps diagnosis available after merge failure and publishes only complete su
const history = steps.find((step) => step.with?.name === "test-timings");
expect(history?.if).toContain("success()");
expect(history?.if).toContain("needs.test-shard.result == 'success'");
expect(history?.if).toContain("needs.changes.outputs.tier == 'full'");
expect(history?.with?.path).toBe(".cache/ci-test-history/test-results.json");
const download = (await workflow()).build!.steps.find(
const buildSteps = (await workflow()).build!.steps;
const lookup = buildSteps.find((step) =>
step.run?.includes("test-history.mjs"),
);
expect(lookup?.env).toMatchObject({
CI_REPOSITORY: "${{ github.repository }}",
CI_REPOSITORY_ID: "${{ github.repository_id }}",
CI_DEFAULT_BRANCH: "${{ github.event.repository.default_branch }}",
});
const download = buildSteps.find(
(step) => step.name === "Download previous timing report",
);
expect(download?.with?.name).toBe(history?.with?.name);
expect(download?.with?.["run-id"]).toBe(
"${{ steps.history.outputs.run-id }}",
);
});
it("rejects successful shard reports with missing or duplicate portable files", async () => {
const root = await createTestTempDirectory("rea-ci-report-inventory-");
await workflowGit(root, ["init"]);
await mkdir(join(root, "tests"));
for (const name of ["first", "second"])
await writeFile(join(root, `tests/${name}.test.ts`), "// fixture\n");
await workflowGit(root, ["add", "tests"]);
const run = async (names: readonly string[]) => {
await writeFile(
join(root, "test-timings.json"),
JSON.stringify({
version: 1,
success: true,
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",
},
});
};
await expect(
run(["tests/first.test.ts", "tests/second.test.ts"]),
).resolves.toMatchObject({ stderr: "" });
for (const names of [
["tests/first.test.ts"],
["tests/first.test.ts", "tests/second.test.ts", "tests/unplanned.test.ts"],
["tests/first.test.ts", "tests/first.test.ts", "tests/second.test.ts"],
]) {
await expect(run(names)).rejects.toMatchObject({
stderr: expect.stringContaining("Incomplete portable test inventory"),
});
await expect(
readFile(join(root, ".cache/ci-test-history/test-results.json")),
).rejects.toMatchObject({ code: "ENOENT" });
}
});
it("runs the existing onboarding and Python producer guards from their selected CI owners", async () => {
@@ -116,20 +192,25 @@ it("exports portable timing history and removes it on a failed, partial, or inva
const summary = join(root, "summary.md");
const history = join(root, ".cache/ci-test-history/test-results.json");
const report = {
version: 1,
success: true,
numFailedTests: 0,
testResults: [
files: [
{
name: join(root, "tests/slow.test.ts"),
startTime: 10,
endTime: 110,
assertionResults: [{ large: "not timing data" }],
durationMs: 100,
phases: {
execution: 20,
preparation: 20,
environment: 10,
imports: 40,
setup: 10,
},
},
{ name: join(root, "tests/fast.test.ts"), startTime: 20, endTime: 30 },
{ name: join(root, "tests/fast.test.ts"), durationMs: 10 },
],
};
const run = async (value: unknown, shards = "success", merge = "success") => {
await writeFile(join(root, "test-results.json"), JSON.stringify(value));
await writeFile(join(root, "test-timings.json"), JSON.stringify(value));
await writeFile(summary, "");
return execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
@@ -143,7 +224,8 @@ it("exports portable timing history and removes it on a failed, partial, or inva
};
await run(report);
const contents = await readFile(history, "utf8");
expect(contents).not.toContain("assertionResults");
expect(contents).not.toContain("phases");
expect(contents).not.toContain("startTime");
expect(contents).not.toContain(root);
expect(
parseTestDurations(contents, resolve(root, "different-checkout")),
@@ -154,7 +236,7 @@ it("exports portable timing history and removes it on a failed, partial, or inva
]),
);
for (const [value, shards, merge] of [
[{ ...report, success: false, numFailedTests: 1 }, "failure", "failure"],
[{ ...report, success: false }, "failure", "failure"],
[report, "cancelled", "success"],
[report, "success", "failure"],
] as const) {
@@ -167,8 +249,211 @@ it("exports portable timing history and removes it on a failed, partial, or inva
await expect(
run({
...report,
testResults: [{ name: "../outside.test.ts", startTime: 1, endTime: 3 }],
files: [{ name: "../outside.test.ts", durationMs: 2 }],
}),
).rejects.toMatchObject({ code: 1 });
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
await run(report);
await expect(
run({
...report,
files: [{ name: "tests/invalid.test.ts", durationMs: -1 }],
}),
).rejects.toMatchObject({ code: 1 });
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
});
it("recovers complete module costs from real blob reports without executing tests again", async () => {
const root = await createTestTempDirectory("rea-ci-module-timing-");
const config = join(root, "vitest.config.mjs");
await writeFile(
config,
'export default { test: { globals: true, include: ["sample.test.js"], maxWorkers: 1 } };',
);
await writeFile(
join(root, "sample.test.js"),
[
'import { writeFileSync } from "node:fs";',
"beforeAll(() => new Promise(resolve => setTimeout(resolve, 80)));",
"afterAll(() => new Promise(resolve => setTimeout(resolve, 80)));",
'it("has cheap assertions and expensive outer hooks", () => { writeFileSync("executed", "yes"); expect(1).toBe(1); });',
].join("\n"),
);
const vitest = fileURLToPath(
new URL("../../../node_modules/vitest/vitest.mjs", import.meta.url),
);
const reporter = fileURLToPath(
new URL("../../../scripts/ci/test-timing-reporter.mjs", import.meta.url),
);
const run = (args: string[]) =>
execute(process.execPath, [vitest, ...args, "--config", config], {
cwd: root,
env: process.env,
timeout: 20_000,
});
await run(["run", "--reporter=blob"]);
expect(await readFile(join(root, "executed"), "utf8")).toBe("yes");
await rm(join(root, "executed"));
await run([
"--merge-reports",
`--reporter=${reporter}`,
"--reporter=json",
"--outputFile.json=body.json",
]);
await expect(readFile(join(root, "executed"))).rejects.toMatchObject({
code: "ENOENT",
});
const report = z
.object({
version: z.literal(1),
success: z.literal(true),
files: z.array(
z.object({
name: z.string(),
durationMs: z.number(),
phases: z.record(z.string(), z.number()),
}),
),
})
.parse(JSON.parse(await readFile(join(root, "test-timings.json"), "utf8")));
expect(
JSON.parse(await readFile(join(root, "test-timings.json"), "utf8")),
).toMatchObject({
reason: "passed",
unhandledErrors: 0,
files: [{ state: "passed" }],
});
expect(report.files).toHaveLength(1);
const file = report.files[0]!;
const json = z
.object({
testResults: z.array(
z.object({ startTime: z.number(), endTime: z.number() }),
),
})
.parse(JSON.parse(await readFile(join(root, "body.json"), "utf8")));
const body = json.testResults[0]!;
expect(
file.phases.execution! - (body.endTime - body.startTime),
).toBeGreaterThan(100);
expect(file.phases.imports).toBeGreaterThan(0);
expect(file.phases.preparation).toBeGreaterThan(0);
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" },
});
expect(
parseTestDurations(
await readFile(
join(root, ".cache/ci-test-history/test-results.json"),
"utf8",
),
root,
)?.get("sample.test.js"),
).toBe(file.durationMs);
await writeFile(
join(root, "sample.test.js"),
'it("fails", () => { throw new Error("fixture failure"); });',
);
await expect(run(["run", "--reporter=blob"])).rejects.toMatchObject({
code: 1,
});
await expect(
run(["--merge-reports", `--reporter=${reporter}`]),
).rejects.toMatchObject({ code: 1 });
const failed = JSON.parse(
await readFile(join(root, "test-timings.json"), "utf8"),
) as unknown;
expect(failed).toMatchObject({
version: 1,
success: false,
reason: "failed",
unhandledErrors: 0,
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 expect(
readFile(join(root, ".cache/ci-test-history/test-results.json")),
).rejects.toMatchObject({ code: "ENOENT" });
});
it("records failed omissions from full reports without treating partial or unhandled outcomes as parity", async () => {
const root = await createTestTempDirectory("rea-ci-selection-report-");
await workflowGit(root, ["init"]);
const paths = [
"src/sqlite/provider.test.ts",
"src/evm/provider.test.ts",
"tests/boundary/mcp/workflow.test.ts",
];
for (const path of paths) {
await mkdir(join(root, path, ".."), { recursive: true });
await writeFile(join(root, path), "// fixture\n");
}
await workflowGit(root, ["add", "src", "tests"]);
const timing = {
version: 1,
success: false,
reason: "failed",
unhandledErrors: 0,
files: paths.map((name, index) => ({
name,
durationMs: 10,
state: index === 1 ? "failed" : "passed",
})),
};
const run = async (report: unknown) => {
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",
},
});
return JSON.parse(
await readFile(
join(root, ".cache/ci-test-selection/report.json"),
"utf8",
),
) as unknown;
};
expect(await run(timing)).toMatchObject({
observational: true,
complete: true,
selected: [paths[0], paths[2]],
omitted: [paths[1]],
missedFailures: [paths[1]],
executionSha: "merge-sha",
prHeadSha: "pr-head-sha",
});
for (const report of [
{ ...timing, files: timing.files.slice(0, 1) },
{ ...timing, unhandledErrors: 1 },
{ ...timing, reason: "interrupted" },
])
expect(await run(report)).toMatchObject({ complete: false });
await expect(run({ ...timing, files: "invalid" })).rejects.toMatchObject({
code: 1,
});
await expect(
readFile(join(root, ".cache/ci-test-selection/report.json")),
).rejects.toMatchObject({ code: "ENOENT" });
await expect(
readFile(join(root, ".cache/ci-test-history/test-results.json")),
).rejects.toMatchObject({ code: "ENOENT" });
});
@@ -17,24 +17,24 @@ describe("CI test history", () => {
const root = resolve("/workspace/rea");
const durations = parseTestDurations(
JSON.stringify({
version: 1,
success: true,
numFailedTests: 0,
testResults: [
files: [
{
name: join(root, "tests/slow.test.ts"),
startTime: 10,
endTime: 110,
durationMs: 100,
},
{
name: join(root, "tests/slow.test.ts"),
startTime: 20,
endTime: 80,
durationMs: 60,
},
{
name: resolve(root, "../outside.test.ts"),
startTime: 10,
endTime: 1000,
durationMs: 990,
},
{ name: "tests/negative.test.ts", durationMs: -1 },
{ name: "tests/zero.test.ts", durationMs: 0 },
{ name: "tests/invalid.test.ts", durationMs: "100" },
null,
],
}),
@@ -43,7 +43,20 @@ describe("CI test history", () => {
expect(durations).toEqual(new Map([["tests/slow.test.ts", 100]]));
expect(
parseTestDurations('{"success": false, "numFailedTests": 1}', root),
parseTestDurations('{"version": 1, "success": false, "files": []}', root),
).toBeUndefined();
// Legacy test-body spans must not be mixed with complete module costs.
expect(
parseTestDurations(
JSON.stringify({
success: true,
numFailedTests: 0,
testResults: [
{ name: "tests/legacy.test.ts", startTime: 0, endTime: 100 },
],
}),
root,
),
).toBeUndefined();
expect(parseTestDurations("not json", root)).toBeUndefined();
expect(parseTestDurations("null", root)).toBeUndefined();
@@ -0,0 +1,137 @@
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
executeWorkflowFixture,
workflowGit,
} from "../../support/workflowGit.js";
const validator = fileURLToPath(
new URL("../../../scripts/ci/verified-package.mjs", import.meta.url),
);
type Fixture = Awaited<ReturnType<typeof createFixture>>;
type FixtureOptions = {
override?: Record<string, string | number>;
manifestContents?: string;
writeManifest?: boolean;
};
it("validates a tarball against the exact checkout and current workflow attempt", async () => {
const fixture = await createFixture();
const result = await validate(fixture);
expect(result.stdout.trim()).toBe(
join(fixture.artifactDirectory, "package.tgz"),
);
expect(await readFile(fixture.output, "utf8")).toBe(
`tarball=${join(fixture.artifactDirectory, "package.tgz")}\n`,
);
});
it("rejects a workflow SHA that differs from the checked out HEAD", async () => {
const fixture = await createFixture();
await expect(validate(fixture, "c".repeat(40))).rejects.toThrow();
});
it.each([
["wrong checkout SHA", { sourceSha: "c".repeat(40) }],
["wrong workflow run", { runId: 124 }],
["future workflow attempt", { runAttempt: 3 }],
["wrong verifier platform", { platform: "darwin" }],
["wrong verifier architecture", { architecture: "arm64" }],
["wrong package digest", { sha256: "c".repeat(64) }],
])("rejects %s", async (_label, override) => {
const fixture = await createFixture({ override });
await expect(validate(fixture)).rejects.toThrow();
});
it("accepts an earlier successful attempt from the same workflow run", async () => {
const fixture = await createFixture({ override: { runAttempt: 1 } });
await expect(validate(fixture)).resolves.toMatchObject({
stdout: expect.any(String),
});
});
it.each([
["malformed manifest", "{"],
["manifest with missing fields", JSON.stringify({ schemaVersion: 1 })],
])("rejects %s", async (_label, contents) => {
const fixture = await createFixture({ manifestContents: contents });
await expect(validate(fixture)).rejects.toThrow();
});
it("rejects an absent manifest", async () => {
const fixture = await createFixture({ writeManifest: false });
await expect(validate(fixture)).rejects.toThrow();
});
async function createFixture({
override = {},
manifestContents,
writeManifest = true,
}: FixtureOptions = {}) {
const directory = await createTestTempDirectory("rea-verified-package-");
await workflowGit(directory, ["init", "--initial-branch=main"]);
await writeFile(
join(directory, "package.json"),
'{"name":"fixture","version":"1.2.3"}\n',
);
await workflowGit(directory, ["add", "package.json"]);
await workflowGit(directory, [
"commit",
"-m",
"test: verified package fixture",
]);
const sourceSha = await workflowGit(directory, ["rev-parse", "HEAD"]);
const artifactDirectory = join(directory, "artifact");
await mkdir(artifactDirectory);
const archive = "verified tarball fixture";
await writeFile(join(artifactDirectory, "package.tgz"), archive);
const manifest = {
schemaVersion: 1,
sourceSha,
runId: 123,
runAttempt: 2,
platform: "linux",
architecture: "x64",
packageVersion: "1.2.3",
nodeVersion: process.version,
sha256: createHash("sha256").update(archive).digest("hex"),
...override,
};
if (writeManifest)
await writeFile(
join(artifactDirectory, "manifest.json"),
manifestContents ?? JSON.stringify(manifest),
);
const output = join(directory, "github-output");
await writeFile(output, "");
return { directory, sourceSha, artifactDirectory, output };
}
function validate(fixture: Fixture, sourceSha = fixture.sourceSha) {
return executeWorkflowFixture(
process.execPath,
[validator, "validate", fixture.artifactDirectory],
{
cwd: fixture.directory,
env: {
...process.env,
GITHUB_SHA: sourceSha,
GITHUB_RUN_ID: "123",
GITHUB_RUN_ATTEMPT: "2",
GITHUB_OUTPUT: fixture.output,
},
},
);
}
@@ -1,13 +1,91 @@
import { chmod, readFile, writeFile } from "node:fs/promises";
import { createHash } from "node:crypto";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { parse as parseToml } from "smol-toml";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import {
configureClientConfiguration,
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("accepts a literal UTF-8 replacement character without changing its value", async () => {
const root = await createTestTempDirectory("rea-client-config-utf8-");
const configPath = join(root, "config.json");
const original = Buffer.concat([
Buffer.from('{"label":"'),
Buffer.from("\uFFFD"),
Buffer.from('"}'),
]);
await writeFile(configPath, original);
const result = await configureClientConfiguration(
{ name: "cursor", format: "json", configPath },
{},
["rea", "mcp"],
);
expect(result.status).toBe("configured");
expect(await readFile(`${configPath}.rea.backup`)).toEqual(original);
expect(JSON.parse(await readFile(configPath, "utf8")).label).toBe("\uFFFD");
});
it("previews and creates a current recovery backup while preserving the first backup", async () => {
const root = await createTestTempDirectory("rea-client-current-recovery-");
const configPath = join(root, "config.json");
const firstOriginal = '{"keep":"first"}\n';
const currentOriginal = '{"keep":"current"}\n';
const client = { name: "cursor", format: "json", configPath } as const;
await writeFile(configPath, currentOriginal);
await writeFile(`${configPath}.rea.backup`, firstOriginal);
const recoveryPath = `${configPath}.rea.backup.${createHash("sha256")
.update(currentOriginal, "utf8")
.digest("hex")}.recovery`;
expect(await inspectClientConfiguration(client, {}, ["rea", "mcp"])).toEqual({
status: "update",
backupPath: recoveryPath,
});
expect(
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
).toEqual({ status: "configured", backupPath: recoveryPath });
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(
firstOriginal,
);
expect(await readFile(recoveryPath, "utf8")).toBe(currentOriginal);
});
it("blocks configuration when the planned content-addressed backup is occupied", async () => {
const root = await createTestTempDirectory("rea-client-recovery-conflict-");
const configPath = join(root, "config.json");
const firstOriginal = '{"keep":"first"}\n';
const currentOriginal = '{"keep":"current"}\n';
const client = { name: "cursor", format: "json", configPath } as const;
await writeFile(configPath, currentOriginal);
await writeFile(`${configPath}.rea.backup`, firstOriginal);
const recoveryPath = `${configPath}.rea.backup.${createHash("sha256")
.update(currentOriginal, "utf8")
.digest("hex")}.recovery`;
await writeFile(recoveryPath, "occupied by other data");
expect(
await inspectClientConfiguration(client, {}, ["rea", "mcp"]),
).toMatchObject({
status: "invalid",
remediation: expect.stringContaining(recoveryPath),
});
expect(
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
).toEqual({ status: "failed", reason: "backup" });
expect(await readFile(configPath, "utf8")).toBe(currentOriginal);
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(
firstOriginal,
);
expect(await readFile(recoveryPath, "utf8")).toBe("occupied by other data");
});
describe("client configuration write failures", () => {
it.skipIf(process.platform === "win32" || process.getuid?.() === 0).each([
["json", configureClientConfiguration],
@@ -71,6 +71,7 @@ describe("client configuration filesystem lifecycle", () => {
"pi",
"hermes",
"qoder",
"droid",
"zcode",
"dsh",
"grok_bot",
@@ -1,110 +0,0 @@
import {
copyFile,
mkdir,
readFile,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const run = (root: string, command: string, arguments_: readonly string[]) =>
execFileOutput(command, arguments_, {
cwd: root,
stopSignal: "SIGTERM",
timeout: 20_000,
});
const commit = (root: string, message: string) =>
run(root, "git", [
"-c",
"user.name=REA fixture",
"-c",
"user.email=fixture@example.invalid",
"-c",
"commit.gpgSign=false",
"commit",
"--quiet",
"-m",
message,
]);
const fixture = async () => {
const root = await createTestTempDirectory("rea-development-tests-");
await mkdir(join(root, "scripts", "lib"), { recursive: true });
await mkdir(join(root, "src"));
for (const path of [
"scripts/run-development-tests.mjs",
"scripts/lib/development-tests.mjs",
])
await copyFile(join(process.cwd(), path), join(root, path));
await symlink(
join(process.cwd(), "node_modules"),
join(root, "node_modules"),
process.platform === "win32" ? "junction" : undefined,
);
await writeFile(join(root, "package.json"), '{"type":"module"}\n');
await writeFile(join(root, ".gitignore"), "node_modules\nselected.txt\n");
await writeFile(
join(root, "vitest.config.mjs"),
'export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };\n',
);
await writeFile(join(root, "src", "value.ts"), "export const value = 1;\n");
await writeFile(
join(root, "src", "value.test.ts"),
'import { expect, it } from "vitest"; import { writeFileSync } from "node:fs"; import { value } from "./value.js"; it("checks the selected source", () => { expect(value).toBe(1); writeFileSync("selected.txt", String(value)); });\n',
);
await run(root, "git", ["init", "--quiet"]);
await run(root, "git", ["add", "."]);
await commit(root, "fixture");
return root;
};
const testCommand = (root: string, ...arguments_: string[]) =>
run(root, process.execPath, [
"scripts/run-development-tests.mjs",
...arguments_,
]);
it("executes an explicitly selected source test on a clean tree without build artifacts", async () => {
const root = await fixture();
const { stdout: status } = await run(root, "git", ["status", "--porcelain"]);
expect(status).toBe("");
await testCommand(root, "local", "src/value.test.ts");
expect(await readFile(join(root, "selected.txt"), "utf8")).toBe("1");
});
it("uses committed dependency changes since the requested Git base to select source tests", async () => {
const root = await fixture();
const { stdout: base } = await run(root, "git", ["rev-parse", "HEAD"]);
await writeFile(join(root, "src", "value.ts"), "export const value = 2;\n");
await run(root, "git", ["add", "src/value.ts"]);
await commit(root, "change dependency");
await expect(
testCommand(root, "changed", "--base", base.trim()),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("src/value.test.ts"),
stderr: expect.stringContaining("expected 2 to be 1"),
});
});
it("rejects a compiled boundary in the source-only command and a missing exact test", async () => {
const root = await fixture();
await expect(
testCommand(root, "local", "tests/acceptance/runtime.test.ts"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("Use test:focused"),
});
await expect(
testCommand(root, "local", "src/missing.test.ts"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("ENOENT"),
});
});
@@ -1,5 +1,5 @@
import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { symlink, writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { describe, expect, it, vi } from "vitest";
@@ -14,7 +14,7 @@ import type {
import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { ok } from "../../../src/domain/result.js";
import { err, ok } from "../../../src/domain/result.js";
import {
readAnalysisSnapshot,
writeAnalysisSnapshot,
@@ -40,6 +40,7 @@ import {
} from "../../fixtures/binarySession.js";
import { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { ProviderAdapterError } from "../../../src/domain/providerAdapterError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
CAPABILITIES as GHIDRA_CAPABILITIES,
@@ -396,7 +397,85 @@ describe("snapshot output cleanup lifecycle", () => {
});
});
const verifyWindowsSnapshotAdmission = async (
selectedPath: "direct" | "junction",
): Promise<void> => {
const fixture = await createSnapshotReplayFixture(
"rea-direct-snapshot-junction-",
);
const rawPath = join(dirname(fixture.path), "image.bin");
await writeFile(rawPath, Buffer.from("a92a60", "hex"));
const linked = join(dirname(fixture.path), "linked");
const linkedPath = join(linked, basename(rawPath));
const identity = { ...GHIDRA_PROVIDER_IDENTITY, version: "12.1.4" };
const profile = createAnalysisProfile(identity, {
fixture: true,
});
const baseProvider = fixture.createProvider({
identity,
profile,
supportedOperations: ["search_strings"],
});
let rejectAdmission = false;
const provider: AnalysisProvider = {
...baseProvider,
createClient: (target, profile, context) => {
const client = baseProvider.createClient(target, profile, context);
return {
...client,
execute: (operation, parameters, options) =>
rejectAdmission && operation === "search_strings"
? Promise.resolve(
err(new ProviderAdapterError("ghidra", operation)),
)
: client.execute(operation, parameters, options),
};
},
};
const dependencies = fixture.dependencies(provider);
const arguments_ = { pattern: "fixture", document: "fixture" };
const options = {
snapshotPath: fixture.snapshotPath,
formatHint: "raw-binary" as const,
architecture: "6502" as const,
entryPoint: "0x8001",
};
const first = await runDirectAnalysis(
dependencies,
rawPath,
"search_strings",
arguments_,
options,
);
expect(first).toMatchObject({ operation: "search_strings" });
expect(fixture.starts).toHaveLength(1);
if (selectedPath === "junction")
await symlink(dirname(fixture.path), linked, "junction");
rejectAdmission = true;
const second = await runDirectAnalysis(
dependencies,
selectedPath === "junction" ? linkedPath : rawPath,
"search_strings",
arguments_,
options,
);
expect(second).toMatchObject({ error: "Analysis failed" });
expect(fixture.starts).toHaveLength(2);
expect(
fixture.calls.filter((call) => call === "search_strings"),
).toHaveLength(1);
};
describe("direct analysis composed snapshot replay", () => {
it.skipIf(process.platform !== "win32")(
"does not replay a CLI snapshot through a Windows junction",
() => verifyWindowsSnapshotAdmission("junction"),
);
it.skipIf(process.platform !== "win32")(
"does not replay a CLI snapshot before native admission on a canonical path",
() => verifyWindowsSnapshotAdmission("direct"),
);
it.each([
{
tool: "search_strings",
@@ -516,7 +595,7 @@ describe("Ghidra composed workflow snapshot replay", () => {
{ tool: "inspect_native_api", arguments: { procedure: "0x1000" } },
{ tool: "trace_feature", arguments: { query: "fixture" } },
] as const)(
"persists and replays $tool with production Ghidra capability policies",
"persists $tool with production Ghidra capability policies",
async ({ tool, arguments: parameters }) => {
const fixture = await createSnapshotReplayFixture("rea-ghidra-workflow-");
const profile = createAnalysisProfile(
@@ -554,8 +633,14 @@ describe("Ghidra composed workflow snapshot replay", () => {
{ snapshotPath: fixture.snapshotPath },
);
expect(replay).toEqual(first);
expect(fixture.starts).toHaveLength(1);
expect(fixture.calls).toEqual(initialCalls);
if (process.platform === "win32") {
// The first provider call in a new CLI session admits its source.
expect(fixture.starts).toHaveLength(2);
expect(fixture.calls.length).toBeGreaterThan(initialCalls.length);
} else {
expect(fixture.starts).toHaveLength(1);
expect(fixture.calls).toEqual(initialCalls);
}
},
);
});
@@ -0,0 +1,167 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { skillDestinations } from "../../../src/application/SetupSkill.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
/**
* The registration command setup writes on the host running the tests. Windows
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
*/
const command = npxRegistrationCommand(process.platform);
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const droidPath = (
home: string,
platform: NodeJS.Platform = "linux",
env: Parameters<typeof supportedClients>[2] = {},
) => supportedClients(home, platform, env).find(({ name }) => name === "droid");
describe("Factory Droid configuration paths", () => {
it("resolves the user MCP config file and marker directory", () => {
expect(droidPath("/home/a")).toEqual({
name: "droid",
displayName: "Factory Droid",
configPath: join("/home/a", ".factory", "mcp.json"),
markerPath: join("/home/a", ".factory"),
format: "json",
});
expect(droidPath("/Users/a", "darwin")?.configPath).toBe(
join("/Users/a", ".factory", "mcp.json"),
);
expect(droidPath("C:\\Users\\a", "win32")?.configPath).toBe(
join("C:\\Users\\a", ".factory", "mcp.json"),
);
});
it("resolves the personal skills directory beside the config root", () => {
expect(
skillDestinations("/home/a", ["droid"]).map(({ path }) => path),
).toEqual([
join("/home/a", ".factory", "skills", "reverse-engineer-anything"),
]);
});
});
describe("Factory Droid JSON registration", () => {
const droidClient = async () => {
const home = await createTestTempDirectory("rea-droid-");
const client = droidPath(home, process.platform);
if (client?.markerPath === undefined)
throw new Error("missing Factory Droid client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("upserts rea into mcpServers while preserving unrelated servers and permissions", async () => {
const { home, client } = await droidClient();
await writeFile(
client.configPath,
`{
"mcpServers": {
"other": {
"type": "stdio",
"command": "other",
"args": [],
"disabled": false
}
},
"persistentPermissions": {
"servers": {
"other": { "approvedAt": "2026-01-01T00:00:00.000Z" }
}
}
}`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.other).toEqual({
type: "stdio",
command: "other",
args: [],
disabled: false,
});
expect(parsed.persistentPermissions).toEqual({
servers: { other: { approvedAt: "2026-01-01T00:00:00.000Z" } },
});
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform: process.platform,
environment: {},
})
).find(({ client }) => client === "droid"),
).toMatchObject({ state: "aligned", command });
});
it("creates the mcpServers table in an existing config file without servers", async () => {
const { client } = await droidClient();
await writeFile(
client.configPath,
JSON.stringify({ persistentPermissions: { servers: {} } }, null, 2),
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.persistentPermissions).toEqual({ servers: {} });
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
});
it("registers into an empty config file", async () => {
const { client } = await droidClient();
await writeFile(client.configPath, "");
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
});
it("removes only the rea entry on uninstall", async () => {
const { home, client } = await droidClient();
await writeFile(
client.configPath,
JSON.stringify(
{ mcpServers: { other: { command: "other-server" } } },
null,
2,
),
);
await configureClientConfiguration(client, {}, command);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
expect(parsed.mcpServers.rea).toBeUndefined();
});
});
@@ -1,5 +1,5 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { join, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
@@ -37,28 +37,76 @@ const dshClient = (
env: Parameters<typeof supportedClients>[2],
platform: NodeJS.Platform = "linux",
) =>
supportedClients(join("/home/a"), platform, env).find(
supportedClients(resolve("/home/a"), platform, env).find(
({ name }) => name === "dsh",
);
describe("DeepSeek Harness configuration paths", () => {
it.each([
[undefined, ".dsh", ".agents", "shared"],
["", ".dsh", ".agents", "shared"],
[" \t ", ".dsh", ".agents", "shared"],
["~", "", "", "dsh"],
["~/selected home", "selected home", "selected home", "dsh"],
["~\\selected home", "selected home", "selected home", "dsh"],
] as const)(
"resolves Harness and agents roots for %j",
(override, dshRoot, agentsRoot, client) => {
const home = resolve("/home/a");
const environment = { DSH_HOME: override, DSH_AGENTS_HOME: override };
expect(
supportedClients(home, process.platform, environment).find(
({ name }) => name === "dsh",
),
).toMatchObject({
configPath: join(home, dshRoot, "cordis.patch.yml"),
markerPath: join(home, dshRoot),
});
expect(clientSkillDirectories(home, ["dsh"], environment)).toEqual([
{ client, directory: join(home, agentsRoot, "skills") },
]);
},
);
it.each(["relative home", " literal home ", "~someone"])(
"resolves a literal root %j relative to cwd without trimming it",
(override) => {
const home = resolve("/home/a");
const root = resolve(override);
const environment = { DSH_HOME: override, DSH_AGENTS_HOME: override };
expect(
supportedClients(home, process.platform, environment).find(
({ name }) => name === "dsh",
),
).toMatchObject({
configPath: join(root, "cordis.patch.yml"),
markerPath: root,
});
expect(clientSkillDirectories(home, ["dsh"], environment)).toEqual([
{ client: "dsh", directory: join(root, "skills") },
]);
},
);
it("resolves the home Cordis patch under the Harness home", () => {
expect(dshClient({})).toEqual({
name: "dsh",
displayName: "DeepSeek Harness",
configPath: join("/home/a", ".dsh", "cordis.patch.yml"),
markerPath: join("/home/a", ".dsh"),
configPath: resolve("/home/a", ".dsh", "cordis.patch.yml"),
markerPath: resolve("/home/a", ".dsh"),
format: "dsh",
});
// The home patch applies to every profile; DSH_HOME relocates it.
expect(dshClient({ DSH_HOME: "/custom/harness" })?.configPath).toBe(
join("/custom/harness", "cordis.patch.yml"),
resolve("/custom/harness", "cordis.patch.yml"),
);
expect(
clientSkillDirectories(join("/home/a"), ["dsh"], {
DSH_AGENTS_HOME: "/custom/agents",
}),
).toEqual([{ client: "dsh", directory: join("/custom/agents", "skills") }]);
).toEqual([
{ client: "dsh", directory: resolve("/custom/agents", "skills") },
]);
});
});
@@ -87,3 +87,43 @@ it.each([
);
},
);
it("bounds the Java version probe and reports an over-budget probe as a failed Java check", async () => {
const root = await createTestTempDirectory("rea-java-probe-bound-");
const configuredHome = join(root, "selected-jdk");
const installDir = join(root, "ghidra");
await mkdir(join(installDir, "Ghidra"), { recursive: true });
await writeFile(
join(installDir, "Ghidra", "application.properties"),
`application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=17\n`,
);
// A chatty or hostile JVM that overruns the capture budget: spawnSync reports
// ENOBUFS, which the probe already treats as a failed observation.
mockSpawnSync.mockReturnValue({
stdout: "",
stderr: "java.version = 21.0.11\n",
status: null,
error: Object.assign(new Error("spawnSync /java ENOBUFS"), {
code: "ENOBUFS",
}),
});
const inspection = inspectGhidraInstallation({
environment: {},
installDir,
javaHome: configuredHome,
});
const [, , options] = mockSpawnSync.mock.calls[0] as [
string,
readonly string[],
{ readonly maxBuffer?: number },
];
expect(options.maxBuffer).toBe(1024 * 1024);
expect(inspection.javaVersion).toBeNull();
expect(inspection.javaHome).toBe(configuredHome);
expect(inspection.checks.find(({ name }) => name === "java")).toMatchObject({
status: "failed",
code: "runtime_missing",
});
});
@@ -52,7 +52,7 @@ const target = {
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.3\n",
readText: () => "application.version=12.1.3\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.12",
@@ -191,12 +191,9 @@ describe.skipIf(process.platform === "win32")(
it.each([
["name=other\nversion=12.1.3\n", "does not match"],
["name=ghidra-allegrex\nversion=12.1.4\n", "does not match"],
[
"name=ghidra-allegrex\nversion=12.1.3\nversion=12.1.3\n",
"exactly one version",
],
["name=ghidra-allegrex\nversion=12.1.\\uZZZZ\n", "Unicode escape"],
])(
"rejects incompatible or ambiguous extension metadata %s",
"rejects mismatched or malformed extension metadata %s",
async (properties, reason) => {
const { root } = await installation();
await writeFile(join(root, "extension.properties"), properties);
@@ -504,3 +501,38 @@ describe.skipIf(process.platform === "win32")(
});
},
);
describe.skipIf(process.platform === "win32")(
"PSP extension property syntax",
() => {
it.each([
{
form: "escaped key and value with colon separator",
properties: "n\\u0061me : ghidra-allegrex\nver\\u0073ion=12.1.3\n",
},
{
form: "continued key and value lines",
properties: "name=ghidra-\\\n allegrex\nversion=12.1.\\\n 3\n",
},
{
form: "duplicate keys use the last value",
properties:
"name=wrong\nname=ghidra-allegrex\nversion=12.1.4\nversion=12.1.3\n",
},
])(
"accepts Java Properties $form and hashes raw bytes",
async ({ properties }) => {
const { root } = await installation();
const canonical = await inspectGhidraPspExtension(root, "12.1.3");
const latin1Properties = Buffer.from(
`${properties}author=caf\u00e9\n`,
"latin1",
);
await writeFile(join(root, "extension.properties"), latin1Properties);
const extension = await inspectGhidraPspExtension(root, "12.1.3");
expect(extension.id).toBe("ghidra-allegrex");
expect(extension.sha256).not.toBe(canonical.sha256);
},
);
},
);
@@ -237,6 +237,38 @@ mcp_servers:
expect(await readFile(client.configPath, "utf8")).toBe(original);
});
it("keeps unrelated numbers as written, including Discord IDs", async () => {
const { home, client } = await hermesClient();
// Hermes reads these exactly: two IDs one apart, an octal mode, a float.
const original = `discord:
free_response_channels:
- 1187654321098765432
channel_prompts:
1187654321098765433: Build questions.
1187654321098765434: Release questions.
mode: 0600
min_score: 0.0000001
mcp_servers:
other:
command: other-server
`;
await writeFile(client.configPath, original);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text.startsWith(original)).toBe(true);
expect(parseYaml(text, { intAsBigInt: true })).toMatchObject({
mcp_servers: {
rea: { command: command[0], args: command.slice(1), enabled: true },
},
});
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(await readFile(client.configPath, "utf8")).toBe(original);
});
it("creates config.yaml when Hermes has no configuration yet", async () => {
const { client } = await hermesClient();
expect(
@@ -11,6 +11,7 @@ import {
import { join } from "node:path";
import { promisify } from "node:util";
import { spawn as spawnPty } from "@lydell/node-pty";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -185,6 +186,69 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
});
});
describe("installer TTY fallback", { timeout: 20_000 }, () => {
it("skips automatic setup when stderr is redirected", async () => {
const fixture = await createFixture();
const script = join(process.cwd(), "install.sh");
const wrapper = `
const { spawnSync } = require("node:child_process");
const { openSync, closeSync } = require("node:fs");
const stderr = openSync(process.argv[2], "w");
const child = spawnSync("/bin/bash", [process.argv[1], ...process.argv.slice(3)], {
stdio: ["inherit", "inherit", stderr],
env: process.env,
});
closeSync(stderr);
process.exit(child.status ?? 1);
`;
let output = "";
const terminal = spawnPty(
process.execPath,
["-e", wrapper, script, fixture.installerStderrLog, "--version", "0.3.0"],
{
cwd: process.cwd(),
env: {
...process.env,
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
TERM: "xterm-256color",
},
name: "xterm-256color",
cols: 120,
rows: 40,
},
);
let timedOut = false;
const exitCode = await new Promise<number>((resolve, reject) => {
const timeout = setTimeout(() => {
timedOut = true;
terminal.kill();
}, 10_000);
terminal.onData((data) => {
output += data;
});
terminal.onExit(({ exitCode: code }) => {
clearTimeout(timeout);
if (timedOut)
reject(new Error(`Installer PTY timed out after output: ${output}`));
else resolve(code);
});
});
expect(exitCode).toBe(0);
expect(output).toContain(
`Run ${join(fixture.home, ".local/bin/rea")} setup to configure Hopper and agents.`,
);
expect(await readFile(fixture.reaLog, "utf8")).toBe("--version\n");
expect(await readFile(fixture.installerStderrLog, "utf8")).toBe("");
});
});
describe("truncated installer download", { timeout: 20_000 }, () => {
it("runs nothing from a download truncated after the npm install line", async () => {
const fixture = await createFixture();
@@ -433,6 +497,7 @@ interface InstallerFixture {
readonly temporary: string;
readonly npmLog: string;
readonly reaLog: string;
readonly installerStderrLog: string;
}
const getProcessOutput = (
@@ -456,6 +521,7 @@ const createFixture = async (): Promise<InstallerFixture> => {
const temporary = join(root, "tmp");
const npmLog = join(root, "npm.log");
const reaLog = join(root, "rea.log");
const installerStderrLog = join(root, "installer.stderr.log");
await Promise.all([mkdir(home), mkdir(bin), mkdir(temporary)]);
await Promise.all([
executable(
@@ -507,7 +573,7 @@ exit 0
symlink(`/usr/bin/${command}`, join(bin, command)),
),
]);
return { home, bin, temporary, npmLog, reaLog };
return { home, bin, temporary, npmLog, reaLog, installerStderrLog };
};
const executable = async (path: string, source: string): Promise<void> => {
@@ -1060,6 +1060,142 @@ describe("NIBArchive UIKit event connections", () => {
"UIRuntimeEventConnection",
);
});
it("reports a runtime connection with no resolvable owner as an omission", async () => {
const root = await createTestTempDirectory("rea-ib-ownerless-");
const bundle = join(root, "Example.app");
await mkdir(bundle, { recursive: true });
// The connector is recognized by class, but carries no UISource reference,
// so no connection can be projected from it.
await writeFile(
join(bundle, "Cell.nib"),
encodeNibArchiveFixture({
classes: [
"UIProxyObject",
"UIClassSwapper",
"UIButton",
"UIRuntimeEventConnection",
"NSString",
],
objects: [
{ classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } },
{ classIndex: 1, values: { UIClassName: { ref: 6 } } },
{ classIndex: 2, values: {} },
{
classIndex: 3,
values: { UIDestination: { ref: 1 }, UIEventMask: 64 },
},
{ classIndex: 2, values: {} },
{ classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } },
{ classIndex: 4, values: { "NS.bytes": "BuildCell" } },
],
}),
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
});
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Cell.nib",
status: "partial",
reason: "connection_unresolved",
examined: 0,
omitted: 1,
}),
);
// The keyed-archive producer counts a recognized connector it cannot emit,
// so this producer has to report the same document total for the same
// connector rather than zero.
expect(analysis.documents).toContainEqual(
expect.objectContaining({
relative_path: "Cell.nib",
connection_count: 1,
}),
);
expect(analysis.graph.truncated).toBe(true);
expect(analysis.limitations).toContain(
"Some recognized NIBArchive connectors declare no resolvable owner; they carry no connection evidence and are reported as omissions.",
);
});
});
describe("NIBArchive ownerless connector accounting", () => {
it("keeps a connection dropped by the limit reported as a limit", async () => {
const root = await createTestTempDirectory("rea-ib-ownerless-limit-");
const bundle = join(root, "Example.app");
await mkdir(bundle, { recursive: true });
// Two resolvable connectors and one ownerless connector with the limit
// below the resolvable count, so this facet has both causes at once. Only a
// higher limit recovers the dropped connection, so that is the reason the
// caller needs, exactly as the keyed-archive producer reports it.
await writeFile(
join(bundle, "Cell.nib"),
encodeNibArchiveFixture({
classes: [
"UIProxyObject",
"UIClassSwapper",
"UIButton",
"UIRuntimeEventConnection",
"NSString",
],
objects: [
{ classIndex: 0, values: { UIProxiedObjectIdentifier: { ref: 5 } } },
{ classIndex: 1, values: { UIClassName: { ref: 6 } } },
{ classIndex: 2, values: {} },
{
classIndex: 3,
values: {
UISource: { ref: 2 },
UIDestination: { ref: 1 },
UILabel: { ref: 7 },
UIEventMask: 64,
},
},
{ classIndex: 2, values: {} },
{ classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } },
{ classIndex: 4, values: { "NS.bytes": "BuildCell" } },
{ classIndex: 4, values: { "NS.bytes": "buildTapped:" } },
{
classIndex: 3,
values: {
UISource: { ref: 4 },
UIDestination: { ref: 1 },
UILabel: { ref: 7 },
},
},
{
classIndex: 3,
values: { UIDestination: { ref: 1 }, UIEventMask: 64 },
},
],
}),
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
limits: { max_connections: 1 },
});
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Cell.nib",
status: "partial",
reason: "connection_limit_reached",
examined: 1,
omitted: 2,
}),
);
expect(analysis.documents).toContainEqual(
expect.objectContaining({
relative_path: "Cell.nib",
connection_count: 3,
}),
);
});
});
// This exact file is already selected by the unchanged native Apple CI lane.
@@ -388,7 +388,7 @@ it("produces deterministic ASAR graphs with unpacked native linkage and complete
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
const first = await reconstructJavaScriptArtifact({
input_path: archive,
@@ -487,7 +487,7 @@ it("keeps ASAR analysis usable when unpacked native companion bytes are absent",
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
const snapshot = await scanArtifactInventory(archive);
@@ -515,7 +515,7 @@ it("recurses into filesystem-backed ASAR containers without losing container-rel
const resources = join(outer, "resources");
await mkdir(resources, { recursive: true });
await createPackageWithOptions(source, join(resources, "app.asar"), {
unpack: "**/*.node",
unpack: "*.node",
});
const result = await reconstructJavaScriptArtifact({
@@ -15,6 +15,60 @@ import {
} from "../../../support/javascriptApplicationFixture.js";
describe("TypeScript source module loader semantics", () => {
it("keeps whole type-only declarations out of runtime module relationships", async () => {
const root = await createTestTempDirectory("rea-type-module-links-");
await writeFixtureFiles(root, {
"main.ts": `
import type { Whole } from "./whole";
export type { Remote } from "./remote";
import { type Inline } from "./inline";
export type LocalType = string;
export interface LocalInterface { value: string }
`,
"whole.ts": "export interface Whole { value: string }",
"remote.ts": "export interface Remote { value: string }",
"inline.ts": "export interface Inline { value: string }",
});
const { graph } = await reconstructJavaScriptFixture(root);
const source = findSourceModule(graph, "main.ts");
const sourceProperties = source?.observations.find(
({ properties }) => properties.semantic_role === "source-module",
)?.properties;
expect(sourceProperties).toMatchObject({
import_relationships: 0,
type_relationships: 5,
export_names: [],
type_export_names: ["LocalInterface", "LocalType", "Remote"],
});
expect(
graph.edges.filter(
({ relation, properties }) =>
relation === "imports" &&
["./whole", "./remote"].includes(String(properties.specifier)),
),
).toEqual([]);
expect(
graph.edges.find(
({ source_node_id, relation, properties }) =>
source_node_id === source?.node_id &&
relation === "imports" &&
properties.kind === "static-import" &&
properties.specifier === "./inline",
),
).toBeDefined();
expect(
source?.observations
.flatMap(({ evidence }) => evidence.limitations)
.join(" "),
).toContain(
"inline type-only imports or re-exports may preserve a module side-effect dependency",
);
expect(findExportNode(graph, "main.ts", "LocalType")).toBeUndefined();
expect(findExportNode(graph, "main.ts", "LocalInterface")).toBeUndefined();
});
it("uses emitted TypeScript loader semantics without changing dynamic imports", async () => {
const root = await createTestTempDirectory("rea-cts-module-loader-");
await writeFixtureFiles(root, {
@@ -98,7 +152,7 @@ describe("TypeScript source module loader semantics", () => {
});
});
describe("CommonJS and ESM module relationships", () => {
describe("JavaScript module relationships", () => {
it("composes bindings, re-exports, dynamic imports, and JSON modules", async () => {
const root = await moduleFixture();
const first = await reconstructJavaScriptFixture(root);
@@ -234,6 +288,122 @@ describe("CommonJS and ESM module relationships", () => {
});
});
describe("Compiler-dependent TypeScript resolution", () => {
it("retains only compiler-independent targets for .ts static imports", async () => {
const root = await createTestTempDirectory("rea-ts-conditional-loader-");
await writeFixtureFiles(root, {
"package.json": '{"type":"commonjs"}',
"main.ts": `import { value as different } from "different";
import { value as same } from "same";
void different; void same;`,
"node_modules/different/package.json": JSON.stringify({
exports: {
".": {
import: "./import.mjs",
require: "./require.cjs",
},
},
}),
"node_modules/different/import.mjs": "export const value = 'import';",
"node_modules/different/require.cjs": "exports.value = 'require';",
"node_modules/same/package.json": JSON.stringify({
exports: { ".": { import: "./shared.js", require: "./shared.js" } },
}),
"node_modules/same/shared.js": "export const value = 'shared';",
});
const { graph } = await reconstructJavaScriptFixture(root);
const different = findRelationshipEdge(graph, {
kind: "import",
specifier: "different",
localName: "different",
});
const same = findRelationshipEdge(graph, {
kind: "import",
specifier: "same",
localName: "same",
resolvedPath: "node_modules/same/shared.js",
});
const staticFinding = (specifier: string) =>
graph.edges.find(
({ relation, properties }) =>
relation === "imports" &&
properties.kind === "static-import" &&
properties.specifier === specifier,
);
expect(
findSourceModule(graph, "main.ts")?.observations[0]?.properties,
).toMatchObject({ module_format: "unknown" });
expect(different).toMatchObject({
properties: {
resolution_mode: "compiler-dependent",
resolution_status: "unavailable",
resolved_path: null,
conditional_resolutions: [
{
mode: "import",
resolution_status: "resolved",
resolved_path: "node_modules/different/import.mjs",
},
{
mode: "require",
resolution_status: "resolved",
resolved_path: "node_modules/different/require.cjs",
},
],
},
});
expect(same).toMatchObject({
properties: {
resolution_mode: "compiler-dependent",
resolved_path: "node_modules/same/shared.js",
resolution_status: "resolved",
},
evidence: {
limitations: expect.arrayContaining([
expect.stringContaining(
"compiler-dependent without retained compiler options",
),
]),
},
});
expect(staticFinding("different")).toMatchObject({
properties: {
resolution_mode: "compiler-dependent",
resolution_status: "unavailable",
conditional_resolutions: [
{
mode: "import",
resolved_path: "node_modules/different/import.mjs",
},
{
mode: "require",
resolved_path: "node_modules/different/require.cjs",
},
],
},
evidence: {
limitations: expect.arrayContaining([
expect.stringContaining(
"compiler-dependent without retained compiler options",
),
]),
},
});
expect(staticFinding("same")).toMatchObject({
properties: { resolved_path: "node_modules/same/shared.js" },
evidence: {
limitations: expect.arrayContaining([
expect.stringContaining(
"compiler-dependent without retained compiler options",
),
]),
},
});
});
});
it("does not assign one module origin to an export with colliding path encodings", async () => {
const root = await createTestTempDirectory("rea-ambiguous-module-origin-");
await writeFixtureFiles(root, {
@@ -21,6 +21,7 @@ import {
type ApplicationVersionComparisonResult,
} from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { electronPageInspectionSchema } from "../../../src/domain/javascript/electronObservation.js";
import { compareJavaScriptApplicationVersions } from "../../../src/domain/javascript/javascriptApplicationVersionComparison.js";
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
import { traceApplicationFeature } from "../../../src/domain/javascript/javascriptFeatureTrace.js";
@@ -443,7 +444,98 @@ describe("JavaScript application workflow error diagnostics", () => {
});
});
const RUNTIME_PATH_CASES = [
{
name: "case-sensitive POSIX input root",
root: null,
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
status: "unknown",
basis: "none",
},
{
name: "case-sensitive POSIX mapping root",
root: "/runtime/App",
path: "/runtime/app/renderer.js",
status: "unknown",
basis: "none",
},
{
name: "matching POSIX mapping root",
root: "/runtime/App",
path: "/runtime/App/renderer.js",
status: "matched",
basis: "operator-file-mapping",
},
{
name: "case-insensitive Windows mapping root",
root: String.raw`C:\runtime\App`,
path: String.raw`c:\runtime\app\renderer.js`,
status: "matched",
basis: "operator-file-mapping",
},
] as const;
describe("JavaScript runtime reconciliation local paths", () => {
it.each(RUNTIME_PATH_CASES)(
"uses $name on every host",
({ root, path, status, basis }) => {
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
const original = base.runtime_observations[0]!;
const inspection = electronPageInspectionSchema.parse(
original.normalized_result,
);
// Keep target and script coordinates consistent so an unrelated target
// cannot activate the static layer after its script mapping was rejected.
const runtime = createEvidence(undefined, original.provider, {
predicateType: original.predicate_type,
operation: original.operation,
parameters: { ...original.parameters, include_script_sources: false },
result: {
...inspection,
target: { ...inspection.target, file_path: path },
scripts: {
...inspection.scripts,
items: inspection.scripts.items.map((script) => ({
...script,
file_path: path,
source: { included: false, reason: "not-requested" },
})),
},
},
confidence: original.confidence,
authority: original.authority,
});
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: base.static_layers.map((layer) => ({
...layer,
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
})),
runtime_observations: [runtime],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
);
expect(
result.reconciliations.find(
({ entity_kind }) => entity_kind === "script",
),
).toMatchObject({ status, basis });
expect(
result.static_load_states.find(
({ kind }) => kind === "javascript-asset",
),
).toMatchObject(
status === "matched"
? { status: "loaded", reason: "runtime-script-correspondence" }
: { status: "unknown", reason: "layer-outside-runtime-scope" },
);
expect(result.static_layers[0]?.runtime_mappings).toEqual(
root === null ? [] : [{ kind: "file-root", root, artifact_prefix: "" }],
);
},
);
it("resolves relative file mapping roots before deriving result Evidence", () => {
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
const relativeRoot = relative(process.cwd(), absoluteRoot);
@@ -105,6 +105,34 @@ it("keeps a contradicted nested ASAR opaque during JavaScript reconstruction", a
expect(result.graph.coverage.omitted_count).toBeNull();
});
it("keeps an ASAR-named file without an ASAR header opaque during JavaScript reconstruction", async () => {
const root = await createTestTempDirectory("rea-opaque-asar-name-");
await writeFile(join(root, "main.js"), "export const outer = true;\n");
// Inventory records this file as ordinary bytes and does not expand it.
await writeFile(join(root, "ordinary.asar"), "ordinary bytes");
const snapshot = await scanCanonicalArtifactInventory(root, {});
const reader = createJavaScriptArtifactReader(root, "directory");
try {
const read = await readJavaScriptArtifactFiles(reader, snapshot);
expect(read.files.map(({ path }) => path)).toEqual(["main.js"]);
expect(read.containers).toEqual([]);
} finally {
await reader.close();
}
const analyzed = await analyzeJavaScriptApplication({
input_path: root,
format: "directory",
});
if (!analyzed.ok) throw analyzed.error;
const result = javascriptApplicationAnalysisResultSchema.parse(
analyzed.value.normalized_result,
);
expect(result.statistics.nested_asar_containers).toBe(0);
expect(result.integrity_contradictions).toEqual([]);
});
it("retains semantic resource limits alongside recorded integrity contradictions", async () => {
const { archive } = await createStrippedAsarAddon([
{ path: "app.js", contents: primitiveCandidateExpansionSource() },
@@ -1,5 +1,11 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import {
mkdir,
readFile,
realpath,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -7,6 +13,37 @@ import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("raw-binary admission", () => {
it("preserves the requested raw path for Windows reparse admission", async () => {
const directory = await createTestTempDirectory("rea-raw-linked-");
const actual = join(directory, "actual");
const linked = join(directory, "linked");
await mkdir(actual);
const bytes = Buffer.from("a90160", "hex");
await writeFile(join(actual, "fixture.bin"), bytes);
await symlink(
actual,
linked,
process.platform === "win32" ? "junction" : "dir",
);
const requested = join(linked, "fixture.bin");
const canonical = await realpath(requested);
const target = await parseBinaryTarget("linked/fixture.bin", {
cwd: directory,
formatHint: "raw-binary",
architecture: "6502",
entryPoint: "0x8000",
});
expect(target).toMatchObject({
ok: true,
value: {
path: canonical,
sourcePath: process.platform === "win32" ? requested : canonical,
sha256: createHash("sha256").update(bytes).digest("hex"),
format: "raw-binary",
architecture: "6502",
},
});
});
it("requires explicit architecture and entry even with a misleading suffix", async () => {
const directory = await createTestTempDirectory("rea-raw-target-");
const path = join(directory, "fixture.js");
@@ -378,6 +378,44 @@ describe("reference source path selection", () => {
});
describe("reference source rooted module specifiers", () => {
it("keeps dot-prefixed bare specifiers external while resolving explicit relative paths", async () => {
const root = await createTestTempDirectory("rea-reference-dot-prefix-");
await Promise.all([
writeFile(
join(root, "main.js"),
'import ".hidden.js"; import "..pkg.js"; import "./.hidden.js"; require(".hidden.js");\n',
),
writeFile(join(root, ".hidden.js"), "export {};\n"),
writeFile(join(root, "..pkg.js"), "export {};\n"),
]);
const result = await importTree(root);
if (!result.ok) throw result.error;
expect(result.value.relationships).toEqual(
expect.arrayContaining([
expect.objectContaining({
to: ".hidden.js",
kind: "imports",
resolution: "external",
}),
expect.objectContaining({
to: "..pkg.js",
kind: "imports",
resolution: "external",
}),
expect.objectContaining({
to: ".hidden.js",
kind: "imports",
resolution: "internal",
}),
expect.objectContaining({
to: ".hidden.js",
kind: "requires",
resolution: "external",
}),
]),
);
});
it("does not rebase an absolute import onto a coincidentally matching source member", async () => {
const root = await createTestTempDirectory("rea-reference-rooted-");
await mkdir(join(root, "src", "outside"), { recursive: true });
@@ -6,6 +6,31 @@ import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
it("imports valid CommonJS wrapper syntax without inventing a parse failure", async () => {
const root = await createTestTempDirectory("rea-reference-commonjs-mode-");
await Promise.all([
writeFile(
join(root, "main.cjs"),
'void new.target; require("./dep.cjs"); return;\n',
),
writeFile(join(root, "dep.cjs"), "module.exports = 1;\n"),
]);
const imported = await importReferenceSource({
root,
caller: "native-commonjs-source",
policy: { secretPatterns: [] },
});
if (!imported.ok) throw imported.error;
expect(imported.value.parse_failures).toEqual([]);
expect(imported.value.relationships).toContainEqual({
from_path: "main.cjs",
to: "dep.cjs",
kind: "requires",
resolution: "internal",
parse_state: "parsed",
});
});
it.each([
["main.ts", "dep.js", "dep.ts"],
["main.mts", "dep.mjs", "dep.mts"],
@@ -649,9 +649,8 @@ it.skipIf(process.platform === "win32").each([
const sourceSha = await candidate(f, valid ? "6.0.0" : "5.1.0");
const workflow = z
.object({
jobs: z.record(
z.string(),
z.object({
jobs: z.object({
[job]: z.object({
steps: z.array(
z.object({
name: z.string().optional(),
@@ -659,7 +658,7 @@ it.skipIf(process.platform === "win32").each([
}),
),
}),
),
}),
})
.parse(
parse(
@@ -34,6 +34,12 @@ async function readReleaseWorkflow() {
"release-proposal": jobSchema,
"release-please": jobSchema,
"merged-release": jobSchema,
qualification: z.object({
if: z.string(),
needs: z.array(z.string()),
uses: z.string(),
with: z.record(z.string(), z.string()),
}),
publish: jobSchema,
"publish-mcp": jobSchema,
}),
@@ -271,10 +277,19 @@ it("binds npm and MCP publication to the same immutable release SHA", async () =
release_created: "${{ steps.release.outputs.release_created }}",
sha: "${{ steps.release.outputs.sha }}",
});
expect(workflow.jobs.publish.if).toContain("inputs.phase == 'publish'");
expect(workflow.jobs.publish.if).toContain(
expect(workflow.jobs.qualification.if).toContain("inputs.phase == 'publish'");
expect(workflow.jobs.qualification.if).toContain(
"needs.release-please.outputs.release_created",
);
expect(workflow.jobs.qualification.uses).toBe("./.github/workflows/ci.yml");
expect(workflow.jobs.qualification.with).toEqual({
source_sha:
"${{ needs.merged-release.outputs.sha || needs.release-please.outputs.sha }}",
});
expect(workflow.jobs.publish.needs).toContain("qualification");
expect(workflow.jobs.publish.if).toContain(
"needs.qualification.result == 'success'",
);
expect(workflow.jobs["publish-mcp"].if).toContain(
"needs.publish.result == 'success'",
);
@@ -309,7 +324,7 @@ it("binds npm and MCP publication to the same immutable release SHA", async () =
)?.run;
expect(publishCommand).toContain("scripts/release-npm-tag.mjs");
expect(publishCommand).toContain(
'npm publish --access public --tag "${tag}"',
'npm publish "${VERIFIED_PACKAGE_TARBALL}" --access public --tag "${tag}"',
);
for (const [version, tag] of [
["6.1.0", "latest"],
@@ -644,7 +659,7 @@ it("routes website verification through the central PR policy", async () => {
// Publishing is irreversible. Keep the release authority invariant as a static
// boundary check; it is not proof that package installation or publishing works.
it("requires package verification before publishing and retains the registry canary", async () => {
it("requires qualified package validation before publishing and retains the registry canary", async () => {
const workflow = z
.object({
jobs: z.object({
@@ -663,7 +678,7 @@ it("requires package verification before publishing and retains the registry can
);
const commands = workflow.jobs.publish.steps.map(({ run }) => run ?? "");
const verify = commands.findIndex((command) =>
command.includes("npm run verify:package"),
command.includes("scripts/ci/verified-package.mjs validate"),
);
const publish = commands.findIndex((command) =>
command.includes("npm publish"),
@@ -489,4 +489,28 @@ describe("safe artifact output Windows stream paths", () => {
await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" });
expect(await readdir(parent)).toEqual([]);
});
it.each(["Folder/Icon\r", "Fold\ter/file.txt"])(
"refuses Windows control characters before creating %j",
async (path) => {
const parent = await createTestTempDirectory("rea-safe-output-control-");
const output = join(parent, "published");
const tree = await SafeOutputTree.create(output, "win32");
const bytes = Buffer.from("regular file content");
await expect(
tree.write(path, Readable.from(bytes), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
}),
).rejects.toMatchObject({
reason: "path",
message: `Windows destination cannot materialize artifact path: ${JSON.stringify(path)}; Windows names cannot contain U+0001-U+001F.`,
});
expect(await readdir(output)).toEqual([]);
expect(await tree.rollback()).toEqual({
status: "complete",
residualPaths: [],
});
},
);
});
@@ -10,6 +10,8 @@ const injectedFilesystemFailures = vi.hoisted(() => ({
closeNext: false,
blockCloseRetries: false,
chmodNext: false,
syncAbortAfter: undefined as AbortController | undefined,
syncCount: 0,
rootIdentityPath: undefined as string | undefined,
}));
@@ -44,6 +46,15 @@ vi.mock("node:fs/promises", async (importOriginal) => {
await close();
};
}
if (injectedFilesystemFailures.syncAbortAfter !== undefined) {
const sync = handle.sync.bind(handle);
handle.sync = async () => {
await sync();
injectedFilesystemFailures.syncCount += 1;
if (injectedFilesystemFailures.syncCount === 2)
injectedFilesystemFailures.syncAbortAfter?.abort();
};
}
return handle;
},
};
@@ -82,6 +93,34 @@ describe("safe artifact output close failures", () => {
},
);
it.skipIf(process.platform === "win32")(
"keeps the tree unpublished when cancellation arrives during commit durability",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-cancel-");
const output = join(parent, "unpublished");
const tree = await SafeOutputTree.create(output);
const bytes = Buffer.from("pending output");
await tree.write("file.txt", Readable.from(bytes), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
});
const controller = new AbortController();
injectedFilesystemFailures.syncCount = 0;
injectedFilesystemFailures.syncAbortAfter = controller;
try {
await expect(tree.commit(controller.signal)).rejects.toMatchObject({
reason: "cancelled",
});
expect(tree.published).toBe(false);
} finally {
injectedFilesystemFailures.syncAbortAfter = undefined;
injectedFilesystemFailures.syncCount = 0;
}
expect(await tree.rollback()).toMatchObject({ status: "complete" });
await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.skipIf(process.platform === "win32")(
"preserves setup failure when closing the staging handle also fails",
async () => {
@@ -11,6 +11,7 @@ import {
} from "../../../src/application/SetupHost.js";
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
import { configureDetectedClients } from "../../../src/application/SetupClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
vi.mock("node:fs/promises", async (importOriginal) => {
@@ -31,6 +32,61 @@ beforeEach(async () => {
afterEach(() => openMock.mockReset());
const holdReadHandle = (path: string, reason: string) => {
const closeAttempts: object[] = [];
let released = false;
openMock.mockImplementation(async (...args) => {
const handle = await actualFs.open(...args);
if (String(args[0]) !== path) return handle;
const nativeClose = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeAttempts.push(handle);
if (!released) throw new Error(reason);
await nativeClose();
});
return handle;
});
return {
closeAttempts,
release: () => {
released = true;
},
};
};
it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fails", async () => {
const home = await createTestTempDirectory("rea-uninstall-utf8-close-");
const path = join(home, "client.json");
const original = Buffer.from([0xff]);
await writeFile(path, original);
const { closeAttempts, release } = holdReadHandle(
path,
"held uninstall handle",
);
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
try {
expect(
await host.removeClient({
name: "cursor",
format: "json",
configPath: path,
}),
).toMatchObject({
status: "failed",
detail: expect.stringContaining("not valid UTF-8"),
});
expect(await readFile(path)).toEqual(original);
expect(closeAttempts).toHaveLength(2);
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
} finally {
release();
await host.close?.();
}
});
describe("ZCode fallback cleanup ownership", () => {
it.each(["preflight", "configure"])(
"retains a failed ZCode fallback close during %s until host cleanup",
@@ -49,19 +105,10 @@ describe("ZCode fallback cleanup ownership", () => {
await mkdir(dirname(fallback), { recursive: true });
const original = '{"mcpServers":{"other":{"command":"other"}}}\n';
await writeFile(fallback, original);
const closeAttempts: object[] = [];
let allowClose = false;
openMock.mockImplementation(async (...args) => {
const handle = await actualFs.open(...args);
if (String(args[0]) !== fallback) return handle;
const nativeClose = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeAttempts.push(handle);
if (!allowClose) throw new Error("held fallback handle");
await nativeClose();
});
return handle;
});
const { closeAttempts, release } = holdReadHandle(
fallback,
"held fallback handle",
);
try {
const action =
operation === "preflight"
@@ -79,12 +126,12 @@ describe("ZCode fallback cleanup ownership", () => {
await expect(readFile(client.configPath)).rejects.toMatchObject({
code: "ENOENT",
});
allowClose = true;
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
} finally {
allowClose = true;
release();
await host.close?.();
}
},
@@ -92,83 +139,87 @@ describe("ZCode fallback cleanup ownership", () => {
});
describe("setup client configuration cleanup ownership", () => {
it("stops client configuration and retries the same alignment handle from host close", async () => {
const home = await createTestTempDirectory("rea-setup-config-close-");
const environment = {
HOME: home,
XDG_CONFIG_HOME: join(home, "xdg"),
};
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
environment,
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
const original = Buffer.from('{"servers": {"other": {}}}\n');
await writeFile(client.configPath, original);
it.each([
["valid UTF-8", Buffer.from('{"servers": {"other": {}}}\n')],
["malformed UTF-8", Buffer.from([0xff])],
] as const)(
"stops configuration and retains the %s read owner until host close",
async (encoding, original) => {
const home = await createTestTempDirectory("rea-setup-config-close-");
const environment = {
HOME: home,
XDG_CONFIG_HOME: join(home, "xdg"),
};
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
environment,
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(client.configPath, original);
const closeAttempts: object[] = [];
let allowClose = false;
openMock.mockImplementation(async (...args) => {
const handle = await actualFs.open(...args);
if (String(args[0]) !== client.configPath) return handle;
const nativeClose = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeAttempts.push(handle);
if (!allowClose) throw new Error("test holds the config handle open");
await nativeClose();
});
return handle;
});
const configure = vi.spyOn(host, "configureClient");
const { closeAttempts, release } = holdReadHandle(
client.configPath,
"test holds the config handle open",
);
const configure = vi.spyOn(host, "configureClient");
try {
const failure = await filterClientsNeedingConfigure(host, [client], {}, [
"rea",
"mcp",
])
.then((detectedClients) =>
configureDetectedClients({
host,
detectedClients,
providerEnvironment: {},
command: ["rea", "mcp"],
clients: {},
appliedActions: [],
}),
try {
const failure = await filterClientsNeedingConfigure(
host,
[client],
{},
["rea", "mcp"],
)
.then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(ConfigurationError);
expect(failure).toMatchObject({
_tag: "ConfigurationError",
cause: expect.any(RegularFileCleanupFailure),
cleanup: {
resources: [client.configPath],
reason: expect.stringContaining("test holds the config handle open"),
},
});
expect(configure).not.toHaveBeenCalled();
expect(closeAttempts).toHaveLength(2);
expect(closeAttempts[0]).toBe(closeAttempts[1]);
expect(await readFile(client.configPath)).toEqual(original);
.then((detectedClients) =>
configureDetectedClients({
host,
detectedClients,
providerEnvironment: {},
command: ["rea", "mcp"],
clients: {},
appliedActions: [],
}),
)
.then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(ConfigurationError);
if (encoding === "malformed UTF-8")
expect(failure).toMatchObject({
cause: {
outcome: { kind: "failed", cause: expect.any(TypeError) },
},
});
expect(failure).toMatchObject({
_tag: "ConfigurationError",
cause: expect.any(RegularFileCleanupFailure),
cleanup: {
resources: [client.configPath],
reason: expect.stringContaining(
"test holds the config handle open",
),
},
});
expect(configure).not.toHaveBeenCalled();
expect(closeAttempts).toHaveLength(2);
expect(closeAttempts[0]).toBe(closeAttempts[1]);
expect(await readFile(client.configPath)).toEqual(original);
allowClose = true;
const close = host.close;
if (close === undefined) throw new Error("Setup host close is missing");
expect(await close()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
} finally {
allowClose = true;
await host.close?.();
}
});
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
} finally {
release();
await host.close?.();
}
},
);
it("waits for an admitted configuration read and rejects later admissions", async () => {
const home = await createTestTempDirectory("rea-setup-config-inflight-");
@@ -6,7 +6,7 @@ import { analyzeJavaScriptApplication } from "../../support/javascriptApplicatio
import { parseApplicationGraphEvidence } from "../../../src/application/javascript/JavaScriptApplicationEvidenceGraph.js";
import { findApplicationFeatureSeeds } from "../../../src/domain/javascript/javascriptFeatureSeed.js";
import { compareSourceToBundle } from "../../../src/domain/javascript/sourceToBundleComparison.js";
import { resolveSourceMapSource } from "../../../src/javascript/sourceMaps/DecodedSourceMap.js";
import { resolveJavaScriptSourceMapUrl } from "../../../src/domain/javascript/javascriptSourceMapPaths.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
@@ -180,7 +180,7 @@ it.each([
decoy: decoyPath = "src/a.js",
}) => {
if (sourceRoot !== undefined) {
const resolved = resolveSourceMapSource(
const resolved = resolveJavaScriptSourceMapUrl(
source,
sourceRoot,
`https://example.test/${mapPath}`,
@@ -31,9 +31,12 @@ it("reads exact binary and empty bytes and rejects symlink/size/cancellation bou
});
const controller = new AbortController();
controller.abort();
await expect(readStableArtifact(real, 3, controller.signal)).rejects.toBe(
controller.signal.reason,
);
await expect(
readStableArtifact(real, 3, controller.signal),
).rejects.toMatchObject({
reason: "cancelled",
cause: controller.signal.reason,
});
});
const checkChange = async (
@@ -1,6 +1,6 @@
import { spawnSync } from "node:child_process";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join, sep } from "node:path";
import { dirname, join, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { z } from "zod";
@@ -138,6 +138,36 @@ it("keeps lint errors failing and visible alongside the retained warnings", asyn
);
});
it("excludes translation staging while retaining authored website errors", async () => {
const root = await fixture();
for (const name of [".gitignore", ".oxlintrc.json"])
await writeFile(join(root, name), await readFile(join(repository, name)));
const authored = "website/public/assets/authored.js";
const staged =
"website/.i18n-regression/site/examples/notes-electron/main.js";
for (const name of [authored, staged]) {
const path = join(root, name);
await mkdir(dirname(path), { recursive: true });
await writeFile(
path,
'const source = require("node:fs");\nconsole.log(source);\n',
);
}
const result = invoke(root, "lint");
expect(result.error).toBeUndefined();
expect(result.status).toBe(1);
expect(result.stdout).toContain("1 errors, 0 warnings");
expect(result.stderr).toContain(authored);
expect(await lintDiagnostics(root)).toEqual([
expect.objectContaining({
severity: "error",
code: "typescript(no-var-requires)",
filename: authored,
}),
]);
});
it("keeps malformed source failing with its parser diagnostic", async () => {
const root = await fixture();
await writeFile(join(root, "src/malformed.js"), "const value = ;\n");
@@ -4,9 +4,35 @@ import { describe, expect, it } from "vitest";
import { systemDoctorHost } from "../../../src/application/Doctor.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { pe } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("executable format refusal diagnostics", () => {
it.each([
[0x01a6, "0x01a6"],
[0x0000, "0x0000"],
[0xffff, "0xffff"],
] as const)(
"retains unsupported PE machine %i in the refusal",
async (machine, expectedMachine) => {
const directory = await createTestTempDirectory("rea-target-pe-machine-");
const path = join(directory, "unsupported.exe");
const bytes = pe(0x014c);
bytes.writeUInt16LE(machine, 0x44);
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (result.ok) throw new Error("unsupported PE target was admitted");
const reason = `unsupported PE architecture (COFF machine ${expectedMachine})`;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "target_unavailable",
category: "unsupported_target",
message: `Cannot open artifact: ${reason}.`,
details: { reason, constraint: "file_format_rejected" },
});
},
);
it.each(["NE", "LE", "LX"] as const)(
"reports unsupported %s executables without path advice",
async (signature) => {
@@ -1,6 +1,6 @@
import { execFile } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { cp, readFile, writeFile } from "node:fs/promises";
import { basename, join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
@@ -78,7 +78,7 @@ it.skipIf(process.platform === "android")(
await workflowGit(root, ["init", "--initial-branch=main"]);
await workflowGit(root, ["add", "."]);
await workflowGit(root, ["commit", "-m", "test: seed cache fixture"]);
const run = () =>
const run = (cwd = root) =>
execute(
process.execPath,
[
@@ -87,7 +87,7 @@ it.skipIf(process.platform === "android")(
"test:run",
"--output-logs=errors-only",
],
{ cwd: root, env: { ...process.env, TURBO_DAEMON: "false" } },
{ cwd, env: { ...process.env, TURBO_DAEMON: "false" } },
);
await run();
await writeFile(join(root, "README_zh.md"), "wrong command");
@@ -104,5 +104,32 @@ it.skipIf(process.platform === "android")(
"prepared\n",
);
}
// Provider jobs receive the producer's cache in a fresh checkout, not its
// outputs. Turbo must restore identical inputs and rebuild changed ones.
const consumer = await createTestTempDirectory("rea-cache-consumer-");
await cp(root, consumer, {
recursive: true,
filter: (path) =>
basename(path) !== ".turbo" &&
!/^prepared-\d+\.txt$/u.test(basename(path)),
});
await cp(join(root, ".turbo/cache"), join(consumer, ".turbo/cache"), {
recursive: true,
});
const restored = await run(consumer);
expect(restored.stdout).toContain(`${dependencies.length} cached`);
for (const index of dependencies.keys())
expect(
await readFile(join(consumer, `prepared-${index}.txt`), "utf8"),
).toBe("prepared\n");
await writeFile(
join(consumer, "artifact-input.txt"),
"changed producer input",
);
await run(consumer);
for (const index of dependencies.keys())
expect(
await readFile(join(consumer, `prepared-${index}.txt`), "utf8"),
).toBe("prepared\nprepared\n");
},
);
@@ -0,0 +1,117 @@
import { createHash } from "node:crypto";
import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { expect } from "vitest";
import { processTest as test } from "../../support/process/processFixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
test("generates locked inventory and rejects stale notice metadata or preserved texts", async ({
processes,
}) => {
const root = await createTestTempDirectory("rea-notice-records-");
await mkdir(resolve(root, "scripts/lib"), { recursive: true });
await mkdir(resolve(root, "licenses"));
for (const file of [
"scripts/generate-third-party-inventory.mjs",
"scripts/lib/generated-file.mjs",
])
await copyFile(resolve(file), resolve(root, file));
const script = resolve(root, "scripts/generate-third-party-inventory.mjs");
const runtime = {
version: "1.0.0",
license: "MIT",
resolved:
"https://registry.npmjs.org/fixture-runtime/-/fixture-runtime-1.0.0.tgz",
integrity: "sha512-fixture-integrity",
optional: true,
};
await writeFile(
resolve(root, "package-lock.json"),
JSON.stringify({
packages: {
"": { name: "fixture", version: "1.0.0" },
"node_modules/fixture-runtime": runtime,
"node_modules/fixture-dev": { ...runtime, dev: true, optional: false },
},
}),
);
const generated = await processes.run(process.execPath, [script]);
expect(generated.exitCode, generated.stderr).toBe(0);
const inventory = await readFile(
resolve(root, "licenses/npm-dependencies.txt"),
"utf8",
);
expect(inventory).toContain("Locked package entries: 2; runtime: 1.");
expect(inventory).toContain(
"fixture-runtime@1.0.0 | runtime, optional | MIT",
);
expect(inventory).toContain("fixture-dev@1.0.0 | development | MIT");
const fingerprint = (
JSON.parse(generated.stdout) as { runtime_dependency_fingerprint: string }
).runtime_dependency_fingerprint;
const notice = [
`Runtime dependency fingerprint (SHA-256): ${fingerprint}`,
"",
"===== fixture-runtime@1.0.0 =====",
"Declared license: MIT",
`Archive: ${runtime.resolved}`,
`Integrity: ${runtime.integrity}`,
"",
"Fixture text; this test does not establish real package attribution.",
"",
].join("\n");
const noticePath = resolve(root, "licenses/npm-runtime-notices.txt");
const referencePath = resolve(root, "licenses/reference.txt");
await writeFile(noticePath, notice);
await writeFile(referencePath, "preserved fixture text\n");
await writeFile(
resolve(root, "licenses/upstream-sources.json"),
JSON.stringify([
{
file: "licenses/reference.txt",
sha256: createHash("sha256")
.update("preserved fixture text\n")
.digest("hex"),
},
]),
);
const check = () => processes.run(process.execPath, [script, "--check"]);
const valid = await check();
expect(valid.exitCode, valid.stderr).toBe(0);
for (const [changed, diagnostic] of [
[
notice.replace(
"===== fixture-runtime@1.0.0 =====",
"===== another-package@1.0.0 =====",
),
"Missing runtime notice",
],
[
notice.replace(runtime.integrity, "sha512-different"),
"Runtime notice metadata differs",
],
[
notice.replace(fingerprint, "0".repeat(64)),
"Runtime notice fingerprint differs",
],
[
notice + notice.slice(notice.indexOf("===== ")),
"Duplicate runtime notice",
],
] as const) {
await writeFile(noticePath, changed);
const rejected = await check();
expect(rejected.exitCode).toBe(1);
expect(rejected.stderr).toContain(diagnostic);
}
await writeFile(noticePath, notice);
await writeFile(referencePath, "changed fixture text\n");
const tampered = await check();
expect(tampered.exitCode).toBe(1);
expect(tampered.stderr).toContain("Preserved notice digest differs");
expect(
await readFile(resolve(root, "licenses/npm-dependencies.txt"), "utf8"),
).toBe(inventory);
});
@@ -0,0 +1,96 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
const injected = vi.hoisted(() => ({
sourcePath: undefined as string | undefined,
abortController: undefined as AbortController | undefined,
failClose: false,
closeAttempts: 0,
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
...actual,
open: async (...args: Parameters<typeof actual.open>) => {
const handle = await actual.open(...args);
if (args[0] !== injected.sourcePath) return handle;
const createReadStream = handle.createReadStream.bind(handle);
handle.createReadStream = (options) => {
injected.abortController?.abort();
return createReadStream(options);
};
const close = handle.close.bind(handle);
handle.close = async () => {
injected.closeAttempts += 1;
if (injected.failClose) throw new Error("fixture close refusal");
await close();
};
return handle;
},
};
});
import { WebModuleTraceService } from "../../../src/application/WebModuleTraceService.js";
import { LocalWebModuleArtifacts } from "../../../src/browser/modules/WebModuleArtifacts.js";
import { webModuleArtifactsFixture } from "../../fixtures/webModuleTrace.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("retains cancelled source read ownership until service close retries it", async () => {
const root = await createTestTempDirectory("rea-web-artifact-read-owner-");
onTestFinished(async () => {
injected.sourcePath = undefined;
injected.abortController = undefined;
injected.failClose = false;
injected.closeAttempts = 0;
await rm(root, { recursive: true, force: true });
});
const source = 'import "./dep.js";';
const fixture = webModuleArtifactsFixture(source);
const manifestPath = join(root, "manifest.json");
const sourcePath = join(root, "files", "modules", "main.js");
await mkdir(join(root, "files", "modules"), { recursive: true });
await writeFile(sourcePath, source);
await writeFile(manifestPath, JSON.stringify(fixture.manifest));
injected.sourcePath = sourcePath;
injected.failClose = true;
const controller = new AbortController();
injected.abortController = controller;
const resolver = {
resolve: vi.fn(),
close: vi.fn(async () => undefined),
};
const service = new WebModuleTraceService(
new LocalWebModuleArtifacts(),
resolver,
);
const input = { manifest_path: manifestPath, script_index: 0 };
const cancelled = await service.trace(input, { signal: controller.signal });
expect(cancelled.ok).toBe(false);
if (cancelled.ok) throw new Error("Expected cancelled source read");
expect(cancelled.error.cleanupIncomplete).toBe(true);
expect(cancelled.error.cleanupResources).toContain(sourcePath);
expect(resolver.resolve).not.toHaveBeenCalled();
injected.abortController = undefined;
const blocked = await service.trace(input);
expect(blocked.ok).toBe(false);
if (blocked.ok) throw new Error("Expected retained cleanup to block load");
expect(blocked.error.cleanupIncomplete).toBe(true);
expect(injected.closeAttempts).toBe(2);
await expect(service.close()).rejects.toThrow(
"Web module trace cleanup failed",
);
expect(resolver.close).toHaveBeenCalledTimes(1);
expect(injected.closeAttempts).toBe(3);
injected.failClose = false;
const attemptsBeforeRetry = injected.closeAttempts;
await service.close();
expect(injected.closeAttempts).toBeGreaterThan(attemptsBeforeRetry);
expect(resolver.close).toHaveBeenCalledTimes(2);
});
+35
View File
@@ -1,4 +1,10 @@
import { expect, it } from "vitest";
import { javaClassFile } from "../../fixtures/javaClassFile.js";
import {
CPU,
fatImage,
machoImage,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { readGoBinaryImage } from "../../../src/go/GoBinaryImage.js";
import {
createGoBinaryFixture,
@@ -221,6 +227,35 @@ it("distinguishes unsupported containers from malformed recognized images", () =
expect(() => readGoBinaryImage(pe.bytes)).toThrowError(/range|truncated/i);
});
it("reports JVM class files as unsupported images instead of fat Mach-O containers", () => {
expect(() => readGoBinaryImage(javaClassFile())).toThrowError(
/Only ELF, PE, and thin Mach-O native images are supported/,
);
expect(() => readGoBinaryImage(javaClassFile(4000))).toThrowError(
/Only ELF, PE, and thin Mach-O native images are supported/,
);
expect(() => readGoBinaryImage(javaClassFile(4000, true))).toThrowError(
/Only ELF, PE, and thin Mach-O native images are supported/,
);
});
it("keeps the thin-slice failure for confirmed universal Mach-O containers", () => {
const slices = [
{ cpu: CPU.x86_64, bytes: machoImage({ cpu: CPU.x86_64 }) },
{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) },
];
for (const universal of [
fatImage(slices),
fatImage(slices, true),
fatImage(slices, false, true),
fatImage(slices, true, true),
]) {
expect(() => readGoBinaryImage(Buffer.from(universal))).toThrowError(
/fat Mach-O containers require selecting a thin slice/,
);
}
});
it("rejects ELF header tables overlapping the native header", () => {
const fixture = createGoBinaryFixture({ sectionless: true });
fixture.bytes.writeBigUInt64LE(0n, 32);
@@ -0,0 +1,128 @@
import { createHash } from "node:crypto";
import { access, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
import { expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const publicationCancellation = vi.hoisted(() => ({
controller: undefined as AbortController | undefined,
directorySyncs: 0,
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
return {
...filesystem,
open: async (...args: Parameters<typeof filesystem.open>) => {
const handle = await filesystem.open(...args);
if (publicationCancellation.controller !== undefined) {
const stats = await handle.stat();
if (stats.isDirectory()) {
const sync = handle.sync.bind(handle);
handle.sync = async () => {
await sync();
publicationCancellation.directorySyncs += 1;
if (publicationCancellation.directorySyncs === 2)
publicationCancellation.controller?.abort();
};
}
}
return handle;
},
};
});
vi.mock(
"../../../src/javascript/recovery/WakaruCommand.js",
async (importOriginal) => {
const actual =
await importOriginal<
typeof import("../../../src/javascript/recovery/WakaruCommand.js")
>();
return {
...actual,
resolveWakaruCommand: async () => ({
command: "/unused/wakaru",
limiter: "/unused/prlimit",
sha256: "a".repeat(64),
bytes: 1,
}),
};
},
);
vi.mock(
"../../../src/javascript/recovery/WakaruExecution.js",
async (importOriginal) => {
const actual =
await importOriginal<
typeof import("../../../src/javascript/recovery/WakaruExecution.js")
>();
const { createAnalysisExecution } =
await import("../../../src/application/AnalysisProvider.js");
return {
...actual,
prepareWakaruExecution: async (
context: Parameters<typeof actual.prepareWakaruExecution>[0],
) => {
const source = context.sources[0];
if (source === undefined) throw new Error("Missing recovery source");
const bytes = Buffer.from("module.exports = 42;");
await context.tree.write("module.js", Readable.from([bytes]), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
});
return createAnalysisExecution(
{ status: "complete" },
{ id: "wakaru", name: "Wakaru", version: "1.14.0" },
{
subject: {
path: source.path,
sha256: source.sha256,
format: "javascript",
},
},
);
},
};
},
);
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { WakaruProvider } from "../../../src/javascript/recovery/WakaruProvider.js";
it.skipIf(process.platform === "win32")(
"keeps mid-commit output-tree cancellation typed through the provider",
async () => {
const root = await createTestTempDirectory("rea-wakaru-cancel-");
const sourcePath = join(root, "source.js");
const output = join(root, "output");
await writeFile(sourcePath, "module.exports = 42;");
const controller = new AbortController();
publicationCancellation.controller = controller;
publicationCancellation.directorySyncs = 0;
const provider = new WakaruProvider({});
try {
const result = await provider.recover(
{
path: sourcePath,
output_directory: output,
extraction_mode: "structural",
rewrite_level: "standard",
},
{ signal: controller.signal },
);
if (result.ok) throw new Error("Expected publication cancellation");
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(projectAnalysisError(result.error).code).toBe("cancelled");
expect(publicationCancellation.directorySyncs).toBe(2);
await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
publicationCancellation.controller = undefined;
publicationCancellation.directorySyncs = 0;
await provider.close();
}
},
);
@@ -0,0 +1,35 @@
import { expect, it } from "vitest";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { runSourceMapCommand } from "../../../src/javascript/sourceMaps/SourceMapCommand.js";
import { PrivateRuntimeRootUnavailableError } from "../../../src/process/PrivateRuntimeRootUnavailableError.js";
it.each([false, true])(
"preserves private-runtime retryable=%s through the source-map operation",
async (retryable) => {
const reason = "Native runtime self-test failed with a sharing violation";
let launches = 0;
const result = await runSourceMapCommand("{}", "/selected.map", undefined, {
prepareOwnership: async () => {},
createRuntime: async () => {
throw new PrivateRuntimeRootUnavailableError(reason, { retryable });
},
launcher: async () => {
launches += 1;
throw new Error("A refused runtime must not launch a codec");
},
});
expect(launches).toBe(0);
if (result.ok) throw new Error("Unavailable runtime must refuse decoding");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "capability_unavailable",
category: retryable ? "unavailable" : "unsupported_provider",
retryable,
details: {
provider_id: "source-map-decoder",
operation: "trace_web_source_location",
reason,
},
});
expect(result.error.cleanupIncomplete).toBe(false);
},
);
@@ -39,6 +39,8 @@ import {
} from "../../fixtures/analysisView.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { BINARY_LAYOUT_TEST_PROVIDER } from "../../fixtures/binaryDiagnostics/layout.js";
import { wasmArtifactFixture } from "../../fixtures/wasm/artifact.js";
import { evmInterfaceFixture } from "../../fixtures/evm/interface.js";
const connect = async (
binaryLayout?: BinaryLayoutService,
@@ -69,6 +71,12 @@ const connect = async (
it("discovers an oversized native dossier by exact metadata and reads its retained view", async () => {
const { client, session } = await connect();
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_analysis_view",
);
expect(advertised?.description).toContain(
'Native function Evidence requires kind native: view: {kind: "native", facet: "procedure"}',
);
const provider = { id: "ghidra", name: "Ghidra", version: "12.1.4" };
const profile = createAnalysisProfile(provider, { language: "fixture" });
const parent = createEvidence(
@@ -98,6 +106,24 @@ it("discovers an oversized native dossier by exact metadata and reads its retain
const retained = session.recordEvidence(record);
if (!retained.ok) throw retained.error;
}
const unsupportedSummary = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(unsupportedSummary).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["view"],
message: "analyze_function Evidence requires a native view.",
},
],
},
});
const broad = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
@@ -286,6 +312,65 @@ it("reports a tampered inline Evidence ID at its full MCP source path", async ()
});
});
it("rejects self-contained WASM and EVM Evidence views when the subject format differs", async () => {
const { client } = await connect();
const wasm = wasmArtifactFixture();
const evm = evmInterfaceFixture();
const cases = [
{
evidence: createEvidence(
{
path: wasm.artifact.path,
format: "elf",
sha256: wasm.artifact.sha256,
},
{ id: "fixture-wabt", name: "WABT", version: "1" },
{
operation: "inspect_wasm_artifact",
parameters: { path: wasm.artifact.path },
result: wasm,
},
),
},
{
evidence: createEvidence(
{
path: evm.artifact.path,
format: "elf",
sha256: evm.artifact.sha256,
},
{ id: "fixture-evm", name: "EVMole", version: "1" },
{
operation: "inspect_evm_interface",
parameters: { path: evm.artifact.path, encoding: "hex" },
result: evm,
},
),
},
] as const;
for (const { evidence } of cases) {
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
expect.objectContaining({
path: ["source", "subject"],
reason: "invalid_value",
}),
],
},
});
}
});
it("admits portable captures before SDK Evidence parsing and preserves capture caveats", async () => {
const { client } = await connect();
const dense = analysisViewCaptureEvidence(analysisViewObjectDenseCapture());
@@ -0,0 +1,295 @@
import { unlink } from "node:fs/promises";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { AndroidAnalysisService } from "../../../src/application/android/AndroidAnalysisService.js";
import { inspectAndroidPackage } from "../../../src/application/android/AndroidPackageInspection.js";
import { inspectAnalysisView } from "../../../src/application/analysisView/AnalysisViewService.js";
import { androidResultSchemas } from "../../../src/domain/android/androidAnalysis.js";
import {
androidPackageSummaryViewResultSchema,
analysisViewResultSchema,
} from "../../../src/domain/analysisView/analysisView.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
createJadxProtocolFixture,
verifyJadxFixtureCleanup,
} from "../../fixtures/android/jadx.js";
it.skipIf(process.platform === "win32")(
"retains complete APK Evidence and reads exact manifest without its source or another engine launch",
async () => {
const { provider, apk, launches } =
await createJadxProtocolFixture("large-manifest");
const harness = await createApplicationMcpHarness({
serverOptions: { androidAnalysis: provider },
});
onTestFinished(harness.close);
const { client, session } = harness;
const catalog = (await client.listTools()).tools;
const definition = catalog.find(
(tool) => tool.name === "inspect_android_package",
);
if (definition?.outputSchema === undefined)
throw new Error("Missing APK schema");
const outputSchema: Record<string, unknown> = definition.outputSchema;
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(definition.inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(definition.inputSchema, { path: apk, detail: "summary" }),
).toBe(true);
expect(
ajv.validate(
catalog.find((tool) => tool.name === "inspect_android_class")!
.inputSchema,
{
path: apk,
class_name: "fixture.Target",
detail: "summary",
},
),
).toBe(false);
const reply = await client.callTool({
name: "inspect_android_package",
arguments: { path: apk, detail: "summary" },
});
expect(reply.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, reply.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const receipt = parseEvidence(reply.structuredContent);
const view = androidPackageSummaryViewResultSchema.parse(
receipt.normalized_result,
);
const parent = session.evidenceById(view.parent_evidence_id);
if (parent === undefined)
throw new Error("Complete package Evidence not retained");
const report = androidResultSchemas.inspect_android_package.parse(
parent.normalized_result,
);
expect(parent.operation).toBe("inspect_android_package");
expect(parent.parameters).toEqual({ path: apk });
expect(view.artifact.sha256).toBe(parent.subject?.digest.sha256);
expect(view.artifact.sha256).not.toBe(report.engine.artifact_sha256);
expect(receipt.evidence_id).not.toBe(parent.evidence_id);
expect(receipt.evidence_links).toEqual([parent.evidence_id]);
const { manifest, ...declarations } = report;
expect(view.summary).toMatchObject(declarations);
expect(view.summary.manifest).toEqual({
status: manifest.status,
reported_total_bytes: manifest.reported_total_bytes,
text_code_units: manifest.text.length,
text_included: false,
});
expect(receipt.raw_result).toBeNull();
expect(parent.raw_result).not.toBeNull();
for (const detail of [undefined, "complete"]) {
const full = parseEvidence(
(
await client.callTool({
name: "inspect_android_package",
arguments: {
path: apk,
...(detail === undefined ? {} : { detail }),
},
})
).structuredContent,
);
expect(full.operation).toBe("inspect_android_package");
expect(full.normalized_result).toEqual(parent.normalized_result);
expect(full.parameters).toEqual(parent.parameters);
expect(full.raw_result).not.toBeNull();
}
const before = JSON.stringify(parent);
await unlink(apk);
let text = "";
let offset = 0;
do {
const paged = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
},
view: { kind: "android", facet: "manifest", offset, limit: 700000 },
},
});
expect(paged.isError).not.toBe(true);
const page = analysisViewResultSchema.parse(
parseEvidence(paged.structuredContent).normalized_result,
);
if (page.kind !== "android") throw new Error("Unexpected manifest page");
text += page.item.text;
expect(page.item.source_status).toBe(manifest.status);
expect(page.item.reported_total_bytes).toBe(
manifest.reported_total_bytes,
);
offset = page.coverage.next_offset ?? manifest.text.length;
} while (offset < manifest.text.length);
expect(text).toBe(manifest.text);
const portable = inspectAnalysisView({
source: { kind: "inline", evidence: parseEvidence(JSON.parse(before)) },
view: { kind: "summary" },
});
if (!portable.ok) throw portable.error;
expect(portable.value.normalized_result).toEqual(view);
expect(JSON.stringify(session.evidenceById(parent.evidence_id))).toBe(
before,
);
expect(
session
.exportEvidenceBundle()
.records.find((record) => record.evidence_id === parent.evidence_id),
).toEqual(parent);
expect(launches).toHaveLength(1);
await harness.close();
await verifyJadxFixtureCleanup(launches);
},
30000,
);
it("preserves partial/unknown declarations and Unicode text while rejecting missing APK identity and malformed source", () => {
const report = {
engine: {
name: "jadx",
version: null,
artifact_sha256: "b".repeat(64),
source_revision: null,
worker_count: 1,
heap_limit_mib: null,
},
package_name: null,
version_name: null,
version_code: null,
min_sdk: null,
target_sdk: null,
permissions: [],
manifest: { status: "partial", text: "a😀b", reported_total_bytes: null },
class_count: 0,
resource_count: 0,
signature_verification: "not_performed",
};
const evidence = (result: JsonValue = report, hasSubject = true) =>
createEvidence(
hasSubject
? { path: "/original.apk", sha256: "a".repeat(64), format: "apk" }
: undefined,
{ id: "jadx", name: "JADX", version: "0.7.1" },
{
operation: "inspect_android_package",
parameters: {},
result,
limitations: ["Original limit"],
},
);
const parent = evidence();
const source = { kind: "inline", evidence: parent };
const summary = inspectAnalysisView({ source, view: { kind: "summary" } });
if (!summary.ok) throw summary.error;
const overview = androidPackageSummaryViewResultSchema.parse(
summary.value.normalized_result,
);
expect(overview.summary.package_name).toBeNull();
expect(overview.summary.manifest.status).toBe("partial");
expect(overview.limitations).toEqual(parent.limitations);
const page = inspectAnalysisView({
source,
view: { kind: "android", facet: "manifest", offset: 0, limit: 4 },
});
if (!page.ok) throw page.error;
const result = analysisViewResultSchema.parse(page.value.normalized_result);
expect(result).toMatchObject({
kind: "android",
item: {
text: "a😀b",
source_status: "partial",
reported_total_bytes: null,
},
coverage: { exhausted: true },
});
expect(result.unknowns.join(" ")).toContain("partial");
for (const offset of [2])
expect(
inspectAnalysisView({
source,
view: { kind: "android", facet: "manifest", offset, limit: 2 },
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
for (const invalid of [
evidence(report, false),
evidence({ ...report, class_count: -1 }),
])
expect(
inspectAnalysisView({
source: { kind: "inline", evidence: invalid },
view: { kind: "summary" },
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
});
it("rejects unavailable retention, invalid selectors and cancellation before provider execution", async () => {
const execute = vi.fn();
const provider = {
execute,
close: async () => {},
inspectAvailability: vi.fn(),
};
const service = new AndroidAnalysisService(provider);
const retention = { recordEvidence: undefined, evidenceById: undefined };
expect(
await inspectAndroidPackage(
service,
{ path: "/missing.apk", detail: "summary" },
retention,
),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
expect(
await inspectAndroidPackage(
service,
{ path: "/missing.apk", detail: "other" },
retention,
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
expect(
await inspectAndroidPackage(
service,
{ path: "/missing.apk", detail: "summary" },
retention,
{ signal: AbortSignal.abort() },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
expect(execute).not.toHaveBeenCalled();
const session = createTestBinarySession(() => {
throw new Error("Unexpected deep provider");
});
const server = createServer(
{ kind: "fixed", analysis: session },
{ androidAnalysis: provider },
);
const client = new Client({ name: "android-fixed-summary", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [a, b] = InMemoryTransport.createLinkedPair();
await server.connect(b);
await client.connect(a);
const reply = await client.callTool({
name: "inspect_android_package",
arguments: { path: "/missing.apk", detail: "summary" },
});
expect(parseMcpToolError(reply).error.code).toBe("capability_unavailable");
expect(execute).not.toHaveBeenCalled();
});
@@ -2,6 +2,7 @@ import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import type { Client } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { AnySchema } from "ajv";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import {
@@ -10,12 +11,143 @@ import {
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "../../../src/domain/javascript/javascriptApplicationGraph.js";
import { createJavaScriptSemanticGraph } from "../../../src/domain/javascript/javascriptSemanticGraph.js";
import {
artifactEvidence,
sourceMapReference,
} from "../../../src/domain/javascript/javascriptApplicationGraph.fixture.js";
import {
createApplicationMcpHarness,
type ApplicationMcpHarness,
} from "../../fixtures/applicationMcpHarness.js";
import { createHistoricalSourceGraph } from "../../../src/domain/referenceSourceGraph.js";
async function runUnicodeSourceMapComparison(
harness: ApplicationMcpHarness,
): Promise<void> {
const baseApplication = SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.application;
const subject = baseApplication.subject;
if (subject === null) throw new Error("Application Evidence has no subject");
const baseResult = javascriptApplicationAnalysisResultSchema.parse(
baseApplication.normalized_result,
);
const baseGraph = baseResult.graph;
const decomposedSource = "cafe\u0301.ts";
const unicodeSourceNode = createJavaScriptApplicationNode({
kind: "source-module",
identity: {
strategy: "source-map-original",
source_root: "../src/",
stability: "source-map-exact",
source_map_sha256: "1".repeat(64),
original_source: decomposedSource,
source_sha256: "3".repeat(64),
},
observations: [
{
label: "decomposed source-map spelling",
source_map_reference: sourceMapReference(
decomposedSource,
"../src/",
"dist/main.js.map",
),
properties: { content_available: true, content_sha256: "3".repeat(64) },
evidence: artifactEvidence("1".repeat(64), "dist/main.js.map"),
},
],
});
const applicationGraph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: [...baseGraph.root_node_ids, unicodeSourceNode.node_id],
nodes: [...baseGraph.nodes, unicodeSourceNode],
edges: baseGraph.edges,
coverage: baseGraph.coverage,
limitations: baseGraph.limitations,
});
const semantic = baseResult.semantic_graph;
const { graph_id: _semanticGraphId, ...semanticInput } = semantic;
const semanticGraph = createJavaScriptSemanticGraph({
...semanticInput,
application_graph_id: applicationGraph.graph_id,
});
const unicodeApplication = createEvidence(
{
path: baseResult.input_path,
sha256: subject.digest.sha256,
format: subject.format,
},
baseApplication.provider,
{
predicateType: baseApplication.predicate_type,
operation: baseApplication.operation,
parameters: baseApplication.parameters,
result: {
...baseResult,
graph: applicationGraph,
semantic_graph: semanticGraph,
},
confidence: baseApplication.confidence,
authority: baseApplication.authority,
limitations: baseApplication.limitations,
evidenceLinks: baseApplication.evidence_links,
},
);
const historicalUnicodePath = "src/caf\u00e9.ts";
const unicodeReference = createHistoricalSourceGraph({
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
root_sha256: undefined,
entries: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.entries.map(
(entry) =>
entry.path === "src/main.ts"
? { ...entry, path: historicalUnicodePath }
: entry,
),
});
const reply = await harness.client.callTool({
name: "compare_source_to_bundle",
arguments: { reference: unicodeReference, application: unicodeApplication },
});
expect(reply.isError).not.toBe(true);
expect(reply.structuredContent).toMatchObject({
normalized_result: {
items: [
{
source_path: historicalUnicodePath,
status: "unknown",
current_node_ids: [],
candidates: [
expect.objectContaining({
confidence: "low",
signals: expect.arrayContaining([
expect.objectContaining({
kind: "unicode-equivalent-path",
source_value: historicalUnicodePath,
current_values: ["src/cafe\u0301.ts"],
}),
]),
}),
],
},
],
},
});
const advertised = (await harness.client.listTools()).tools.find(
({ name }) => name === "compare_source_to_bundle",
);
if (advertised?.outputSchema === undefined)
throw new Error("Comparison tool output schema is missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const outputSchema = advertised.outputSchema as AnySchema;
expect(ajv.validateSchema(outputSchema)).toBe(true);
const validateOutput = ajv.compile(outputSchema);
expect(validateOutput(reply.structuredContent)).toBe(true);
}
async function runInlineWorkflowScenarios(
harness: ApplicationMcpHarness,
): Promise<void> {
@@ -92,6 +224,8 @@ async function runInlineWorkflowScenarios(
},
});
await runUnicodeSourceMapComparison(harness);
const referenceWithExclusion = createHistoricalSourceGraph({
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
root_sha256: undefined,
@@ -0,0 +1,285 @@
import { unlink } from "node:fs/promises";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { FlutterBuildAnalysisService } from "../../../src/application/flutter/FlutterBuildAnalysisService.js";
import { inspectDartAot } from "../../../src/application/flutter/DartAotInspection.js";
import { inspectAnalysisView } from "../../../src/application/analysisView/AnalysisViewService.js";
import { createFlutterBuildAnalysisProvider } from "../../../src/composition/flutter.js";
import {
analysisViewResultSchema,
dartAotSummaryViewResultSchema,
} from "../../../src/domain/analysisView/analysisView.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { flutterResultSchemas } from "../../../src/domain/flutter/flutterBuildAnalysis.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { aotFixtureImage } from "../../../src/flutter/FlutterBuild.fixture.js";
import { createFlutterApk } from "../../fixtures/flutterApk.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
it("honors explicit ABI and old full requests, validates SDK schemas and reuses complete Evidence after APK removal", async () => {
const path = await createFlutterApk("views.apk", [
{ path: "lib/arm64-v8a/libapp.so", bytes: aotFixtureImage() },
{ path: "lib/x86_64/libapp.so", bytes: aotFixtureImage("b".repeat(32)) },
]);
const provider = createFlutterBuildAnalysisProvider();
const execute = vi.spyOn(provider, "execute");
const harness = await createApplicationMcpHarness({
serverOptions: { flutterAnalysis: provider },
});
onTestFinished(harness.close);
const { client, session } = harness;
const catalog = (await client.listTools()).tools;
const definition = catalog.find((tool) => tool.name === "inspect_dart_aot");
if (definition?.outputSchema === undefined)
throw new Error("Missing AOT output schema");
const outputSchema: Record<string, unknown> = definition.outputSchema;
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(definition.inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(
catalog.find((tool) => tool.name === "identify_flutter_build")!
.inputSchema,
{ path, detail: "summary" },
),
).toBe(false);
const reply = await client.callTool({
name: "inspect_dart_aot",
arguments: { path, abi: "x86_64", detail: "summary" },
});
expect(reply.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, reply.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const receipt = parseEvidence(reply.structuredContent);
const view = dartAotSummaryViewResultSchema.parse(receipt.normalized_result);
const parent = session.evidenceById(view.parent_evidence_id);
if (parent === undefined)
throw new Error("Complete AOT source was not retained");
const report = flutterResultSchemas.inspect_dart_aot.parse(
parent.normalized_result,
);
expect(report.abi).toBe("x86_64");
expect(report.libapp.snapshot_hash).toBe("b".repeat(32));
expect(parent.parameters).toEqual({ path, abi: "x86_64" });
expect(execute).toHaveBeenLastCalledWith(
{ operation: "inspect_dart_aot", input: { path, abi: "x86_64" } },
expect.anything(),
);
expect(view.summary.libapp).toEqual(report.libapp);
expect(view.summary.target).toEqual(report.target);
expect(view.summary.coverage).toBe(report.coverage);
expect(receipt.evidence_id).not.toBe(parent.evidence_id);
expect(receipt.evidence_links).toEqual([parent.evidence_id]);
for (const detail of [undefined, "complete"]) {
const complete = parseEvidence(
(
await client.callTool({
name: "inspect_dart_aot",
arguments: {
path,
abi: "x86_64",
...(detail === undefined ? {} : { detail }),
},
})
).structuredContent,
);
expect(complete.operation).toBe("inspect_dart_aot");
expect(complete.normalized_result).toEqual(parent.normalized_result);
expect(complete.parameters).toEqual(parent.parameters);
}
const preferred = parseEvidence(
(await client.callTool({ name: "inspect_dart_aot", arguments: { path } }))
.structuredContent,
);
expect(
flutterResultSchemas.inspect_dart_aot.parse(preferred.normalized_result)
.abi,
).toBe("arm64-v8a");
const original = JSON.stringify(parent);
await unlink(path);
const calls = execute.mock.calls.length;
for (const collection of [
"package_uris",
"dart_uris",
"class_like_tokens",
] as const) {
const strings: string[] = [];
let offset = 0;
do {
const reply = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
},
view: { kind: "dart-aot", collection, offset, limit: 1 },
},
});
expect(reply.isError).not.toBe(true);
const page = analysisViewResultSchema.parse(
parseEvidence(reply.structuredContent).normalized_result,
);
if (page.kind !== "dart-aot") throw new Error("Wrong pool page kind");
strings.push(...page.items);
expect(page.libapp).toEqual(report.libapp);
expect(page.source_coverage).toBe(report.coverage);
expect(page.string_pool.coverage).toBe(report.string_pool.coverage);
offset =
page.coverage.next_offset ?? report.string_pool[collection].length;
} while (offset < report.string_pool[collection].length);
expect(strings).toEqual(report.string_pool[collection]);
}
expect(execute).toHaveBeenCalledTimes(calls);
expect(JSON.stringify(session.evidenceById(parent.evidence_id))).toBe(
original,
);
expect(
session
.exportEvidenceBundle()
.records.find((record) => record.evidence_id === parent.evidence_id),
).toEqual(parent);
const portable = inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view: { kind: "summary" },
});
if (!portable.ok) throw portable.error;
expect(portable.value.normalized_result).toEqual(view);
}, 30000);
it("preserves null snapshot facts and pool lower bounds after exhaustion, rejecting malformed and conflicting identities", () => {
const report = {
target: { path: "/source.apk", bytes: 10, sha256: "a".repeat(64) },
abi: "arm64-v8a",
libapp: {
coverage: "partial",
bytes: 1,
sha256: "b".repeat(64),
snapshot_hash: null,
snapshot_hash_candidates: [],
snapshot_hash_sources: 0,
sections: [],
},
string_pool: {
coverage: "partial",
package_uris: ["package:opaque/a.dart"],
package_uri_count_at_least: 1000,
dart_uris: [],
dart_uri_count_at_least: 0,
class_like_tokens: ["incidental"],
class_like_token_count_at_least: 4000,
printable_run_count: 12,
},
coverage: "partial",
};
const evidence = (
result: JsonValue = report,
sha: string | null = "a".repeat(64),
) =>
createEvidence(
sha === null
? undefined
: { path: "/source.apk", sha256: sha, format: "apk" },
{ id: "flutter", name: "Flutter", version: null },
{
operation: "inspect_dart_aot",
parameters: {},
result,
limitations: ["Original uncertainty"],
},
);
for (const parent of [evidence(), evidence(report, null)]) {
const summary = inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view: { kind: "summary" },
});
if (!summary.ok) throw summary.error;
const result = dartAotSummaryViewResultSchema.parse(
summary.value.normalized_result,
);
expect(result.summary.libapp.snapshot_hash).toBeNull();
expect(result.summary.string_pool.package_uri_count_at_least).toBe(1000);
expect(result.summary.string_pool.returned_counts.package_uris).toBe(1);
expect(result.limitations).toEqual(parent.limitations);
const page = inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view: {
kind: "dart-aot",
collection: "package_uris",
offset: 0,
limit: 10,
},
});
if (!page.ok) throw page.error;
expect(page.value.normalized_result).toMatchObject({
kind: "dart-aot",
items: report.string_pool.package_uris,
source_coverage: "partial",
string_pool: { coverage: "partial", package_uri_count_at_least: 1000 },
coverage: { total: 1, exhausted: true },
});
}
expect(
inspectAnalysisView({
source: { kind: "inline", evidence: evidence(report, "c".repeat(64)) },
view: { kind: "summary" },
}),
).toMatchObject({ ok: false, error: { _tag: "EvidenceIntegrityError" } });
expect(
inspectAnalysisView({
source: {
kind: "inline",
evidence: evidence({
...report,
string_pool: {
...report.string_pool,
package_uri_count_at_least: -1,
},
}),
},
view: { kind: "summary" },
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
expect(
inspectAnalysisView({
source: { kind: "inline", evidence: evidence() },
view: { kind: "android", facet: "manifest", offset: 0, limit: 1 },
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
});
it("rejects unavailable retention, invalid delivery and cancellation before producer work", async () => {
const provider = createFlutterBuildAnalysisProvider();
onTestFinished(() => provider.close());
const execute = vi.spyOn(provider, "execute");
const service = new FlutterBuildAnalysisService(provider);
const retention = { recordEvidence: undefined, evidenceById: undefined };
expect(
await inspectDartAot(
service,
{ path: "/missing.apk", abi: "x86_64", detail: "summary" },
retention,
),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
expect(
await inspectDartAot(
service,
{ path: "/missing.apk", detail: "other" },
retention,
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
expect(
await inspectDartAot(
service,
{ path: "/missing.apk", detail: "summary" },
retention,
{ signal: AbortSignal.abort() },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
expect(execute).not.toHaveBeenCalled();
});
+46
View File
@@ -471,3 +471,49 @@ it("exposes the target-free static JavaScript application workflow", async () =>
const evidenceFor = (value: unknown) => {
return parseEvidence(value);
};
it("reports every unresolved Electron path without starting a provider", async () => {
const root = await createTestTempDirectory("rea-electron-invalid-paths-");
const capture = vi.fn();
const session = createTestBinarySession(() => {
throw new Error("must not start");
});
const server = createServer(
{ kind: "session", session },
{
electronActiveObservation: {
capture,
identity: () => ({ id: "test", name: "test", version: "1" }),
},
},
);
const client = new Client({ name: "electron-path-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const fields = ["executable_path", "application_path", "application_root"];
const result = await client.callTool({
name: "capture_electron_scenario",
arguments: {
...Object.fromEntries(fields.map((field) => [field, join(root, field)])),
actions: [],
},
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: fields.map((field) => ({
path: [field],
reason: "invalid_value",
message: expect.stringContaining("ENOENT"),
})),
},
},
});
expect(capture).not.toHaveBeenCalled();
await client.ping();
});
@@ -144,14 +144,26 @@ describe("enhanced MCP tools", () => {
);
expect(result).toEqual({
document: "fixture",
image_base: "0x1000",
segments: [
{ name: "__TEXT", start: "0x1000", end: "0x1800", length: 2048 },
{ name: "__DATA", start: "0x1800", end: "0x2000", length: 2048 },
{
name: "__TEXT",
start: "0x1000",
end: "0x1800",
length: 2048,
image_base: "0x1000",
},
{
name: "__DATA",
start: "0x1800",
end: "0x2000",
length: 2048,
image_base: "0x1000",
},
],
segment_count: 2,
procedure_count: 2,
string_count: 700,
image_base: "0x1000",
});
});
@@ -0,0 +1,249 @@
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { AnalysisOutputError } from "../../../src/domain/analysisErrorCore.js";
import { err, ok } from "../../../src/domain/result.js";
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
afterEach(closeEnhancedToolResources);
const PROVIDER = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
} as const;
type Coverage = boolean | undefined;
interface Behavior {
/** What the provider reports for the references of each match address. */
readonly coverage?: Readonly<Record<string, Coverage>>;
readonly limitations?: readonly string[];
/** Also report the first string match as a procedure match. */
readonly duplicateProcedure?: boolean;
/** Fail the references read of this address. */
readonly failXrefsOf?: string;
readonly calls?: string[];
}
const containing = (address: string) => ({
query_address: address,
found: false,
procedure: null,
reason: "not_in_procedure",
});
/**
* A provider with two string matches (0x10 and 0x11), each referenced from
* one address (0x20 and 0x21).
*/
const provider = (behavior: Behavior = {}): AnalysisOperationPort => ({
execute: async (name, arguments_) => {
const address = String(arguments_.address);
behavior.calls?.push(`${name}:${address}`);
switch (name) {
case "search_strings":
return ok(
createAnalysisExecution(
[
{ address: "0x10", value: "hello" },
{ address: "0x11", value: "hello again" },
],
PROVIDER,
),
);
case "search_procedures":
return ok(
createAnalysisExecution(
behavior.duplicateProcedure === true
? [{ address: "0x10", value: "hello" }]
: [],
PROVIDER,
),
);
case "xrefs": {
if (address === behavior.failXrefsOf)
return err(new AnalysisOutputError("xrefs", "provider failed"));
const reported = behavior.coverage?.[address];
return ok(
createAnalysisExecution(
[address === "0x10" ? "0x20" : "0x21"],
PROVIDER,
{
limitations: behavior.limitations ?? [],
...(reported === undefined
? {}
: { referencesTruncated: reported }),
},
),
);
}
case "resolve_containing_procedure":
return ok(createAnalysisExecution(containing(address), PROVIDER));
default:
throw new Error(`Unexpected operation: ${name}`);
}
},
});
const expectedTrace = (
residual: readonly string[],
extraMatches: readonly object[] = [],
) => ({
query: "hello",
search_mode: "literal",
matches: [
{ type: "string", address: "0x10", value: "hello" },
{ type: "string", address: "0x11", value: "hello again" },
...extraMatches,
],
references: [
{
target_address: "0x10",
source_address: "0x20",
containing_procedure: containing("0x20"),
},
{
target_address: "0x11",
source_address: "0x21",
containing_procedure: containing("0x21"),
},
...extraMatches.map(() => ({
target_address: "0x10",
source_address: "0x20",
containing_procedure: containing("0x20"),
})),
],
truncated: residual.length > 0,
residual_unknowns: residual,
});
const unknownFor = (address: string) =>
`References to ${address} were truncated by the provider; additional references may exist.`;
const trace = async (analysis: AnalysisOperationPort) => {
const client = await connect(analysis);
const result = await client.callTool({
name: "trace_feature",
arguments: { query: "hello" },
});
expect(result.isError).not.toBe(true);
return result.structuredContent as { normalized_result: unknown };
};
describe("trace_feature reference coverage", () => {
it("marks the trace truncated for the target whose references the provider capped", async () => {
const output = await trace(
provider({ coverage: { "0x10": true, "0x11": false } }),
);
expect(
output.normalized_result,
"the received references are kept and only the capped target is a residual unknown",
).toEqual(expectedTrace([unknownFor("0x10")]));
});
it("does not carry a truncation over to the next target that reports nothing", async () => {
const output = await trace(provider({ coverage: { "0x10": true } }));
expect(output.normalized_result).toEqual(
expectedTrace([unknownFor("0x10")]),
);
});
it("reports a capped target once when it is matched twice", async () => {
const output = await trace(
provider({ coverage: { "0x10": true }, duplicateProcedure: true }),
);
expect(output.normalized_result).toEqual(
expectedTrace(
[unknownFor("0x10")],
[{ type: "procedure", address: "0x10", value: "hello" }],
),
);
});
it("resolves the containing procedure of a repeated reference source once", async () => {
const calls: string[] = [];
const output = await trace(provider({ duplicateProcedure: true, calls }));
expect(
calls.filter((call) => call.startsWith("resolve_containing_procedure:")),
"the source 0x20 is referenced by two matches of the same address and resolved once",
).toEqual([
"resolve_containing_procedure:0x20",
"resolve_containing_procedure:0x21",
]);
expect(
output.normalized_result,
"every reference is still reported with its containing procedure",
).toEqual(
expectedTrace(
[],
[{ type: "procedure", address: "0x10", value: "hello" }],
),
);
});
it("keeps the trace complete when the provider explicitly reports no cap", async () => {
const output = await trace(
provider({ coverage: { "0x10": false, "0x11": false } }),
);
expect(output.normalized_result).toEqual(expectedTrace([]));
});
it("does not change the trace of a provider that reports no coverage", async () => {
const output = await trace(
provider({
limitations: ["Upstream xrefs_to capped results at 1000 references."],
}),
);
expect(
output.normalized_result,
"a limitation text alone never truncates, and an absent field keeps the previous result",
).toEqual(expectedTrace([]));
});
it("never exposes the coverage field in the tool output", async () => {
const output = await trace(
provider({ coverage: { "0x10": true, "0x11": false } }),
);
expect(JSON.stringify(output)).not.toMatch(
/referencesTruncated|references_truncated/,
);
});
it("fails the trace when a references read fails and reads nothing further", async () => {
const calls: string[] = [];
const result = await new EnhancedTools(
provider({ failXrefsOf: "0x10", calls }),
).execute("trace_feature", { query: "hello" });
expect(result.ok).toBe(false);
expect(
calls.filter((call) => call.startsWith("xrefs:")),
"the next target is not read after the failure",
).toEqual(["xrefs:0x10"]);
});
it("stops without reading references when the trace is cancelled", async () => {
const calls: string[] = [];
const controller = new AbortController();
controller.abort();
const result = await new EnhancedTools(provider({ calls })).execute(
"trace_feature",
{ query: "hello" },
controller.signal,
);
expect(result.ok).toBe(false);
expect(calls.filter((call) => call.startsWith("xrefs:"))).toEqual([]);
});
});
@@ -1,10 +1,20 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ANALYSIS_SNAPSHOT_TARGET } from "../../../src/domain/analysisSnapshot.fixture.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
import { createServer } from "../../../src/server/createServer.js";
it("returns the complete session Evidence bundle in the tool result", async () => {
@@ -44,3 +54,251 @@ it("returns the complete session Evidence bundle in the tool result", async () =
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
it("rejects bundle field stripping at MCP import without changing retained evidence", async () => {
const root = await createTestTempDirectory("rea-evidence-bundle-mcp-");
const sourceSession = createBundleSourceSession();
const targetSession = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
const source = await connectEvidenceMcp("bundle-source", sourceSession);
const target = await connectEvidenceMcp("bundle-target", targetSession);
const { client: sourceClient } = source;
const { client: targetClient } = target;
const bundlePath = join(root, "exported.json");
const targetExportPath = join(root, "round-trip.json");
try {
const { sourceJson, records, evidenceIndex } = await exportFixtureBundle(
sourceClient,
bundlePath,
);
const initial = structured(
await targetClient.callTool({
name: "get_evidence_bundle",
arguments: {},
}),
).result;
for (const [label, path] of unsupportedBundleFields(evidenceIndex)) {
const candidate = structuredClone(sourceJson);
setPath(candidate, path, "unsupported-metadata");
const malformedPath = join(root, `${label.replaceAll(" ", "-")}.json`);
await writeFile(malformedPath, JSON.stringify(candidate));
const rejected = await targetClient.callTool({
name: "import_evidence_bundle",
arguments: { path: malformedPath },
});
expect(parseMcpToolError(rejected), label).toMatchObject({
error: { code: "evidence_integrity_mismatch" },
});
expect(
structured(
await targetClient.callTool({
name: "get_evidence_bundle",
arguments: {},
}),
).result,
label,
).toEqual(initial);
}
const imported = await targetClient.callTool({
name: "import_evidence_bundle",
arguments: { path: bundlePath },
});
if (imported.isError === true)
throw new Error(JSON.stringify(parseMcpToolError(imported)));
await targetClient.callTool({
name: "export_evidence_bundle",
arguments: { path: targetExportPath },
});
expect(JSON.parse(await readFile(targetExportPath, "utf8"))).toEqual(
sourceJson,
);
const observedRecord = records[evidenceIndex]!;
expect(observedRecord.parameters).toEqual({ caller: { note: "preserve" } });
expect(observedRecord.normalized_result).toEqual({
producer: { extension: "preserve" },
});
expect(object(observedRecord.analysis_profile).parameters).toEqual({
loader: { mode: "full" },
});
} finally {
await Promise.allSettled([
sourceClient.close(),
source.server.close(),
sourceSession.close(),
targetClient.close(),
target.server.close(),
targetSession.close(),
]);
}
});
const createBundleSourceSession = () => {
const provider = { id: "fixture", name: "Fixture", version: "1" };
const evidence = createEvidence(ANALYSIS_SNAPSHOT_TARGET, provider, {
operation: "observe",
parameters: { caller: { note: "preserve" } },
result: { producer: { extension: "preserve" } },
analysisProfile: createAnalysisProfile(provider, {
loader: { mode: "full" },
}),
environment: {
id: "fixture-linux",
platform: "linux",
architecture: "x86_64",
isolation: "process",
},
locations: [{ kind: "address", address: "0x1000" }],
});
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
expect(session.recordEvidence(evidence).ok).toBe(true);
for (const extra of [
createEvidence(ANALYSIS_SNAPSHOT_TARGET, provider, {
operation: "controlled_replay",
parameters: {},
result: { completed: true },
authority: "controlled-replay",
}),
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
confidence: "observed",
authority: "controlled-replay",
}),
])
expect(session.recordEvidence(extra).ok).toBe(true);
return session;
};
const exportFixtureBundle = async (
client: Client,
path: string,
): Promise<{
readonly sourceJson: unknown;
readonly records: Record<string, unknown>[];
readonly evidenceIndex: number;
}> => {
const unknown = await client.callTool({
name: "record_unknown",
arguments: {
question: "Does this remain unknown?",
severity: "medium",
domain: "bundle-format",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [{ operation: "observe", rationale: "Inspect it." }],
relationships: [],
},
});
expect(unknown.isError).not.toBe(true);
const exported = await client.callTool({
name: "export_evidence_bundle",
arguments: { path },
});
expect(exported.isError).not.toBe(true);
const sourceJson = JSON.parse(await readFile(path, "utf8")) as unknown;
const records = array(object(sourceJson).records).map(object);
const evidenceIndex = records.findIndex(
(record) => record.operation === "observe",
);
expect(evidenceIndex).toBeGreaterThanOrEqual(0);
return { sourceJson, records, evidenceIndex };
};
const unsupportedBundleFields = (
evidenceIndex: number,
): readonly [string, readonly (string | number)[]][] => [
["bundle envelope", ["schema_version"]],
["record provider", ["records", evidenceIndex, "provider", "future_field"]],
["provider manifest", ["providers", 0, "future_field"]],
["record subject", ["records", evidenceIndex, "subject", "future_field"]],
[
"subject digest",
["records", evidenceIndex, "subject", "digest", "future_field"],
],
["artifact manifest", ["artifacts", 0, "future_field"]],
[
"record environment",
["records", evidenceIndex, "environment", "future_field"],
],
["environment manifest", ["environments", 0, "future_field"]],
[
"source location",
["records", evidenceIndex, "locations", 0, "future_field"],
],
["scenario manifest", ["scenarios", 0, "future_field"]],
["capture manifest", ["captures", 0, "future_field"]],
[
"analysis profile",
["records", evidenceIndex, "analysis_profile", "future_field"],
],
[
"profile provider",
["records", evidenceIndex, "analysis_profile", "provider", "future_field"],
],
["unknown revision", ["unknowns", 0, "future_field"]],
["unknown probe", ["unknowns", 0, "recommended_probes", 0, "future_field"]],
];
const connectEvidenceMcp = async (
name: string,
session: ReturnType<typeof createTestBinarySession>,
) => {
const server = createServer({ kind: "session", session });
const client = new Client({ name, version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return { client, server };
};
const object = (value: unknown): Record<string, unknown> => {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new Error("Expected object in exported Evidence bundle");
return value as Record<string, unknown>;
};
const array = (value: unknown): unknown[] => {
if (!Array.isArray(value))
throw new Error("Expected array in Evidence bundle");
return value;
};
const setPath = (
root: unknown,
path: readonly (string | number)[],
value: unknown,
): void => {
const [last, ...parents] = [...path].reverse();
if (last === undefined) throw new Error("Expected a nonempty bundle path");
const target = parents
.reverse()
.reduce<unknown>(
(current, segment) =>
typeof segment === "number"
? array(current)[segment]
: object(current)[segment],
root,
);
object(target)[String(last)] = value;
};
const structured = (result: Awaited<ReturnType<Client["callTool"]>>) => {
if (result.isError === true) throw parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("Missing structured MCP result");
return result.structuredContent as Record<string, unknown>;
};
@@ -0,0 +1,155 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
import { createServer } from "../../../src/server/createServer.js";
import {
createDeferred,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const connectImportSession = async () => {
const root = await createTestTempDirectory("rea-mcp-import-lifecycle-");
const session = createTestBinarySession(() => {
throw new Error("Evidence import must not start a binary provider");
});
const server = createServer({ kind: "session", session });
const client = new Client({
name: "evidence-import-lifecycle",
version: "1",
});
const readCompleted = createDeferred<void>();
const releaseRead = createDeferred<void>();
const originalFileClose = OwnedFileHandle.prototype.close;
vi.spyOn(OwnedFileHandle.prototype, "close").mockImplementationOnce(
async function (this: OwnedFileHandle) {
await originalFileClose.call(this);
readCompleted.resolve();
await releaseRead.promise;
},
);
const closeStarted = createDeferred<void>();
const originalSessionClose = session.close.bind(session);
const events: string[] = [];
vi.spyOn(session, "close").mockImplementation((...args) => {
const closing = originalSessionClose(...args);
closeStarted.resolve();
return closing.then((result) => {
events.push("close");
return result;
});
});
const originalImport = session.importEvidenceBundle.bind(session);
vi.spyOn(session, "importEvidenceBundle").mockImplementation((bundle) => {
const imported = originalImport(bundle);
events.push("import");
return imported;
});
onTestFinished(async () => {
releaseRead.resolve();
vi.restoreAllMocks();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const laterImportDispatched = createDeferred<void>();
let importsDispatched = 0;
const send = clientTransport.send.bind(clientTransport);
vi.spyOn(clientTransport, "send").mockImplementation(
async (message, ...args) => {
await send(message, ...args);
if (
"method" in message &&
message.method === "tools/call" &&
message.params?.name === "import_evidence_bundle"
) {
importsDispatched += 1;
if (importsDispatched === 2) laterImportDispatched.resolve();
}
},
);
await server.connect(serverTransport);
await client.connect(clientTransport);
const importBundle = async (operation: string) => {
const record = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation, parameters: {}, result: { retained: operation } },
);
const path = join(root, `${operation}.json`);
await writeFile(path, JSON.stringify(createEvidenceBundle([record])));
return client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
};
return {
client,
session,
events,
importBundle,
readCompleted: readCompleted.promise,
closeStarted: closeStarted.promise,
laterImportDispatched: laterImportDispatched.promise,
releaseRead: () => releaseRead.resolve(),
};
};
it("drains a file import before close_binary clears the session", async () => {
const fixture = await connectImportSession();
const importing = fixture.importBundle("before_close");
await fixture.readCompleted;
const closing = fixture.client.callTool({
name: "close_binary",
arguments: {},
});
await fixture.closeStarted;
await fixture.client.ping();
fixture.releaseRead();
const [imported, closed] = await Promise.all([importing, closing]);
expect(imported.isError, JSON.stringify(imported)).not.toBe(true);
expect(imported.structuredContent).toMatchObject({
result: { imported: 1, unknowns_added: 0, total: 1 },
});
expect(closed.isError, JSON.stringify(closed)).not.toBe(true);
expect(fixture.events).toEqual(["import", "close"]);
expect(fixture.session.exportEvidenceBundle().records).toEqual([]);
await fixture.client.ping();
});
it("admits a later import after close_binary without retaining the earlier bundle", async () => {
const fixture = await connectImportSession();
const earlier = fixture.importBundle("before_close");
await fixture.readCompleted;
const closing = fixture.client.callTool({
name: "close_binary",
arguments: {},
});
await fixture.closeStarted;
const later = fixture.importBundle("after_close");
await fixture.laterImportDispatched;
await fixture.client.ping();
fixture.releaseRead();
const results = await Promise.all([earlier, closing, later]);
for (const result of results)
expect(result.isError, JSON.stringify(result)).not.toBe(true);
expect(results[2]?.structuredContent).toMatchObject({
result: { imported: 1, unknowns_added: 0, total: 1 },
});
expect(fixture.events).toEqual(["import", "close", "import"]);
expect(
fixture.session
.exportEvidenceBundle()
.records.map((record) => record.operation),
).toEqual(["after_close"]);
await fixture.client.ping();
});
@@ -107,6 +107,30 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
).toBe(true);
});
it("rejects an EVM provider response with a non-file subject before recording Evidence", async () => {
const value = evmInterfaceFixture();
const execution = evmInterfaceExecution(value);
const malformed = {
...execution,
subject: { ...execution.subject, format: "elf" },
} as unknown as typeof execution;
const harness = await createApplicationMcpHarness({
serverOptions: {
evmInterface: new EvmInterfaceService({
inspect: () => Promise.resolve(ok(malformed)),
}),
},
});
onTestFinished(harness.close);
const before = harness.session.exportEvidenceBundle().records.length;
const response = await harness.client.callTool({
name: "inspect_evm_interface",
arguments: { path: value.artifact.path, encoding: "hex" },
});
expect(parseMcpToolError(response).error.code).toBe("unreadable_output");
expect(harness.session.exportEvidenceBundle().records).toHaveLength(before);
});
it.each(["unavailable", "incompatible-output"])(
"preserves a healthy WASM peer and explicit EVM failure: %s",
async (scenario) => {
+3 -1
View File
@@ -46,6 +46,8 @@ it("retains terminal-call qualifications across function views and snapshot repl
limitations: [limitation],
},
],
["procedure_callees", ["0x402000"]],
["procedure_callers", [identity.address]],
["analyze_function", jsonValueSchema.parse(dossier)],
]);
const harness = await connectGhidraMcp(
@@ -81,7 +83,7 @@ it("retains terminal-call qualifications across function views and snapshot repl
});
expect(evidence.limitations, name).toContain(limitation);
expect(evidence.analysis_profile?.parameters).toMatchObject({
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
function_boundary_observations: "ghidra-terminal-call-limitations-v2",
});
const replay = await harness.session.execute(name, evidence.parameters);
if (!replay.ok) throw replay.error;
+3 -1
View File
@@ -95,7 +95,7 @@ export const sessionEvidence = (session: BinarySession, value: unknown) => {
const installationHost = (): GhidraInstallationHost => ({
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
@@ -263,6 +263,8 @@ const resultFor = (
const functionObservationOperations: ReadonlySet<GhidraOperation> = new Set([
"analyze_function",
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"read_function_instructions",
+1 -1
View File
@@ -99,7 +99,7 @@ class FixtureLauncher implements GhidraLauncher {
const installationHost: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
@@ -0,0 +1,121 @@
import { afterEach, expect, it } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { AnySchemaObject } from "ajv";
import {
closeEnhancedToolResources,
connect,
jsonResult,
} from "./enhancedToolsHarness.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import type { SegmentSummary } from "../../../src/domain/hopperValues.js";
afterEach(closeEnhancedToolResources);
const segment = {
name: ".text",
start: "0x101000",
end: "0x101100",
readable: true,
writable: false,
executable: true,
image_base: "0x100000",
address_space: "ram",
};
const overviewClient = (segments: SegmentSummary[]) =>
connect({
execute: (name) => {
switch (name) {
case "current_document":
return Promise.resolve(ok("fixture"));
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_segments":
return Promise.resolve(ok(segments));
case "list_procedures":
return Promise.resolve(ok([{ address: "0x101013", value: "entry" }]));
case "list_strings":
return Promise.resolve(ok([]));
default:
throw new Error(`Unexpected operation: ${name}`);
}
},
});
it("preserves observed coordinates and main's optional-string output contract after SDK conversion", async () => {
const client = await overviewClient([segment]);
const schema = (await client.listTools()).tools.find(
({ name }) => name === "binary_overview",
)?.outputSchema;
if (schema === undefined) throw new Error("Missing overview output schema");
const validate = new Ajv2020({ strict: false }).compile(
schema as AnySchemaObject,
);
const response = await client.callTool({
name: "binary_overview",
arguments: {},
});
expect(validate(response.structuredContent)).toBe(true);
expect(jsonResult(response)).toMatchObject({
image_base: "0x100000",
segments: [
{ start: "0x101000", image_base: "0x100000", address_space: "ram" },
],
});
const absent = JSON.parse(JSON.stringify(response.structuredContent));
delete absent.normalized_result.image_base;
expect(validate(absent)).toBe(true);
absent.normalized_result.image_base = null;
expect(validate(absent)).toBe(false);
});
it("omits unreported bases without inventing zero and preserves explicit zero", async () => {
const { image_base: _base, ...unreported } = segment;
const client = await overviewClient([unreported]);
expect(
jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
),
).not.toHaveProperty("image_base");
const zero = await overviewClient([{ ...segment, image_base: "0x0" }]);
expect(
jsonResult(await zero.callTool({ name: "binary_overview", arguments: {} })),
).toMatchObject({ image_base: "0x0" });
});
it("keeps a partially reported base unknown while retaining the reported segment observation", async () => {
const { image_base: _base, ...unreported } = segment;
const client = await overviewClient([
segment,
{ ...unreported, name: ".data" },
]);
const result = jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
);
expect(result).not.toHaveProperty("image_base");
expect(result).toMatchObject({
segments: [{ image_base: "0x100000" }, { name: ".data" }],
});
});
it("retains all conflicting observations after repeated early bases without selecting one", async () => {
const { address_space: _space, ...unreported } = segment;
const client = await overviewClient([
...Array.from({ length: 40 }, () => unreported),
{
...segment,
name: ".data",
start: "other%20space:0x201000",
end: "other%20space:0x201100",
image_base: "0x200000",
address_space: "other space",
},
]);
const result = jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
);
expect(result).not.toHaveProperty("image_base");
expect(result).toHaveProperty("segments.length", 41);
expect(result).toHaveProperty("segments.40.image_base", "0x200000");
expect(result).toHaveProperty("segments.40.address_space", "other space");
expect(result).not.toHaveProperty("segments.0.address_space");
});
@@ -0,0 +1,216 @@
import { silentLogger } from "../../../src/logger.js";
import { copyFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
import { z } from "zod";
import { createBinarySession } from "../../../src/composition/binary.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { inspectMachoSchema } from "../../../src/domain/native/nativeInspection.js";
import { createServer } from "../../../src/server/createServer.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { ok } from "../../../src/domain/result.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
const evidenceOf = <Schema extends z.ZodType>(schema: Schema) =>
z.object({
evidence_id: z.string(),
parameters: z.record(z.string(), z.unknown()),
normalized_result: schema,
});
const countSchema = z.object({
returned: z.number(),
total: z.number().nullable(),
exhaustive: z.boolean(),
});
const summarySchema = z.object({
kind: z.literal("summary"),
parent_evidence_id: z.string(),
summary: z.object({
uuid: z.string().nullable(),
collections: z.record(z.string(), countSchema),
provenance_count: z.number(),
}),
});
const pageSchema = z.object({
kind: z.literal("macho"),
item: z.array(z.unknown()),
coverage: z.object({ next_offset: z.number().nullable() }),
});
describe.skipIf(process.platform !== "darwin")(
"Mach-O summary delivery through MCP",
() => {
mcpTest(
"retains complete inspect_macho Evidence and pages its exact rows",
async ({ mcp, onTestFinished }) => {
const target = join(
await createTestTempDirectory("rea-macho-summary-mcp-"),
"ls",
);
await copyFile("/bin/ls", target);
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(
configured.value,
silentLogger,
process.env,
);
onTestFinished(async () => {
await session.close();
});
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: target },
});
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
const complete = await client.callTool({
name: "inspect_macho",
arguments: {},
});
expect(complete.isError, JSON.stringify(complete.content)).not.toBe(
true,
);
const full = evidenceOf(inspectMachoSchema).parse(
complete.structuredContent,
);
// Omitted detail keeps the default Evidence parameters unchanged.
expect(full.parameters).toEqual({});
const summarized = await client.callTool({
name: "inspect_macho",
arguments: { detail: "summary" },
});
expect(summarized.isError, JSON.stringify(summarized.content)).not.toBe(
true,
);
const summary = evidenceOf(summarySchema).parse(
summarized.structuredContent,
).normalized_result;
// Delivery detail never reaches the tools or the source Evidence ID.
expect(summary.parent_evidence_id).toBe(full.evidence_id);
const report = full.normalized_result;
expect(summary.summary.uuid).toBe(report.uuid);
expect(summary.summary.provenance_count).toBe(report.provenance.length);
for (const name of ["imports", "exports", "dependencies"] as const)
expect(summary.summary.collections[name]).toEqual({
returned: report[name].items.length,
total: report[name].total,
exhaustive: report[name].exhaustive,
});
expect(JSON.stringify(summarized.structuredContent)).not.toContain(
report.imports.items[0]?.name ?? "_",
);
// Every facet must reassemble the unparsed complete rows exactly.
const raw = z
.object({ normalized_result: z.record(z.string(), z.unknown()) })
.parse(complete.structuredContent).normalized_result;
const facets = [
"entrypoints",
"architectures",
"build_metadata",
"load_commands",
"dependencies",
"imports",
"exports",
"segments",
"provenance",
] as const;
for (const facet of facets) {
const rows: unknown[] = [];
let offset: number | null = 0;
while (offset !== null) {
const paged = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "macho", facet, offset, limit: 16 },
},
});
expect(paged.isError, JSON.stringify(paged.content)).not.toBe(true);
const page = evidenceOf(pageSchema).parse(
paged.structuredContent,
).normalized_result;
rows.push(...page.item);
offset = page.coverage.next_offset;
}
expect(rows, facet).toEqual(
facet === "provenance"
? raw.provenance
: z.object({ items: z.array(z.unknown()) }).parse(raw[facet])
.items,
);
}
const wrongKind = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "wasm", facet: "exports" },
},
});
expect(wrongKind.isError).toBe(true);
expect(JSON.stringify(wrongKind.content)).toContain(
"Mach-O inspection supports summary and macho views.",
);
},
);
},
);
mcpTest(
"refuses summary delivery before analysis when the server retains no Evidence",
async ({ mcp, onTestFinished }) => {
const target = join(
await createTestTempDirectory("rea-summary-preflight-"),
"tool",
);
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
const executed: string[] = [];
const session = createTestBinarySession(() => ({
execute: (operation) => {
executed.push(operation);
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(ok(null)),
}));
onTestFinished(async () => {
await session.close();
});
const opened = await session.open(target);
if (!opened.ok) throw opened.error;
const client = await mcp.connect(
createServer({ kind: "fixed", analysis: session }),
);
const refused = [];
for (const name of ["inspect_macho", "inspect_artifact"])
refused.push(
await client.callTool({ name, arguments: { detail: "summary" } }),
);
// Neither analysis ran only to be discarded by the delivery refusal.
expect(executed.filter((operation) => operation !== "health")).toEqual([]);
for (const result of refused)
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
message: expect.stringContaining("does not retain Evidence"),
},
});
},
);
+52 -35
View File
@@ -8,42 +8,53 @@ import { Ajv2020 } from "ajv/dist/2020.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
it("advertises valid target-free packet capture schemas and actionable missing-tool diagnostics", async () => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
({ name }) => name === "inspect_packet_capture",
);
if (tool?.outputSchema === undefined) throw new Error("Capture tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input = {
path:
process.platform === "win32" ? "C:\\recording.pcap" : "/recording.pcap",
fields: ["ip.addr"],
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(false);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
it.each(["inspect_packet_capture", "inspect_packet_fields"])(
"advertises valid target-free schemas and missing-tool diagnostics: %s",
async (name) => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
(tool) => tool.name === name,
);
if (tool?.outputSchema === undefined)
throw new Error("Capture tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input =
name === "inspect_packet_fields"
? { query: "usb" }
: {
path:
process.platform === "win32"
? "C:\\recording.pcap"
: "/recording.pcap",
fields: ["ip.addr"],
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(
false,
);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
},
},
},
});
await harness.client.ping();
});
});
await harness.client.ping();
},
);
it.each(["cancelled", "cleanup"])(
"retains completed Evidence after %s failure",
@@ -78,6 +89,9 @@ it.each(["cancelled", "cleanup"])(
},
);
const packetCapture = new PacketCaptureService({
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => err(failure),
close: async () => {},
});
@@ -120,6 +134,9 @@ it.each(["cancelled", "cleanup"])(
it("rejects oversized selector expansion through the MCP boundary before invoking the provider", async () => {
let calls = 0;
const packetCapture = new PacketCaptureService({
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
calls++;
return err(new AnalysisCancelledError("inspect_packet_capture"));
+118
View File
@@ -0,0 +1,118 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import type { PcapAnalysisPort } from "../../../src/application/pcap/PcapAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { assertAdvertisedMcpContracts } from "./mcpContractHarness.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const identity = { id: "pcap", name: "Packet capture analysis", version: null };
const clientIdentity = {
tshark_command: "/usr/bin/tshark",
tshark_source: "path",
tshark_version: "TShark (Wireshark) 4.6.6",
capinfos_command: "/usr/bin/capinfos",
capinfos_source: "path",
capinfos_version: "Capinfos (Wireshark) 4.6.6",
};
it("advertises exact valid pcap schemas and records inline evidence through MCP", async () => {
const provider: PcapAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute(request) {
if (request.operation === "inspect_pcap_client")
return ok(
createAnalysisExecution({ client: clientIdentity }, identity),
);
return ok(
createAnalysisExecution(
{
client: clientIdentity,
target: {
path: "/captures/session.pcap",
bytes: 23279,
sha256: "a".repeat(64),
},
file_type: "Wireshark/tcpdump/... - pcap",
encapsulation: "Linux cooked-mode capture v2",
packet_count: 50,
capture_start: "2026-10-11 14:13:40.608505",
capture_end: "2026-10-11 14:13:40.981978",
capture_duration_seconds: 0.373473,
snapshot_length: 262144,
endpoints: [
{ address: "192.168.1.100", port: null, packet_count: 30 },
{ address: "8.8.8.8", port: 53, packet_count: 5 },
],
endpoint_count: 2,
dns_queries: [
{
query: "example.com",
response_addresses: ["93.184.216.34"],
response_address_count: 1,
},
],
dns_query_count: 1,
tls_sni_values: ["example.com"],
tls_sni_count: 1,
protocol_distribution: [
{ protocol: "ip:tcp:tls", packet_count: 25 },
{ protocol: "ip:udp:dns", packet_count: 5 },
],
protocol_count: 2,
http_request_uris: ["http://example.com/api"],
http_request_uri_count: 1,
http_uri_redaction_count: 0,
unattributed_dns_addresses: [],
unattributed_dns_address_count: 0,
unattributed_dns_packet_count: 0,
coverage: "complete",
},
identity,
),
);
},
};
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ pcapAnalysis: provider },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "pcap-boundary", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const { tools } = await client.listTools();
assertAdvertisedMcpContracts(
["inspect_pcap_client", "inspect_pcap_capture"],
tools,
);
const inspected = await client.callTool({
name: "inspect_pcap_capture",
arguments: { path: "/captures/session.pcap" },
});
expect(inspected.isError).not.toBe(true);
const text = (inspected.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
const evidence = parseEvidence(JSON.parse(text));
expect(evidence.normalized_result).toMatchObject({
packet_count: 50,
tls_sni_values: ["example.com"],
coverage: "complete",
});
});

Some files were not shown because too many files have changed in this diff Show More