fix(ghidra): preserve Swift literal provenance and partial coverage
This commit is contained in:
@@ -13,7 +13,10 @@ const execute = promisify(execFile);
|
||||
const createModuleLookupFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-module-lookup-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": JSON.stringify({ name: "module-lookup-fixture" }),
|
||||
"package.json": JSON.stringify({
|
||||
name: "module-lookup-fixture",
|
||||
type: "commonjs",
|
||||
}),
|
||||
"esm/entry.mjs": [
|
||||
'import "./extensionless";',
|
||||
'import "./directory";',
|
||||
@@ -26,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;",
|
||||
@@ -33,11 +44,19 @@ 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": [
|
||||
'require("./extensionless");',
|
||||
'require("./directory");',
|
||||
'require("./feature");',
|
||||
'require("./feature.cjs");',
|
||||
'require("./module-only");',
|
||||
'require("./valid-directory");',
|
||||
'require("./default-js");',
|
||||
'require("./default-json");',
|
||||
'require("./default-node");',
|
||||
@@ -47,10 +66,22 @@ 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;",
|
||||
"cjs/valid-directory/index.js": "module.exports = 42;",
|
||||
"cjs/typed.cts":
|
||||
'const value = require("./typed-dep.cjs"); module.exports = value;',
|
||||
"cjs/typed-dep.cts": "module.exports = 42;",
|
||||
"cjs/default-js.js": "module.exports = 3;",
|
||||
"cjs/default-json.json": JSON.stringify({ value: 4 }),
|
||||
// Inventory-only placeholder: never pass this path to Node's runtime.
|
||||
@@ -67,19 +98,19 @@ 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 { await import(specifier); results.push({ specifier, ok: true }); }",
|
||||
" try { const value = (await import(specifier)).default; results.push({ specifier, ok: true, value }); }",
|
||||
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
|
||||
"}",
|
||||
"console.log(JSON.stringify(results));",
|
||||
].join("\n"),
|
||||
"cjs/runtime-control.cjs": [
|
||||
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./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 { require(specifier); results.push({ specifier, ok: true }); }",
|
||||
" try { const value = require(specifier); results.push({ specifier, ok: true, value }); }",
|
||||
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
|
||||
"}",
|
||||
"console.log(JSON.stringify(results));",
|
||||
@@ -97,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 }) => {
|
||||
@@ -111,75 +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;
|
||||
}>;
|
||||
const cjsResults = JSON.parse(cjsControl.stdout) as Array<{
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
}>;
|
||||
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 },
|
||||
{ specifier: "./actual.cjs?cache=1", ok: true },
|
||||
{ specifier: "empty-main", ok: true },
|
||||
{ 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 },
|
||||
{ specifier: "./default-js", ok: true },
|
||||
{ specifier: "./default-json", ok: true },
|
||||
{ specifier: "empty-main", ok: true },
|
||||
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: true },
|
||||
{ specifier: "ancestor-empty", ok: true },
|
||||
{ specifier: "ancestor-blocked", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-sub/parser", ok: true },
|
||||
]);
|
||||
expectNodeRuntimeControls(esmControl.stdout, cjsControl.stdout);
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const expectations = [
|
||||
@@ -188,16 +255,33 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
["import", "./explicit.js", null, "not-found"],
|
||||
["import", "./exact.js", "esm/exact.js", "resolved"],
|
||||
["import", "./actual.cjs?cache=1", "esm/actual.cjs", "resolved"],
|
||||
["import", "./typed-dep.js", "esm/typed-dep.ts", "resolved"],
|
||||
["import", "empty-main", "node_modules/empty-main/index.js", "resolved"],
|
||||
["import", "nested-main", null, "not-found"],
|
||||
["import", "file-only", null, "external"],
|
||||
["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"],
|
||||
["require", "./feature.cjs", "cjs/feature.cjs", "resolved"],
|
||||
["require", "./module-only", null, "not-found"],
|
||||
[
|
||||
"require",
|
||||
"./valid-directory",
|
||||
"cjs/valid-directory/index.js",
|
||||
"resolved",
|
||||
],
|
||||
["require", "./typed-dep.cjs", "cjs/typed-dep.cts", "resolved"],
|
||||
["require", "./default-js", "cjs/default-js.js", "resolved"],
|
||||
["require", "./default-json", "cjs/default-json.json", "resolved"],
|
||||
["require", "./default-node", "cjs/default-node.node", "resolved"],
|
||||
@@ -217,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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
|
||||
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
type JavaScriptApplicationAnalysisResult,
|
||||
@@ -1530,6 +1531,60 @@ const analyzeComparisonSources = async (
|
||||
);
|
||||
};
|
||||
|
||||
it("retains bundled isolated-world contextBridge APIs through dedicated and generic CLI routes", async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-context-bridge-isolated-cli-",
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "preload.js"),
|
||||
`(() => {
|
||||
const modules = {
|
||||
2(module) { module.exports = require("electron"); },
|
||||
5(module, exports, load) {
|
||||
const electron = load(2);
|
||||
electron.contextBridge.exposeInIsolatedWorld(1001, "isolatedApi", { ping: true });
|
||||
},
|
||||
};
|
||||
function load(id) {
|
||||
const module = { exports: {} };
|
||||
modules[id].call(module.exports, module, module.exports, load);
|
||||
return module.exports;
|
||||
}
|
||||
load(5);
|
||||
})();`,
|
||||
);
|
||||
|
||||
for (const arguments_ of [
|
||||
["analyze-javascript-application", root, "--json"],
|
||||
["analyze", root, "--format", "json"],
|
||||
]) {
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(await runCli(arguments_)).normalized_result,
|
||||
);
|
||||
expect(result.summary.context_bridge_apis).toBe(1);
|
||||
const bridge = result.graph.nodes.find(
|
||||
({ kind }) => kind === "context-bridge-api",
|
||||
);
|
||||
expect(bridge?.observations).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
world: "isolated",
|
||||
world_id: { status: "literal", value: 1001, expression: null },
|
||||
api_key: "isolatedApi",
|
||||
members: ["ping"],
|
||||
resolution_basis: "wrapper-substitution",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
location: expect.objectContaining({
|
||||
available: true,
|
||||
value: expect.objectContaining({ source: "preload.js" }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const runCli = async (
|
||||
arguments_: readonly string[],
|
||||
environment: Readonly<Record<string, string>> = {},
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { buildBinary } from "plist";
|
||||
|
||||
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
|
||||
import { appleAssetCatalogResultSchema } from "../../../src/domain/apple/appleAssetCatalog.js";
|
||||
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
// Exact rooted NIBArchive bytes from #2176; inert parser fixture, not ibtool output.
|
||||
const reportedArchive = Buffer.from(
|
||||
"TklCQXJjaGl2ZQEAAAAKAAAABAAAADIAAAAEAAAAPgAAAAQAAABgAAAABAAAAHwAAACAgIGBgYGCgoGDg4GGTlNSb290hWltYWdli05TSW1hZ2VOYW1liE5TLmJ5dGVzgAoBAAAAgQoCAAAAggoDAAAAgwiHVG9vbGJhco6ATlNJQk9iamVjdERhdGGLgE5TSW1hZ2VWaWV3h4BOU0ltYWdliIBOU1N0cmluZw==",
|
||||
"base64",
|
||||
);
|
||||
const resourceArchive = (field: string) =>
|
||||
encodeNibArchiveFixture({
|
||||
classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
|
||||
objects: [
|
||||
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
|
||||
{ classIndex: 1, values: { image: { ref: 2 } } },
|
||||
{ classIndex: 2, values: { [field]: { ref: 3 } } },
|
||||
{ classIndex: 3, values: { "NS.bytes": "Toolbar" } },
|
||||
],
|
||||
});
|
||||
|
||||
const keyedArchive = (nested: boolean) =>
|
||||
buildBinary({
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$top: { root: { UID: 1 } },
|
||||
$objects: [
|
||||
"$null",
|
||||
{
|
||||
$class: { UID: 2 },
|
||||
...(nested
|
||||
? { nibValues: { NSImageName: "Toolbar" } }
|
||||
: { NSImageName: "Toolbar" }),
|
||||
},
|
||||
{ $classname: "NSImage", $classes: ["NSImage", "NSObject"] },
|
||||
],
|
||||
});
|
||||
|
||||
cliTest.skipIf(process.platform !== "darwin")(
|
||||
"retains recognized NIBArchive resource keys and provenance through CLI and MCP without a catalog",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-asset-resource-keys-");
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [name, field, archive, recognized] of [
|
||||
["reported", "NSImageName", reportedArchive, true],
|
||||
["alias", "imageName", resourceArchive("imageName"), true],
|
||||
["title", "title", resourceArchive("title"), false],
|
||||
["keyed-direct", "NSImageName", keyedArchive(false), true],
|
||||
["keyed-nested", "NSImageName", keyedArchive(true), false],
|
||||
] as const) {
|
||||
const app = join(root, `${name}.app`);
|
||||
const contents = join(app, "Contents");
|
||||
await mkdir(join(contents, "Resources"), { recursive: true });
|
||||
await mkdir(join(contents, "MacOS"));
|
||||
const mach = Buffer.alloc(32);
|
||||
mach.writeUInt32LE(0xfeedfacf, 0);
|
||||
mach.writeUInt32LE(0x0100000c, 4);
|
||||
mach.writeUInt32LE(2, 12);
|
||||
await writeFile(join(contents, "MacOS", "App"), mach);
|
||||
await writeFile(
|
||||
join(contents, "Info.plist"),
|
||||
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
|
||||
);
|
||||
await writeFile(join(contents, "Resources", "Panel.nib"), archive);
|
||||
const decoded = await cli.run({
|
||||
arguments: ["decode-interface-builder", app, "--json"],
|
||||
});
|
||||
expect(decoded.exitCode, decoded.stderr).toBe(0);
|
||||
const graph = interfaceBuilderAnalysisSchema.parse(
|
||||
parseEvidence(decoded.json).normalized_result,
|
||||
).graph;
|
||||
expect(graph.truncated).toBe(false);
|
||||
const resource = graph.nodes.find(
|
||||
(node) =>
|
||||
node.kind === "resource" && node.attributes.class_name === "NSImage",
|
||||
);
|
||||
expect(
|
||||
name === "keyed-direct"
|
||||
? resource?.attributes
|
||||
: resource?.attributes.nibValues,
|
||||
).toMatchObject({
|
||||
[field]: "Toolbar",
|
||||
});
|
||||
const inspected = await cli.run({
|
||||
arguments: ["inspect-asset-catalog", app, "--json"],
|
||||
});
|
||||
expect(inspected.exitCode, inspected.stderr).toBe(0);
|
||||
const result = appleAssetCatalogResultSchema.parse(
|
||||
parseEvidence(inspected.json).normalized_result,
|
||||
);
|
||||
expect(result.catalogs).toEqual([]);
|
||||
expect(result.resource_key_matches).toEqual(
|
||||
!recognized
|
||||
? []
|
||||
: [
|
||||
{
|
||||
source_node_id: resource?.id,
|
||||
source_path: "Contents/Resources/Panel.nib",
|
||||
source_archive_sha256: createHash("sha256")
|
||||
.update(archive)
|
||||
.digest("hex"),
|
||||
field,
|
||||
key: "Toolbar",
|
||||
status: "unmatched",
|
||||
renditions: [],
|
||||
},
|
||||
],
|
||||
);
|
||||
const opened = await call("open_binary", { path: app });
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const mcp = await call("inspect_asset_catalog", {});
|
||||
expect(mcp.isError).not.toBe(true);
|
||||
expect(parseEvidence(mcp.structuredContent).normalized_result).toEqual(
|
||||
result,
|
||||
);
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
@@ -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,69 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"reports every unresolved Electron path through CLI and MCP without launching",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-electron-invalid-paths-");
|
||||
const application = join(root, "main.js");
|
||||
await writeFile(application, "module.exports = {};\n");
|
||||
const missing = {
|
||||
executable_path: join(root, "missing-electron"),
|
||||
application_path: join(root, "missing-application"),
|
||||
application_root: join(root, "missing-root"),
|
||||
};
|
||||
const requestPath = join(root, "input.json");
|
||||
await writeFile(requestPath, JSON.stringify(missing));
|
||||
const response = await cli.run({
|
||||
arguments: ["capture-electron-scenario", requestPath, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode).toBe(1);
|
||||
const expectedIssues = Object.entries(missing).map(([field, path]) => ({
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(path),
|
||||
}));
|
||||
expect(response.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: expectedIssues },
|
||||
});
|
||||
expect(response.stdout).toContain("ENOENT");
|
||||
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [field, path] of Object.entries(missing)) {
|
||||
const result = await call("capture_electron_scenario", {
|
||||
executable_path: process.execPath,
|
||||
application_path: application,
|
||||
application_root: root,
|
||||
[field]: path,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const content = result.content.find((item) => item.type === "text");
|
||||
if (content?.type !== "text") throw new Error("Missing error response");
|
||||
expect(JSON.parse(content.text)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(path),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(content.text).toContain("ENOENT");
|
||||
}
|
||||
const session = await call("binary_session", {});
|
||||
expect(session.isError, JSON.stringify(session)).not.toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,88 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"decodes a rooted UIKit keyed-archive outlet through CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-uikit-outlet-");
|
||||
const app = join(root, "UIKitFixture.app");
|
||||
const contents = join(app, "Contents");
|
||||
const resources = join(contents, "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
await mkdir(join(contents, "MacOS"));
|
||||
await writeFile(
|
||||
join(contents, "MacOS", "Fixture"),
|
||||
thinMach(0xfeedfacf, 0x0100000c),
|
||||
);
|
||||
await writeFile(
|
||||
join(contents, "Info.plist"),
|
||||
"<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
|
||||
);
|
||||
await writeFile(
|
||||
join(resources, "Main.nib"),
|
||||
await readFile(
|
||||
join(process.cwd(), "tests/fixtures/interface-builder/UIKitOutlet.xml"),
|
||||
),
|
||||
);
|
||||
|
||||
const output = await cli.run({
|
||||
arguments: ["decode-interface-builder", app, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
const result = interfaceBuilderAnalysisSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
const owner = result.graph.nodes.find(
|
||||
({ attributes }) => attributes.interface_builder_object_id === "1",
|
||||
);
|
||||
const destination = result.graph.nodes.find(
|
||||
({ attributes }) => attributes.interface_builder_object_id === "2",
|
||||
);
|
||||
const outlet = result.graph.nodes.find(({ kind }) => kind === "outlet");
|
||||
expect(result.documents).toEqual([
|
||||
expect.objectContaining({ connection_count: 1 }),
|
||||
]);
|
||||
expect(outlet).toMatchObject({
|
||||
id: 'ib:"Contents/Resources/Main.nib":outlet:["archive:3"]',
|
||||
name: "view",
|
||||
attributes: {
|
||||
UISource: { archiveUID: 1 },
|
||||
UIDestination: { archiveUID: 2 },
|
||||
UILabel: "view",
|
||||
},
|
||||
});
|
||||
expect(owner).toBeDefined();
|
||||
expect(destination).toBeDefined();
|
||||
expect(
|
||||
result.graph.edges.some(
|
||||
({ from, to, relation }) =>
|
||||
from === owner?.id && to === outlet?.id && relation === "contains",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.graph.edges.some(
|
||||
({ from, to, relation }) =>
|
||||
from === outlet?.id &&
|
||||
to === destination?.id &&
|
||||
relation === "outlet_to",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(result.graph.coverage).toContainEqual(
|
||||
expect.objectContaining({
|
||||
facet: "connections:Contents/Resources/Main.nib",
|
||||
status: "complete",
|
||||
examined: 1,
|
||||
omitted: 0,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,626 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import type { JavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const workerReferences = (graph: JavaScriptApplicationGraph) =>
|
||||
graph.nodes
|
||||
.filter(({ kind }) => kind === "worker")
|
||||
.flatMap((node) =>
|
||||
node.observations.map(({ properties, evidence }) => ({
|
||||
source:
|
||||
evidence.location.available &&
|
||||
evidence.location.value.kind === "source-range"
|
||||
? evidence.location.value.source
|
||||
: null,
|
||||
declared_specifier: properties.declared_specifier,
|
||||
expression: properties.expression,
|
||||
resolved_path: properties.resolved_path,
|
||||
mapped_paths: graph.edges
|
||||
.filter(
|
||||
({ relation, source_node_id }) =>
|
||||
relation === "maps_to" && source_node_id === node.node_id,
|
||||
)
|
||||
.map(({ properties: edge }) => edge.resolved_path),
|
||||
})),
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"promotes Worker URLs only for known constructor bindings through the CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-identity-");
|
||||
const identityCases = [
|
||||
...["globalThis", "window", "self"].map((namespace) => ({
|
||||
prefix: "",
|
||||
constructor: `new ${namespace}.Worker`,
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
})),
|
||||
...["worker_threads", "node:worker_threads"].flatMap((specifier) => [
|
||||
{
|
||||
prefix: `import { Worker } from "${specifier}";`,
|
||||
constructor: "new Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: `import * as threads from "${specifier}";`,
|
||||
constructor: "new threads.Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
]),
|
||||
{
|
||||
prefix: 'import { Worker as ThreadWorker } from "node:worker_threads";',
|
||||
constructor: "new ThreadWorker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
constructor: "new (Worker as typeof Worker)",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
constructor: "new ((threads as typeof threads).Worker!)",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix:
|
||||
'import { Worker } from "node:worker_threads"; function start(globalThis) { globalThis.URL = Fake;',
|
||||
constructor: "new Worker",
|
||||
suffix: "}",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'globalThis.unrelated = Fake; URL.extra = "metadata";',
|
||||
constructor: "new Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
...[
|
||||
["class Worker {}", "new Worker", ""],
|
||||
["globalThis.Worker = Fake;", "new Worker", ""],
|
||||
["globalThis.Worker = Fake;", "new window.Worker", ""],
|
||||
["globalThis = replacement;", "new globalThis.Worker", ""],
|
||||
["function start(Worker) {", "new Worker", "}"],
|
||||
['import { Worker } from "./custom.js";', "new Worker", ""],
|
||||
["const custom = { Worker: class {} };", "new custom.Worker", ""],
|
||||
["function start(window) {", "new window.Worker", "}"],
|
||||
["function start(globalThis) {", "new globalThis.Worker", "}"],
|
||||
[
|
||||
'import type { Worker } from "node:worker_threads";',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import { type Worker } from "node:worker_threads";',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import type * as threads from "node:worker_threads";',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import threads from "node:worker_threads"; threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'const threads = require("node:worker_threads"); threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import threads = require("node:worker_threads"); threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import { Worker } from "node:worker_threads"; Worker = Fake;',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
["", "Worker", ""],
|
||||
].map(([prefix, constructor, suffix]) => ({
|
||||
prefix,
|
||||
constructor,
|
||||
suffix,
|
||||
resolves: false,
|
||||
})),
|
||||
].map(({ prefix, constructor, suffix, resolves }, index) => ({
|
||||
source: `identity-${index}.ts`,
|
||||
prefix,
|
||||
expression: `${constructor}(new URL("./worker.js", import.meta.url))`,
|
||||
suffix,
|
||||
resolves,
|
||||
}));
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
identityCases.map(({ source, prefix, expression, suffix }) => [
|
||||
source,
|
||||
`${prefix}\n${expression};${suffix}`,
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('existing worker file');",
|
||||
"custom.js": "export class Worker {}",
|
||||
"custom-alias.mjs":
|
||||
'import { Worker as ThreadWorker } from "./custom.js"; new ThreadWorker(new URL("./worker.js", import.meta.url));',
|
||||
});
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(identityCases.length);
|
||||
expect(references.some(({ source }) => source === "custom-alias.mjs")).toBe(
|
||||
false,
|
||||
);
|
||||
for (const { source, expression, resolves } of identityCases)
|
||||
expect(references).toContainEqual({
|
||||
source,
|
||||
declared_specifier: resolves ? "./worker.js" : null,
|
||||
expression: resolves ? null : expression,
|
||||
resolved_path: resolves ? "worker.js" : null,
|
||||
mapped_paths: resolves ? ["worker.js"] : [],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"resolves module-relative Worker URL constructors through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-module-url-");
|
||||
const cases = [
|
||||
{
|
||||
source: "nested/relative.mjs",
|
||||
expression: 'new Worker(new URL("./worker.js", import.meta.url));',
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
},
|
||||
...[
|
||||
'import.meta.unrelated = "metadata";',
|
||||
'globalThis["import.meta"] = { url: "file:///other/entry.mjs" };',
|
||||
'const meta = import.meta; meta.unrelated = "metadata";',
|
||||
'const ambient = globalThis; ambient.unrelated = "metadata";',
|
||||
'const copy = { ...import.meta }; Object.defineProperty(copy, "url", { value: "file:///other/entry.mjs" });',
|
||||
"const copy = { ...globalThis }; copy.URL = replacement;",
|
||||
"function update(globalThis) { const ambient = globalThis; ambient.URL = replacement; } update({});",
|
||||
"const define = Object.defineProperty.bind(Object);",
|
||||
'Object.defineProperty(...[import.meta, "unrelated", { value: "metadata" }]);',
|
||||
'let meta = import.meta; meta = {}; let base = import.meta.url; base = "file:///other/entry.mjs";',
|
||||
].map((mutation, index) => ({
|
||||
source: `nested/unrelated-meta-${index}.mjs`,
|
||||
expression: `import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
})),
|
||||
{
|
||||
source: "nested/parent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("../parent-worker.js", import.meta.url));',
|
||||
specifier: "../parent-worker.js",
|
||||
resolved: "parent-worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/dot-segments.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./child/.././worker.js", import.meta.url));',
|
||||
specifier: "./child/.././worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/template.mjs",
|
||||
expression:
|
||||
"new Worker(new URL(`./template-worker.js`, import.meta.url));",
|
||||
specifier: "./template-worker.js",
|
||||
resolved: "nested/template-worker.js",
|
||||
},
|
||||
...[
|
||||
'new URL("./worker.js", import.meta.url) as URL',
|
||||
'<URL>new URL("./worker.js", import.meta.url)',
|
||||
'new URL("./worker.js", import.meta.url)!',
|
||||
'new URL("./worker.js", import.meta.url) satisfies URL',
|
||||
'((new URL("./worker.js", import.meta.url) as URL)!) satisfies URL',
|
||||
'new (URL as typeof URL)("./worker.js", import.meta.url)',
|
||||
'new URL("./worker.js" as string, import.meta.url as string)',
|
||||
'new URL("./worker.js", (import.meta as ImportMeta).url)',
|
||||
'new globalThis.URL("./worker.js", import.meta.url)',
|
||||
'new window.URL("./worker.js", import.meta.url)',
|
||||
'new self.URL("./worker.js", import.meta.url)',
|
||||
'new global.URL("./worker.js", import.meta.url)',
|
||||
'new ((globalThis as typeof globalThis)["URL"]!)("./worker.js", import.meta.url)',
|
||||
].map((urlExpression, index) => ({
|
||||
source: `nested/typed-${index}.ts`,
|
||||
expression: `new Worker(${urlExpression});`,
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
})),
|
||||
{
|
||||
source: "nested/space.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./space%20worker.js?worker=1#entry", import.meta.url));',
|
||||
specifier: "./space%20worker.js?worker=1#entry",
|
||||
resolved: "nested/space worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/percent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./percent%2520worker.js", import.meta.url));',
|
||||
specifier: "./percent%2520worker.js",
|
||||
resolved: "nested/percent%20worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/literal-percent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./percent%25worker.js", import.meta.url));',
|
||||
specifier: "./percent%25worker.js",
|
||||
resolved: "nested/percent%worker.js",
|
||||
},
|
||||
...["?value=", "#value="].map((suffix, index) => {
|
||||
const specifier = `./worker.js${suffix}%2F%2E%5C%00%FF%GG%2%\\\0`;
|
||||
return {
|
||||
source: `nested/suffix-${index}.mjs`,
|
||||
expression: `new Worker(new URL(${JSON.stringify(specifier)}, import.meta.url));`,
|
||||
specifier,
|
||||
resolved: "nested/worker.js",
|
||||
};
|
||||
}),
|
||||
{
|
||||
source: "bundled/entry.mjs",
|
||||
expression:
|
||||
'self.webpackChunkdemo.push([[1], {1: function(module, exports, require) { new Worker(new URL("./worker.js", import.meta.url)); }, "./worker.js": function(module) { module.exports = 42; }}]);',
|
||||
specifier: "./worker.js",
|
||||
resolved: "bundled/worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/literal.mjs",
|
||||
expression: 'new Worker("./literal-worker.js");',
|
||||
specifier: "./literal-worker.js",
|
||||
resolved: "nested/literal-worker.js",
|
||||
},
|
||||
];
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
cases.flatMap(({ source, expression, resolved }) => [
|
||||
[source, expression],
|
||||
[resolved, `self.postMessage(${JSON.stringify(resolved)});`],
|
||||
]),
|
||||
),
|
||||
"nested/percent worker.js": "self.postMessage('double-decoding decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
expect(workerReferences(result.graph)).toEqual(
|
||||
expect.arrayContaining(
|
||||
cases.map(({ source, specifier, resolved }) => ({
|
||||
source,
|
||||
declared_specifier: specifier,
|
||||
expression: null,
|
||||
resolved_path: resolved,
|
||||
mapped_paths: [resolved],
|
||||
})),
|
||||
),
|
||||
);
|
||||
expect(workerReferences(result.graph)).toHaveLength(cases.length);
|
||||
expect(result.graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "javascript-module",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({ module_key: "./worker.js" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"keeps unsupported Worker URL expressions and missing exact files unresolved through the CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-url-unknown-");
|
||||
const malformedPercentPaths = [
|
||||
["./worker%.js", "worker%.js"],
|
||||
["./worker%2.js", "worker%2.js"],
|
||||
["./worker%GG.js", "worker%GG.js"],
|
||||
["./space%20worker%GG.js", "space worker%GG.js"],
|
||||
];
|
||||
const expressions = {
|
||||
"dynamic-path.mjs": "new Worker(new URL(path, import.meta.url));",
|
||||
"absolute.mjs":
|
||||
'import { Worker } from "node:worker_threads"; new Worker(new URL("/worker.js", import.meta.url));',
|
||||
"typed-apply-meta.ts":
|
||||
'import { Worker } from "node:worker_threads"; Object.defineProperty.apply(Object, ([import.meta, "url", { value: "file:///other.mjs" }] as const)); new Worker(new URL("./worker.js", import.meta.url));',
|
||||
"overwritten-qualified-url.mjs":
|
||||
'globalThis.URL = replacement; new Worker(new globalThis.URL("./worker.js", import.meta.url));',
|
||||
"shadowed-qualified-url.mjs":
|
||||
'function start(window) { new Worker(new window.URL("./worker.js", import.meta.url)); }',
|
||||
...Object.fromEntries(
|
||||
["globalThis.URL", "URL", 'globalThis["URL"]'].map((target, index) => [
|
||||
`overwritten-url-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; const RealURL = URL; ${target} = class { constructor() { return new RealURL("./other.js", import.meta.url); } }; new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
[
|
||||
"delete globalThis.URL;",
|
||||
"({ URL: globalThis.URL } = replacements);",
|
||||
"globalThis[key] = replacement;",
|
||||
'Object.defineProperty(globalThis, "URL", { value: replacement });',
|
||||
'Reflect.set(globalThis, "URL", replacement);',
|
||||
"globalThis.globalThis.URL = replacement;",
|
||||
"globalThis.global.URL = replacement;",
|
||||
"const ambient = globalThis; ambient.URL = replacement;",
|
||||
"const { globalThis: ambient } = globalThis; ambient.URL = replacement;",
|
||||
].map((mutation, index) => [
|
||||
`mutated-url-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
[
|
||||
'import.meta.url = "file:///other/entry.mjs";',
|
||||
"delete import.meta.url;",
|
||||
'Object.defineProperty(import.meta, "url", { value: "file:///other/entry.mjs" });',
|
||||
"import.meta[key] = replacement;",
|
||||
'const meta = import.meta; const alias = meta; alias.url = "file:///other/entry.mjs";',
|
||||
'let meta = import.meta; meta.url = "file:///other/entry.mjs"; meta = {};',
|
||||
'const define = Object.defineProperty; define(import.meta, "url", { value: "file:///other/entry.mjs" });',
|
||||
'const set = Reflect.set.bind(Reflect); set(import.meta, "url", "file:///other/entry.mjs");',
|
||||
'Object.defineProperty.bind(Object, import.meta, "url")({ value: "file:///other/entry.mjs" });',
|
||||
'Object.assign(...[import.meta, { url: "file:///other/entry.mjs" }]);',
|
||||
'Object.defineProperty(...[import.meta, "url", { value: "file:///other/entry.mjs" }]);',
|
||||
].map((mutation, index) => [
|
||||
`mutated-import-meta-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
malformedPercentPaths.map(([specifier], index) => [
|
||||
`malformed-percent-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; new Worker(new URL(${JSON.stringify(specifier)}, import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
"dynamic-base.mjs": 'new Worker(new URL("./worker.js", base));',
|
||||
"shadowed.mjs":
|
||||
'function start(URL) { return new Worker(new URL("./worker.js", import.meta.url)); }',
|
||||
"typed-shadowed.ts":
|
||||
'function start(URL: typeof globalThis.URL) { return new Worker((new (URL as typeof globalThis.URL)("./worker.js", import.meta.url) as URL)!); }',
|
||||
"typed-dynamic-path.ts":
|
||||
"new Worker((new URL(path as string, import.meta.url) as URL)!);",
|
||||
"typed-dynamic-base.ts":
|
||||
'new Worker((new URL("./worker.js", base as string) as URL)!);',
|
||||
"call.mjs": 'new Worker(URL("./worker.js", import.meta.url));',
|
||||
"custom.mjs":
|
||||
'new Worker(new custom.URL("./worker.js", import.meta.url));',
|
||||
"extension.mjs":
|
||||
'new Worker(new URL("./extensionless", import.meta.url));',
|
||||
"directory.mjs": 'new Worker(new URL("./directory", import.meta.url));',
|
||||
"directory-dot.mjs":
|
||||
'new Worker(new URL("./worker.js/.", import.meta.url));',
|
||||
"directory-parent.mjs":
|
||||
'new Worker(new URL("./worker.js/child/..", import.meta.url));',
|
||||
"empty-segment.mjs":
|
||||
'new Worker(new URL("./child//../worker.js", import.meta.url));',
|
||||
"package.mjs":
|
||||
'new Worker(new URL("./package-worker", import.meta.url));',
|
||||
"external.mjs":
|
||||
'new Worker(new URL("https://example.test/worker.js", import.meta.url));',
|
||||
"empty.mjs": 'new Worker(new URL("", import.meta.url));',
|
||||
"query.mjs": 'new Worker(new URL("?worker=1", import.meta.url));',
|
||||
"whitespace.mjs":
|
||||
'new Worker(new URL(" ./worker.js ", import.meta.url));',
|
||||
"control.mjs": 'new Worker(new URL("./worker\\t.js", import.meta.url));',
|
||||
"leading-control.mjs":
|
||||
'new Worker(new URL("\\u0001./worker.js", import.meta.url));',
|
||||
};
|
||||
const knownSpecifiers: Readonly<Record<string, string>> = {
|
||||
"extension.mjs": "./extensionless",
|
||||
"directory.mjs": "./directory",
|
||||
"directory-dot.mjs": "./worker.js/.",
|
||||
"directory-parent.mjs": "./worker.js/child/..",
|
||||
"empty-segment.mjs": "./child//../worker.js",
|
||||
"package.mjs": "./package-worker",
|
||||
"external.mjs": "https://example.test/worker.js",
|
||||
};
|
||||
await writeFixtureFiles(root, {
|
||||
...expressions,
|
||||
...Object.fromEntries(
|
||||
malformedPercentPaths.map(([, decoy]) => [
|
||||
decoy,
|
||||
"self.postMessage('malformed percent pathname decoy');",
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('existing decoy');",
|
||||
"other.js": "self.postMessage('custom URL result decoy');",
|
||||
"extensionless.js": "self.postMessage('extension decoy');",
|
||||
"directory/index.js": "self.postMessage('index decoy');",
|
||||
"package-worker/package.json": JSON.stringify({ main: "selected.js" }),
|
||||
"package-worker/selected.js": "self.postMessage('package main decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(Object.keys(expressions).length);
|
||||
for (const [source, expression] of Object.entries(expressions)) {
|
||||
const specifier = knownSpecifiers[source] ?? null;
|
||||
expect(references).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source,
|
||||
declared_specifier: specifier,
|
||||
expression:
|
||||
specifier === null
|
||||
? expression.slice(
|
||||
expression.indexOf("new Worker("),
|
||||
expression.lastIndexOf(";"),
|
||||
)
|
||||
: null,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"bounds repeated ambient alias branches through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-alias-branches-");
|
||||
const aliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const alias${index + 1} = flag${index} ? alias${index} : alias${index};`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const splitAliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const left${index} = alias${index}; const right${index} = alias${index}; const alias${index + 1} = flag${index} ? left${index} : right${index};`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const memberAliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const alias${index + 1} = flag${index} ? alias${index}.globalThis : alias${index}.window;`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const expression = 'new Worker(new URL("./worker.js", import.meta.url))';
|
||||
await writeFixtureFiles(root, {
|
||||
"entry.mjs": `import { Worker } from "node:worker_threads";\n${aliases}\n${expression};`,
|
||||
"split.mjs": `import { Worker } from "node:worker_threads";\n${splitAliases}\n${expression};`,
|
||||
"member.mjs": `import { Worker } from "node:worker_threads";\n${memberAliases}\n${expression};`,
|
||||
"worker.js": "self.postMessage('existing alias-mutation decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory(
|
||||
"CLI",
|
||||
{ run: (invocation) => cli.run({ ...invocation, timeoutMs: 20_000 }) },
|
||||
root,
|
||||
);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(3);
|
||||
expect(references).toEqual(
|
||||
expect.arrayContaining(
|
||||
["entry.mjs", "split.mjs", "member.mjs"].map((source) => ({
|
||||
source,
|
||||
declared_specifier: null,
|
||||
expression,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
})),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"keeps Node Worker filesystem strings unresolved through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-node-worker-filesystem-");
|
||||
const cases = [
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
expression: 'new Worker("./worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker as ThreadWorker } from "worker_threads";',
|
||||
expression: 'new ThreadWorker("/worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
expression: 'new threads.Worker("./worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
expression: 'new (Worker as typeof Worker)("/worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
expression: 'new ((threads as typeof threads).Worker!)("./worker.js")',
|
||||
},
|
||||
].map((fixture, index) => ({
|
||||
...fixture,
|
||||
source: `nested/node-literal-${index}.ts`,
|
||||
}));
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
cases.map(({ prefix, expression, source }) => [
|
||||
source,
|
||||
`${prefix}\n${expression};`,
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('filesystem-root decoy');",
|
||||
"nested/worker.js": "self.postMessage('source-sibling decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(cases.length);
|
||||
for (const { source, expression } of cases)
|
||||
expect(references).toContainEqual({
|
||||
source,
|
||||
declared_specifier: null,
|
||||
expression,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Windows cannot materialize the pipe-named directory needed for this decoy.
|
||||
cliTest.skipIf(process.platform === "win32")(
|
||||
"keeps file-URL drive letters distinct from encoded POSIX paths through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-url-drive-");
|
||||
await writeFixtureFiles(root, {
|
||||
"dist/drive.mjs": 'new Worker(new URL("c|/worker.js", import.meta.url));',
|
||||
"dist/encoded.mjs":
|
||||
'new Worker(new URL("c%7C/worker.js", import.meta.url));',
|
||||
"dist/c|/worker.js": "self.postMessage('existing relative-path decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(2);
|
||||
expect(references).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
source: "dist/drive.mjs",
|
||||
declared_specifier: "c|/worker.js",
|
||||
expression: null,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
},
|
||||
{
|
||||
source: "dist/encoded.mjs",
|
||||
declared_specifier: "c%7C/worker.js",
|
||||
expression: null,
|
||||
resolved_path: "dist/c|/worker.js",
|
||||
mapped_paths: ["dist/c|/worker.js"],
|
||||
},
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -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,
|
||||
);
|
||||
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
@@ -28,12 +29,18 @@ const createPackageSubpathFixture = async () => {
|
||||
'const literal = require("fi%xture");',
|
||||
'const scalar = require("scalar");',
|
||||
'const self = require("../node_modules/fi%xture/run.cjs");',
|
||||
'const uri = require("file:///src/uri-dep.cjs");',
|
||||
'const relativeUri = require("./uri-dep.cjs");',
|
||||
].join("\n");
|
||||
const selfSource = 'const self = require("fi%xture"); module.exports = self;';
|
||||
const importSource = 'import literal from "fi%xture";';
|
||||
const importSource = [
|
||||
'import literal from "fi%xture";',
|
||||
'import uri from "FILE:///src/uri-dep.cjs?token=%2F#entry";',
|
||||
].join("\n");
|
||||
const files = {
|
||||
"src/main.cjs": source,
|
||||
"src/imports.mjs": importSource,
|
||||
"src/uri-dep.cjs": "module.exports = 42;",
|
||||
"src/node_modules/fixture/parser.js": "module.exports = 1;",
|
||||
"src/node_modules/fixture.js": "module.exports = 'file';",
|
||||
"src/node_modules/fixture/index.js": "module.exports = 'directory';",
|
||||
@@ -104,11 +111,20 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"fi%xture": "node_modules/fi%xture.js",
|
||||
scalar: "node_modules/scalar.js",
|
||||
"../node_modules/fi%xture/run.cjs": "node_modules/fi%xture/run.cjs",
|
||||
"./uri-dep.cjs": "src/uri-dep.cjs",
|
||||
};
|
||||
for (const [specifier, target] of Object.entries(expectedTargets))
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(specifier)).replaceAll("\\", "/"),
|
||||
).toBe(target);
|
||||
expect(nativeRequire("./uri-dep.cjs")).toBe(42);
|
||||
for (const specifier of [
|
||||
"file:///src/uri-dep.cjs",
|
||||
pathToFileURL(join(root, "src/uri-dep.cjs")).href,
|
||||
])
|
||||
expect(() => nativeRequire.resolve(specifier)).toThrow(
|
||||
expect.objectContaining({ code: "MODULE_NOT_FOUND" }),
|
||||
);
|
||||
for (const specifier of ["exported/parser/", "exported/hidden", "blocked"])
|
||||
expect(() => nativeRequire.resolve(specifier)).toThrow(
|
||||
expect.objectContaining({ code: "ERR_PACKAGE_PATH_NOT_EXPORTED" }),
|
||||
@@ -137,6 +153,41 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
},
|
||||
])
|
||||
expectResolvedImports(imports, observation);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "require",
|
||||
specifier: "file:///src/uri-dep.cjs",
|
||||
resolved_path: null,
|
||||
resolution_status: "external",
|
||||
}),
|
||||
evidence: sourceEvidence("src/main.cjs", source),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
kind: "require",
|
||||
specifier: "file:///src/uri-dep.cjs",
|
||||
resolved_path: null,
|
||||
}),
|
||||
evidence: sourceEvidence("src/main.cjs", source),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "import",
|
||||
specifier: "FILE:///src/uri-dep.cjs?token=%2F#entry",
|
||||
resolved_path: "src/uri-dep.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: sourceEvidence("src/imports.mjs", importSource),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
|
||||
import { expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
@@ -85,6 +86,13 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
}),
|
||||
"unnamed-empty.js.map": JSON.stringify({
|
||||
version: 3,
|
||||
sources: [null, "original.ts"],
|
||||
sourcesContent: [null, original],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
}),
|
||||
};
|
||||
await writeFixtureFiles(root, {
|
||||
...maps,
|
||||
@@ -92,13 +100,32 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"export const absent = 1;\n//# sourceMappingURL=absent.js.map\n",
|
||||
"mixed.js":
|
||||
"export const answer = 42;\n//# sourceMappingURL=mixed.js.map\n",
|
||||
"unnamed-empty.js":
|
||||
"export const answer = 42;\n//# sourceMappingURL=unnamed-empty.js.map\n",
|
||||
});
|
||||
for (const [mapPath, expectedSource] of [
|
||||
["absent.js.map", "unembedded.ts"],
|
||||
["mixed.js.map", "original.ts"],
|
||||
["unnamed-empty.js.map", "original.ts"],
|
||||
] as const)
|
||||
expect(
|
||||
originalPositionFor(new TraceMap(maps[mapPath], `file:///${mapPath}`), {
|
||||
line: 1,
|
||||
column: 0,
|
||||
}).source,
|
||||
).toBe(`file:///${expectedSource}`);
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const digest = (text: string) =>
|
||||
createHash("sha256").update(text).digest("hex");
|
||||
for (const [name, mapPath, content] of [
|
||||
["unembedded.ts", "absent.js.map", null],
|
||||
["original.ts", "mixed.js.map", original],
|
||||
expect(
|
||||
graph.nodes.filter(
|
||||
(node) => node.identity.strategy === "source-map-original",
|
||||
),
|
||||
).toHaveLength(3);
|
||||
for (const [name, mapPath, content, sourceIndex] of [
|
||||
["unembedded.ts", "absent.js.map", null, 0],
|
||||
["original.ts", "mixed.js.map", original, 1],
|
||||
["original.ts", "unnamed-empty.js.map", original, 1],
|
||||
] as const) {
|
||||
const mapDigest = digest(maps[mapPath]);
|
||||
expect(graph.nodes).toContainEqual(
|
||||
@@ -117,6 +144,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
map_path: mapPath,
|
||||
}),
|
||||
properties: expect.objectContaining({
|
||||
source_index: sourceIndex,
|
||||
declaration_index: sourceIndex,
|
||||
source_name_available: true,
|
||||
content_available: content !== null,
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
@@ -127,27 +157,77 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const [mapPath, content] of [
|
||||
["mixed.js.map", unnamed],
|
||||
["unnamed-empty.js.map", null],
|
||||
] as const)
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "unknown",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
source_map_reference: null,
|
||||
properties: expect.objectContaining({
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
source_name_available: false,
|
||||
content_available: content !== null,
|
||||
content_sha256: content === null ? null : digest(content),
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: digest(maps[mapPath]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(graph.coverage.status).toBe("complete");
|
||||
for (const [path, text] of Object.entries(maps))
|
||||
expect(await readFile(join(root, path), "utf8")).toBe(text);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"rejects non-string source-map names without inventing originals through %s",
|
||||
async (surface, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-invalid-map-source-");
|
||||
const mapText = JSON.stringify({
|
||||
version: 3,
|
||||
sources: [42, "discarded.ts"],
|
||||
sourcesContent: [null, "export const answer: number = 42;"],
|
||||
names: [],
|
||||
mappings: "ACAA",
|
||||
});
|
||||
await writeFixtureFiles(root, { "invalid.js.map": mapText });
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
expect(graph.coverage.status).toBe("partial");
|
||||
expect(
|
||||
graph.nodes.some(
|
||||
(node) => node.identity.strategy === "source-map-original",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "unknown",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
source_name_available: false,
|
||||
content_available: true,
|
||||
content_sha256: digest(unnamed),
|
||||
operation: "parse-local-source-map",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: digest(maps["mixed.js.map"]),
|
||||
sha256: createHash("sha256").update(mapText).digest("hex"),
|
||||
}),
|
||||
limitations: expect.arrayContaining([
|
||||
"Source map contains a non-string source name.",
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(graph.coverage.status).toBe("complete");
|
||||
for (const [path, text] of Object.entries(maps))
|
||||
expect(await readFile(join(root, path), "utf8")).toBe(text);
|
||||
expect(await readFile(join(root, "invalid.js.map"), "utf8")).toBe(mapText);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { join, relative } from "node:path";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
@@ -10,6 +12,318 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const compiler = join(
|
||||
dirname(createRequire(import.meta.url).resolve("typescript/package.json")),
|
||||
"bin",
|
||||
"tsc",
|
||||
);
|
||||
|
||||
const typedLines = [
|
||||
'export import typed = require("typed-package");',
|
||||
'import type TypeOnly = require("./type-only.cjs");',
|
||||
] as const;
|
||||
const typedSource = typedLines.join("\n");
|
||||
const aliasSource = [
|
||||
'import raw = require("typed-package");',
|
||||
"const alias = raw;",
|
||||
"export { alias };",
|
||||
].join("\n");
|
||||
const mixedSource = [
|
||||
'import { value as imported } from "mixed-package";',
|
||||
'import required = require("mixed-package");',
|
||||
"const mixed = Date.now() > 0 ? imported : required.value;",
|
||||
"export { imported as staticChoice, mixed };",
|
||||
"export const requireChoice = required.value;",
|
||||
].join("\n");
|
||||
const typescriptSourceFiles = {
|
||||
"typed.cts": typedSource,
|
||||
"typed.mts": typedSource,
|
||||
"alias.cts": aliasSource,
|
||||
"alias.mts": aliasSource,
|
||||
"mixed.cts": mixedSource,
|
||||
"mixed.mts": mixedSource,
|
||||
};
|
||||
const typedPackageFiles = {
|
||||
"node_modules/typed-package/package.json": JSON.stringify({
|
||||
exports: { require: "./actual.cjs", import: "./decoy.mjs" },
|
||||
}),
|
||||
"node_modules/typed-package/actual.cjs": "module.exports = 42;",
|
||||
"node_modules/typed-package/actual.d.cts":
|
||||
"declare const value: number; export = value;",
|
||||
"node_modules/typed-package/decoy.mjs": "export default 99;",
|
||||
"node_modules/typed-package/decoy.d.mts":
|
||||
"declare const value: number; export default value;",
|
||||
"node_modules/mixed-package/package.json": JSON.stringify({
|
||||
exports: { require: "./actual.cjs", import: "./decoy.mjs" },
|
||||
}),
|
||||
"node_modules/mixed-package/actual.cjs": "exports.value = 42;",
|
||||
"node_modules/mixed-package/actual.d.cts":
|
||||
"export declare const value: number;",
|
||||
"node_modules/mixed-package/decoy.mjs": "export const value = 99;",
|
||||
"node_modules/mixed-package/decoy.d.mts":
|
||||
"export declare const value: number;",
|
||||
};
|
||||
|
||||
const expectNativeModuleControls = async (root: string): Promise<void> => {
|
||||
const emitted = await createTestTempDirectory("rea-import-equals-output-");
|
||||
await writeFixtureFiles(emitted, typedPackageFiles);
|
||||
await execute(
|
||||
process.execPath,
|
||||
[
|
||||
compiler,
|
||||
"--module",
|
||||
"NodeNext",
|
||||
"--moduleResolution",
|
||||
"NodeNext",
|
||||
"--target",
|
||||
"ES2022",
|
||||
"--skipLibCheck",
|
||||
"--allowJs",
|
||||
"--outDir",
|
||||
emitted,
|
||||
join(root, "typed.cts"),
|
||||
join(root, "typed.mts"),
|
||||
join(root, "alias.cts"),
|
||||
join(root, "alias.mts"),
|
||||
join(root, "mixed.cts"),
|
||||
join(root, "mixed.mts"),
|
||||
],
|
||||
{ cwd: root, timeout: 10_000 },
|
||||
);
|
||||
for (const [filename, script] of [
|
||||
[
|
||||
"typed.cjs",
|
||||
'console.log(require("./typed.cjs").typed, require("./alias.cjs").alias);',
|
||||
],
|
||||
[
|
||||
"typed.mjs",
|
||||
'Promise.all([import("./typed.mjs"), import("./alias.mjs")]).then(([first, second]) => console.log(first.typed, second.alias));',
|
||||
],
|
||||
] as const) {
|
||||
const typedControl = await execute(process.execPath, ["-e", script], {
|
||||
cwd: emitted,
|
||||
timeout: 5_000,
|
||||
});
|
||||
expect(typedControl.stdout.trim()).toBe("42 42");
|
||||
expect(await readFile(join(emitted, filename), "utf8")).not.toContain(
|
||||
"./type-only.cjs",
|
||||
);
|
||||
}
|
||||
for (const [filename, expected] of [
|
||||
["mixed.cjs", "42 42 42"],
|
||||
["mixed.mjs", "99 42 99"],
|
||||
] as const) {
|
||||
const control = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
"-e",
|
||||
`import("./${filename}").then(({staticChoice, requireChoice, mixed}) => console.log(staticChoice, requireChoice, mixed));`,
|
||||
],
|
||||
{ cwd: emitted, timeout: 5_000 },
|
||||
);
|
||||
expect(control.stdout.trim()).toBe(expected);
|
||||
}
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
for (const name of ["dependency", "nested"])
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
|
||||
"\\",
|
||||
"/",
|
||||
),
|
||||
).toBe(`${name}.cjs`);
|
||||
};
|
||||
|
||||
const expectAliasRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
for (const source of ["alias.cts", "alias.mts"]) {
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "export",
|
||||
local_name: "alias",
|
||||
exported_name: "alias",
|
||||
resolution_mode: "require",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(aliasSource).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const expectMixedRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
const exported = (source: string, name: string) =>
|
||||
graph.edges.filter(
|
||||
({ relation, properties, evidence }) =>
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "export" &&
|
||||
properties.exported_name === name &&
|
||||
evidence.location.available &&
|
||||
evidence.location.value.kind === "source-range" &&
|
||||
evidence.location.value.source === source,
|
||||
);
|
||||
for (const source of ["mixed.cts", "mixed.mts"]) {
|
||||
for (const [name, target] of [
|
||||
["staticChoice", source.endsWith(".cts") ? "actual.cjs" : "decoy.mjs"],
|
||||
["requireChoice", "actual.cjs"],
|
||||
] as const)
|
||||
expect(exported(source, name)).toMatchObject([
|
||||
{
|
||||
properties: {
|
||||
resolved_path: `node_modules/mixed-package/${target}`,
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
sha256: createHash("sha256").update(mixedSource).digest("hex"),
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
expect(exported("mixed.cts", "mixed")).toMatchObject([
|
||||
{
|
||||
properties: {
|
||||
resolved_path: "node_modules/mixed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
sha256: createHash("sha256").update(mixedSource).digest("hex"),
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(exported("mixed.mts", "mixed")).toEqual([]);
|
||||
};
|
||||
|
||||
const expectImportEqualsRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
for (const [sourcePath, format] of [
|
||||
["typed.cts", "commonjs"],
|
||||
["typed.mts", "esm"],
|
||||
] as const) {
|
||||
const typedLinks = graph.edges.filter(
|
||||
({ relation, properties, evidence: edgeEvidence }) =>
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "require" &&
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.source === sourcePath,
|
||||
);
|
||||
expect(typedLinks).toHaveLength(1);
|
||||
expect(typedLinks[0]).toMatchObject({
|
||||
properties: {
|
||||
specifier: "typed-package",
|
||||
imported_name: null,
|
||||
local_name: "typed",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
available: true,
|
||||
sha256: createHash("sha256").update(typedSource).digest("hex"),
|
||||
},
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
source: sourcePath,
|
||||
start: { line: 1, column: 7 },
|
||||
end: { line: 1, column: typedLines[0].length },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "export",
|
||||
local_name: "typed",
|
||||
resolution_mode: "require",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: sourcePath }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.nodes.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
semantic_role: "source-module",
|
||||
path: sourcePath,
|
||||
export_names: ["typed"],
|
||||
export_relationships: 1,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, evidence: edgeEvidence }) =>
|
||||
relation === "exposes" &&
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.source === sourcePath,
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
kind: "require",
|
||||
specifier: "typed-package",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.nodes.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
semantic_role: "source-module",
|
||||
path: sourcePath,
|
||||
module_format: format,
|
||||
import_relationships: 1,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" && properties.specifier === "./type-only.cjs",
|
||||
),
|
||||
).toHaveLength(0);
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"retains unbound CommonJS semantic relationships through %s",
|
||||
@@ -34,20 +348,16 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"imports.mjs": 'import "./dependency.cjs";',
|
||||
"dependency.cjs": 'throw new Error("fixture must not execute");',
|
||||
"nested.cjs": 'throw new Error("fixture must not execute");',
|
||||
...typescriptSourceFiles,
|
||||
"type-only.d.cts": "declare const value: unknown; export = value;",
|
||||
};
|
||||
await Promise.all(
|
||||
Object.entries(files).map(([path, text]) =>
|
||||
writeFile(join(root, path), text),
|
||||
),
|
||||
);
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
for (const name of ["dependency", "nested"])
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
|
||||
"\\",
|
||||
"/",
|
||||
),
|
||||
).toBe(`${name}.cjs`);
|
||||
await writeFixtureFiles(root, typedPackageFiles);
|
||||
await expectNativeModuleControls(root);
|
||||
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
@@ -70,6 +380,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expectImportEqualsRelationships(graph);
|
||||
expectAliasRelationships(graph);
|
||||
expectMixedRelationships(graph);
|
||||
const links = graph.edges.filter(
|
||||
({ relation, properties, evidence: edgeEvidence }) =>
|
||||
relation === "imports" &&
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"reports Webpack exports attached to renamed factory parameters",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-webpack-renamed-exports-");
|
||||
await mkdir(join(root, "src"));
|
||||
await writeFile(
|
||||
join(root, "src", "chunk.js"),
|
||||
`globalThis.webpackChunkApp.push([[1], {
|
||||
17(module, __webpack_exports__, __webpack_require__) {
|
||||
__webpack_require__.d(__webpack_exports__, { alpha: () => 1, "beta.gamma": () => 2 });
|
||||
Object.defineProperty(__webpack_exports__, "delta", { enumerable: true, get() { return 3; } });
|
||||
__webpack_require__.d(__webpack_exports__.nested, { nested_target: () => 0 });
|
||||
__webpack_exports__ = { rebound: () => 0 };
|
||||
__webpack_require__.d({}, { unrelated: () => 0 });
|
||||
{ const exports = {}; __webpack_require__.d(exports, { shadowed_exports: () => 5 }); }
|
||||
},
|
||||
23(m, e, r) { r.d(e, { alpha: () => 1 }); }
|
||||
}]);`,
|
||||
);
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(response.json).normalized_result,
|
||||
);
|
||||
const modules = result.graph.nodes
|
||||
.filter(({ kind }) => kind === "javascript-module")
|
||||
.map(({ observations }) => observations[0]?.properties);
|
||||
expect(modules).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
module_key: "17",
|
||||
exports: ["alpha", "beta.gamma", "delta"],
|
||||
}),
|
||||
expect.objectContaining({ module_key: "23", exports: ["alpha"] }),
|
||||
]),
|
||||
);
|
||||
expect(result.graph.coverage.status).toBe("complete");
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,84 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const cli = fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url));
|
||||
const plist =
|
||||
'<?xml version="1.0"?><plist version="1.0"><dict><key>label</key><string>hello</string></dict></plist>';
|
||||
|
||||
it("compares identical complete plist inventories across CLI and MCP and creates no unknowns", async () => {
|
||||
const root = await createTestTempDirectory("rea-plist-compare-acceptance-");
|
||||
const leftPath = join(root, "left.plist");
|
||||
const rightPath = join(root, "right.plist");
|
||||
await Promise.all([writeFile(leftPath, plist), writeFile(rightPath, plist)]);
|
||||
|
||||
const cliResult = await execute(process.execPath, [
|
||||
cli,
|
||||
"inspect-artifact",
|
||||
leftPath,
|
||||
"--json",
|
||||
]);
|
||||
const cliInspection = artifactInspectionResultSchema.parse(
|
||||
parseEvidence(JSON.parse(cliResult.stdout)).normalized_result,
|
||||
);
|
||||
const cliInventory = cliInspection.substeps[0]?.evidence;
|
||||
if (cliInventory === undefined)
|
||||
throw new Error("CLI inspection did not retain inventory Evidence");
|
||||
expect(cliInventory.normalized_result).toMatchObject({
|
||||
coverage_status: "complete",
|
||||
limitations: ["Artifact has no child container entries."],
|
||||
});
|
||||
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const opened = await call("open_binary", { path: rightPath });
|
||||
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
|
||||
const inspected = await call("inspect_artifact", {});
|
||||
expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
|
||||
const mcpInspection = artifactInspectionResultSchema.parse(
|
||||
parseEvidence(inspected.structuredContent).normalized_result,
|
||||
);
|
||||
const mcpInventory = mcpInspection.substeps[0]?.evidence;
|
||||
if (mcpInventory === undefined)
|
||||
throw new Error("MCP inspection did not retain inventory Evidence");
|
||||
expect(mcpInventory.normalized_result).toMatchObject({
|
||||
coverage_status: "complete",
|
||||
limitations: ["Artifact has no child container entries."],
|
||||
});
|
||||
|
||||
const compared = await call("compare_artifacts", {
|
||||
left: cliInventory,
|
||||
right: mcpInventory,
|
||||
});
|
||||
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
|
||||
const comparison = parseEvidence(compared.structuredContent);
|
||||
expect(comparison.normalized_result).toMatchObject({
|
||||
status: "unchanged",
|
||||
summary: { unchanged: 1, unknown: 0 },
|
||||
changes: [],
|
||||
});
|
||||
|
||||
const behavior = await call("find_changed_behavior", {
|
||||
comparisons: [comparison],
|
||||
});
|
||||
expect(behavior.isError, JSON.stringify(behavior)).not.toBe(true);
|
||||
expect(behavior.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
behavior_status: "unknown",
|
||||
findings: { items: [] },
|
||||
},
|
||||
});
|
||||
const unknowns = await call("list_unknowns", {
|
||||
domain: "artifact-comparison",
|
||||
});
|
||||
expect(unknowns.isError, JSON.stringify(unknowns)).not.toBe(true);
|
||||
expect(unknowns.structuredContent).toMatchObject({ result: { items: [] } });
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
|
||||
import { artifactInventoryResultSchema } from "../../src/domain/artifactGraph.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import {
|
||||
fatImage,
|
||||
CPU,
|
||||
machoImage,
|
||||
} from "../../src/artifacts/apple/MachoImage.fixture.js";
|
||||
import { javaClassFile } from "../fixtures/javaClassFile.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const cli = fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url));
|
||||
|
||||
const archive = async (
|
||||
entries: readonly (readonly [string, Uint8Array])[],
|
||||
): Promise<Buffer> => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
for (const [name, bytes] of entries)
|
||||
await writer.add(name, new Uint8ArrayReader(bytes));
|
||||
return Buffer.from(await writer.close());
|
||||
};
|
||||
|
||||
const inspectArchive = async (path: string) => {
|
||||
const result = await execute(process.execPath, [
|
||||
cli,
|
||||
"inspect-artifact",
|
||||
path,
|
||||
"--json",
|
||||
]);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
parseEvidence(JSON.parse(result.stdout)).normalized_result,
|
||||
);
|
||||
const evidence = inspection.substeps[0]?.evidence;
|
||||
if (evidence === undefined)
|
||||
throw new Error("CLI inspection did not retain inventory Evidence");
|
||||
return artifactInventoryResultSchema.parse(evidence.normalized_result);
|
||||
};
|
||||
|
||||
it("keeps valid JVM classes from being classified as Mach-O while identifying FAT controls", async () => {
|
||||
const directory = await createTestTempDirectory("rea-jvm-inventory-");
|
||||
const javaEntries = [
|
||||
["Hello.class", javaClassFile()],
|
||||
["pkg/Big.class", javaClassFile(4000)],
|
||||
] as const;
|
||||
const fatControls = [
|
||||
[
|
||||
"fat-be32.bin",
|
||||
fatImage([{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }]),
|
||||
],
|
||||
[
|
||||
"fat-le32.bin",
|
||||
fatImage(
|
||||
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
|
||||
false,
|
||||
true,
|
||||
),
|
||||
],
|
||||
[
|
||||
"fat-be64.bin",
|
||||
fatImage(
|
||||
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
|
||||
true,
|
||||
),
|
||||
],
|
||||
[
|
||||
"fat-le64.bin",
|
||||
fatImage(
|
||||
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
|
||||
true,
|
||||
true,
|
||||
),
|
||||
],
|
||||
] as const;
|
||||
|
||||
const jarPath = join(directory, "classes.jar");
|
||||
await writeFile(
|
||||
jarPath,
|
||||
await archive([
|
||||
["META-INF/MANIFEST.MF", Buffer.from("Manifest-Version: 1.0\n\n")],
|
||||
...javaEntries,
|
||||
]),
|
||||
);
|
||||
const jar = await inspectArchive(jarPath);
|
||||
expect(
|
||||
jar.occurrences
|
||||
.filter(({ logical_path }) => logical_path.endsWith(".class"))
|
||||
.map(({ logical_path, artifact_kind, artifact_format }) => ({
|
||||
logical_path,
|
||||
artifact_kind,
|
||||
artifact_format,
|
||||
})),
|
||||
).toEqual([
|
||||
{
|
||||
logical_path: "Hello.class",
|
||||
artifact_kind: "resource",
|
||||
artifact_format: "file",
|
||||
},
|
||||
{
|
||||
logical_path: "pkg/Big.class",
|
||||
artifact_kind: "unknown",
|
||||
artifact_format: "unknown",
|
||||
},
|
||||
]);
|
||||
const jarClassIds = new Set(
|
||||
jar.occurrences
|
||||
.filter(({ logical_path }) => logical_path.endsWith(".class"))
|
||||
.map(({ artifact_id }) => artifact_id),
|
||||
);
|
||||
expect(
|
||||
jar.nodes
|
||||
.filter(({ artifact_id }) => jarClassIds.has(artifact_id))
|
||||
.map(({ format }) => format)
|
||||
.sort(),
|
||||
).toEqual(["file", "unknown"]);
|
||||
|
||||
const mixedPath = join(directory, "mixed.zip");
|
||||
await writeFile(mixedPath, await archive([...javaEntries, ...fatControls]));
|
||||
const mixed = await inspectArchive(mixedPath);
|
||||
const formatsByPath = new Map(
|
||||
mixed.occurrences.map(
|
||||
({ logical_path, artifact_kind, artifact_format }) => [
|
||||
logical_path,
|
||||
{ artifact_kind, artifact_format },
|
||||
],
|
||||
),
|
||||
);
|
||||
for (const [name] of javaEntries)
|
||||
expect(formatsByPath.get(name)).toEqual(
|
||||
name === "Hello.class"
|
||||
? { artifact_kind: "resource", artifact_format: "file" }
|
||||
: { artifact_kind: "unknown", artifact_format: "unknown" },
|
||||
);
|
||||
for (const [name] of fatControls)
|
||||
expect(formatsByPath.get(name)).toEqual({
|
||||
artifact_kind: "executable",
|
||||
artifact_format: "mach-o-universal",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
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,
|
||||
REFERENCE_HASH,
|
||||
} from "../../src/flutter/FlutterBuild.fixture.js";
|
||||
import {
|
||||
createFlutterApk,
|
||||
createDuplicateFlutterApk,
|
||||
} from "../fixtures/flutterApk.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"CLI and stdio MCP retain Flutter identity, selected ABI and duplicate-member refusals",
|
||||
async ({ cli }) => {
|
||||
const image = aotFixtureImage();
|
||||
Buffer.from("Login\0").copy(image, 0x2300);
|
||||
const engine = engineFixtureImage({
|
||||
notes: Buffer.from(
|
||||
"040000000800000003000000474e55000123456789abcdef",
|
||||
"hex",
|
||||
),
|
||||
prefix: Buffer.from(
|
||||
"040000000800000003000000474e55001111111111111111",
|
||||
"hex",
|
||||
),
|
||||
labels: ["Android (test) clang version 9.0.8"],
|
||||
});
|
||||
const path = await createFlutterApk("selected target.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
|
||||
{
|
||||
path: "lib/arm64-v8a/libflutter.so",
|
||||
bytes: engine,
|
||||
},
|
||||
{ path: "lib/x86_64/libapp.so", bytes: image },
|
||||
{
|
||||
path: "lib/x86_64/libflutter.so",
|
||||
bytes: engine,
|
||||
},
|
||||
]);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [name, abi] of [
|
||||
["identify_flutter_build", undefined],
|
||||
["inspect_dart_aot", undefined],
|
||||
["inspect_dart_aot", "x86_64"],
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
name.replaceAll("_", "-"),
|
||||
path,
|
||||
"--json",
|
||||
...(abi === undefined ? [] : ["--abi", abi]),
|
||||
],
|
||||
});
|
||||
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 }),
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const mcp = parseEvidence(response.structuredContent);
|
||||
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
|
||||
expect(mcp.subject).toEqual(evidence.subject);
|
||||
expect(mcp.subject).toMatchObject({
|
||||
local_path: path,
|
||||
format: "apk",
|
||||
digest: { sha256: complete.target.sha256 },
|
||||
});
|
||||
expect(mcp.evidence_id).toBe(evidence.evidence_id);
|
||||
if (name === "inspect_dart_aot") {
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
abi: abi ?? "arm64-v8a",
|
||||
libapp: {
|
||||
coverage: "complete",
|
||||
snapshot_hash: REFERENCE_HASH,
|
||||
sha256: createHash("sha256").update(image).digest("hex"),
|
||||
},
|
||||
string_pool: {
|
||||
coverage: "complete",
|
||||
class_like_tokens: expect.arrayContaining(["Login"]),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const identified = toolContract(
|
||||
"identify_flutter_build",
|
||||
).outputSchema.parse(result.json).normalized_result;
|
||||
expect(identified.coverage).toBe("complete");
|
||||
for (const abi of identified.abis) {
|
||||
expect(abi.libflutter).toMatchObject({
|
||||
build_id: "0123456789abcdef",
|
||||
build_id_candidates: ["0123456789abcdef"],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const duplicate = await createDuplicateFlutterApk();
|
||||
for (const name of [
|
||||
"identify_flutter_build",
|
||||
"inspect_dart_aot",
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [name.replaceAll("_", "-"), duplicate, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
const mcp = parseMcpToolError(await call(name, { path: duplicate }));
|
||||
expect(mcp.error).toEqual(result.json);
|
||||
expect(mcp.error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: [{ message: expect.stringContaining(duplicate) }] },
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"CLI and MCP retain unsupported snapshot kinds as partial evidence",
|
||||
async ({ cli }) => {
|
||||
const image = aotFixtureImage();
|
||||
for (const offset of [0x1000, 0x2000])
|
||||
image.writeBigUInt64LE(4n, offset + 12);
|
||||
const path = await createFlutterApk("unsupported-kind.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
|
||||
]);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-dart-aot", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
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);
|
||||
expect(parseEvidence(response.structuredContent).normalized_result).toEqual(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
coverage: "partial",
|
||||
libapp: { coverage: "partial", snapshot_hash: REFERENCE_HASH },
|
||||
string_pool: { coverage: "complete" },
|
||||
});
|
||||
expect(
|
||||
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);
|
||||
@@ -177,6 +177,38 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI rejects repeated or empty type selections as invalid input",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-cli-types-");
|
||||
const path = join(root, "fixture.dll");
|
||||
await writeFile(path, buildManagedPeFixture());
|
||||
for (const [types, message] of [
|
||||
[["Fixture.Empty0", "Fixture.Empty0"], "must not repeat a name"],
|
||||
[[""], ">=1 characters"],
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-managed-members",
|
||||
path,
|
||||
...types.flatMap((type) => ["--type", type]),
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
fieldErrors: [
|
||||
expect.objectContaining({
|
||||
path: expect.stringMatching(/^type/u),
|
||||
message: expect.stringContaining(message),
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI bounds CIL claims by section virtual ranges",
|
||||
async ({ cli }) => {
|
||||
@@ -275,3 +307,36 @@ cliTest(
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI reports a section table past EOF as invalid input",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-cli-sections-");
|
||||
const path = join(root, "fixture.dll");
|
||||
const bytes = buildManagedPeFixture();
|
||||
const pe = bytes.readUInt32LE(0x3c);
|
||||
const sections = pe + 24 + bytes.readUInt16LE(pe + 20);
|
||||
bytes.writeUInt32LE(bytes.length + 0x1000, sections + 20);
|
||||
await writeFile(path, bytes);
|
||||
for (const command of [
|
||||
"inspect-managed-artifact",
|
||||
"inspect-managed-members",
|
||||
"inspect-managed-native-boundaries",
|
||||
]) {
|
||||
const result = await cli.run({ arguments: [command, path, "--json"] });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: expect.stringContaining("pe.section-data"),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -30,7 +30,7 @@ type CaptureOutcome =
|
||||
| { readonly kind: "partial"; readonly partial: unknown };
|
||||
|
||||
const captureScenario = (
|
||||
mode: "cooperative" | "ignoring" | "descendant",
|
||||
mode: "cooperative" | "ignoring" | "delayed-ignoring" | "descendant",
|
||||
root: string,
|
||||
additions: CaptureScenario = {},
|
||||
finalExitCode?: number,
|
||||
@@ -453,11 +453,13 @@ captureTest(
|
||||
"rea-finalization-cli-cancel-",
|
||||
);
|
||||
const cliScenarioPath = join(cliRoot, "scenario.json");
|
||||
// Match the other finalization cases' observation window. The old 300 ms
|
||||
// deadline could signal the fixture before it installed its handlers.
|
||||
await writeFile(
|
||||
cliScenarioPath,
|
||||
JSON.stringify(
|
||||
captureScenario("ignoring", cliRoot, {
|
||||
timeout_ms: 300,
|
||||
captureScenario("delayed-ignoring", cliRoot, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
),
|
||||
@@ -527,18 +529,36 @@ captureTest(
|
||||
const mcpRoot = await createTestTempDirectory(
|
||||
"rea-finalization-mcp-cancel-",
|
||||
);
|
||||
const { client } = await connectLocalToolsMcp();
|
||||
const { client, call: callTool } = await connectLocalToolsMcp();
|
||||
const controller = new AbortController();
|
||||
const call = client.callTool(
|
||||
{
|
||||
name: "capture_process_scenario",
|
||||
arguments: captureScenario("ignoring", mcpRoot, {
|
||||
timeout_ms: 300,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
let reportStarted: (() => void) | undefined;
|
||||
const captureStarted = new Promise<void>((resolve) => {
|
||||
reportStarted = resolve;
|
||||
});
|
||||
const call = callTool(
|
||||
"capture_process_scenario",
|
||||
captureScenario("delayed-ignoring", mcpRoot, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
{ signal: controller.signal, onprogress: () => reportStarted?.() },
|
||||
);
|
||||
// Observe rejection immediately: a failed readiness wait must not leave a
|
||||
// pending request to reject unhandled when the fixture closes its client.
|
||||
// The original promise remains available for the cancellation assertion.
|
||||
const observedCall = call.catch(() => undefined);
|
||||
onTestFinished(async () => {
|
||||
controller.abort();
|
||||
await observedCall;
|
||||
});
|
||||
// Start the fixture's readiness wait after the server begins this capture;
|
||||
// SDK schema preparation before dispatch is not target startup time.
|
||||
await Promise.race([
|
||||
captureStarted,
|
||||
call.then(() => {
|
||||
throw new Error("MCP capture completed before reporting startup");
|
||||
}),
|
||||
]);
|
||||
const mcpFixturePid = await waitForFinalization(mcpRoot);
|
||||
const mcpStarted = Date.now();
|
||||
controller.abort(new Error("cancel finalization acceptance fixture"));
|
||||
@@ -548,7 +568,7 @@ captureTest(
|
||||
).rejects.toThrow("cancel finalization acceptance fixture");
|
||||
await waitForProcessExit(mcpFixturePid);
|
||||
await expect(
|
||||
client.listTools(),
|
||||
client.listTools(undefined, { cacheMode: "refresh" }),
|
||||
"the server accepts a follow-up request after cancelling the capture",
|
||||
).resolves.toMatchObject({ tools: expect.any(Array) });
|
||||
expect(
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
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",
|
||||
text: "[]",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "null",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: '{"mcpServers":null,"keep":1}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: '{"mcpServers":"x","keep":1}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "pi",
|
||||
path: ".pi/agent/mcp.json",
|
||||
text: '{"mcpServers":[]}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "codex",
|
||||
path: ".codex/config.toml",
|
||||
text: 'mcp_servers = "x"\n',
|
||||
diagnostic: '"mcp_servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "opencode",
|
||||
path: ".config/opencode/opencode.json",
|
||||
text: '{"mcp":{"servers":null}}',
|
||||
diagnostic: '"mcp.servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "- item\n",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "mcp_servers: null\nkeep: 1\n",
|
||||
diagnostic: '"mcp_servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "not-json",
|
||||
diagnostic: "Configuration is not valid JSON",
|
||||
syntax: "JSON",
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "mcp_servers: [\n",
|
||||
diagnostic: "Configuration is not valid YAML",
|
||||
syntax: "YAML",
|
||||
},
|
||||
{
|
||||
client: "dsh",
|
||||
path: ".dsh/cordis.patch.yml",
|
||||
text: "- insert: [\n",
|
||||
diagnostic: "Configuration is not valid YAML",
|
||||
syntax: "YAML",
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const scenario of cases)
|
||||
cliTest(
|
||||
`setup and uninstall explain ${scenario.client} configuration ${scenario.text}`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory(
|
||||
"rea-client-config-diagnostic-",
|
||||
);
|
||||
const config = join(home, scenario.path);
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
const original =
|
||||
"bytes" in scenario ? scenario.bytes : Buffer.from(scenario.text);
|
||||
await writeFile(config, original);
|
||||
const environment = {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
HERMES_HOME: join(home, ".hermes"),
|
||||
DSH_HOME: join(home, ".dsh"),
|
||||
};
|
||||
const setup = await cli.run({
|
||||
arguments: [
|
||||
"setup",
|
||||
"--client",
|
||||
scenario.client,
|
||||
"--skill=false",
|
||||
"--yes",
|
||||
"--json",
|
||||
],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(setup.exitCode).toBe(1);
|
||||
expect(setup.json).toMatchObject({
|
||||
status: "needs_human",
|
||||
plannedActions: [],
|
||||
appliedActions: [],
|
||||
});
|
||||
if ("syntax" in scenario) {
|
||||
expect(setup.json).toMatchObject({ remediation: expect.any(String) });
|
||||
if (scenario.syntax === "JSON")
|
||||
expect(setup.stdout).toContain("Invalid JSON/JSONC");
|
||||
} else {
|
||||
expect(setup.json).toMatchObject({
|
||||
remediation: expect.stringContaining(scenario.diagnostic),
|
||||
});
|
||||
expect(setup.stdout).not.toContain("invalid_type");
|
||||
}
|
||||
const uninstall = await cli.run({
|
||||
arguments: ["uninstall", "--json"],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(uninstall.exitCode).toBe(1);
|
||||
expect(uninstall.json).toMatchObject({
|
||||
status: "failed",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: scenario.client,
|
||||
status: "failed",
|
||||
detail: expect.stringContaining(scenario.diagnostic),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
if (!("syntax" in scenario))
|
||||
expect(uninstall.stdout).not.toContain("not valid JSON");
|
||||
expect(await readFile(config)).toEqual(original);
|
||||
expect(await readdir(dirname(config))).toEqual([
|
||||
scenario.path.split("/").at(-1),
|
||||
]);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,139 @@
|
||||
import { access, mkdir, readFile } from "node:fs/promises";
|
||||
import { userInfo } from "node:os";
|
||||
import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import { parse } from "jsonc-parser";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"setup dry run resolves empty home values without writing to the cwd",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-empty-home-dry-run-");
|
||||
const workingDirectory = join(directory, "cwd");
|
||||
await mkdir(workingDirectory);
|
||||
const hostHome = userInfo().homedir;
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"setup",
|
||||
"--client",
|
||||
"cursor",
|
||||
"--skill=false",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
],
|
||||
cwd: workingDirectory,
|
||||
environment: {
|
||||
HOME: "",
|
||||
USERPROFILE: "",
|
||||
HOMEDRIVE: "",
|
||||
HOMEPATH: "",
|
||||
XDG_CONFIG_HOME: "",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.exitCode, result.stdout).toBe(0);
|
||||
const output = result.json as {
|
||||
plannedActions?: Array<{ kind?: unknown; target?: unknown }>;
|
||||
status?: unknown;
|
||||
};
|
||||
expect(["planned", "ready"]).toContain(output.status);
|
||||
const configTargets = (output.plannedActions ?? [])
|
||||
.filter((action) => action.kind === "configure_client")
|
||||
.map((action) => action.target);
|
||||
for (const target of configTargets) {
|
||||
expect(typeof target).toBe("string");
|
||||
if (typeof target !== "string") continue;
|
||||
expect(isAbsolute(target)).toBe(true);
|
||||
const relativeTarget = relative(hostHome, target);
|
||||
expect(
|
||||
relativeTarget === "" ||
|
||||
(!relativeTarget.startsWith(`..${sep}`) && relativeTarget !== ".."),
|
||||
).toBe(true);
|
||||
}
|
||||
expect(configTargets).not.toContain(
|
||||
join(workingDirectory, ".cursor", "mcp.json"),
|
||||
);
|
||||
await expect(
|
||||
access(join(workingDirectory, ".cursor", "mcp.json")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.skipIf(process.platform === "win32")(
|
||||
"setup, doctor, and uninstall use the nonempty fallback home when HOME is empty",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-empty-home-lifecycle-",
|
||||
);
|
||||
const home = join(directory, "fallback-home");
|
||||
const workingDirectory = join(directory, "cwd");
|
||||
await mkdir(home);
|
||||
await mkdir(workingDirectory);
|
||||
const environment = {
|
||||
HOME: "",
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
};
|
||||
const run = (arguments_: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: workingDirectory,
|
||||
environment,
|
||||
});
|
||||
|
||||
const setup = await run(["setup", "--client", "cursor", "--yes", "--json"]);
|
||||
expect(setup.exitCode, setup.stderr).toBe(0);
|
||||
expect(setup.json).toMatchObject({ status: "ready" });
|
||||
await access(join(home, ".cursor", "mcp.json"));
|
||||
await access(
|
||||
join(home, ".agents", "skills", "reverse-engineer-anything", "SKILL.md"),
|
||||
);
|
||||
await expect(
|
||||
access(join(workingDirectory, ".cursor", "mcp.json")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
await expect(
|
||||
access(join(workingDirectory, ".agents", "skills")),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
const doctor = await run([
|
||||
"doctor",
|
||||
"--client",
|
||||
"cursor",
|
||||
"--skill",
|
||||
"--json",
|
||||
]);
|
||||
expect(doctor.exitCode, doctor.stdout).toBe(0);
|
||||
expect(doctor.json).toMatchObject({ healthy: true });
|
||||
|
||||
const uninstall = await run(["uninstall", "--json"]);
|
||||
expect(uninstall.exitCode, uninstall.stderr).toBe(0);
|
||||
expect(uninstall.json).toMatchObject({ status: "complete" });
|
||||
const remainingConfig = parse(
|
||||
await readFile(join(home, ".cursor", "mcp.json"), "utf8"),
|
||||
);
|
||||
expect(remainingConfig).not.toHaveProperty("mcpServers.rea");
|
||||
await expect(
|
||||
access(
|
||||
join(
|
||||
home,
|
||||
".agents",
|
||||
"skills",
|
||||
"reverse-engineer-anything",
|
||||
"SKILL.md",
|
||||
),
|
||||
),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(
|
||||
access(join(workingDirectory, ".cursor", "mcp.json")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,597 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { expect, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
expandProviderCapabilities,
|
||||
expandToolAvailability,
|
||||
providerCapabilitySet,
|
||||
toolAvailabilityInventory,
|
||||
} from "../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
|
||||
import { SQLITE_NATIVE_LIMITS_AVAILABLE } from "../fixtures/sqlite/database.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
const digest = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"bounds default context and projects exact columns without evaluating unrelated cells",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-selective-");
|
||||
const path = join(root, "selected.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`
|
||||
CREATE TABLE selected(id INTEGER, "" TEXT, payload BLOB GENERATED ALWAYS AS (zeroblob(72*1024*1024)) VIRTUAL);
|
||||
CREATE TABLE unrelated(value TEXT);
|
||||
CREATE VIEW unrelated_view AS SELECT value FROM unrelated;
|
||||
CREATE INDEX selected_id ON selected(id);
|
||||
CREATE TRIGGER selected_trigger AFTER INSERT ON selected BEGIN SELECT 1; END;
|
||||
WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n<21)
|
||||
INSERT INTO selected(id, "") SELECT n, 'retained' FROM numbers;
|
||||
`);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const before = await readFile(path);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const inventory = await call("inspect_sqlite_database", { path });
|
||||
expect(inventory.isError).not.toBe(true);
|
||||
const schema = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
schema: z.object({
|
||||
scope: z.literal("inventory"),
|
||||
tables: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
columns: z.array(z.unknown()),
|
||||
columns_completeness: z.literal("not_requested"),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(inventory.structuredContent).normalized_result.schema;
|
||||
expect(schema.tables.map((table) => table.name)).toEqual([
|
||||
"selected",
|
||||
"unrelated",
|
||||
]);
|
||||
expect(schema.tables.every((table) => table.columns.length === 0)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(JSON.stringify(inventory.structuredContent)).not.toContain(
|
||||
"zeroblob",
|
||||
);
|
||||
const selected = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "selected",
|
||||
columns: ["", "id", "id"],
|
||||
});
|
||||
expect(selected.isError).not.toBe(true);
|
||||
expect(selected.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
schema: {
|
||||
scope: "selected_table",
|
||||
tables: [{ name: "selected" }],
|
||||
views: [],
|
||||
indexes: [{ name: "selected_id" }],
|
||||
triggers: [{ name: "selected_trigger" }],
|
||||
},
|
||||
rows: {
|
||||
columns: ["", "id", "id"],
|
||||
row_limit: 20,
|
||||
returned_rows: 20,
|
||||
truncated: true,
|
||||
values: expect.arrayContaining([
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
value: "retained",
|
||||
bytes_hex: "72657461696e6564",
|
||||
encoding: "UTF-8",
|
||||
},
|
||||
{ type: "integer", value: "1" },
|
||||
{ type: "integer", value: "1" },
|
||||
],
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
const cliResult = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"selected",
|
||||
"--column",
|
||||
"id",
|
||||
"--column",
|
||||
"",
|
||||
"--row-limit",
|
||||
"1",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(cliResult.exitCode, cliResult.stdout + cliResult.stderr).toBe(0);
|
||||
expect(cliResult.json).toMatchObject({
|
||||
normalized_result: { rows: { columns: ["id", ""], returned_rows: 1 } },
|
||||
});
|
||||
for (const input of [
|
||||
{ path, columns: ["id"] },
|
||||
{ path, schema_scope: "selected_table" },
|
||||
{ path, table: "selected", columns: [] },
|
||||
{ path, table: "selected", columns: ["ID"] },
|
||||
])
|
||||
expect((await call("inspect_sqlite_database", input)).isError).toBe(true);
|
||||
expect(await readFile(path)).toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"discovers SQLite runtime availability before inspecting a database through CLI and MCP",
|
||||
async ({ cli }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["capabilities", "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
const status = z
|
||||
.object({
|
||||
open: z.literal(false),
|
||||
capabilities: z.array(providerCapabilitySet),
|
||||
})
|
||||
.parse(result.json);
|
||||
expect(expandProviderCapabilities(status.capabilities)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "inspect_sqlite_database",
|
||||
available: SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
reason: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
|
||||
availability_code: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: "unsupported_version",
|
||||
limitations: [expect.stringContaining("DatabaseSync.limits")],
|
||||
effects: {
|
||||
mutates_artifact: false,
|
||||
launches_process: true,
|
||||
may_show_ui: false,
|
||||
may_access_network: false,
|
||||
may_write_filesystem: true,
|
||||
changes_permissions: false,
|
||||
requires_root: false,
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("binary_session", {});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const sessionStatus = z
|
||||
.object({
|
||||
result: z.object({ tool_availability: toolAvailabilityInventory }),
|
||||
})
|
||||
.parse(response.structuredContent);
|
||||
expect(
|
||||
expandToolAvailability(sessionStatus.result.tool_availability),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "inspect_sqlite_database",
|
||||
available: SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
remediation: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.skipIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"reports the required native SQLite limits capability through CLI and MCP",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-unavailable-");
|
||||
const path = join(root, "selected.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec("CREATE TABLE items(value INTEGER)");
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-sqlite-database", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("DatabaseSync.limits"),
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", { path });
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response).error).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("DatabaseSync.limits"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"accepts small samples above 1000 rows within the real resource budgets",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-row-budget-");
|
||||
const path = join(root, "rows.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`CREATE TABLE items(value INTEGER);
|
||||
WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers WHERE value < 1002)
|
||||
INSERT INTO items SELECT value FROM numbers;`);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const limit of [1001, Number.MAX_SAFE_INTEGER]) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"items",
|
||||
"--row-limit",
|
||||
String(limit),
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
rows: {
|
||||
row_limit: limit,
|
||||
returned_rows: Math.min(limit, 1002),
|
||||
truncated: limit < 1002,
|
||||
},
|
||||
},
|
||||
});
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "items",
|
||||
row_limit: limit,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const sourceState = async (path: string) => {
|
||||
const bytes = await readFile(path);
|
||||
const metadata = await stat(path, { bigint: true });
|
||||
return {
|
||||
bytes,
|
||||
device: metadata.dev,
|
||||
inode: metadata.ino,
|
||||
size: metadata.size,
|
||||
modified: metadata.mtimeNs,
|
||||
changed: metadata.ctimeNs,
|
||||
};
|
||||
};
|
||||
|
||||
const createLosslessSnapshot = (path: string, journalMode: string): void => {
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`PRAGMA journal_mode=${journalMode}`);
|
||||
database.exec(`
|
||||
CREATE TABLE "odd "" table" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
payload BLOB,
|
||||
amount REAL,
|
||||
missing TEXT,
|
||||
text_value TEXT,
|
||||
negative_zero,
|
||||
generated TEXT GENERATED ALWAYS AS (hex(payload)) VIRTUAL
|
||||
);
|
||||
CREATE UNIQUE INDEX "quoted "" index" ON "odd "" table"(payload, id);
|
||||
CREATE VIEW readable AS SELECT id FROM "odd "" table";
|
||||
CREATE TRIGGER observed AFTER INSERT ON "odd "" table" BEGIN SELECT 1; END;
|
||||
CREATE TABLE keyed(k TEXT PRIMARY KEY) WITHOUT ROWID, STRICT;
|
||||
`);
|
||||
const insert = database.prepare(
|
||||
'INSERT INTO "odd "" table"(id,payload,amount,missing,text_value,negative_zero) VALUES(?,?,?,NULL,CAST(X\'80ff\' AS TEXT),?)',
|
||||
);
|
||||
insert.setReadBigInts(true);
|
||||
expect(
|
||||
insert.run(
|
||||
9007199254740993n,
|
||||
Buffer.from("deadbeef", "hex"),
|
||||
Infinity,
|
||||
-0,
|
||||
).lastInsertRowid,
|
||||
).toBe(9007199254740993n);
|
||||
insert.run(9007199254740994n, Buffer.from("deadbeef", "hex"), Infinity, -0);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
};
|
||||
|
||||
cliTest
|
||||
.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)
|
||||
.for(["DELETE", "PERSIST", "TRUNCATE"])(
|
||||
"inspects a real %s SQLite schema and lossless selected records identically through CLI and MCP",
|
||||
async (journalMode, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-public-");
|
||||
const path = join(root, "selected.db");
|
||||
createLosslessSnapshot(path, journalMode);
|
||||
const original = await readFile(path);
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
"selected.db",
|
||||
"--schema-scope",
|
||||
"database",
|
||||
"--table",
|
||||
'odd " table',
|
||||
"--row-limit",
|
||||
"1",
|
||||
"--json",
|
||||
],
|
||||
cwd: root,
|
||||
environment: {
|
||||
REA_LOG_LEVEL: "silent",
|
||||
REA_ANALYSIS_PROVIDER: "ghidra",
|
||||
REA_GHIDRA_HOME: "/unconfigured/ghidra",
|
||||
},
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
operation: "inspect_sqlite_database",
|
||||
confidence: "observed",
|
||||
subject: { local_path: path, digest: { sha256: digest(original) } },
|
||||
normalized_result: {
|
||||
artifact: { path, sha256: digest(original), bytes: original.length },
|
||||
wal: null,
|
||||
schema: {
|
||||
completeness: "complete",
|
||||
tables: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: 'odd " table',
|
||||
columns: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "id",
|
||||
primary_key_position: 1,
|
||||
}),
|
||||
expect.objectContaining({ name: "generated", hidden: 2 }),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "keyed",
|
||||
without_rowid: true,
|
||||
strict: true,
|
||||
}),
|
||||
]),
|
||||
indexes: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: 'quoted " index',
|
||||
table: 'odd " table',
|
||||
}),
|
||||
]),
|
||||
views: [
|
||||
{ name: "readable", sql: expect.stringContaining("SELECT id") },
|
||||
],
|
||||
triggers: [
|
||||
{
|
||||
name: "observed",
|
||||
table: 'odd " table',
|
||||
sql: expect.stringContaining("AFTER INSERT"),
|
||||
},
|
||||
],
|
||||
},
|
||||
rows: {
|
||||
table: 'odd " table',
|
||||
columns: [
|
||||
"id",
|
||||
"payload",
|
||||
"amount",
|
||||
"missing",
|
||||
"text_value",
|
||||
"negative_zero",
|
||||
"generated",
|
||||
],
|
||||
returned_rows: 1,
|
||||
row_limit: 1,
|
||||
truncated: true,
|
||||
values: [
|
||||
[
|
||||
{
|
||||
type: "integer",
|
||||
value: expect.stringMatching(/^900719925474099[34]$/),
|
||||
},
|
||||
{ type: "blob", hex: "deadbeef" },
|
||||
{ type: "real", value: "Infinity" },
|
||||
{ type: "null" },
|
||||
{ type: "text", value: "\ufffd\ufffd", bytes_hex: "80ff" },
|
||||
{ type: "real", value: "-0" },
|
||||
{
|
||||
type: "text",
|
||||
value: "DEADBEEF",
|
||||
bytes_hex: "4445414442454546",
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: 'odd " table',
|
||||
schema_scope: "database",
|
||||
row_limit: 1,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
expect(await readFile(path)).toEqual(original);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"includes uncheckpointed committed WAL data without modifying the source database or sidecars",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-wal-public-");
|
||||
const path = join(root, "wal.db");
|
||||
const database = new DatabaseSync(path);
|
||||
onTestFinished(() => database.close());
|
||||
database.exec(
|
||||
"PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; CREATE TABLE committed(value TEXT); INSERT INTO committed VALUES('only in WAL');",
|
||||
);
|
||||
const files = [path, `${path}-wal`, `${path}-shm`];
|
||||
const before = await Promise.all(files.map(sourceState));
|
||||
const db = before[0];
|
||||
const wal = before[1];
|
||||
expect(db).toBeDefined();
|
||||
expect(wal).toBeDefined();
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"committed",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
artifact: { sha256: db === undefined ? "missing" : digest(db.bytes) },
|
||||
wal: {
|
||||
path: `${path}-wal`,
|
||||
sha256: wal === undefined ? "missing" : digest(wal.bytes),
|
||||
},
|
||||
rows: {
|
||||
values: [
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
value: "only in WAL",
|
||||
bytes_hex: Buffer.from("only in WAL").toString("hex"),
|
||||
},
|
||||
],
|
||||
],
|
||||
returned_rows: 1,
|
||||
truncated: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "committed",
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
const after = await Promise.all(files.map(sourceState));
|
||||
expect(after).toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"returns actionable public errors for corrupt input, unknown or ambiguous tables and invalid record choices",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-errors-public-");
|
||||
const path = join(root, "invalid.db");
|
||||
await writeFile(path, "not a SQLite database");
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const corrupt = await cli.run({
|
||||
arguments: ["inspect-sqlite-database", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(corrupt.exitCode).toBe(1);
|
||||
expect(corrupt.json).toMatchObject({ code: "invalid_request" });
|
||||
expect((await call("inspect_sqlite_database", { path })).isError).toBe(
|
||||
true,
|
||||
);
|
||||
const valid = join(root, "valid.db");
|
||||
const database = new DatabaseSync(valid);
|
||||
try {
|
||||
database.exec(
|
||||
"CREATE TABLE present(value TEXT); CREATE VIRTUAL TABLE search USING fts5(body);",
|
||||
);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const bytes = await readFile(valid);
|
||||
const declaration = bytes.indexOf(Buffer.from("USING fts5"));
|
||||
if (declaration < 0) throw new Error("Virtual declaration missing");
|
||||
bytes.write("zzzz", declaration + Buffer.byteLength("USING "), "utf8");
|
||||
await writeFile(valid, bytes);
|
||||
const schema = await call("inspect_sqlite_database", { path: valid });
|
||||
expect(schema.isError).not.toBe(true);
|
||||
expect(schema.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
schema: {
|
||||
tables: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "search_data", kind: "unknown" }),
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
const ambiguous = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
valid,
|
||||
"--table",
|
||||
"search_data",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(ambiguous.exitCode).toBe(1);
|
||||
expect(ambiguous.stdout).toContain("shadow table");
|
||||
expect(
|
||||
(
|
||||
await call("inspect_sqlite_database", {
|
||||
path: valid,
|
||||
table: "search_data",
|
||||
})
|
||||
).isError,
|
||||
).toBe(true);
|
||||
const missing = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
valid,
|
||||
"--table",
|
||||
"absent",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(missing.exitCode).toBe(1);
|
||||
expect(missing.stdout).toContain("absent");
|
||||
expect(
|
||||
(await call("inspect_sqlite_database", { path: valid, table: "absent" }))
|
||||
.isError,
|
||||
).toBe(true);
|
||||
for (const input of [
|
||||
{ path: valid, row_limit: 1 },
|
||||
{ path: valid, table: "present", row_limit: 0 },
|
||||
{ path: valid, query: "DELETE FROM present" },
|
||||
]) {
|
||||
expect(
|
||||
(await call("inspect_sqlite_database", input)).isError,
|
||||
JSON.stringify(input),
|
||||
).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -19,6 +19,25 @@ const electron = {
|
||||
executable_path: "/tmp/Electron",
|
||||
application_path: "/tmp/main.js",
|
||||
};
|
||||
|
||||
const runCliExpectingInputError = async (
|
||||
scenarioPath: string,
|
||||
): Promise<unknown> => {
|
||||
const failure = await execute(process.execPath, [
|
||||
cli,
|
||||
"capture-process",
|
||||
scenarioPath,
|
||||
"--json",
|
||||
]).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toMatchObject({ code: 1 });
|
||||
if (!(failure instanceof Error) || !("stdout" in failure))
|
||||
throw new Error("Expected the CLI to report an input error on stdout");
|
||||
return JSON.parse(String(failure.stdout)) as unknown;
|
||||
};
|
||||
|
||||
const pathRequests: readonly [string, Record<string, unknown>][] = [
|
||||
["open_binary", { path: nul }],
|
||||
["open_binary", { path: process.execPath, snapshot_path: nul }],
|
||||
@@ -235,25 +254,80 @@ captureTest(
|
||||
});
|
||||
expect(parseMcpToolError(failed)).toMatchObject({
|
||||
error: {
|
||||
code: "process_capture_failed",
|
||||
message: expect.stringContaining(missing),
|
||||
details: { execution_failure: expect.stringContaining(missing) },
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["executable"],
|
||||
message: expect.stringContaining(`${missing} (ENOENT)`),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
await writeFile(
|
||||
join(root, "scenario.json"),
|
||||
JSON.stringify({ executable: missing }),
|
||||
);
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
cli,
|
||||
"capture-process",
|
||||
join(root, "scenario.json"),
|
||||
"--json",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining(missing),
|
||||
const executableCliFailure = await runCliExpectingInputError(
|
||||
join(root, "scenario.json"),
|
||||
);
|
||||
expect(executableCliFailure).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["executable"],
|
||||
message: expect.stringContaining(`${missing} (ENOENT)`),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const missingWorkingDirectory = join(root, "missing-working-directory");
|
||||
const cwdFailure = await call("capture_process_scenario", {
|
||||
executable: process.execPath,
|
||||
working_directory: missingWorkingDirectory,
|
||||
});
|
||||
expect(parseMcpToolError(cwdFailure)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["working_directory"],
|
||||
message: expect.stringContaining(
|
||||
`${missingWorkingDirectory} (ENOENT)`,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const cwdScenario = join(root, "missing-working-directory.json");
|
||||
await writeFile(
|
||||
cwdScenario,
|
||||
JSON.stringify({
|
||||
executable: process.execPath,
|
||||
working_directory: missingWorkingDirectory,
|
||||
}),
|
||||
);
|
||||
expect(await runCliExpectingInputError(cwdScenario)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["working_directory"],
|
||||
message: expect.stringContaining(
|
||||
`${missingWorkingDirectory} (ENOENT)`,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
60_000,
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
@@ -35,7 +35,9 @@ cliTest(
|
||||
environment,
|
||||
timeoutMs: 15000,
|
||||
});
|
||||
expect(cliResponse.exitCode).toBe(0);
|
||||
expect(cliResponse.exitCode, cliResponse.stdout + cliResponse.stderr).toBe(
|
||||
0,
|
||||
);
|
||||
expect(cliResponse.json).toMatchObject({
|
||||
normalized_result: {
|
||||
engine: null,
|
||||
|
||||
@@ -40,7 +40,7 @@ cliTest(
|
||||
},
|
||||
timeoutMs: 45000,
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
expect(response.exitCode, response.stdout + response.stderr).toBe(0);
|
||||
expect(response.json).toMatchObject({
|
||||
normalized_result: {
|
||||
source: { script_index: 0 },
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/Pwntool
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
||||
import { binaryLayoutFixture } from "../../fixtures/binaryDiagnostics/layout.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
|
||||
@@ -94,6 +95,7 @@ it.runIf(!unsupportedHost)(
|
||||
async () => {
|
||||
const { path } = await fixture();
|
||||
let ownedPath = "";
|
||||
let cleanupAllowed = false;
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
async (spawn) => {
|
||||
@@ -106,22 +108,37 @@ it.runIf(!unsupportedHost)(
|
||||
return {
|
||||
...launched,
|
||||
cleanup: async () => {
|
||||
await launched.cleanup?.();
|
||||
if (cleanupAllowed)
|
||||
return cleanupOwnedProcessGroup(launched.ownership);
|
||||
throw new Error("injected post-cleanup reporting failure");
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
});
|
||||
const result = await provider.inspect({ path });
|
||||
if (result.ok) throw new Error("Expected compounded lifecycle failure");
|
||||
expect(result.error).toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
diagnostics: {
|
||||
reason: "injected post-cleanup reporting failure",
|
||||
previous_error: { failure_kind: "output-limit" },
|
||||
captured_output: { truncated: true, stderr: "" },
|
||||
primary_error: {
|
||||
code: "unreadable_output",
|
||||
details: { captured_output: { truncated: true, stderr: "" } },
|
||||
},
|
||||
cleanup_error: {
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: { reason: "injected post-cleanup reporting failure" },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(access(ownedPath)).resolves.toBeUndefined();
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
@@ -418,8 +435,11 @@ it.runIf(!unsupportedHost)(
|
||||
cleanupIncomplete: true,
|
||||
cleanupResources: [root],
|
||||
diagnostics: {
|
||||
reason: "root cleanup failed",
|
||||
previous_error: { category: "invalid_input" },
|
||||
primary_error: { category: "invalid_input" },
|
||||
cleanup_error: {
|
||||
code: "cleanup_incomplete",
|
||||
details: { diagnostics: { reason: "root cleanup failed" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { AnalysisError } from "../../../src/domain/analysisErrorBase.js";
|
||||
import type { RecordedCrash } from "../../../src/domain/native/recordedCrash.js";
|
||||
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
@@ -9,7 +10,10 @@ import {
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
import { PwntoolsRecordedCrashProvider } from "../../../src/native/pwntools/PwntoolsRecordedCrashProvider.js";
|
||||
import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/PwntoolsRelease.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import {
|
||||
spawnOwnedProviderProcess,
|
||||
type SpawnedOwnedProviderProcess,
|
||||
} from "../../../src/process/ProviderProcess.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
||||
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
|
||||
import {
|
||||
@@ -27,6 +31,19 @@ const requestSchema = z.object({
|
||||
});
|
||||
const host = process.platform === "linux" && process.arch === "x64";
|
||||
|
||||
const withCleanupGate = (
|
||||
launched: SpawnedOwnedProviderProcess,
|
||||
cleanupAllowed: () => boolean,
|
||||
): SpawnedOwnedProviderProcess => ({
|
||||
...launched,
|
||||
cleanup: async () => {
|
||||
const result = await cleanupOwnedProcessGroup(launched.ownership);
|
||||
if (!cleanupAllowed())
|
||||
throw new Error("source-owned post-cleanup reporting failure");
|
||||
return result;
|
||||
},
|
||||
});
|
||||
|
||||
it
|
||||
.runIf(host)
|
||||
.each([
|
||||
@@ -132,6 +149,7 @@ it
|
||||
"invalid-context",
|
||||
"cancelled",
|
||||
"cleanup-failure",
|
||||
"decoder-cleanup-failure",
|
||||
] as const)(
|
||||
"owns optional context from the same snapshot: %s",
|
||||
async (scenario) => {
|
||||
@@ -139,6 +157,8 @@ it
|
||||
const controller = new AbortController();
|
||||
let owned = "";
|
||||
let snapshotPath = "";
|
||||
let cleanupAllowed = false;
|
||||
let launches = 0;
|
||||
const venv = join(root, "venv");
|
||||
const plugin = join(root, "gdbinit.py");
|
||||
await mkdir(venv);
|
||||
@@ -155,6 +175,7 @@ it
|
||||
}),
|
||||
},
|
||||
async (spawn) => {
|
||||
launches++;
|
||||
const request = requestSchema.parse(
|
||||
JSON.parse(await readFile(spawn.arguments.at(-1) ?? "", "utf8")),
|
||||
);
|
||||
@@ -177,11 +198,14 @@ it
|
||||
value: raw,
|
||||
}),
|
||||
);
|
||||
return spawnOwnedProviderProcess({
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.stdout.write('basic stage diagnostic')"],
|
||||
});
|
||||
return scenario === "decoder-cleanup-failure"
|
||||
? withCleanupGate(launched, () => cleanupAllowed)
|
||||
: launched;
|
||||
}
|
||||
expect(request.snapshot_path).toBe(snapshotPath);
|
||||
const context = recordedCrashDebuggerFixture();
|
||||
@@ -207,17 +231,15 @@ it
|
||||
await waitForProviderProcessReady(launched.process);
|
||||
setImmediate(() => controller.abort());
|
||||
}
|
||||
if (scenario === "cleanup-failure")
|
||||
return {
|
||||
...launched,
|
||||
cleanup: async () => {
|
||||
await cleanupOwnedProcessGroup(launched.ownership);
|
||||
throw new Error("source-owned post-cleanup reporting failure");
|
||||
},
|
||||
};
|
||||
return launched;
|
||||
return scenario === "cleanup-failure"
|
||||
? withCleanupGate(launched, () => cleanupAllowed)
|
||||
: launched;
|
||||
},
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
});
|
||||
const result = await provider.inspect(
|
||||
{
|
||||
path,
|
||||
@@ -234,46 +256,90 @@ it
|
||||
});
|
||||
} else {
|
||||
if (result.ok) throw new Error("Expected optional debugger failure");
|
||||
const projected = projectAnalysisError(result.error);
|
||||
if (scenario === "unconfigured")
|
||||
expect(projected).toMatchObject({
|
||||
details: { captured_output: { stdout: "basic stage diagnostic" } },
|
||||
});
|
||||
else if (
|
||||
scenario === "invalid-context" ||
|
||||
scenario === "cancelled" ||
|
||||
scenario === "cleanup-failure"
|
||||
) {
|
||||
const serialized = JSON.stringify(projected);
|
||||
expect(serialized).toContain("basic stage diagnostic");
|
||||
expect(serialized).toContain(
|
||||
scenario === "cancelled" ? "ready" : "debugger stage diagnostic",
|
||||
);
|
||||
expect(result.error._tag).toBe(
|
||||
scenario === "invalid-context"
|
||||
? "AnalysisOutputError"
|
||||
: scenario === "cancelled"
|
||||
? "AnalysisCancelledError"
|
||||
: "ProviderAdapterError",
|
||||
);
|
||||
if (scenario === "cleanup-failure")
|
||||
expect(result.error).toBeInstanceOf(ProviderCleanupError);
|
||||
} else
|
||||
expect(projected).toMatchObject({
|
||||
category: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
preceding_output: { stdout: "basic stage diagnostic" },
|
||||
stderr: "debugger failed",
|
||||
},
|
||||
},
|
||||
});
|
||||
expectOptionalContextFailure(scenario, result.error);
|
||||
}
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
if (
|
||||
scenario === "cleanup-failure" ||
|
||||
scenario === "decoder-cleanup-failure"
|
||||
) {
|
||||
await expect(access(owned)).resolves.toBeUndefined();
|
||||
expect(await readFile(snapshotPath)).toEqual(bytes);
|
||||
const refused = await provider.inspect({
|
||||
path,
|
||||
include_debugger_context: true,
|
||||
});
|
||||
if (refused.ok)
|
||||
throw new Error("Unreleased ownership must block a launch");
|
||||
expect(refused.error.cleanupResources).toContain(owned);
|
||||
expect(launches).toBe(scenario === "decoder-cleanup-failure" ? 1 : 2);
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
await expect(access(owned)).resolves.toBeUndefined();
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
}
|
||||
await expect(access(owned)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
const expectOptionalContextFailure = (
|
||||
scenario: string,
|
||||
error: AnalysisError,
|
||||
) => {
|
||||
const projected = projectAnalysisError(error);
|
||||
if (scenario === "unconfigured")
|
||||
expect(projected).toMatchObject({
|
||||
details: { captured_output: { stdout: "basic stage diagnostic" } },
|
||||
});
|
||||
else if (scenario === "decoder-cleanup-failure")
|
||||
expect(projected).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: { captured_output: { stdout: "basic stage diagnostic" } },
|
||||
},
|
||||
});
|
||||
else if (
|
||||
scenario === "invalid-context" ||
|
||||
scenario === "cancelled" ||
|
||||
scenario === "cleanup-failure"
|
||||
) {
|
||||
const serialized = JSON.stringify(projected);
|
||||
expect(serialized).toContain("basic stage diagnostic");
|
||||
expect(serialized).toContain(
|
||||
scenario === "cancelled" ? "ready" : "debugger stage diagnostic",
|
||||
);
|
||||
expect(error._tag).toBe(
|
||||
scenario === "invalid-context"
|
||||
? "AnalysisOutputError"
|
||||
: scenario === "cancelled"
|
||||
? "AnalysisCancelledError"
|
||||
: "ProviderAdapterError",
|
||||
);
|
||||
if (scenario === "cleanup-failure" || scenario === "invalid-context") {
|
||||
if (scenario === "cleanup-failure")
|
||||
expect(error).toBeInstanceOf(ProviderCleanupError);
|
||||
expect(projected).toMatchObject({
|
||||
details: {
|
||||
partial_observation: {
|
||||
debugger: { status: "unavailable", requested: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
} else
|
||||
expect(projected).toMatchObject({
|
||||
category: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
preceding_output: { stdout: "basic stage diagnostic" },
|
||||
stderr: "debugger failed",
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const fixture = async (includeSignal = false, opaqueOwner = false) => {
|
||||
const workspace = await createTestWorkspace("rea-recorded-core-seam-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
|
||||
@@ -14,6 +14,36 @@ import {
|
||||
import { trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describe("CdpBrowserProvider: cancellation and session events", () => {
|
||||
it("honors cancellation during the final progress callback before publishing inspection", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 0,
|
||||
}),
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
report(update) {
|
||||
if (update.completed === 3) controller.abort();
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "inspect_web_page",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("projects direct-session cancellation onto the requested operation", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
|
||||
@@ -131,6 +131,203 @@ it("preserves unavailable response observations and captures completed peers", a
|
||||
).toEqual(["missing-body", "available"]);
|
||||
});
|
||||
|
||||
it("marks JSON response bodies unavailable when their events arrive during body capture", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
const session =
|
||||
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
|
||||
if (command.method === "Network.enable") {
|
||||
const url = `${origin}/initial.json`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "initial",
|
||||
request: { url, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "initial",
|
||||
response: { url, status: 200, mimeType: "application/json" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "initial", encodedDataLength: 16 },
|
||||
},
|
||||
];
|
||||
}
|
||||
if (command.method !== "Network.getResponseBody") return undefined;
|
||||
const url = `${origin}/late.json`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "late",
|
||||
request: { url, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "late",
|
||||
response: { url, status: 200, mimeType: "application/json" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "late", encodedDataLength: 14 },
|
||||
},
|
||||
];
|
||||
},
|
||||
commandResult(command) {
|
||||
return command.method === "Network.getResponseBody"
|
||||
? { body: '{"initial":true}', base64Encoded: false }
|
||||
: undefined;
|
||||
},
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 20,
|
||||
include_json_body_shapes: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([
|
||||
expect.objectContaining({
|
||||
request_id: "initial",
|
||||
body_shapes: {
|
||||
status: "included",
|
||||
request: null,
|
||||
response: expect.any(Object),
|
||||
},
|
||||
}),
|
||||
expect.objectContaining({
|
||||
request_id: "late",
|
||||
body_shapes: { status: "unavailable", request: null, response: null },
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.unavailable_sections).toContain(
|
||||
"json_body_shapes",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not attach a redirect response body to the reused request ID", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
const session =
|
||||
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
|
||||
if (command.method === "Network.enable") {
|
||||
const url = `${origin}/before-redirect.json`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "reused",
|
||||
request: { url, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "reused",
|
||||
response: { url, status: 302, mimeType: "application/json" },
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "reused", encodedDataLength: 12 },
|
||||
},
|
||||
];
|
||||
}
|
||||
if (command.method !== "Network.getResponseBody") return undefined;
|
||||
const previousUrl = `${origin}/before-redirect.json`;
|
||||
const nextUrl = `${origin}/after-redirect.json`;
|
||||
return [
|
||||
{
|
||||
...session,
|
||||
method: "Network.requestWillBeSent",
|
||||
params: {
|
||||
requestId: "reused",
|
||||
request: { url: nextUrl, method: "GET" },
|
||||
initiator: { type: "other" },
|
||||
redirectResponse: {
|
||||
url: previousUrl,
|
||||
status: 302,
|
||||
mimeType: "application/json",
|
||||
encodedDataLength: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.responseReceived",
|
||||
params: {
|
||||
requestId: "reused",
|
||||
response: {
|
||||
url: nextUrl,
|
||||
status: 200,
|
||||
mimeType: "application/json",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
...session,
|
||||
method: "Network.loadingFinished",
|
||||
params: { requestId: "reused", encodedDataLength: 14 },
|
||||
},
|
||||
];
|
||||
},
|
||||
commandResult(command) {
|
||||
return command.method === "Network.getResponseBody"
|
||||
? { body: '{"belongs":"redirect"}', base64Encoded: false }
|
||||
: undefined;
|
||||
},
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 20,
|
||||
include_json_body_shapes: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([
|
||||
expect.objectContaining({
|
||||
request_id: "reused",
|
||||
url: `${browser.allowedOrigin}/after-redirect.json`,
|
||||
redirects: [expect.objectContaining({ status: 302 })],
|
||||
body_shapes: { status: "unavailable", request: null, response: null },
|
||||
}),
|
||||
]);
|
||||
expect(result.value.completeness.unavailable_sections).toContain(
|
||||
"json_body_shapes",
|
||||
);
|
||||
});
|
||||
|
||||
it("marks malformed JSON body shapes unavailable while preserving partial request shapes", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandEvents(command, origin) {
|
||||
@@ -301,6 +498,12 @@ it("rejects malformed response-body envelopes and preserves request shapes", asy
|
||||
reason: "invalid_protocol_value",
|
||||
count: 2,
|
||||
});
|
||||
expect(result.value.completeness.excluded).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
section: "json_body_shapes",
|
||||
reason: "provider_unavailable",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("CDP target inventory", () => {
|
||||
type: "page",
|
||||
title: `Page ${String(index)}`,
|
||||
url: `https://allowed.example/page/${String(index)}`,
|
||||
attached: false,
|
||||
...(index === 0 ? {} : { attached: index === 1 ? false : true }),
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${String(port)}/devtools/page/${id}`,
|
||||
};
|
||||
});
|
||||
@@ -60,6 +60,14 @@ describe("CDP target inventory", () => {
|
||||
expect(result.value.targets).toHaveLength(targets.length);
|
||||
expect(result.value.targets[0]?.target_id).toBe("target-0000");
|
||||
expect(result.value.targets.at(-1)?.target_id).toBe("target-1100");
|
||||
expect(
|
||||
result.value.targets.slice(0, 3).map(({ attached }) => attached),
|
||||
).toEqual([null, false, true]);
|
||||
expect(
|
||||
result.value.limitations.some((item) =>
|
||||
item.includes("attachment state"),
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
if (server.listening)
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
|
||||
@@ -83,6 +83,7 @@ describe("CdpElectronProvider target selection", () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(index).href,
|
||||
duplicateElectronInventory: true,
|
||||
omitElectronTargetAttachmentState: true,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const provider = new CdpElectronProvider();
|
||||
@@ -96,8 +97,14 @@ describe("CdpElectronProvider target selection", () => {
|
||||
expect.objectContaining({
|
||||
target_id: "electron-page",
|
||||
file_path: index,
|
||||
attached: null,
|
||||
}),
|
||||
]);
|
||||
expect(
|
||||
listed.value.limitations.some((item) =>
|
||||
item.includes("attachment state"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(listed.value.excluded).toEqual({
|
||||
unsupported_url: 3,
|
||||
non_page: 2,
|
||||
@@ -112,6 +119,12 @@ describe("CdpElectronProvider target selection", () => {
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.file_path).toBe(index);
|
||||
expect(inspected.value.target.attached).toBeNull();
|
||||
expect(
|
||||
inspected.value.limitations.some((item) =>
|
||||
item.includes("attachment state"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(inspected.value.frames).toEqual([
|
||||
expect.objectContaining({ file_path: index }),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { createServer } from "node:http";
|
||||
import type { RequestListener, Server } from "node:http";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { readCdpJson } from "../../../src/browser/CdpEndpoint.js";
|
||||
|
||||
const servers: Server[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
servers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
server.closeAllConnections();
|
||||
server.close((error) =>
|
||||
error === undefined ? resolve() : reject(error),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("CDP discovery response bounds", () => {
|
||||
it("accepts a complete JSON response exactly at the byte limit", async () => {
|
||||
const body = JSON.stringify("x".repeat(14));
|
||||
expect(Buffer.byteLength(body)).toBe(16);
|
||||
const server = await startServer((_request, response) =>
|
||||
response.end(body),
|
||||
);
|
||||
|
||||
await expect(
|
||||
readCdpJson(server.url, "list_browser_targets", undefined, {
|
||||
bytes: 16,
|
||||
timeoutMs: 1_000,
|
||||
}),
|
||||
).resolves.toBe("x".repeat(14));
|
||||
});
|
||||
|
||||
it("rejects and closes an oversized chunked response without parsing a prefix", async () => {
|
||||
let responseClosed: (() => void) | undefined;
|
||||
const closed = new Promise<void>((resolve) => {
|
||||
responseClosed = resolve;
|
||||
});
|
||||
const server = await startServer((_request, response) => {
|
||||
response.once("close", () => responseClosed?.());
|
||||
response.write(JSON.stringify("x".repeat(15)));
|
||||
});
|
||||
|
||||
await expect(
|
||||
readCdpJson(server.url, "list_browser_targets", undefined, {
|
||||
bytes: 16,
|
||||
timeoutMs: 1_000,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "BrowserObservationError",
|
||||
reason: "payload_limit",
|
||||
});
|
||||
await closed;
|
||||
});
|
||||
|
||||
it("ends a response that exceeds the total elapsed deadline", async () => {
|
||||
let responseClosed: (() => void) | undefined;
|
||||
let requestStarted: (() => void) | undefined;
|
||||
const closed = new Promise<void>((resolve) => {
|
||||
responseClosed = resolve;
|
||||
});
|
||||
const started = new Promise<void>((resolve) => {
|
||||
requestStarted = resolve;
|
||||
});
|
||||
const server = await startServer((_request, response) => {
|
||||
response.once("close", () => responseClosed?.());
|
||||
requestStarted?.();
|
||||
});
|
||||
const pending = readCdpJson(server.url, "list_browser_targets", undefined, {
|
||||
bytes: 16,
|
||||
timeoutMs: 50,
|
||||
});
|
||||
const timeoutAssertion = expect(pending).rejects.toMatchObject({
|
||||
_tag: "BrowserObservationError",
|
||||
reason: "timeout",
|
||||
});
|
||||
await started;
|
||||
|
||||
await timeoutAssertion;
|
||||
await closed;
|
||||
});
|
||||
|
||||
it("preserves caller cancellation and closes the response", async () => {
|
||||
let responseClosed: (() => void) | undefined;
|
||||
let requestStarted: (() => void) | undefined;
|
||||
const closed = new Promise<void>((resolve) => {
|
||||
responseClosed = resolve;
|
||||
});
|
||||
const started = new Promise<void>((resolve) => {
|
||||
requestStarted = resolve;
|
||||
});
|
||||
const server = await startServer((_request, response) => {
|
||||
response.once("close", () => responseClosed?.());
|
||||
requestStarted?.();
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const pending = readCdpJson(
|
||||
server.url,
|
||||
"list_browser_targets",
|
||||
controller.signal,
|
||||
{
|
||||
bytes: 16,
|
||||
timeoutMs: 1_000,
|
||||
},
|
||||
);
|
||||
await started;
|
||||
controller.abort();
|
||||
|
||||
await expect(pending).rejects.toMatchObject({
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "list_browser_targets",
|
||||
});
|
||||
await closed;
|
||||
});
|
||||
|
||||
it("destroys an unsuccessful HTTP response", async () => {
|
||||
let responseClosed: (() => void) | undefined;
|
||||
const closed = new Promise<void>((resolve) => {
|
||||
responseClosed = resolve;
|
||||
});
|
||||
const server = await startServer((_request, response) => {
|
||||
response.once("close", () => responseClosed?.());
|
||||
response.writeHead(503).flushHeaders();
|
||||
});
|
||||
|
||||
await expect(
|
||||
readCdpJson(server.url, "list_browser_targets", undefined, {
|
||||
bytes: 16,
|
||||
timeoutMs: 1_000,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "BrowserObservationError",
|
||||
reason: "invalid_endpoint_response",
|
||||
});
|
||||
await closed;
|
||||
});
|
||||
});
|
||||
|
||||
const startServer = async (
|
||||
handler: RequestListener,
|
||||
): Promise<{ readonly url: URL }> => {
|
||||
const server = createServer(handler);
|
||||
servers.push(server);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string")
|
||||
throw new TypeError("Expected a TCP listener address");
|
||||
return { url: new URL(`http://127.0.0.1:${String(address.port)}`) };
|
||||
};
|
||||
@@ -339,8 +339,10 @@ const captureBody = (source: BodySource, body: string): WebPageInspection => {
|
||||
encodedDataLength: Buffer.byteLength(responseBody),
|
||||
},
|
||||
});
|
||||
expect(events.responseBodyRequestIds()).toEqual(["request-1"]);
|
||||
events.ingestResponseBody("request-1", {
|
||||
const candidate = events.responseBodyRequests()[0];
|
||||
expect(candidate?.requestId).toBe("request-1");
|
||||
expect(candidate).toBeDefined();
|
||||
events.ingestResponseBody(candidate!, {
|
||||
body:
|
||||
source === "base64 response"
|
||||
? Buffer.from(responseBody).toString("base64")
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
it.each(["omitted", "null"] as const)(
|
||||
"excludes TargetInfo workers with %s required attached state",
|
||||
async (attachmentState) => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandResult: (command, origin) => {
|
||||
if (command.method !== "Target.getTargets") return undefined;
|
||||
return {
|
||||
targetInfos: [
|
||||
{
|
||||
targetId: "worker-1",
|
||||
type: "service_worker",
|
||||
url: `${origin}/worker.js`,
|
||||
openerId: "allowed-page",
|
||||
...(attachmentState === "null" ? { attached: null } : {}),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
});
|
||||
try {
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.workers).toEqual([]);
|
||||
expect(result.value.completeness.excluded).toContainEqual({
|
||||
section: "workers",
|
||||
reason: "invalid_protocol_value",
|
||||
count: 1,
|
||||
});
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -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 }));
|
||||
|
||||
@@ -1,6 +1,49 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readdir } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects an exited fixture before returning a lease and removes its profile",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-runtime-startup-failure-");
|
||||
const helper = new URL(
|
||||
"../../../scripts/lib/browser-runtime-fixture-lifecycle.mjs",
|
||||
import.meta.url,
|
||||
);
|
||||
const script = `
|
||||
const { startRuntimeFixtureBrowser } = await import(${JSON.stringify(helper.href)});
|
||||
// Node rejects Chrome's arguments immediately, exercising actual process exit.
|
||||
try {
|
||||
const fixture = await startRuntimeFixtureBrowser(process.execPath, 'http://127.0.0.1');
|
||||
await fixture.close();
|
||||
throw new Error('Expected startup failure');
|
||||
} catch (error) {
|
||||
if (error._tag !== 'BrowserStartupError') throw error;
|
||||
console.log(JSON.stringify({
|
||||
failure: error.failure,
|
||||
exitCode: error.exitCode,
|
||||
stderr: error.stderr,
|
||||
}));
|
||||
}
|
||||
`;
|
||||
const { stdout } = await promisify(execFile)(
|
||||
process.execPath,
|
||||
["--input-type=module", "-e", script],
|
||||
{
|
||||
env: { ...process.env, TMPDIR: root, TMP: root, TEMP: root },
|
||||
timeout: 10_000,
|
||||
},
|
||||
);
|
||||
expect(JSON.parse(stdout)).toEqual({
|
||||
failure: "exited",
|
||||
exitCode: expect.any(Number),
|
||||
stderr: expect.stringContaining("bad option"),
|
||||
});
|
||||
expect(await readdir(root)).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("attempts every fixture cleanup and retains the primary capture failure", async () => {
|
||||
const helper = new URL(
|
||||
|
||||
@@ -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",
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,107 @@
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
|
||||
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const cleanup = vi.hoisted(() => ({
|
||||
path: "",
|
||||
denied: false,
|
||||
handles: [] as FileHandle[],
|
||||
}));
|
||||
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 (args[0] === cleanup.path) {
|
||||
cleanup.handles.push(handle);
|
||||
const close = handle.close.bind(handle);
|
||||
handle.close = async () => {
|
||||
if (cleanup.denied && handle.fd >= 0)
|
||||
throw new Error("Descriptor close deliberately denied");
|
||||
await close();
|
||||
};
|
||||
}
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
it
|
||||
.runIf(process.platform === "linux")
|
||||
.each(["capture", "tool", "limiter", "kernel"])(
|
||||
"retains failed %s descriptors and retries them before further acquisition and shutdown",
|
||||
async (member) => {
|
||||
const directory = await createTestTempDirectory("rea-capture-descriptor-");
|
||||
const path = join(directory, "recording.pcap");
|
||||
const command = join(directory, "tshark.mjs");
|
||||
const limiter = join(directory, "limiter");
|
||||
await writeFile(path, "recording bytes");
|
||||
await writeFile(limiter, "limiter", { mode: 0o700 });
|
||||
await writeFile(
|
||||
command,
|
||||
`if(process.argv.includes('--version'))console.log('TShark (Wireshark) 4.0.17');else console.log('[{"_source":{"layers":{"frame.number":["1"]}}}]');`,
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
let launches = 0;
|
||||
const provider = new TsharkCaptureProvider(
|
||||
{
|
||||
...process.env,
|
||||
REA_TSHARK_COMMAND: command,
|
||||
REA_TSHARK_PRLIMIT_COMMAND: limiter,
|
||||
},
|
||||
(input) => {
|
||||
launches += 1;
|
||||
return spawnOwnedProviderProcess({
|
||||
...input,
|
||||
command: process.execPath,
|
||||
arguments: [command, ...input.arguments],
|
||||
expectedCommand: process.execPath,
|
||||
});
|
||||
},
|
||||
() => PrivateRuntimeRoot.create({ parent: directory }),
|
||||
);
|
||||
cleanup.path =
|
||||
member === "capture"
|
||||
? path
|
||||
: member === "tool"
|
||||
? command
|
||||
: member === "limiter"
|
||||
? limiter
|
||||
: "/proc/self/limits";
|
||||
cleanup.denied = true;
|
||||
cleanup.handles = [];
|
||||
onTestFinished(async () => {
|
||||
cleanup.denied = false;
|
||||
await provider.close();
|
||||
for (const handle of cleanup.handles) await handle.close();
|
||||
cleanup.path = "";
|
||||
});
|
||||
const service = new PacketCaptureService(provider);
|
||||
const first = await service.inspect({ path, fields: ["frame.number"] });
|
||||
expect(first).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
|
||||
});
|
||||
expect(cleanup.handles).toHaveLength(1);
|
||||
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
|
||||
const launchCount = launches;
|
||||
expect(
|
||||
await service.inspect({ path, fields: ["frame.number"] }),
|
||||
).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
|
||||
expect(cleanup.handles).toHaveLength(1);
|
||||
expect(launches).toBe(launchCount);
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
cleanup.denied = false;
|
||||
await provider.close();
|
||||
expect(cleanup.handles[0]?.fd).toBe(-1);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,627 @@
|
||||
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";
|
||||
import { join } from "node:path";
|
||||
import { readStableArtifact } from "../../../src/artifacts/readStableArtifact.js";
|
||||
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
|
||||
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
|
||||
import { packetCaptureSchema } from "../../../src/domain/captures/packetCapture.js";
|
||||
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { createDeferred } from "../../fixtures/binarySession.js";
|
||||
|
||||
// A command-boundary simulator: real process ownership/filesystem, not real TShark coverage.
|
||||
const fixture = async (mode = "ok", failCleanup = false) => {
|
||||
const directory = await createTestTempDirectory("rea-capture-test-");
|
||||
const path = join(directory, "recorded bytes.pcap");
|
||||
await writeFile(path, "recording bytes");
|
||||
const script = join(directory, "producer.mjs");
|
||||
await writeFile(
|
||||
script,
|
||||
`import {readFileSync, writeFileSync, chmodSync, truncateSync} from 'node:fs';
|
||||
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((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'); }
|
||||
`,
|
||||
);
|
||||
await chmod(script, 0o700);
|
||||
const configuredCommand =
|
||||
mode === "symlink" ? join(directory, "configured-tool") : script;
|
||||
if (mode === "symlink") await symlink(script, configuredCommand);
|
||||
const controller = new AbortController();
|
||||
let calls = 0;
|
||||
let mayClean = !failCleanup;
|
||||
const acquired = createDeferred<void>();
|
||||
const release = createDeferred<void>();
|
||||
const provider = new TsharkCaptureProvider(
|
||||
{
|
||||
...process.env,
|
||||
REA_TSHARK_COMMAND: configuredCommand,
|
||||
REA_TSHARK_PRLIMIT_COMMAND: configuredCommand,
|
||||
},
|
||||
async (input) => {
|
||||
calls++;
|
||||
if (mode === "file-limit" && !input.arguments.includes("--version")) {
|
||||
const stdout = { text: "", bytes: 0, observedBytes: 0 };
|
||||
const stderr = {
|
||||
text: "before file limit\n",
|
||||
bytes: 18,
|
||||
observedBytes: 18,
|
||||
};
|
||||
throw new OwnedCommandFailure("process", "Synthetic SIGXFSZ snapshot", {
|
||||
stdout,
|
||||
stderr,
|
||||
exitCode: null,
|
||||
signal: "SIGXFSZ",
|
||||
});
|
||||
}
|
||||
const spawned = await spawnOwnedProviderProcess({
|
||||
...input,
|
||||
command: process.execPath,
|
||||
arguments: [script, ...input.arguments],
|
||||
expectedCommand: process.execPath,
|
||||
});
|
||||
if (mode === "wait" && !input.arguments.includes("--version"))
|
||||
spawned.process.stdout?.once("data", () => controller.abort());
|
||||
return spawned;
|
||||
},
|
||||
async () => {
|
||||
if (mode === "workspace-full")
|
||||
throw Object.assign(new Error("No space left on device"), {
|
||||
code: "ENOSPC",
|
||||
});
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
parent: directory,
|
||||
prefix: "decoder-",
|
||||
});
|
||||
if (mode === "gated") {
|
||||
acquired.resolve();
|
||||
await release.promise;
|
||||
}
|
||||
if (mode === "snapshot-write-failure")
|
||||
await writeFile(join(root.path, "capture"), "existing");
|
||||
return {
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (!mayClean) throw new Error("cleanup fixture failure");
|
||||
await root.close();
|
||||
},
|
||||
};
|
||||
},
|
||||
"linux",
|
||||
async (...args) => {
|
||||
if (mode === "oversized-tool" && calls === 2 && args[0] === script) {
|
||||
const { truncate } = await import("node:fs/promises");
|
||||
await truncate(script, 64 * 1024 * 1024 + 1);
|
||||
}
|
||||
if (mode === "post-run-abort" && calls === 2) controller.abort();
|
||||
return readStableArtifact(...args);
|
||||
},
|
||||
async (limits) => ({ ...limits, file_bytes: 1048576 }),
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
release.resolve();
|
||||
mayClean = true;
|
||||
await provider.close();
|
||||
});
|
||||
const service = new PacketCaptureService(provider);
|
||||
return {
|
||||
service,
|
||||
directory,
|
||||
path,
|
||||
controller,
|
||||
calls: () => calls,
|
||||
acquired: acquired.promise,
|
||||
release: () => release.resolve(),
|
||||
allowCleanup: () => {
|
||||
mayClean = true;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("refuses new acquisition after provider shutdown", async () => {
|
||||
const f = await fixture();
|
||||
await f.service.close();
|
||||
expect(
|
||||
await f.service.inspect({ path: f.path, fields: ["ip.addr"] }),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(f.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it("pages matching observations without changing dissection scope or frame identities", async () => {
|
||||
const f = await fixture("many");
|
||||
const input = { path: f.path, fields: ["ip.addr"] };
|
||||
for (const [options, first, count] of [
|
||||
[{}, 1, 50],
|
||||
[{ match_offset: 50, match_limit: 30 }, 51, 30],
|
||||
[{ match_limit: null }, 1, 90],
|
||||
[{ match_offset: 100 }, undefined, 0],
|
||||
] as const) {
|
||||
const result = await f.service.inspect({ ...input, ...options });
|
||||
if (!result.ok) throw result.error;
|
||||
const report = packetCaptureSchema.parse(result.value.normalized_result);
|
||||
expect(report.packets).toHaveLength(count);
|
||||
expect(report.packets[0]?.["frame.number"][0]).toBe(
|
||||
first === undefined ? undefined : String(first),
|
||||
);
|
||||
expect(report.output_window.matching_packets).toBe(90);
|
||||
expect(report.output_window.returned_packets).toBe(count);
|
||||
expect(report.read_scope).toBe("to-eof");
|
||||
expect(report.tool.arguments).not.toContain("-c");
|
||||
}
|
||||
});
|
||||
|
||||
it("bounds admission without queuing additional snapshots or delaying cancellation", async () => {
|
||||
const f = await fixture("gated");
|
||||
const input = { path: f.path, fields: ["ip.addr"] };
|
||||
const first = f.service.inspect(input);
|
||||
await f.acquired;
|
||||
const second = f.service.inspect(input);
|
||||
const cancelled = f.service.inspect(input, { signal: AbortSignal.abort() });
|
||||
f.release();
|
||||
expect(await first).toMatchObject({ ok: true });
|
||||
expect(await second).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisResourceConstraintError", resource: "capacity" },
|
||||
});
|
||||
expect(await cancelled).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(f.calls()).toBe(2);
|
||||
expect(await f.service.inspect(input)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("inspects an immutable copy, preserves options and warnings, and releases its directory", async () => {
|
||||
const f = await fixture();
|
||||
const result = await f.service.inspect({
|
||||
path: f.path,
|
||||
fields: ["ip.addr"],
|
||||
display_filter: "udp",
|
||||
packet_limit: 10,
|
||||
decode_as: ["udp.port==5555,dns"],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
const report = packetCaptureSchema.parse(result.value.normalized_result);
|
||||
expect(report.packets).toEqual([
|
||||
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
|
||||
]);
|
||||
expect(report.diagnostics).toBe("producer warning\n");
|
||||
expect(report.tool.version_diagnostics).toBe("version warning\n");
|
||||
expect(report.read_scope).toBe("up-to-input-packet-limit");
|
||||
expect(report.tool.arguments).toEqual([
|
||||
"-n",
|
||||
"-r",
|
||||
"capture",
|
||||
"-T",
|
||||
"json",
|
||||
"--no-duplicate-keys",
|
||||
"--temp-dir=.",
|
||||
"-2",
|
||||
"-c",
|
||||
"10",
|
||||
"-Y",
|
||||
"udp",
|
||||
"-d",
|
||||
"udp.port==5555,dns",
|
||||
"-e",
|
||||
"frame.number",
|
||||
"-e",
|
||||
"ip.addr",
|
||||
]);
|
||||
expect((await readdir(f.directory)).sort()).toEqual([
|
||||
"producer.mjs",
|
||||
"recorded bytes.pcap",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["invalid-json", "AnalysisOutputError"],
|
||||
["nonzero", "ProviderAdapterError"],
|
||||
["malformed-copy", "AnalysisArtifactChangedError"],
|
||||
["overflow", "AnalysisResourceConstraintError"],
|
||||
["wait", "AnalysisCancelledError"],
|
||||
])(
|
||||
"preserves %s failure and releases the process and snapshot",
|
||||
async (mode, tag) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspect(
|
||||
{ path: f.path, fields: ["ip.addr"] },
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected capture analysis failure");
|
||||
expect(result.error._tag).toBe(tag);
|
||||
expect(result.error.cleanupIncomplete).toBe(false);
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) =>
|
||||
name.startsWith("decoder-"),
|
||||
),
|
||||
).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains a completed observation and cleanup ownership for retry", async () => {
|
||||
const f = await fixture("ok", true);
|
||||
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
if (result.ok) throw new Error("Expected cleanup failure");
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
operation: "inspect_packet_capture",
|
||||
});
|
||||
const retry = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
expect(retry.ok).toBe(false);
|
||||
expect(f.calls()).toBe(2);
|
||||
f.allowCleanup();
|
||||
await f.service.close();
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects cancelled and invalid requests before any provider work", async () => {
|
||||
const f = await fixture();
|
||||
for (const input of [
|
||||
{ path: "relative.pcap", fields: ["ip.addr"] },
|
||||
{ path: f.path, fields: ["ip.addr"], interface: "lo0" },
|
||||
]) {
|
||||
const result = await f.service.inspect(input);
|
||||
expect(result.ok).toBe(false);
|
||||
}
|
||||
const result = await f.service.inspect(
|
||||
{ path: f.path, fields: ["ip.addr"] },
|
||||
{ signal: AbortSignal.abort() },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected cancellation");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(f.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it("retains a completed observation when cancellation arrives at the service boundary", async () => {
|
||||
const f = await fixture();
|
||||
const input = {
|
||||
path: f.path,
|
||||
fields: ["ip.addr"],
|
||||
display_filter: null,
|
||||
decode_as: [],
|
||||
packet_limit: null,
|
||||
two_pass: true,
|
||||
match_offset: 0,
|
||||
match_limit: 50,
|
||||
};
|
||||
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;
|
||||
},
|
||||
close: async () => {},
|
||||
});
|
||||
const result = await service.inspect(input, { signal: f.controller.signal });
|
||||
if (result.ok) throw new Error("Expected late cancellation");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
operation: "inspect_packet_capture",
|
||||
normalized_result: {
|
||||
packets: [
|
||||
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["workspace-full", "AnalysisResourceConstraintError"],
|
||||
["snapshot-write-failure", "ProviderAdapterError"],
|
||||
])(
|
||||
"reports %s against the private workspace, not the selected input",
|
||||
async (mode, tag) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspect({
|
||||
path: f.path,
|
||||
fields: ["ip.addr"],
|
||||
});
|
||||
if (result.ok) throw new Error("Expected workspace failure");
|
||||
expect(result.error._tag).toBe(tag);
|
||||
if (result.error._tag === "ProviderAdapterError")
|
||||
expect(result.error).toMatchObject({
|
||||
diagnostics: {
|
||||
stage: "workspace",
|
||||
system_code: "EEXIST",
|
||||
},
|
||||
});
|
||||
if (result.error._tag === "AnalysisResourceConstraintError")
|
||||
expect(result.error).toMatchObject({
|
||||
reportedLimits: {
|
||||
system_code: "ENOSPC",
|
||||
},
|
||||
});
|
||||
expect(f.calls()).toBe(mode === "workspace-full" ? 0 : 1);
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) =>
|
||||
name.startsWith("decoder-"),
|
||||
),
|
||||
).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses unsupported hosts before launching or allocating a workspace", async () => {
|
||||
const provider = new TsharkCaptureProvider(
|
||||
{ REA_TSHARK_COMMAND: process.execPath },
|
||||
async () => {
|
||||
throw new Error("Must not launch");
|
||||
},
|
||||
async () => {
|
||||
throw new Error("Must not allocate");
|
||||
},
|
||||
"darwin",
|
||||
);
|
||||
const result = await new PacketCaptureService(provider).inspect({
|
||||
path: "/recording.pcap",
|
||||
fields: ["ip.addr"],
|
||||
});
|
||||
if (result.ok) throw new Error("Expected host refusal");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("Linux"),
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves complete Evidence when aborted during post-run integrity checks", async () => {
|
||||
const f = await fixture("post-run-abort");
|
||||
const result = await f.service.inspect(
|
||||
{ path: f.path, fields: ["ip.addr"] },
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected late cancellation");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
normalized_result: {
|
||||
packets: [
|
||||
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
|
||||
],
|
||||
diagnostics: "producer warning\n",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
|
||||
).toEqual([]);
|
||||
});
|
||||
it("preserves configured symlink paths separately from resolved tool identities", async () => {
|
||||
const f = await fixture("symlink");
|
||||
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
tool: {
|
||||
configured_path: join(f.directory, "configured-tool"),
|
||||
path: join(f.directory, "producer.mjs"),
|
||||
},
|
||||
resource_limiter: {
|
||||
configured_path: join(f.directory, "configured-tool"),
|
||||
path: join(f.directory, "producer.mjs"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["oversized-copy", "oversized-tool"])(
|
||||
"identifies the mutated %s without blaming the admitted source",
|
||||
async (mode) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspect({
|
||||
path: f.path,
|
||||
fields: ["ip.addr"],
|
||||
});
|
||||
if (result.ok) throw new Error("Expected changed artifact");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisArtifactChangedError",
|
||||
path:
|
||||
mode === "oversized-tool"
|
||||
? join(f.directory, "producer.mjs")
|
||||
: expect.stringMatching(/decoder-.*[/\\]capture$/u),
|
||||
});
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) =>
|
||||
name.startsWith("decoder-"),
|
||||
),
|
||||
).toEqual([]);
|
||||
},
|
||||
);
|
||||
it("preserves termination signal and effective file ceiling as a resource failure", async () => {
|
||||
const f = await fixture("file-limit");
|
||||
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
if (result.ok) throw new Error("Expected resource failure");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
resource: "file-size",
|
||||
reportedLimits: { file_bytes: 1048576 },
|
||||
capturedOutput: { signal: "SIGXFSZ", stderr: "before file limit\n" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects oversized selector lists and UTF-8 argv expansion before provider work", async () => {
|
||||
const f = await fixture();
|
||||
for (const selections of [
|
||||
{ fields: Array.from({ length: 1025 }, () => "ip.addr") },
|
||||
{ fields: ["x".repeat(8193)] },
|
||||
{ fields: ["x".repeat(8192)], display_filter: "界".repeat(8192) },
|
||||
{
|
||||
fields: ["ip.addr"],
|
||||
decode_as: Array.from({ length: 1025 }, () => "udp.port==5555,dns"),
|
||||
},
|
||||
]) {
|
||||
const result = await f.service.inspect({ path: f.path, ...selections });
|
||||
if (result.ok) throw new Error("Expected invalid selectors");
|
||||
expect(result.error._tag).toBe("AnalysisInputError");
|
||||
}
|
||||
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,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { parsePacketOutput } from "../../../src/captures/parsePacketOutput.js";
|
||||
|
||||
it("preserves repeated field values and missing fields while discarding export index metadata", () => {
|
||||
const output = JSON.stringify([
|
||||
{
|
||||
_index: "packets-2026",
|
||||
_score: null,
|
||||
_source: {
|
||||
layers: {
|
||||
"frame.number": ["2"],
|
||||
"ip.addr": ["192.0.2.1", "192.0.2.2"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ _source: { layers: { "frame.number": ["7"] } } },
|
||||
]);
|
||||
expect(parsePacketOutput(output, ["ip.addr"])).toEqual([
|
||||
{ "frame.number": ["2"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
|
||||
{ "frame.number": ["7"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(
|
||||
[
|
||||
[{ "ip.addr": ["192.0.2.1"] }],
|
||||
[{ "frame.number": ["1"], "ip.addr": "192.0.2.1" }],
|
||||
[{ "frame.number": ["0"] }],
|
||||
[{ "frame.number": ["1", "2"] }],
|
||||
[{ "frame.number": ["1"], "unselected.field": ["hidden"] }],
|
||||
[{ "frame.number": ["2"] }, { "frame.number": ["2"] }],
|
||||
[{ "frame.number": ["2"] }, { "frame.number": ["1"] }],
|
||||
].map((layers) => [layers]),
|
||||
)("rejects malformed, repeated or reordered producer frames: %j", (layers) => {
|
||||
expect(() =>
|
||||
parsePacketOutput(
|
||||
JSON.stringify(layers.map((value) => ({ _source: { layers: value } }))),
|
||||
["ip.addr"],
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
|
||||
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
// Real kernel-limit verification with a synthetic producer; real TShark has its own verifier.
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"enforces both address-space limits before any producer allocation",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory("rea-tshark-limits-");
|
||||
const command = join(directory, "memory-probe");
|
||||
await writeFile(
|
||||
command,
|
||||
`#!/usr/bin/python3
|
||||
import json, resource, sys
|
||||
assert resource.getrlimit(resource.RLIMIT_AS) == (1073741824, 1073741824)
|
||||
assert resource.getrlimit(resource.RLIMIT_FSIZE) == (67108864, 67108864)
|
||||
assert resource.getrlimit(resource.RLIMIT_CORE) == (0, 0)
|
||||
if '--version' in sys.argv:
|
||||
print('TShark (Wireshark) 4.6.9 (resource fixture)')
|
||||
else:
|
||||
try:
|
||||
bytearray(1073741825)
|
||||
except MemoryError:
|
||||
print(json.dumps([{'_source': {'layers': {'frame.number': ['1']}}}]))
|
||||
else:
|
||||
raise RuntimeError('allocation unexpectedly succeeded')
|
||||
`,
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
const path = join(directory, "recording.pcap");
|
||||
await writeFile(path, "selected fixture");
|
||||
const service = new PacketCaptureService(
|
||||
new TsharkCaptureProvider({
|
||||
...process.env,
|
||||
REA_TSHARK_COMMAND: command,
|
||||
}),
|
||||
);
|
||||
onTestFinished(() => service.close());
|
||||
const result = await service.inspect({ path, fields: ["frame.number"] });
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
packets: [{ "frame.number": ["1"] }],
|
||||
limits: { address_space_bytes: 1073741824 },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"preserves lower inherited file/CPU limits in the real launch",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-tshark-inherited-limits-",
|
||||
);
|
||||
const command = join(directory, "limit-probe");
|
||||
const path = join(directory, "recording.pcap");
|
||||
await writeFile(path, "selected fixture");
|
||||
await writeFile(
|
||||
command,
|
||||
`#!/usr/bin/python3
|
||||
import json, resource, sys
|
||||
assert resource.getrlimit(resource.RLIMIT_FSIZE) == (1048576, 1048576)
|
||||
assert resource.getrlimit(resource.RLIMIT_CPU) == (20, 20)
|
||||
if '--version' in sys.argv:
|
||||
print('TShark (Wireshark) 4.6.9 (resource fixture)')
|
||||
else:
|
||||
print(json.dumps([{'_source': {'layers': {'frame.number': ['1']}}}]))
|
||||
`,
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
const runner = join(directory, "runner.mjs");
|
||||
const serviceModule = new URL(
|
||||
"../../../dist/application/captures/PacketCaptureService.js",
|
||||
import.meta.url,
|
||||
).href;
|
||||
const providerModule = new URL(
|
||||
"../../../dist/captures/TsharkCaptureProvider.js",
|
||||
import.meta.url,
|
||||
).href;
|
||||
await writeFile(
|
||||
runner,
|
||||
`import { PacketCaptureService } from ${JSON.stringify(serviceModule)};
|
||||
import { TsharkCaptureProvider } from ${JSON.stringify(providerModule)};
|
||||
const service = new PacketCaptureService(new TsharkCaptureProvider({ ...process.env, REA_TSHARK_COMMAND: ${JSON.stringify(command)} }));
|
||||
try {
|
||||
const result = await service.inspect({ path: ${JSON.stringify(path)}, fields: ['frame.number'] });
|
||||
if (!result.ok) throw result.error;
|
||||
console.log(JSON.stringify(result.value.normalized_result.limits));
|
||||
} finally { await service.close(); }
|
||||
`,
|
||||
);
|
||||
const { stdout } = await promisify(execFile)(
|
||||
"/usr/bin/prlimit",
|
||||
[
|
||||
"--fsize=1048576:2097152",
|
||||
"--cpu=20:25",
|
||||
"--",
|
||||
process.execPath,
|
||||
runner,
|
||||
],
|
||||
{ timeout: 30000, maxBuffer: 65536 },
|
||||
);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
file_bytes: 1048576,
|
||||
cpu_seconds: 20,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"reports a real kernel file-limit termination with its effective ceiling",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory("rea-tshark-file-limit-");
|
||||
const command = join(directory, "file-probe");
|
||||
const path = join(directory, "recording.pcap");
|
||||
await writeFile(path, "selected fixture");
|
||||
await writeFile(
|
||||
command,
|
||||
`#!/usr/bin/python3
|
||||
import signal, sys
|
||||
if '--version' in sys.argv:
|
||||
print('TShark (Wireshark) 4.6.9 (resource fixture)')
|
||||
else:
|
||||
signal.signal(signal.SIGXFSZ, signal.SIG_DFL)
|
||||
print('before file limit', file=sys.stderr, flush=True)
|
||||
with open('overflow', 'wb', buffering=0) as output:
|
||||
output.write(b'x' * 4096)
|
||||
output.write(b'x')
|
||||
`,
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
const service = new PacketCaptureService(
|
||||
new TsharkCaptureProvider(
|
||||
{ ...process.env, REA_TSHARK_COMMAND: command },
|
||||
undefined,
|
||||
undefined,
|
||||
process.platform,
|
||||
undefined,
|
||||
async (limits) => ({ ...limits, file_bytes: 4096 }),
|
||||
),
|
||||
);
|
||||
onTestFinished(() => service.close());
|
||||
const result = await service.inspect({ path, fields: ["frame.number"] });
|
||||
if (result.ok) throw new Error("Expected file-limit failure");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
resource: "file-size",
|
||||
reportedLimits: { file_bytes: 4096 },
|
||||
capturedOutput: { signal: "SIGXFSZ", stderr: "before file limit\n" },
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { mkdir, unlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
@@ -15,11 +15,56 @@ import {
|
||||
analysisViewCaptureEvidence,
|
||||
analysisViewObjectDenseCapture,
|
||||
} from "../../fixtures/analysisView.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js";
|
||||
|
||||
cliTest(
|
||||
"projects portable artifact inventory after the original ZIP is removed",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-inventory-view-cli-");
|
||||
const archive = join(root, "fixture.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("main.js", new TextReader("console.log('portable');\n"));
|
||||
await writeFile(archive, await writer.close());
|
||||
const inspected = await cli.run({
|
||||
arguments: ["inspect-artifact", archive, "--json"],
|
||||
});
|
||||
expect(inspected.exitCode).toBe(0);
|
||||
const parent = parseEvidence(inspected.json);
|
||||
await unlink(archive);
|
||||
const request = join(root, "view.json");
|
||||
await writeFile(
|
||||
request,
|
||||
JSON.stringify({
|
||||
source: { kind: "inline", evidence: parent },
|
||||
view: {
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: ["main.js"],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const projected = await cli.run({
|
||||
arguments: ["inspect-analysis-view", request, "--json"],
|
||||
});
|
||||
expect(projected.exitCode).toBe(0);
|
||||
expect(projected.json).toMatchObject({
|
||||
operation: "inspect_analysis_view",
|
||||
evidence_links: [parent.evidence_id],
|
||||
normalized_result: {
|
||||
parent_evidence_id: parent.evidence_id,
|
||||
kind: "inventory",
|
||||
source_complete: true,
|
||||
artifact: { path: archive, sha256: parent.subject?.digest.sha256 },
|
||||
items: [expect.objectContaining({ logical_path: "main.js" })],
|
||||
coverage: { total: 1, exhausted: true, next_offset: null },
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"admits portable captures before parsing and preserves capture caveats",
|
||||
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");
|
||||
});
|
||||
@@ -93,7 +93,7 @@ it(
|
||||
const compared = await runCli(
|
||||
[
|
||||
"compare-web-captures",
|
||||
JSON.stringify({ inspection }),
|
||||
JSON.stringify({ inspection, scenario: { caller_metadata: true } }),
|
||||
JSON.stringify({ inspection }),
|
||||
"--json",
|
||||
],
|
||||
@@ -183,6 +183,119 @@ it(
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
describe("scenario comparison CLI diagnostics", () => {
|
||||
const rule = {
|
||||
rule_id: "domain",
|
||||
artifacts: ["url"],
|
||||
match: "app.example.test",
|
||||
replacement: "normalized.test",
|
||||
};
|
||||
it.each([
|
||||
{
|
||||
name: "duplicate rule IDs",
|
||||
normalization: { rules: [rule, rule] },
|
||||
issue: {
|
||||
path: ["normalization", "rules", 1, "rule_id"],
|
||||
reason: "invalid_value",
|
||||
message: "Normalization rule IDs must be unique",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "duplicate artifact kinds",
|
||||
normalization: { rules: [{ ...rule, artifacts: ["url", "url"] }] },
|
||||
issue: {
|
||||
path: ["normalization", "rules", 0, "artifacts"],
|
||||
reason: "invalid_value",
|
||||
message: "Normalization rule artifact kinds must be unique",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "structurally invalid rules",
|
||||
normalization: { rules: "invalid" },
|
||||
issue: {
|
||||
path: ["normalization", "rules"],
|
||||
reason: "invalid_type",
|
||||
expected: "array",
|
||||
},
|
||||
},
|
||||
])(
|
||||
"retains scenario normalization diagnostics for $name",
|
||||
async ({ normalization, issue }) => {
|
||||
const capture = JSON.stringify(completeScenarioCapture());
|
||||
const result = await runCli([
|
||||
"compare-web-captures",
|
||||
capture,
|
||||
capture,
|
||||
"--normalization-json",
|
||||
JSON.stringify(normalization),
|
||||
"--json",
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { operation: "compare_web_captures", issues: [issue] },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps malformed scenario diagnostics in the selected capture group", async () => {
|
||||
const capture = completeScenarioCapture();
|
||||
const result = await runCli([
|
||||
"compare-web-captures",
|
||||
JSON.stringify({ ...capture, duration_ms: "invalid" }),
|
||||
JSON.stringify(capture),
|
||||
"--json",
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_captures",
|
||||
issues: [
|
||||
{
|
||||
path: ["before_scenario", "duration_ms"],
|
||||
reason: "invalid_type",
|
||||
expected: "number",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["omitted", "misspelled"])(
|
||||
"reports the missing scenario manifest when it is %s on both captures",
|
||||
async (kind) => {
|
||||
const { scenario, ...capture } = completeScenarioCapture();
|
||||
const input = JSON.stringify(
|
||||
kind === "omitted" ? capture : { ...capture, scneario: scenario },
|
||||
);
|
||||
const result = await runCli([
|
||||
"compare-web-captures",
|
||||
input,
|
||||
input,
|
||||
"--json",
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_captures",
|
||||
issues: expect.arrayContaining([
|
||||
{
|
||||
path: ["before_scenario", "scenario"],
|
||||
reason: "missing_argument",
|
||||
expected: "object",
|
||||
},
|
||||
{
|
||||
path: ["after_scenario", "scenario"],
|
||||
reason: "missing_argument",
|
||||
expected: "object",
|
||||
},
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain('"inspection"');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser CLI capture parity", () => {
|
||||
it(
|
||||
"runs analysis, session, WebMCP, screenshot, and comparison from explicit request scope",
|
||||
@@ -352,6 +465,7 @@ const completeScenarioCapture = () => {
|
||||
response_body: false,
|
||||
header_values: false,
|
||||
},
|
||||
event_families: [],
|
||||
},
|
||||
duration_ms: 1,
|
||||
steps: [
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { workspaceCliTest as cliTest } from "../../support/cli/workspaceCliFixture.js";
|
||||
|
||||
const malformedEndpoint = "not a url";
|
||||
const browserEndpoint = "http://127.0.0.1:9222";
|
||||
const inspectorEndpoint = "http://127.0.0.1:9229";
|
||||
|
||||
const invalidInputs = [
|
||||
{
|
||||
command: "list-browser-targets",
|
||||
arguments: [malformedEndpoint],
|
||||
operation: "list_browser_targets",
|
||||
error: "Browser observation failed",
|
||||
issue: {
|
||||
path: ["cdp_endpoint"],
|
||||
reason: "invalid_value",
|
||||
message: "Invalid CDP endpoint URL",
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "inspect-web-page",
|
||||
arguments: [browserEndpoint, ""],
|
||||
operation: "inspect_web_page",
|
||||
error: "Browser observation failed",
|
||||
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
|
||||
},
|
||||
{
|
||||
command: "analyze-web-bundle",
|
||||
arguments: [malformedEndpoint, "target"],
|
||||
operation: "analyze_web_bundle",
|
||||
error: "Browser observation failed",
|
||||
issue: {
|
||||
path: ["cdp_endpoint"],
|
||||
reason: "invalid_value",
|
||||
message: "Invalid CDP endpoint URL",
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "observe-web-session",
|
||||
arguments: [browserEndpoint, ""],
|
||||
operation: "observe_web_session",
|
||||
error: "Browser observation failed",
|
||||
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
|
||||
},
|
||||
{
|
||||
command: "list-javascript-runtime-targets",
|
||||
arguments: [""],
|
||||
operation: "list_javascript_runtime_targets",
|
||||
error: "JavaScript runtime observation failed",
|
||||
issue: {
|
||||
path: ["inspector_endpoint"],
|
||||
reason: "out_of_range",
|
||||
minimum: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "observe-javascript-runtime",
|
||||
arguments: [inspectorEndpoint, ""],
|
||||
operation: "observe_javascript_runtime",
|
||||
error: "JavaScript runtime observation failed",
|
||||
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
|
||||
},
|
||||
{
|
||||
command: "discover-webmcp-tools",
|
||||
arguments: [malformedEndpoint, "target"],
|
||||
operation: "discover_webmcp_tools",
|
||||
error: "Browser observation failed",
|
||||
issue: {
|
||||
path: ["cdp_endpoint"],
|
||||
reason: "invalid_value",
|
||||
message: "Invalid CDP endpoint URL",
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "capture-web-screenshot",
|
||||
arguments: [browserEndpoint, ""],
|
||||
operation: "capture_web_screenshot",
|
||||
error: "Browser observation failed",
|
||||
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
|
||||
},
|
||||
] as const;
|
||||
|
||||
describe("inspection branch diagnostics", () => {
|
||||
cliTest.for([[], ["--include-script-sources"]])(
|
||||
"reports only the selected inspection branch's endpoint error (%j)",
|
||||
async (flags, { cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-web-page",
|
||||
malformedEndpoint,
|
||||
"target",
|
||||
...flags,
|
||||
"--json",
|
||||
],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "inspect_web_page",
|
||||
issues: [
|
||||
{
|
||||
path: ["cdp_endpoint"],
|
||||
reason: "invalid_value",
|
||||
message: "Invalid CDP endpoint URL",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser and Inspector CLI input diagnostics", () => {
|
||||
cliTest.for(invalidInputs)(
|
||||
"$command retains the named contract's correction details",
|
||||
async (input, { cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: [input.command, ...input.arguments, "--json"],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
error: input.error,
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Analysis input is invalid. Check the arguments and try again.",
|
||||
retryable: true,
|
||||
remediation: { action: "Correct the listed arguments and retry." },
|
||||
details: {
|
||||
operation: input.operation,
|
||||
issues: expect.arrayContaining([input.issue]),
|
||||
},
|
||||
});
|
||||
expect(result.stdout).not.toContain(malformedEndpoint);
|
||||
expect(result.stderr).not.toContain(malformedEndpoint);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for([
|
||||
["list-browser-targets", "cdp_endpoint"],
|
||||
["list-javascript-runtime-targets", "inspector_endpoint"],
|
||||
] as const)(
|
||||
"%s does not echo rejected endpoint credentials",
|
||||
async ([command, field], { cli, workspace }) => {
|
||||
const endpoint =
|
||||
"http://rea-diagnostic-user:rea-diagnostic-secret@127.0.0.1:9222/";
|
||||
const result = await cli.run({
|
||||
arguments: [command, endpoint, "--json"],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "debug" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"CDP endpoint must be an explicit-port HTTP URL on 127.0.0.1 or ::1",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(output).not.toContain(endpoint);
|
||||
expect(output).not.toContain("rea-diagnostic-user");
|
||||
expect(output).not.toContain("rea-diagnostic-secret");
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"retains authored cross-field correction guidance",
|
||||
async ({ cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-web-page",
|
||||
browserEndpoint,
|
||||
"target",
|
||||
"--include-storage-fingerprints",
|
||||
"--json",
|
||||
],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "inspect_web_page",
|
||||
issues: expect.arrayContaining([
|
||||
{
|
||||
path: ["include_storage_fingerprints"],
|
||||
reason: "invalid_value",
|
||||
message: "Storage fingerprints require storage key capture",
|
||||
},
|
||||
]),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"retains correction details for invalid capture comparison inputs",
|
||||
async ({ cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["compare-web-captures", "{}", "{}", "--json"],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_captures",
|
||||
issues: expect.arrayContaining([
|
||||
expect.objectContaining({ reason: expect.any(String) }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"preserves the parser diagnostic for an omitted endpoint",
|
||||
async ({ cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["list-browser-targets", "--json"],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
fieldErrors: [
|
||||
{
|
||||
path: "endpoint",
|
||||
code: "invalid_type",
|
||||
missing: true,
|
||||
expected: "string",
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import { Cli } from "incur";
|
||||
import { expect, it } from "vitest";
|
||||
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
|
||||
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",
|
||||
async (failAgain) => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Completed capture fixture", version: "1" },
|
||||
{
|
||||
operation: "inspect_packet_capture",
|
||||
parameters: {},
|
||||
result: { packets: [{ "frame.number": ["1"] }] },
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
const original = new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
["original-workspace"],
|
||||
{ reason: "original cleanup failure" },
|
||||
{ operation: "inspect_packet_capture", partialObservation: evidence },
|
||||
);
|
||||
let closed = false;
|
||||
const cli = Cli.create("capture-cleanup-test", { sync: false });
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => err(original),
|
||||
close: async () => {
|
||||
await Promise.resolve();
|
||||
closed = true;
|
||||
if (failAgain)
|
||||
throw new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
["retry-workspace"],
|
||||
{ reason: "retry failed" },
|
||||
{ operation: "inspect_packet_capture" },
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
expect(closed).toBe(true);
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
partial_observation: evidence,
|
||||
resources: expect.arrayContaining(["original-workspace"]),
|
||||
},
|
||||
});
|
||||
if (failAgain)
|
||||
expect(output).toMatchObject({
|
||||
details: { resources: expect.arrayContaining(["retry-workspace"]) },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
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;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
},
|
||||
close: async () => {},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"x".repeat(8192),
|
||||
"--display_filter",
|
||||
"界".repeat(8192),
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
expect(stdout).toContain("32 KiB");
|
||||
});
|
||||
|
||||
it("rejects conflicting output options before the CLI invokes its service", async () => {
|
||||
const cli = Cli.create("capture-window-test", { sync: false });
|
||||
let called = false;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
},
|
||||
close: async () => {},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--all_matches",
|
||||
"--match_limit",
|
||||
"20",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
expect(stdout).toContain("mutually exclusive");
|
||||
});
|
||||
@@ -131,3 +131,73 @@ describe("CLI advertised input schemas", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("firmware CLI advertised input schema", () => {
|
||||
it("keeps limits and defaults from its shared input contract", async () => {
|
||||
const cli = createCli({});
|
||||
const advertised = await advertisedSchema(cli, "extract-firmware");
|
||||
const ajv = new Ajv2020({ strict: false });
|
||||
const args = ajv.compile(advertised.args ?? {});
|
||||
const options = ajv.compile(advertised.options ?? {});
|
||||
|
||||
expect(args({ path: "firmware.bin", outputDirectory: "output" })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(args({ path: "", outputDirectory: "output" })).toBe(false);
|
||||
expect(args({ path: "firmware.bin", outputDirectory: "" })).toBe(false);
|
||||
expect(options({})).toBe(true);
|
||||
expect(options({ maxDepth: 0 })).toBe(false);
|
||||
expect(options({ maxDepth: 11 })).toBe(false);
|
||||
expect(options({ maxOutputBytes: 0 })).toBe(false);
|
||||
expect(options({ maxOutputBytes: 512 * 1024 * 1024 + 1 })).toBe(false);
|
||||
expect(options({ maxOutputFiles: 100_001 })).toBe(false);
|
||||
expect(advertised.options?.properties?.["maxDepth"]).toMatchObject({
|
||||
default: 3,
|
||||
});
|
||||
expect(advertised.options?.properties?.["maxOutputBytes"]).toMatchObject({
|
||||
default: 256 * 1024 * 1024,
|
||||
});
|
||||
expect(advertised.options?.properties?.["maxOutputFiles"]).toMatchObject({
|
||||
default: 10_000,
|
||||
});
|
||||
|
||||
const maxOffset = Number.MAX_SAFE_INTEGER;
|
||||
expect(options({ offset: maxOffset + 1 })).toBe(false);
|
||||
expect(options({ length: maxOffset + 1 })).toBe(false);
|
||||
|
||||
expect(
|
||||
parserSchema(cli, "extract-firmware", "options")?.parse({}),
|
||||
).toMatchObject({
|
||||
maxDepth: 3,
|
||||
maxOutputBytes: 256 * 1024 * 1024,
|
||||
maxOutputFiles: 10_000,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web module CLI advertised input schema", () => {
|
||||
it("advertises the shared path and URL constraints", async () => {
|
||||
const cli = createCli({});
|
||||
const advertised = await advertisedSchema(cli, "trace-web-module-imports");
|
||||
const ajv = new Ajv2020({ strict: false });
|
||||
const args = ajv.compile(advertised.args ?? {});
|
||||
const options = ajv.compile(advertised.options ?? {});
|
||||
|
||||
expect(
|
||||
args({ manifestPath: resolve("manifest.json"), scriptIndex: 0 }),
|
||||
).toBe(true);
|
||||
expect(args({ manifestPath: "", scriptIndex: 0 })).toBe(false);
|
||||
expect(args({ manifestPath: "manifest\u0000.json", scriptIndex: 0 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(args({ manifestPath: "./manifest.json", scriptIndex: -1 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(options({})).toBe(true);
|
||||
expect(options({ importerUrl: "" })).toBe(false);
|
||||
expect(options({ importMapPath: "" })).toBe(false);
|
||||
expect(options({ importMapPath: "map\u0000.json" })).toBe(false);
|
||||
expect(options({ importMapBaseUrl: "" })).toBe(false);
|
||||
});
|
||||
});
|
||||
import { resolve } from "node:path";
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const level of ["loud", "INFO"])
|
||||
cliTest(
|
||||
`reports REA_LOG_LEVEL=${level} as invalid configuration`,
|
||||
async ({ cli }) => {
|
||||
for (const arguments_ of [["doctor", "--json"], ["--help"]]) {
|
||||
const result = await cli.run({
|
||||
arguments: arguments_,
|
||||
environment: { REA_LOG_LEVEL: level },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).toBe("");
|
||||
expect(result.stderr).toBe(
|
||||
'REA configuration is invalid: REA_LOG_LEVEL: Invalid option: expected one of "trace"|"debug"|"info"|"warn"|"error"|"fatal"|"silent".\n',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -1,5 +1,6 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { access, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { spawn } from "@lydell/node-pty";
|
||||
@@ -73,6 +74,61 @@ const clientStates = [
|
||||
|
||||
const agentActions = actions.filter(({ kind }) => kind !== "install_hopper");
|
||||
|
||||
describe("TTY setup dry run", () => {
|
||||
it("prints the plan and no-mutation notice for a TTY dry run", async () => {
|
||||
const home = await createTestTempDirectory("rea-cli-setup-dry-run-");
|
||||
const terminal = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/rea.mjs",
|
||||
"setup",
|
||||
"--dry-run",
|
||||
"--client",
|
||||
"codex",
|
||||
"--skill=false",
|
||||
],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
...process.env,
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
NO_COLOR: "1",
|
||||
},
|
||||
name: "xterm-256color",
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
},
|
||||
);
|
||||
let output = "";
|
||||
terminal.onData((data) => {
|
||||
output += data;
|
||||
});
|
||||
const exitCode = await new Promise<number>((resolvePromise, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
terminal.kill();
|
||||
reject(new Error(`TTY dry run timed out after output:\n${output}`));
|
||||
}, 15_000);
|
||||
terminal.onExit(({ exitCode: code }) => {
|
||||
clearTimeout(timeout);
|
||||
resolvePromise(code);
|
||||
});
|
||||
});
|
||||
|
||||
expect(exitCode, output).toBe(0);
|
||||
expect(output).toContain("CREATE Codex");
|
||||
expect(output).toContain(join(home, ".codex/config.toml"));
|
||||
expect(output).toContain("Dry run complete. No changes were made.");
|
||||
await expect(
|
||||
access(join(home, ".codex/config.toml")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("interactive setup journey", () => {
|
||||
it("shows detected and absent clients without preselecting detected clients", async () => {
|
||||
const result = await runJourney(
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
@@ -259,3 +260,39 @@ for (const group of groups) {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest("uninstall names each retained skill directory", async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-skill-paths-");
|
||||
const shared = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
|
||||
const claude = join(home, ".claude", "skills", PRODUCT_IDENTITY.skillName);
|
||||
for (const directory of [shared, claude]) {
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(join(directory, "SKILL.md"), "---\nname: unrelated\n---\n");
|
||||
}
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["uninstall", "--json"],
|
||||
cwd: home,
|
||||
environment: {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CLAUDE_CONFIG_DIR: join(home, ".claude"),
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const report = result.json as {
|
||||
items?: readonly { name: string; status: string; detail: string }[];
|
||||
};
|
||||
const skill = report.items?.find(({ name }) => name === "skill");
|
||||
expect(skill?.status).toBe("retained");
|
||||
for (const directory of [shared, claude]) {
|
||||
expect(skill?.detail).toContain(
|
||||
`${directory}: retained (Skill manifest is not REA-owned.)`,
|
||||
);
|
||||
expect(await readFile(join(directory, "SKILL.md"), "utf8")).toBe(
|
||||
"---\nname: unrelated\n---\n",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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"),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,15 +25,15 @@ describe("executable dispatcher", () => {
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli-runtime/cli.js",
|
||||
'export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
'export const cliConfigurationError = () => undefined; export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli-runtime/cliOutput.js",
|
||||
"export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => ''; export const renderEmptyFilteredCliOutput = () => undefined;\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli-runtime/streamedJsonOutput.js",
|
||||
"export const createStreamedCliJsonOutput = () => undefined;\n",
|
||||
"dist/cli-runtime/cliResultOutput.js",
|
||||
"export const createCliResultOutput = () => undefined;\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli-runtime/mcpDoctor.js",
|
||||
|
||||
@@ -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";
|
||||
@@ -471,6 +473,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",
|
||||
"--json",
|
||||
],
|
||||
environment: ENVIRONMENT,
|
||||
});
|
||||
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
|
||||
const trace = dylibResolutionResultSchema.parse(
|
||||
parseEvidence(result.json).normalized_result,
|
||||
);
|
||||
expect(
|
||||
trace.roots.filter(({ architecture }) => architecture === "arm64e"),
|
||||
).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 }) => {
|
||||
|
||||
@@ -66,6 +66,27 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"reports a standalone Evidence record as the wrong input file kind",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-record-input-");
|
||||
const path = join(root, "record.json");
|
||||
const record = revisionBundle().records[0];
|
||||
if (record === undefined) throw new Error("Missing fixture Evidence");
|
||||
await writeFile(path, JSON.stringify(record));
|
||||
const result = await cli.run({
|
||||
arguments: ["evidence-import", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: { path },
|
||||
message: expect.stringContaining("this JSON is one Evidence record"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects altered Evidence and incomplete unknown history before reporting counts",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { serveCli } from "./cliServeHarness.js";
|
||||
|
||||
it.each(["identify-flutter-build", "inspect-dart-aot"])(
|
||||
"%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("reports an unreadable target with an input refusal", async () => {
|
||||
const result = await serveCli([
|
||||
"identify-flutter-build",
|
||||
"/nonexistent/app.apk",
|
||||
"--json",
|
||||
]);
|
||||
expect(result.stdout).toContain("invalid_request");
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
|
||||
|
||||
it("maps one-shot Frida CLI target, script, duration, and remote options", async () => {
|
||||
const calls: unknown[] = [];
|
||||
const provider: FridaInstrumentationPort = {
|
||||
async listDevices() {
|
||||
calls.push({ operation: "devices" });
|
||||
return { ok: true, value: { devices: [], cleanupError: null } };
|
||||
},
|
||||
async listProcesses() {
|
||||
return {
|
||||
ok: true,
|
||||
value: { deviceId: "local", processes: [], cleanupError: null },
|
||||
};
|
||||
},
|
||||
async startSession(input) {
|
||||
calls.push({ operation: "start", input });
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
deviceId: "remote",
|
||||
target: "fixture",
|
||||
pid: 71,
|
||||
mode: input.mode,
|
||||
state: "running",
|
||||
},
|
||||
};
|
||||
},
|
||||
async loadScript(sessionId, source) {
|
||||
calls.push({ operation: "load", sessionId, source });
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
scriptId: "00000000-0000-4000-8000-000000000002",
|
||||
sourceKind: source.sourceKind,
|
||||
sourcePath: source.sourceKind === "file" ? source.path : null,
|
||||
sourceSha256: "a".repeat(64),
|
||||
messages: [{ type: "send", payload: "observed" }],
|
||||
messagesTruncated: false,
|
||||
},
|
||||
};
|
||||
},
|
||||
async resumeSession(sessionId) {
|
||||
calls.push({ operation: "resume", sessionId });
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
async unloadScript() {
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
status(sessionId) {
|
||||
return {
|
||||
sessionId,
|
||||
deviceId: "remote",
|
||||
target: "fixture",
|
||||
pid: 71,
|
||||
mode: "attach",
|
||||
state: "running",
|
||||
targetResumeObserved: false,
|
||||
scripts: [],
|
||||
messages: [],
|
||||
messagesTruncated: false,
|
||||
};
|
||||
},
|
||||
async closeSession(sessionId) {
|
||||
calls.push({ operation: "close", sessionId });
|
||||
return { ok: true, value: { targetResumeObserved: false } };
|
||||
},
|
||||
async closeAll() {},
|
||||
};
|
||||
const cli = createCli({}, undefined, provider);
|
||||
let stdout = "";
|
||||
let exitCode = 0;
|
||||
await cli.serve(
|
||||
[
|
||||
"instrument-with-frida",
|
||||
"attach",
|
||||
"71",
|
||||
"--script",
|
||||
"send('hello')",
|
||||
"--remote-address",
|
||||
"127.0.0.1:27042",
|
||||
"--token",
|
||||
"synthetic-secret-token",
|
||||
"--keepalive-interval",
|
||||
"10",
|
||||
"--duration-ms",
|
||||
"0",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(exitCode).toBe(0);
|
||||
const result: unknown = JSON.parse(stdout);
|
||||
expect(JSON.stringify(result)).not.toContain("synthetic-secret-token");
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
operation: "start",
|
||||
input: {
|
||||
mode: "attach",
|
||||
pid: 71,
|
||||
remote: {
|
||||
address: "127.0.0.1:27042",
|
||||
token: "synthetic-secret-token",
|
||||
keepaliveInterval: 10,
|
||||
},
|
||||
source: { sourceKind: "inline", source: "send('hello')" },
|
||||
durationMs: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: "load",
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
source: { sourceKind: "inline", source: "send('hello')" },
|
||||
},
|
||||
{
|
||||
operation: "close",
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
},
|
||||
]);
|
||||
|
||||
stdout = "";
|
||||
exitCode = 0;
|
||||
await cli.serve(
|
||||
["list-frida-devices", "--token", "synthetic-secret-token", "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(stdout).not.toContain("synthetic-secret-token");
|
||||
});
|
||||
|
||||
it("awaits failed startup cleanup and retains the primary error if cleanup still fails", async () => {
|
||||
for (const cleanupFails of [false, true]) {
|
||||
const calls: string[] = [];
|
||||
const provider: FridaInstrumentationPort =
|
||||
new FridaInstrumentationManager();
|
||||
provider.startSession = async () => {
|
||||
calls.push("start");
|
||||
return {
|
||||
ok: false,
|
||||
error: new AnalysisCapabilityUnavailableError(
|
||||
"frida",
|
||||
"start_frida_session",
|
||||
"attach failed after spawn",
|
||||
{
|
||||
cleanup: {
|
||||
reason: "first resume failed",
|
||||
resources: ["paused spawn"],
|
||||
},
|
||||
},
|
||||
),
|
||||
};
|
||||
};
|
||||
provider.closeAll = async () => {
|
||||
calls.push("cleanup");
|
||||
if (cleanupFails) throw new Error("resume still failed");
|
||||
};
|
||||
let stdout = "";
|
||||
await createCli({}, undefined, provider).serve(
|
||||
[
|
||||
"instrument-with-frida",
|
||||
"spawn",
|
||||
"/tmp/fixture",
|
||||
"--script",
|
||||
"send('ready')",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
exit: () => {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(calls).toEqual(["start", "cleanup"]);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: cleanupFails ? "cleanup_incomplete" : "capability_unavailable",
|
||||
});
|
||||
expect(stdout).toContain("attach failed after spawn");
|
||||
if (cleanupFails) expect(stdout).toContain("primary_error");
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves observed devices when CLI provider cleanup fails", async () => {
|
||||
const provider: FridaInstrumentationPort = new FridaInstrumentationManager();
|
||||
const devices = [
|
||||
{ deviceId: "remote-device", name: "selected endpoint", type: "remote" },
|
||||
];
|
||||
provider.listDevices = async () => ({
|
||||
ok: true,
|
||||
value: { devices, cleanupError: null },
|
||||
});
|
||||
provider.closeAll = async () => {
|
||||
throw new Error("remote removal failed");
|
||||
};
|
||||
let stdout = "";
|
||||
await createCli({}, undefined, provider).serve(
|
||||
["list-frida-devices", "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: () => {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { diagnostics: { partial_observation: { devices } } },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
["attach", "abc", "--script", "send(1)"],
|
||||
"target",
|
||||
"attach mode needs a positive integer process ID.",
|
||||
],
|
||||
[
|
||||
["attach", "71"],
|
||||
"script",
|
||||
"Provide exactly one of --script or --script-file.",
|
||||
],
|
||||
])(
|
||||
"names the rejected instrument-with-frida argument for %j",
|
||||
async (argv, path, message) => {
|
||||
let starts = 0;
|
||||
const provider = {
|
||||
async startSession() {
|
||||
starts += 1;
|
||||
throw new Error("Frida must not start for invalid input");
|
||||
},
|
||||
} as unknown as FridaInstrumentationPort;
|
||||
const cli = createCli({}, undefined, provider);
|
||||
let stdout = "";
|
||||
await cli.serve(["instrument-with-frida", ...argv, "--json"], {
|
||||
env: {},
|
||||
exit: () => undefined,
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
});
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [{ path: [path], reason: "invalid_value", message }],
|
||||
},
|
||||
});
|
||||
expect(starts).toBe(0);
|
||||
},
|
||||
);
|
||||
@@ -30,3 +30,14 @@ it("validates decompile item input before contacting the engine", async () => {
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an invalid endpoint without breaking other commands", async () => {
|
||||
const environment = { REA_JEB_MCP_URL: "http://localhost:8425/mcp" };
|
||||
const jeb = await serveCli(["inspect-jeb-client", "--json"], environment);
|
||||
expect(JSON.parse(jeb.stdout)).toMatchObject({
|
||||
code: "configuration_invalid",
|
||||
details: { settings: [{ setting: "REA_JEB_MCP_URL" }] },
|
||||
});
|
||||
const capabilities = await serveCli(["capabilities", "--json"], environment);
|
||||
expect(capabilities.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
@@ -2,15 +2,19 @@ import { constants } from "node:buffer";
|
||||
import { createHash } from "node:crypto";
|
||||
import { Writable } from "node:stream";
|
||||
|
||||
import { Cli } from "incur";
|
||||
import { Cli, Formatter } from "incur";
|
||||
import { estimateTokenCount } from "tokenx";
|
||||
import { parse as parseYaml } from "yaml";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { writeJsonOutput } from "../../../src/cli/jsonOutput.js";
|
||||
import {
|
||||
createStreamedCliJsonOutput,
|
||||
createCliResultOutput,
|
||||
streamCliCommandResults,
|
||||
} from "../../../src/cli/streamedJsonOutput.js";
|
||||
} from "../../../src/cli/cliResultOutput.js";
|
||||
import { logCliCommand } from "../../../src/cliLogging.js";
|
||||
import { registerManagedCommands } from "../../../src/cli/managedCommands.js";
|
||||
import { analysisErrorProjectionSchema } from "../../../src/contracts/errorSchemas.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
|
||||
const collect = async (
|
||||
@@ -157,16 +161,283 @@ describe("incremental CLI JSON", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("streamed CLI result surface", () => {
|
||||
describe("CLI result output surface", () => {
|
||||
it.each(["json", "yaml", "toon", "md"] as const)(
|
||||
"places typed analysis failures in the full-output error envelope (%s)",
|
||||
async (format) => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const failure = {
|
||||
error: "Analysis failed",
|
||||
code: "target_unavailable",
|
||||
category: "unavailable",
|
||||
message: "The selected artifact is missing.",
|
||||
retryable: false,
|
||||
remediation: { action: "Check that the path exists." },
|
||||
details: { source: "artifact-open" },
|
||||
input_path: "missing.dll",
|
||||
input_reason: "read-failed",
|
||||
};
|
||||
const argv = [
|
||||
"inspect-managed-artifact",
|
||||
"missing.dll",
|
||||
"--format",
|
||||
format,
|
||||
"--full-output",
|
||||
"--filter-output",
|
||||
"message",
|
||||
];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined)
|
||||
throw new Error("Missing structured output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
registerManagedCommands(cli, silentLogger, async () => failure);
|
||||
streamCliCommandResults(cli, output);
|
||||
let fallback = "";
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, {
|
||||
stdout: (text) => {
|
||||
if (!output.handled) fallback += text;
|
||||
},
|
||||
});
|
||||
expect(process.exitCode).toBe(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
|
||||
const text = Buffer.concat(chunks).toString("utf8");
|
||||
expect(output.handled).toBe(true);
|
||||
expect(fallback).toBe("");
|
||||
if (format === "json" || format === "yaml") {
|
||||
const document = format === "json" ? JSON.parse(text) : parseYaml(text);
|
||||
expect(document).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: failure.code,
|
||||
category: failure.category,
|
||||
message: failure.message,
|
||||
retryable: false,
|
||||
remediation: failure.remediation,
|
||||
details: {
|
||||
...failure.details,
|
||||
input_path: failure.input_path,
|
||||
input_reason: failure.input_reason,
|
||||
},
|
||||
},
|
||||
meta: { command: "inspect-managed-artifact" },
|
||||
});
|
||||
expect(() =>
|
||||
analysisErrorProjectionSchema.parse(document.error),
|
||||
).not.toThrow();
|
||||
expect(document).not.toHaveProperty("data");
|
||||
} else {
|
||||
expect(text).toContain("false");
|
||||
expect(text).toContain(failure.code);
|
||||
expect(text).not.toContain("true");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "custom command failure",
|
||||
value: {
|
||||
status: "failed",
|
||||
message: "Update was not applied.",
|
||||
remediation: "Check the package manager, then retry.",
|
||||
details: { stage: "install" },
|
||||
},
|
||||
isFailure: () => true,
|
||||
},
|
||||
{
|
||||
name: "unhealthy doctor result",
|
||||
value: { healthy: false, checks: [{ name: "provider", ok: false }] },
|
||||
isFailure: undefined,
|
||||
},
|
||||
])("preserves $name as a full-output error payload", async (scenario) => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const argv = ["fixture", "--json", "--full-output"];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
cli.command("fixture", {
|
||||
run: () =>
|
||||
logCliCommand(
|
||||
silentLogger,
|
||||
"fixture",
|
||||
async () => scenario.value,
|
||||
scenario.isFailure,
|
||||
),
|
||||
});
|
||||
streamCliCommandResults(cli, output);
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, { stdout: () => undefined });
|
||||
expect(process.exitCode).toBe(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
expect(JSON.parse(Buffer.concat(chunks).toString("utf8"))).toMatchObject({
|
||||
ok: false,
|
||||
error: scenario.value,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("full-output token windows", () => {
|
||||
it("preserves Incur token-window metadata when truncating a TOON failure", async () => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const argv = [
|
||||
"inspect-managed-artifact",
|
||||
"missing.dll",
|
||||
"--format",
|
||||
"toon",
|
||||
"--full-output",
|
||||
"--token-limit",
|
||||
"3",
|
||||
];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing TOON output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
registerManagedCommands(cli, silentLogger, async () => ({
|
||||
code: "target_unavailable",
|
||||
category: "unavailable",
|
||||
message: "The selected artifact is missing.",
|
||||
retryable: false,
|
||||
remediation: { action: "Check that the path exists." },
|
||||
details: { source: "artifact-open" },
|
||||
}));
|
||||
streamCliCommandResults(cli, output);
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, { stdout: () => undefined });
|
||||
expect(process.exitCode).toBe(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
const text = Buffer.concat(chunks).toString("utf8");
|
||||
expect(text).toContain("[truncated: showing tokens 0–3 of");
|
||||
expect(text).toMatch(/nextOffset:?\s*3/);
|
||||
expect(text).toContain("ok: false");
|
||||
});
|
||||
});
|
||||
|
||||
describe("logger classification handoff", () => {
|
||||
it("honors an explicit success for data containing error-shaped fields", async () => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const result = {
|
||||
error: {
|
||||
code: "target_unavailable",
|
||||
category: "unavailable",
|
||||
message: "Source data describes a missing target.",
|
||||
retryable: false,
|
||||
remediation: { action: "Use the value as source data." },
|
||||
},
|
||||
source: "captured-metadata",
|
||||
};
|
||||
const argv = ["fixture", "--json", "--full-output"];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
cli.command("fixture", {
|
||||
run: () =>
|
||||
logCliCommand(
|
||||
silentLogger,
|
||||
"fixture",
|
||||
async () => result,
|
||||
() => false,
|
||||
),
|
||||
});
|
||||
streamCliCommandResults(cli, output);
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, { stdout: () => undefined });
|
||||
expect(process.exitCode).toBe(previousExitCode);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
expect(JSON.parse(Buffer.concat(chunks).toString("utf8"))).toMatchObject({
|
||||
ok: true,
|
||||
data: result,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("full-output token counts", () => {
|
||||
it("counts the full failure payload before applying output filters", async () => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const failure = {
|
||||
code: "target_unavailable",
|
||||
category: "unavailable",
|
||||
message: "The selected artifact is missing.",
|
||||
retryable: false,
|
||||
remediation: { action: "Check that the path exists." },
|
||||
details: { source: "artifact-open" },
|
||||
};
|
||||
const argv = [
|
||||
"inspect-managed-artifact",
|
||||
"missing.dll",
|
||||
"--json",
|
||||
"--full-output",
|
||||
"--token-count",
|
||||
"--filter-output",
|
||||
"message",
|
||||
];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
registerManagedCommands(cli, silentLogger, async () => failure);
|
||||
streamCliCommandResults(cli, output);
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, { stdout: () => undefined });
|
||||
expect(process.exitCode).toBe(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
expect(output.handled).toBe(true);
|
||||
expect(Buffer.concat(chunks).toString("utf8")).toBe(
|
||||
`${estimateTokenCount(Formatter.format(failure, "json"))}\n`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CLI result output surface", () => {
|
||||
it.each([
|
||||
[],
|
||||
["--format", "md"],
|
||||
["--json", "--token-limit", "5"],
|
||||
["--json", "--format", "invalid"],
|
||||
])("delegates unsupported output controls %j", (...arguments_) => {
|
||||
expect(createStreamedCliJsonOutput(arguments_, new Writable())).toBe(
|
||||
undefined,
|
||||
);
|
||||
expect(createCliResultOutput(arguments_, new Writable())).toBe(undefined);
|
||||
});
|
||||
|
||||
it("keeps ownership after a failed write so no second document is emitted", async () => {
|
||||
@@ -176,7 +447,7 @@ describe("streamed CLI result surface", () => {
|
||||
callback(cause);
|
||||
},
|
||||
});
|
||||
const output = createStreamedCliJsonOutput(["--json"], destination);
|
||||
const output = createCliResultOutput(["--json"], destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
await expect(
|
||||
output.write(
|
||||
@@ -228,7 +499,7 @@ describe("streamed CLI result surface", () => {
|
||||
// A terminal destination exercises the indented encoding past the limit.
|
||||
Object.defineProperty(destination, "isTTY", { value: true });
|
||||
const argv = ["inspect-managed-members", "fixture.dll", "--json"];
|
||||
const output = createStreamedCliJsonOutput(argv, destination);
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
streamCliCommandResults(cli, output);
|
||||
let exitCode = 0;
|
||||
@@ -248,7 +519,7 @@ describe("streamed CLI result surface", () => {
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const tokenArgv = [...argv, "--token-count", "--full-output"];
|
||||
const tokenOutput = createStreamedCliJsonOutput(
|
||||
const tokenOutput = createCliResultOutput(
|
||||
tokenArgv,
|
||||
new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { build } from "plist";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { deeplyNestedXmlPlist } from "../../fixtures/keyedArchiveXmlNesting.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const [name, xml] of [
|
||||
["dictionaries", deeplyNestedXmlPlist(3000)],
|
||||
[
|
||||
"quoted attributes",
|
||||
deeplyNestedXmlPlist(3000).replaceAll("<dict>", '<dict note="/>">'),
|
||||
],
|
||||
[
|
||||
"plist wrappers",
|
||||
"<plist>".repeat(3000) + "<string>x</string>" + "</plist>".repeat(3000),
|
||||
],
|
||||
] as const) {
|
||||
cliTest(
|
||||
`compiled CLI reports deeply nested XML ${name} as the decode limit`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-keyed-cli-depth-");
|
||||
const path = join(root, "Deep.plist");
|
||||
await writeFile(path, xml);
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-keyed-archive", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(1);
|
||||
expect(output.json).toMatchObject({
|
||||
code: "truncated",
|
||||
category: "truncated",
|
||||
details: {
|
||||
reason: "limit",
|
||||
truncated: true,
|
||||
detail:
|
||||
"Cannot decode selected Foundation keyed archive: Plist exceeds 128 nesting levels",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"compiled CLI decodes a shallow archive with opaque DOCTYPE markup",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-keyed-cli-doctype-");
|
||||
const path = join(root, "Shallow.plist");
|
||||
const archive = build({
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$objects: ["$null", "leaf"],
|
||||
$top: { root: { UID: 1 } },
|
||||
});
|
||||
await writeFile(
|
||||
path,
|
||||
archive.replace(
|
||||
/<!DOCTYPE[^>]*>/u,
|
||||
`<!DOCTYPE plist [<!ENTITY first "unused"><!ENTITY second "${"<dict>".repeat(130)}">]>`,
|
||||
),
|
||||
);
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-keyed-archive", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
expect(parseEvidence(output.json).normalized_result).toMatchObject({
|
||||
archive_format: "xml-plist",
|
||||
objects: expect.arrayContaining([
|
||||
expect.objectContaining({ value: "leaf" }),
|
||||
]),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,336 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
// A recording port checks the experimental producer/consumer representation.
|
||||
// Real provider verification remains in the separate native experiment receipts.
|
||||
const generate = `
|
||||
import {measureNativeEntry} from './experiments/analysis-efficiency/native-entry.mjs';
|
||||
const sha='0'.repeat(64);
|
||||
const duplicate=process.argv[1]==='duplicate';
|
||||
const stale=process.argv[1]==='stale-dos';
|
||||
const collision=process.argv[1];
|
||||
const dos=process.argv[1]==='dos'||stale||collision==='load-collision';
|
||||
const dossier={procedure:{address:'0x1000'},pseudocode:'return;',callers:[],callees:[]};
|
||||
class ToolFailure extends Error {}
|
||||
const build=async digit=>{
|
||||
const parent='ev_'+digit.repeat(63)+'0';
|
||||
let ordinal=0;
|
||||
const call=async(name,args)=>{
|
||||
if(stale)process.stdout.write(name+'\\n');
|
||||
if(name==='open_binary'||name==='close_binary')return {};
|
||||
if(name==='inspect_native_load_image')return {evidence_id:'ev_'+digit.repeat(63)+'6',normalized_result:{status:'verified',target_sha256:stale?'f'.repeat(64):sha,entry:{linear_address:'0x1000'}}};
|
||||
if(name==='resolve_containing_procedure')return {evidence_id:'ev_'+digit.repeat(63)+'7',normalized_result:{found:true}};
|
||||
if(name==='analyze_function')return {evidence_id:parent,subject:{digest:{sha256:sha}},normalized_result:dossier};
|
||||
const id='ev_'+digit.repeat(63)+(collision==='containing-collision'?7:collision==='load-collision'?6:duplicate?1:++ordinal);
|
||||
if(args.view.kind==='summary')return {evidence_id:id};
|
||||
const facet=args.view.facet;
|
||||
const item=facet==='pseudocode'?{text:dossier.pseudocode,unit:'utf16-code-units'}:dossier[facet];
|
||||
return {evidence_id:id,normalized_result:{parent_evidence_id:parent,artifact:{sha256:sha},item,coverage:{exhausted:true},limitations:[],unknowns:[]}};
|
||||
};
|
||||
return measureNativeEntry({seed:dos?undefined:'0x1000',values:{path:'/selected/input','native-question':'entry-views'},call,inputSha:sha,ToolFailure});
|
||||
};
|
||||
process.stdout.write(JSON.stringify([await build('1'),await build('2')]));
|
||||
`;
|
||||
|
||||
it.each([
|
||||
"observed",
|
||||
"missing",
|
||||
"errored",
|
||||
"wrong-target",
|
||||
"wrong-entry",
|
||||
"unreferenced",
|
||||
])(
|
||||
"binds the DOS model grade to its observed load image: %s",
|
||||
async (scenario) => {
|
||||
// Synthetic transcripts exercise grading; they are not real-provider or
|
||||
// resource measurements. Real DOS transcripts are replayed separately.
|
||||
const root = await createTestTempDirectory("rea-dos-grader-");
|
||||
const trial = join(root, "trial");
|
||||
const referenceDirectory = join(root, "reference");
|
||||
await mkdir(trial);
|
||||
await mkdir(referenceDirectory);
|
||||
const sha = "0".repeat(64);
|
||||
const imageId = "ev_" + "1".repeat(64);
|
||||
const procedureId = "ev_" + "2".repeat(64);
|
||||
const procedure = {
|
||||
address: "0x1000",
|
||||
name: "entry",
|
||||
classification: "observed",
|
||||
signature: null,
|
||||
locals: [],
|
||||
body: { ranges: [], total_bytes: 0 },
|
||||
};
|
||||
const loadImage = {
|
||||
status: "verified",
|
||||
target_sha256: sha,
|
||||
entry: { linear_address: "0x1000" },
|
||||
};
|
||||
const reference = {
|
||||
artifact_sha256: sha,
|
||||
entry_address: "0x1000",
|
||||
caller_count: 0,
|
||||
callee_count: 0,
|
||||
pseudocode_prefix: "return;",
|
||||
containing_procedure: { procedure },
|
||||
procedure,
|
||||
load_image: loadImage,
|
||||
};
|
||||
const answer = {
|
||||
...reference,
|
||||
load_image_status: "verified",
|
||||
evidence_ids: [
|
||||
procedureId,
|
||||
...(["missing", "errored", "unreferenced"].includes(scenario)
|
||||
? []
|
||||
: [imageId]),
|
||||
],
|
||||
};
|
||||
const event = (tool: string, status: string, value: unknown) => ({
|
||||
type: "item.completed",
|
||||
item: {
|
||||
type: "mcp_tool_call",
|
||||
tool,
|
||||
status,
|
||||
arguments: {},
|
||||
result: { structured_content: value },
|
||||
},
|
||||
});
|
||||
const events = [
|
||||
event("analyze_function", "completed", { evidence_id: procedureId }),
|
||||
];
|
||||
if (scenario !== "missing")
|
||||
events.push(
|
||||
event(
|
||||
"inspect_native_load_image",
|
||||
scenario === "errored" ? "failed" : "completed",
|
||||
scenario === "errored"
|
||||
? { error: { code: "unsupported_target" } }
|
||||
: {
|
||||
operation: "inspect_native_load_image",
|
||||
evidence_id: imageId,
|
||||
normalized_result: {
|
||||
...loadImage,
|
||||
target_sha256:
|
||||
scenario === "wrong-target" ? "f".repeat(64) : sha,
|
||||
entry: {
|
||||
linear_address:
|
||||
scenario === "wrong-entry" ? "0x2000" : "0x1000",
|
||||
},
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
const resourceLog = join(root, "resource.log");
|
||||
const output = join(root, "review.json");
|
||||
for (const [path, value] of [
|
||||
[
|
||||
join(trial, "summary.json"),
|
||||
{
|
||||
completed_mcp_calls: [
|
||||
{ tool: "close_binary", status: "completed", arguments: {} },
|
||||
],
|
||||
},
|
||||
],
|
||||
[join(trial, "trial-settings.json"), {}],
|
||||
[join(trial, "cleanup.json"), { profile_removed: true }],
|
||||
[join(trial, "answer.txt"), answer],
|
||||
[join(referenceDirectory, "answer.json"), reference],
|
||||
[
|
||||
resourceLog,
|
||||
{
|
||||
resource_scope: "synthetic-grader-fixture",
|
||||
abort: null,
|
||||
resource_counters_verified: true,
|
||||
resource_events_final: {
|
||||
"memory.events": { high: 0, max: 0, oom: 0, oom_kill: 0 },
|
||||
"pids.events": { max: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
] as const)
|
||||
await writeFile(path, JSON.stringify(value));
|
||||
await writeFile(
|
||||
join(trial, "events.jsonl"),
|
||||
events.map((value) => JSON.stringify(value)).join("\n"),
|
||||
);
|
||||
const command = execute("python3", [
|
||||
resolve("experiments/analysis-efficiency/review-model.py"),
|
||||
"--domain",
|
||||
"native",
|
||||
"--trial",
|
||||
trial,
|
||||
"--reference",
|
||||
referenceDirectory,
|
||||
"--resource-log",
|
||||
resourceLog,
|
||||
"--output",
|
||||
output,
|
||||
]);
|
||||
if (scenario === "observed") await command;
|
||||
else await expect(command).rejects.toMatchObject({ code: 1 });
|
||||
const report = JSON.parse(await readFile(output, "utf8"));
|
||||
expect(report.all_selected_checks_pass).toBe(scenario === "observed");
|
||||
if (["missing", "errored", "unreferenced"].includes(scenario))
|
||||
expect(report.checks.load_image_source_observed_and_referenced).toBe(
|
||||
false,
|
||||
);
|
||||
if (scenario === "wrong-target")
|
||||
expect(report.checks["load_image.target_sha256"]).toBe(false);
|
||||
if (scenario === "wrong-entry")
|
||||
expect(report.checks["load_image.source_entry"]).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains the DOS load-image source for its facts and derived entry seed", async () => {
|
||||
const { stdout } = await execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"dos",
|
||||
]);
|
||||
const [answer] = JSON.parse(stdout);
|
||||
expect(answer).toMatchObject({
|
||||
entry_address: "0x1000",
|
||||
load_image: { status: "verified", entry: { linear_address: "0x1000" } },
|
||||
evidence_ids: { native_load_image: "ev_" + "1".repeat(63) + "6" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a stale DOS load image before using its entry and closes the session", async () => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"stale-dos",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stdout: "open_binary\ninspect_native_load_image\nclose_binary\n",
|
||||
stderr: expect.stringContaining(
|
||||
"The DOS load image belongs to a different target",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["containing-collision", "load-collision"])(
|
||||
"rejects a retained view that reuses an earlier producer identity: %s",
|
||||
async (collision) => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
collision,
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stderr: expect.stringContaining(
|
||||
"Retained native view reused an Evidence identity",
|
||||
),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects a producer that reuses a view identity across facets", async () => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"duplicate",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stderr: expect.stringContaining(
|
||||
"Retained native view reused an Evidence identity",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["references", "item", "coverage", "limitations", "unknowns"])(
|
||||
"separates native references while comparing %s exactly",
|
||||
async (change) => {
|
||||
const { stdout: generated } = await execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
]);
|
||||
const [leftAnswer, rightAnswer] = JSON.parse(generated);
|
||||
if (change === "item")
|
||||
rightAnswer.retained_views[0].item.address = "0x1001";
|
||||
if (change === "coverage")
|
||||
rightAnswer.retained_views[0].coverage.exhausted = false;
|
||||
if (change === "limitations")
|
||||
rightAnswer.retained_views[0].limitations.push("partial");
|
||||
if (change === "unknowns")
|
||||
rightAnswer.retained_views[0].unknowns.push("unresolved");
|
||||
|
||||
const root = await createTestTempDirectory("rea-native-comparison-");
|
||||
const left = join(root, "left");
|
||||
const right = join(root, "right");
|
||||
const summary = {
|
||||
artifact: "sharex.exe",
|
||||
native_question: "entry-views",
|
||||
provider_search_path_sha256: "0".repeat(64),
|
||||
native_workflow_source_sha256: "1".repeat(64),
|
||||
calls: [],
|
||||
failure: null,
|
||||
};
|
||||
for (const [directory, answer] of [
|
||||
[left, leftAnswer],
|
||||
[right, rightAnswer],
|
||||
]) {
|
||||
await mkdir(directory);
|
||||
await writeFile(join(directory, "summary.json"), JSON.stringify(summary));
|
||||
await writeFile(join(directory, "answer.json"), JSON.stringify(answer));
|
||||
}
|
||||
const output = join(root, "comparison.json");
|
||||
const command = execute(process.execPath, [
|
||||
resolve("experiments/analysis-efficiency/compare.mjs"),
|
||||
"--left",
|
||||
left,
|
||||
"--right",
|
||||
right,
|
||||
"--output",
|
||||
output,
|
||||
]);
|
||||
if (change !== "references") {
|
||||
await expect(command).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining('"retained_views"'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const { stdout } = await command;
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
settings_match: true,
|
||||
facts_match: true,
|
||||
preserved_run_specific_values: [
|
||||
{
|
||||
side: "left",
|
||||
path: ["evidence_ids"],
|
||||
value: leftAnswer.evidence_ids,
|
||||
},
|
||||
{
|
||||
side: "right",
|
||||
path: ["evidence_ids"],
|
||||
value: rightAnswer.evidence_ids,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(leftAnswer.evidence_ids).not.toEqual(rightAnswer.evidence_ids);
|
||||
expect(leftAnswer.evidence_ids.retained_views[0]).toMatchObject({
|
||||
evidence_id: "ev_" + "1".repeat(64),
|
||||
parent_evidence_id: "ev_" + "1".repeat(63) + "0",
|
||||
});
|
||||
expect(leftAnswer.evidence_ids.native_summary).toBe(
|
||||
"ev_" + "1".repeat(63) + "5",
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -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",
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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",
|
||||
);
|
||||
});
|
||||
@@ -47,8 +47,8 @@ describe("compiled Windows reference-source import", () => {
|
||||
expect(result.json).toEqual(
|
||||
scenario.fullOutput
|
||||
? expect.objectContaining({
|
||||
ok: true,
|
||||
data: unsupportedHostOutput,
|
||||
ok: false,
|
||||
error: unsupportedHostOutput,
|
||||
})
|
||||
: unsupportedHostOutput,
|
||||
);
|
||||
@@ -113,16 +113,14 @@ describe("compiled reference-source import preflight failures", () => {
|
||||
message: expect.stringContaining(rootReason),
|
||||
};
|
||||
if (scenario.fullOutput) {
|
||||
// Incur's legacy wrapper remains unchanged; operation status is
|
||||
// conveyed by the exit code and command log, not this `ok` field.
|
||||
expect(result.json).toMatchObject({
|
||||
ok: true,
|
||||
data: invalidRootOutput,
|
||||
ok: false,
|
||||
error: invalidRootOutput,
|
||||
});
|
||||
} else {
|
||||
expect(result.json).toMatchObject(invalidRootOutput);
|
||||
}
|
||||
const messagePath = scenario.fullOutput ? "data.message" : "message";
|
||||
const messagePath = scenario.fullOutput ? "error.message" : "message";
|
||||
expect(result.json).toHaveProperty(
|
||||
messagePath,
|
||||
expect.stringContaining(
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"imports a legacy subtree of a Git checkout with its own source facts",
|
||||
async ({ cli }) => {
|
||||
const repository = await createTestTempDirectory("rea-reference-legacy-");
|
||||
const source = join(repository, "source");
|
||||
await mkdir(source);
|
||||
await Promise.all([
|
||||
// `.cjs` is CommonJS, so the strict-mode rule does not apply.
|
||||
writeFile(
|
||||
join(source, "legacy.cjs"),
|
||||
"var messages = {};\ndelete messages;\n",
|
||||
),
|
||||
// Deleting a plain binding is valid only in a sloppy-mode script.
|
||||
writeFile(
|
||||
join(source, "legacy.js"),
|
||||
"var messages = {};\ndelete messages;\n",
|
||||
),
|
||||
// An explicit module keeps the strict-mode error.
|
||||
writeFile(
|
||||
join(source, "module.mjs"),
|
||||
"var messages = {};\ndelete messages;\n",
|
||||
),
|
||||
writeFile(join(source, "index.php"), "<?php echo 'legacy';\n"),
|
||||
writeFile(join(source, "Program.cs"), "class Program {}\n"),
|
||||
]);
|
||||
const git = (...args: string[]) =>
|
||||
execFileOutput("git", args, { cwd: repository });
|
||||
await git("init", "--initial-branch=main");
|
||||
await git("add", ".");
|
||||
await git(
|
||||
"-c",
|
||||
"user.name=REA fixture",
|
||||
"-c",
|
||||
"user.email=fixture@example.invalid",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"-m",
|
||||
"fixture",
|
||||
);
|
||||
const head = (await git("rev-parse", "HEAD")).stdout.trim();
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["import-reference-source", source, "--json"],
|
||||
environment: {
|
||||
HOME: repository,
|
||||
XDG_CONFIG_HOME: repository,
|
||||
XDG_CACHE_HOME: repository,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const graph = historicalSourceGraphSchema.parse(result.json);
|
||||
expect(graph.parse_failures).toEqual([
|
||||
{
|
||||
path: "module.mjs",
|
||||
parser: "babel",
|
||||
reason: "Deleting local variable in strict mode. (2:0)",
|
||||
},
|
||||
]);
|
||||
// Outside `.mjs`/`.mts`/`.cjs` the mode stays unknown, not forced to script.
|
||||
const limitations = (path: string) =>
|
||||
graph.entries.find((entry) => entry.path === path)?.limitations;
|
||||
for (const path of ["legacy.js"])
|
||||
expect(limitations(path)).toEqual([
|
||||
"Strict-mode errors apply only if this file is an ES module: Deleting local variable in strict mode. (2:0)",
|
||||
]);
|
||||
expect(limitations("legacy.cjs")).toEqual([]);
|
||||
expect(graph.languages).toEqual(["C#", "JavaScript", "PHP"]);
|
||||
for (const path of ["Program.cs", "index.php"])
|
||||
expect(
|
||||
graph.entries.find((entry) => entry.path === path)?.classifications,
|
||||
).toContain("source");
|
||||
expect(graph.vcs).toEqual({ kind: "git", head, dirty: null });
|
||||
expect(graph.provenance.importer_version).toBe(
|
||||
PRODUCT_IDENTITY.packageVersion,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,138 @@
|
||||
import { Cli } from "incur";
|
||||
import { expect, it } from "vitest";
|
||||
import { registerSignalCommands } from "../../../src/cli/signalCommands.js";
|
||||
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";
|
||||
|
||||
it.each([
|
||||
{
|
||||
flags: ["--decoders", "uart", "--all_lines", "--line_limit", "20"],
|
||||
message: "mutually exclusive",
|
||||
},
|
||||
{
|
||||
flags: [
|
||||
"--decoders",
|
||||
"x".repeat(8192),
|
||||
"--input_format",
|
||||
"界".repeat(8192),
|
||||
],
|
||||
message: "32 KiB",
|
||||
},
|
||||
])(
|
||||
"rejects invalid selections before invoking the CLI service: $message",
|
||||
async ({ flags, message }) => {
|
||||
const cli = Cli.create("signal-selection-test", { sync: false });
|
||||
let called = false;
|
||||
registerSignalCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectDecoders: async () => {
|
||||
throw new Error("Unexpected discovery call");
|
||||
},
|
||||
decode: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not decode");
|
||||
},
|
||||
close: async () => {},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"decode-signal-recording",
|
||||
"recording.vcd",
|
||||
...flags,
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
expect(stdout).toContain(message);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"awaits cleanup retry and preserves completed output when retry failure is %s",
|
||||
async (failAgain) => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Completed decoder fixture", version: "1" },
|
||||
{
|
||||
operation: "decode_signal_recording",
|
||||
parameters: {},
|
||||
result: { annotations_text: "retained annotation" },
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
const original = new ProviderCleanupError(
|
||||
"sigrok-recording",
|
||||
["original-workspace"],
|
||||
{ reason: "original cleanup failure" },
|
||||
{ operation: "decode_signal_recording", partialObservation: evidence },
|
||||
);
|
||||
let closed = false;
|
||||
const cli = Cli.create("signal-cleanup-test", { sync: false });
|
||||
registerSignalCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectDecoders: async () => {
|
||||
throw new Error("Unexpected discovery call");
|
||||
},
|
||||
decode: async () => err(original),
|
||||
close: async () => {
|
||||
await Promise.resolve();
|
||||
closed = true;
|
||||
if (failAgain)
|
||||
throw new ProviderCleanupError(
|
||||
"sigrok-recording",
|
||||
["retry-workspace"],
|
||||
{ reason: "retry failed" },
|
||||
{ operation: "decode_signal_recording" },
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"decode-signal-recording",
|
||||
"recording.vcd",
|
||||
"--decoders",
|
||||
"uart",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
expect(closed).toBe(true);
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
partial_observation: evidence,
|
||||
resources: expect.arrayContaining(["original-workspace"]),
|
||||
},
|
||||
});
|
||||
if (failAgain)
|
||||
expect(output).toMatchObject({
|
||||
details: { resources: expect.arrayContaining(["retry-workspace"]) },
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,10 +1,11 @@
|
||||
import { readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { holdFirstFileRead } from "../../support/holdFirstFileRead.js";
|
||||
|
||||
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
|
||||
import {
|
||||
@@ -29,6 +30,8 @@ import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { readJsonObjectFile } from "../../../src/application/JsonInputFile.js";
|
||||
import { RegularFileChangedError } from "../../../src/filesystem/RegularFile.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
|
||||
|
||||
const snapshotFixture = (): AnalysisSnapshot => {
|
||||
const target = snapshotTarget(TARGET);
|
||||
@@ -227,20 +230,67 @@ describe("analysis snapshot member decoding", () => {
|
||||
`${" ".repeat(9 * 1024 * 1024)}${JSON.stringify(snapshot)}`,
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const reads = await holdFirstFileRead(path);
|
||||
onTestFinished(() => {
|
||||
controller.abort();
|
||||
reads.release();
|
||||
});
|
||||
const pending = readAnalysisSnapshot(path, controller.signal);
|
||||
const timer = setTimeout(() => controller.abort(), 1);
|
||||
await reads.firstRead;
|
||||
controller.abort();
|
||||
reads.release();
|
||||
try {
|
||||
expect(await pending).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(reads.readCount).toBe(1);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
const loaded = await readAnalysisSnapshot(path);
|
||||
if (!loaded.ok) throw loaded.error;
|
||||
expect(loaded.value).toEqual(snapshot);
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis snapshot file ownership", () => {
|
||||
it.each([false, true])(
|
||||
"retains the file owner when snapshot close fails (cancelled: %s)",
|
||||
async (cancelDuringClose) => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-cleanup-");
|
||||
const path = join(directory, "snapshot.json");
|
||||
await writeFile(path, JSON.stringify(snapshotFixture()));
|
||||
const controller = new AbortController();
|
||||
const cleanupCause = new Error("injected snapshot file close failure");
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementationOnce(async () => {
|
||||
if (cancelDuringClose) controller.abort();
|
||||
throw cleanupCause;
|
||||
});
|
||||
let failure: unknown;
|
||||
try {
|
||||
try {
|
||||
await readAnalysisSnapshot(
|
||||
path,
|
||||
cancelDuringClose ? controller.signal : undefined,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
failure = cause;
|
||||
}
|
||||
expect(failure).toBeInstanceOf(RegularFileCleanupFailure);
|
||||
if (!(failure instanceof RegularFileCleanupFailure))
|
||||
throw new Error("Expected the retained snapshot file handle owner");
|
||||
expect(failure.cleanupCause).toBe(cleanupCause);
|
||||
expect(failure.owner.handle.fd).toBeGreaterThanOrEqual(0);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
if (failure instanceof RegularFileCleanupFailure)
|
||||
await failure.owner.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects changed bytes between scans on the same descriptor", async () => {
|
||||
const directory = await createTestTempDirectory("rea-snapshot-changed-");
|
||||
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -227,6 +227,9 @@ describe("case-distinct APK resource names", () => {
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
expect(inventory.normalized_result).toMatchObject({
|
||||
coverage_status: "partial",
|
||||
});
|
||||
const result = projectAndroidApplicationEvidence({
|
||||
inventory_evidence: [inventory],
|
||||
});
|
||||
@@ -234,6 +237,13 @@ describe("case-distinct APK resource names", () => {
|
||||
requireSuccessfulProjection(result).normalized_result,
|
||||
);
|
||||
expect(projection.root_format).toBe("apk");
|
||||
expect(projection.coverage).toEqual({
|
||||
status: "partial",
|
||||
inventory_complete: true,
|
||||
});
|
||||
expect(projection.limitations).toContain(
|
||||
"Source inventory coverage is partial; absence is unknown.",
|
||||
);
|
||||
expect(projection.components.manifests).toHaveLength(1);
|
||||
expect(projection.components.dex).toHaveLength(1);
|
||||
expect(JSON.stringify(inventory)).toContain("res/2F.xml");
|
||||
|
||||
@@ -75,6 +75,42 @@ async function createCompleteAppleProjection() {
|
||||
}
|
||||
|
||||
describe("Apple application projection", () => {
|
||||
it("keeps a case-colliding real IPA inventory partial", async () => {
|
||||
const root = await createTestTempDirectory("rea-apple-case-collision-");
|
||||
const path = join(root, "CaseCollision.ipa");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add(
|
||||
"Payload/Example.app/Contents/Info.plist",
|
||||
new TextReader("upper"),
|
||||
);
|
||||
await writer.add(
|
||||
"Payload/Example.app/contents/Info.plist",
|
||||
new TextReader("lower"),
|
||||
);
|
||||
await writeFile(path, await writer.close());
|
||||
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
expect(inventory.normalized_result).toMatchObject({
|
||||
coverage_status: "partial",
|
||||
});
|
||||
const result = projectAppleApplicationEvidence({
|
||||
inventory_evidence: [inventory],
|
||||
});
|
||||
const projection = appleApplicationProjectionResultSchema.parse(
|
||||
requireSuccessfulProjection(result).normalized_result,
|
||||
);
|
||||
|
||||
expect(projection.coverage).toEqual({
|
||||
status: "partial",
|
||||
inventory_complete: true,
|
||||
});
|
||||
expect(projection.limitations).toContain(
|
||||
"Source inventory coverage is partial; absence is unknown.",
|
||||
);
|
||||
});
|
||||
|
||||
it("projects deterministic IPA components and bridge hypotheses from exact inventory Evidence", async () => {
|
||||
const root = await createTestTempDirectory("rea-apple-");
|
||||
const path = join(root, "Fixture.ipa");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { chmod, mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
artifactComparisonResultSchema,
|
||||
compareArtifacts,
|
||||
} from "../../../src/domain/artifactComparison.js";
|
||||
import { parseArtifactInventoryEvidence } from "../../../src/domain/artifactInventoryEvidence.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
|
||||
@@ -61,6 +62,187 @@ const changedArtifactComparison = async () => {
|
||||
};
|
||||
};
|
||||
|
||||
describe("leaf artifact comparison", () => {
|
||||
it("accepts persisted complete leaf inventory Evidence without coverage_status", async () => {
|
||||
const root = await createTestTempDirectory("rea-artifact-plist-compare-");
|
||||
const leftPath = join(root, "left.plist");
|
||||
const rightPath = join(root, "right.plist");
|
||||
const xml =
|
||||
'<?xml version="1.0"?><plist version="1.0"><dict><key>label</key><string>hello</string></dict></plist>';
|
||||
await Promise.all([writeFile(leftPath, xml), writeFile(rightPath, xml)]);
|
||||
const [left, right] = await Promise.all([
|
||||
observe(leftPath),
|
||||
observe(rightPath),
|
||||
]);
|
||||
// Persisted inventory Evidence predates coverage_status. The known leaf
|
||||
// notice remains complete when normalized at the inventory boundary.
|
||||
const parsed = artifactInventoryResultSchema.parse(left.normalized_result);
|
||||
const { coverage_status: _coverageStatus, ...legacyInventory } = parsed;
|
||||
const legacy = createEvidence(
|
||||
{
|
||||
path: left.subject!.local_path,
|
||||
sha256: left.subject!.digest.sha256,
|
||||
format: left.subject!.format,
|
||||
},
|
||||
PROVIDER,
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(legacyInventory),
|
||||
confidence: "observed",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
expect(compareArtifacts(legacy, right)).toMatchObject({
|
||||
status: "unchanged",
|
||||
summary: { unchanged: 1, unknown: 0 },
|
||||
changes: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps content and executable changes visible for complete plist roots", async () => {
|
||||
const root = await createTestTempDirectory("rea-artifact-plist-deltas-");
|
||||
const leftPath = join(root, "left.plist");
|
||||
const rightPath = join(root, "right.plist");
|
||||
const plist = (label: string) =>
|
||||
`<?xml version="1.0"?><plist version="1.0"><dict><key>label</key><string>${label}</string></dict></plist>`;
|
||||
await Promise.all([
|
||||
writeFile(leftPath, plist("hello"), { mode: 0o644 }),
|
||||
writeFile(rightPath, plist("world"), { mode: 0o644 }),
|
||||
]);
|
||||
const [left, changed] = await Promise.all([
|
||||
observe(leftPath),
|
||||
observe(rightPath),
|
||||
]);
|
||||
expect(compareArtifacts(left, changed)).toMatchObject({
|
||||
status: "changed",
|
||||
summary: { changed: 1, unknown: 0 },
|
||||
changes: [
|
||||
expect.objectContaining({
|
||||
logical_path: ".",
|
||||
classification: "changed",
|
||||
dimensions: expect.arrayContaining(["content"]),
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
if (process.platform !== "win32") {
|
||||
await writeFile(rightPath, plist("hello"), { mode: 0o644 });
|
||||
await chmod(rightPath, 0o755);
|
||||
const executable = await observe(rightPath);
|
||||
expect(compareArtifacts(left, executable)).toMatchObject({
|
||||
status: "changed",
|
||||
summary: { changed: 1, unknown: 0 },
|
||||
changes: [
|
||||
expect.objectContaining({
|
||||
logical_path: ".",
|
||||
classification: "changed",
|
||||
dimensions: expect.arrayContaining(["executable"]),
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("artifact inventory coverage", () => {
|
||||
it("keeps explicit and legacy unknown coverage fail-closed", async () => {
|
||||
const root = await createTestTempDirectory("rea-artifact-coverage-");
|
||||
const path = join(root, "complete.plist");
|
||||
await writeFile(
|
||||
path,
|
||||
'<?xml version="1.0"?><plist version="1.0"><dict/></plist>',
|
||||
);
|
||||
const complete = await observe(path);
|
||||
const graph = artifactInventoryResultSchema.parse(
|
||||
complete.normalized_result,
|
||||
);
|
||||
const partial = createEvidence(
|
||||
{
|
||||
path: complete.subject!.local_path,
|
||||
sha256: complete.subject!.digest.sha256,
|
||||
format: complete.subject!.format,
|
||||
},
|
||||
PROVIDER,
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse({ ...graph, coverage_status: "partial" }),
|
||||
confidence: "observed",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
expect(parseArtifactInventoryEvidence(partial).inventory.complete).toBe(
|
||||
true,
|
||||
);
|
||||
expect(compareArtifacts(partial, partial)).toMatchObject({
|
||||
status: "unknown",
|
||||
summary: { unchanged: 0, unknown: 1 },
|
||||
});
|
||||
|
||||
const { coverage_status: _coverageStatus, ...legacyGraph } = graph;
|
||||
const unknownLegacy = createEvidence(
|
||||
{
|
||||
path: complete.subject!.local_path,
|
||||
sha256: complete.subject!.digest.sha256,
|
||||
format: complete.subject!.format,
|
||||
},
|
||||
PROVIDER,
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse({
|
||||
...legacyGraph,
|
||||
limitations: ["Producer omitted unexamined child entries."],
|
||||
}),
|
||||
confidence: "observed",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
expect(compareArtifacts(unknownLegacy, unknownLegacy)).toMatchObject({
|
||||
status: "unknown",
|
||||
summary: { unchanged: 0, unknown: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects inventory fragments that disagree on producer coverage", async () => {
|
||||
const parent = await createTestTempDirectory("rea-artifact-page-coverage-");
|
||||
const path = join(parent, "fixture.app");
|
||||
await mkdir(path);
|
||||
await writeFile(join(path, "main.js"), "main();");
|
||||
const source = await observe(path);
|
||||
const fragments = fragmentInventoryEvidence(source, 2);
|
||||
const firstFragment = fragments[0];
|
||||
const fragment = fragments[1];
|
||||
if (firstFragment === undefined || fragment === undefined)
|
||||
throw new Error("Missing test fragment");
|
||||
const fragmentGraph = artifactInventoryResultSchema.parse(
|
||||
fragment.normalized_result,
|
||||
);
|
||||
const mixed = createEvidence(
|
||||
{
|
||||
path: fragment.subject!.local_path,
|
||||
sha256: fragment.subject!.digest.sha256,
|
||||
format: fragment.subject!.format,
|
||||
},
|
||||
PROVIDER,
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: fragment.parameters,
|
||||
result: jsonValueSchema.parse({
|
||||
...fragmentGraph,
|
||||
coverage_status: "partial",
|
||||
}),
|
||||
confidence: "derived",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
expect(() =>
|
||||
parseArtifactInventoryEvidence([firstFragment, mixed]),
|
||||
).toThrow("Artifact inventory pages disagree on coverage status");
|
||||
});
|
||||
});
|
||||
|
||||
describe("artifact comparison", () => {
|
||||
it("classifies deterministic path changes and cites both inventories", async () => {
|
||||
const firstObservation = await changedArtifactComparison();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
@@ -11,10 +11,46 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { ZipArtifactReader } from "../../../src/artifacts/ZipArtifactReader.js";
|
||||
import { withArtifactClient } from "../../support/artifactClientScope.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
artifactInventoryResultSchema,
|
||||
} from "../../../src/domain/artifactGraph.js";
|
||||
|
||||
it("completes an empty ZIP extraction with an empty identity", async () => {
|
||||
const root = await createTestTempDirectory("rea-empty-artifact-extraction-");
|
||||
const archive = join(root, "empty.zip");
|
||||
await writeOrderedZip(archive, []);
|
||||
const archiveTarget = await parseBinaryTarget(archive);
|
||||
if (!archiveTarget.ok) throw archiveTarget.error;
|
||||
|
||||
const output = join(root, "output");
|
||||
const result = await withArtifactClient(archiveTarget.value, (client) =>
|
||||
client.execute("extract_artifact", { output_root: output }),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
const extraction = artifactExtractionResultSchema.parse(result.value.result);
|
||||
expect(extraction.extraction_manifest).toMatchObject({
|
||||
source_manifest_id: extraction.manifest.manifest_id,
|
||||
selected_occurrence_ids: [],
|
||||
});
|
||||
expect(extraction.artifacts).toEqual([]);
|
||||
expect(extraction.containment_verified).toBe(true);
|
||||
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]),
|
||||
@@ -43,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");
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "../../../src/application/AppBundleExecutable.js";
|
||||
import {
|
||||
dosMz,
|
||||
elf,
|
||||
fat,
|
||||
pe,
|
||||
thinMach,
|
||||
@@ -245,6 +246,17 @@ describe("binary target I/O: package classification", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies a binary plist by its magic under any extension", async () => {
|
||||
const directory = await createTestTempDirectory("rea-bplist-target-");
|
||||
const path = join(directory, "Model.archive");
|
||||
await writeFile(path, buildBinary({ $archiver: "NSKeyedArchiver" }));
|
||||
const result = await parseBinaryTarget(path);
|
||||
expect(result.ok && result.value).toMatchObject({
|
||||
kind: "artifact",
|
||||
format: "plist",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not trust a ZIP-family extension without ZIP magic", async () => {
|
||||
const directory = await createTestTempDirectory("rea-fake-archive-");
|
||||
const path = join(directory, "fake.zip");
|
||||
@@ -793,6 +805,32 @@ describe("binary Info.plist app bundle targets", () => {
|
||||
});
|
||||
|
||||
describe("DOS binary target I/O", () => {
|
||||
it("resolves a short-header PE signature beyond the bounded prefix", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-short-stub-pe-target-",
|
||||
);
|
||||
const path = join(directory, "short-stub.dll");
|
||||
const offset = 8192;
|
||||
const stub = dosMz(64);
|
||||
stub.writeUInt32LE(offset, 60);
|
||||
const peRecord = pe(0x8664, offset, 0x2002).subarray(offset);
|
||||
const bytes = Buffer.concat([
|
||||
stub,
|
||||
Buffer.alloc(offset - stub.length),
|
||||
peRecord,
|
||||
]);
|
||||
await writeFile(path, bytes);
|
||||
|
||||
expect(await parseBinaryTarget(path)).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
format: "pe",
|
||||
architecture: "x86_64",
|
||||
executableRole: "shared-library",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("validates a complete DOS file beyond the initial metadata probe", async () => {
|
||||
const directory = await createTestTempDirectory("rea-dos-target-");
|
||||
const path = join(directory, "legacy.exe");
|
||||
@@ -809,3 +847,40 @@ describe("DOS binary target I/O", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"EI_VERSION",
|
||||
(bytes: Buffer) => {
|
||||
bytes[6] = 0;
|
||||
},
|
||||
],
|
||||
[
|
||||
"e_version",
|
||||
(bytes: Buffer) => {
|
||||
bytes.writeUInt32LE(0, 20);
|
||||
},
|
||||
],
|
||||
[
|
||||
"e_ehsize",
|
||||
(bytes: Buffer) => {
|
||||
bytes.writeUInt16LE(51, 40);
|
||||
},
|
||||
],
|
||||
])(
|
||||
"rejects an ELF with malformed %s during public target opening",
|
||||
async (_name, corrupt) => {
|
||||
const directory = await createTestTempDirectory("rea-invalid-elf-header-");
|
||||
const path = join(directory, "invalid.elf");
|
||||
const bytes = elf(1, 1, 3);
|
||||
corrupt(bytes);
|
||||
await writeFile(path, bytes);
|
||||
expect(await parseBinaryTarget(path)).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BinaryTargetError",
|
||||
constraint: "file_format_rejected",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
chmod,
|
||||
cp,
|
||||
mkdir,
|
||||
readFile,
|
||||
@@ -6,7 +7,8 @@ import {
|
||||
rename,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
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"]);
|
||||
@@ -157,17 +234,152 @@ it("retains complete checks when implementation is renamed into documentation",
|
||||
const head = await commit(directory);
|
||||
expect(await classify(directory, base, head)).toMatchObject({
|
||||
code: true,
|
||||
package: true,
|
||||
runtime: true,
|
||||
});
|
||||
});
|
||||
|
||||
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",
|
||||
@@ -268,6 +488,94 @@ it.each([
|
||||
{ code: false, evm: true, browser: false, package: false },
|
||||
],
|
||||
["unknown-input", { code: true, package: true, evm: true, browser: true }],
|
||||
[
|
||||
"src/application/Example.ts",
|
||||
{
|
||||
code: true,
|
||||
runtime: true,
|
||||
package: false,
|
||||
apple: false,
|
||||
evm: false,
|
||||
browser: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"bridge/ghidra/Example.java",
|
||||
{ code: true, runtime: true, package: false, apple: false },
|
||||
],
|
||||
[
|
||||
"src/native/AppleExample.ts",
|
||||
{ code: true, runtime: true, apple: true, package: false, evm: false },
|
||||
],
|
||||
[
|
||||
"scripts/verify/apple/example.mjs",
|
||||
{ code: true, apple: true, package: false, runtime: false },
|
||||
],
|
||||
[
|
||||
"src/windows/Example.ts",
|
||||
{ code: true, runtime: true, package: true, apple: false, evm: false },
|
||||
],
|
||||
["install.sh", { code: true, runtime: true, package: true, evm: false }],
|
||||
[
|
||||
".agents/skills/reverse-engineer-anything/SKILL.md",
|
||||
{ code: true, runtime: true, docs: true, package: false, evm: false },
|
||||
],
|
||||
[
|
||||
"scripts/verify-real-ghidra.mjs",
|
||||
{ code: true, runtime: false, package: false, apple: false, evm: false },
|
||||
],
|
||||
[
|
||||
"scripts/verify-claude-client.mjs",
|
||||
{ code: true, runtime: false, package: false, browser: false },
|
||||
],
|
||||
[
|
||||
"tests/boundary/process/darwinProcessRunTokenReader.test.ts",
|
||||
{ code: true, apple: true, package: false, runtime: false },
|
||||
],
|
||||
[
|
||||
"tests/boundary/cli/nativePlistCli.test.ts",
|
||||
{ code: true, apple: true, package: false, runtime: false },
|
||||
],
|
||||
[
|
||||
"tests/boundary/filesystem/windowsNpxRegistration.test.ts",
|
||||
{ code: true, package: true, runtime: true, apple: false },
|
||||
],
|
||||
[
|
||||
"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]);
|
||||
@@ -310,6 +618,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"],
|
||||
@@ -326,7 +680,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(
|
||||
@@ -363,10 +719,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" },
|
||||
@@ -386,6 +751,10 @@ it("rejects skipped selected work while allowing unselected lanes to skip", asyn
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
".github/workflows/sqlite-runtime.yml",
|
||||
{ workflows: true, code: true, package: false, website: false },
|
||||
],
|
||||
[
|
||||
".github/workflows/real-termux.yml",
|
||||
{ workflows: true, code: false, package: false, website: false },
|
||||
@@ -398,12 +767,23 @@ 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 },
|
||||
],
|
||||
["docs/.vitepress/config.ts", { code: false, docs: true, package: false }],
|
||||
["CHANGELOG.md", { code: false, docs: true, package: false }],
|
||||
["SECURITY.md", { code: false, docs: true, package: false }],
|
||||
[".github/pull_request_template.md", { code: false, docs: true }],
|
||||
[
|
||||
".github/ISSUE_TEMPLATE/bug.yml",
|
||||
{ code: false, docs: true, workflows: false },
|
||||
],
|
||||
["native/windows/README.md", { code: false, docs: true, package: false }],
|
||||
[
|
||||
"src/contracts/evm/tools.ts",
|
||||
{ code: true, docs: true, evm: true, package: false },
|
||||
@@ -462,6 +842,43 @@ it("fails without emitting a plan when package metadata is malformed", async ()
|
||||
expect(await readFile(join(directory, "scope-output"), "utf8")).toBe("");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"verify:keyed-archive",
|
||||
"npm run build:cached && node scripts/verify/apple/keyed-archive.mjs",
|
||||
{ apple: true, package: false, evm: false, browser: false },
|
||||
],
|
||||
[
|
||||
"verify:inspector",
|
||||
"npm run build:cached && node scripts/verify/inspector/runtime-observation.mjs",
|
||||
{ package: true, apple: false, evm: false, browser: false },
|
||||
],
|
||||
[
|
||||
"verify:windows-native",
|
||||
"node scripts/verify-windows-native.mjs",
|
||||
{ package: true, apple: false, evm: false, browser: false },
|
||||
],
|
||||
])(
|
||||
"routes the %s script to its glob-owned lane",
|
||||
async (script, command, expected) => {
|
||||
const { directory } = await fixture();
|
||||
const base = await change(
|
||||
directory,
|
||||
["package.json"],
|
||||
JSON.stringify({ scripts: { [script]: command } }),
|
||||
);
|
||||
const head = await change(
|
||||
directory,
|
||||
["package.json"],
|
||||
JSON.stringify({ scripts: { [script]: `${command} --verbose` } }),
|
||||
);
|
||||
expect(await classify(directory, base, head)).toMatchObject({
|
||||
code: true,
|
||||
...expected,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("retains a broad fallback when a provider script adds shared shell work", async () => {
|
||||
const { directory } = await fixture();
|
||||
const before = {
|
||||
@@ -490,8 +907,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,
|
||||
});
|
||||
@@ -505,7 +924,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,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -538,3 +964,121 @@ it.each(["compile:termux", "build:termux", "build:termux:run"])(
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const INTEL_HOST = {
|
||||
os: "macos-15-intel",
|
||||
platform: "darwin",
|
||||
architecture: "x64",
|
||||
};
|
||||
|
||||
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()) });
|
||||
const hosts = async (event: string, full: boolean) =>
|
||||
matrix.parse((await classify(directory, base, head, event, full)).matrix)
|
||||
.include;
|
||||
const pullRequest = await hosts("pull_request", false);
|
||||
expect(pullRequest).toHaveLength(3);
|
||||
expect(pullRequest).not.toContainEqual(INTEL_HOST);
|
||||
expect(await hosts("pull_request", true)).toContainEqual(INTEL_HOST);
|
||||
expect(await hosts("push", false)).not.toContainEqual(INTEL_HOST);
|
||||
for (const event of ["schedule", "workflow_dispatch"])
|
||||
expect(await hosts(event, false)).toContainEqual(INTEL_HOST);
|
||||
});
|
||||
|
||||
const workflowFile = async (name: string): Promise<unknown> =>
|
||||
parse(
|
||||
await readFile(
|
||||
new URL(`../../../.github/workflows/${name}`, import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
|
||||
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()),
|
||||
});
|
||||
|
||||
const loadScopes = async () =>
|
||||
scopesSchema.parse(
|
||||
await import(
|
||||
new URL("../../../scripts/ci/scopes.mjs", import.meta.url).href
|
||||
),
|
||||
);
|
||||
|
||||
const stepRuns = z.object({
|
||||
on: z.unknown(),
|
||||
jobs: z.record(
|
||||
z.string(),
|
||||
z.object({
|
||||
steps: z.array(z.object({ run: z.string().optional() })).optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
it("owns every explicit native-host test path with the lane that runs it", async () => {
|
||||
const { SCOPES } = await loadScopes();
|
||||
const ci = stepRuns.parse(await workflowFile("ci.yml"));
|
||||
const listed = (job: string) =>
|
||||
(ci.jobs[job]?.steps ?? [])
|
||||
.flatMap((step) => step.run?.split(/\s+/) ?? [])
|
||||
.filter((token) => token.endsWith(".test.ts"));
|
||||
const unowned = (job: string, scope: string) =>
|
||||
listed(job).filter(
|
||||
(path) =>
|
||||
!(SCOPES[scope] ?? []).some((pattern) => matchesGlob(path, pattern)),
|
||||
);
|
||||
expect(listed("apple-artifacts").length).toBeGreaterThan(0);
|
||||
expect(listed("windows-curated").length).toBeGreaterThan(0);
|
||||
expect(unowned("apple-artifacts", "apple")).toEqual([]);
|
||||
expect(unowned("windows-curated", "package")).toEqual([]);
|
||||
});
|
||||
|
||||
it("never runs a manual-only verifier from an automatic workflow", async () => {
|
||||
const { MANUAL_VERIFIERS } = await loadScopes();
|
||||
const scripts = z
|
||||
.object({ scripts: z.record(z.string(), z.string()) })
|
||||
.parse(
|
||||
JSON.parse(
|
||||
await readFile(
|
||||
new URL("../../../package.json", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
).scripts;
|
||||
const directory = new URL("../../../.github/workflows/", import.meta.url);
|
||||
const commands: string[] = [];
|
||||
for (const name of await readdir(directory)) {
|
||||
const workflow = stepRuns.parse(await workflowFile(name));
|
||||
const triggers = JSON.stringify(workflow.on);
|
||||
if (
|
||||
name !== "ci.yml" &&
|
||||
!triggers.includes("workflow_call") &&
|
||||
!triggers.includes("pull_request")
|
||||
)
|
||||
continue;
|
||||
for (const job of Object.values(workflow.jobs))
|
||||
for (const step of job.steps ?? []) if (step.run) commands.push(step.run);
|
||||
}
|
||||
const files = new Set<string>();
|
||||
const seen = new Set<string>();
|
||||
while (commands.length) {
|
||||
const command = commands.pop() ?? "";
|
||||
for (const [, file] of command.matchAll(/\b(scripts\/[\w./-]+\.mjs)\b/g))
|
||||
if (file) files.add(file);
|
||||
for (const [, script] of command.matchAll(/npm run ([\w:.-]+)/g)) {
|
||||
if (!script || seen.has(script)) continue;
|
||||
seen.add(script);
|
||||
const body = scripts[script];
|
||||
if (body) commands.push(body);
|
||||
}
|
||||
}
|
||||
expect(files.size).toBeGreaterThan(0);
|
||||
expect(
|
||||
[...files].filter((file) =>
|
||||
MANUAL_VERIFIERS.some((pattern) => matchesGlob(file, pattern)),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -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_");
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,506 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, it } from "vitest";
|
||||
import { parse } from "yaml";
|
||||
import { z } from "zod";
|
||||
import { executeWorkflowFixture } from "../../support/workflowGit.js";
|
||||
|
||||
const workflow = async (filename = "ci.yml") =>
|
||||
z
|
||||
.object({
|
||||
jobs: z.record(
|
||||
z.string(),
|
||||
z
|
||||
.object({
|
||||
needs: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
),
|
||||
})
|
||||
.parse(
|
||||
parse(
|
||||
await readFile(
|
||||
new URL(`../../../.github/workflows/${filename}`, import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
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(),
|
||||
with: z
|
||||
.object({ name: z.string().optional(), path: z.string().optional() })
|
||||
.optional(),
|
||||
}),
|
||||
);
|
||||
const uploads = steps.parse((await workflow()).jobs.build?.steps).filter(
|
||||
(step) =>
|
||||
step.uses?.startsWith("actions/upload-artifact@") &&
|
||||
step.with?.path
|
||||
?.split(/\r?\n/u)
|
||||
.map((path) => path.trim())
|
||||
.includes("dist/"),
|
||||
);
|
||||
expect(uploads).toHaveLength(1);
|
||||
const name = z.string().min(1).parse(uploads[0]?.with?.name);
|
||||
const downloads = steps
|
||||
.parse((await workflow("sqlite-runtime.yml")).jobs.sqlite?.steps)
|
||||
.filter((step) => step.uses?.startsWith("actions/download-artifact@"));
|
||||
expect(downloads).toHaveLength(1);
|
||||
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) };
|
||||
};
|
||||
|
||||
it("makes the required gate wait for every CI lane, including future additions", async () => {
|
||||
const { jobs, needs } = await requiredNeeds();
|
||||
expect(new Set(needs)).toEqual(
|
||||
new Set(Object.keys(jobs).filter((name) => name !== "required")),
|
||||
);
|
||||
});
|
||||
|
||||
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 === "actions/download-artifact@v4",
|
||||
);
|
||||
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],
|
||||
["true", "cancelled", false],
|
||||
["true", "skipped", false],
|
||||
["true", "missing", false],
|
||||
["false", "skipped", true],
|
||||
["false", "failure", false],
|
||||
] as const)(
|
||||
"enforces mapped required scopes for selected=%s and result=%s",
|
||||
async (selected, result, passes) => {
|
||||
const workflow = await requiredNeeds();
|
||||
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({
|
||||
changes: { result: "success", outputs },
|
||||
static: { result: "success" },
|
||||
test: { result: "success" },
|
||||
}),
|
||||
CI_QUALIFICATION_DIRECTORY: "",
|
||||
},
|
||||
},
|
||||
);
|
||||
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("");
|
||||
});
|
||||
@@ -0,0 +1,459 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { 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);
|
||||
const stepsSchema = z.array(
|
||||
z.object({
|
||||
name: z.string().optional(),
|
||||
run: z.string().optional(),
|
||||
uses: z.string().optional(),
|
||||
if: z.string().optional(),
|
||||
env: z.record(z.string(), z.string()).optional(),
|
||||
with: z.record(z.string(), z.unknown()).optional(),
|
||||
}),
|
||||
);
|
||||
const workflow = async () =>
|
||||
z
|
||||
.object({
|
||||
jobs: z.object({
|
||||
test: z.object({ steps: stepsSchema }),
|
||||
build: z.object({ steps: stepsSchema }),
|
||||
docs: z.object({ steps: stepsSchema }),
|
||||
static: z.object({ steps: stepsSchema }),
|
||||
}),
|
||||
})
|
||||
.parse(
|
||||
parse(
|
||||
await readFile(
|
||||
new URL("../../../.github/workflows/ci.yml", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
).jobs;
|
||||
|
||||
it("collects failed-shard diagnostics before enforcing the shard result", async () => {
|
||||
const steps = (await workflow()).test!.steps;
|
||||
const merge = steps.findIndex((step) => step.run?.includes("test:ci:merge"));
|
||||
const upload = steps.findIndex((step) => step.with?.name === "test-results");
|
||||
const gate = steps.findIndex(
|
||||
(step) => step.env?.SHARD_RESULT && step.run?.includes("test "),
|
||||
);
|
||||
expect(merge).toBeGreaterThan(0);
|
||||
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", ""]) {
|
||||
await expect(
|
||||
execute("bash", ["-c", command], {
|
||||
env: { ...process.env, CODE_REQUIRED: "true", SHARD_RESULT: result },
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 1 });
|
||||
}
|
||||
await expect(
|
||||
execute("bash", ["-c", command], {
|
||||
env: { ...process.env, CODE_REQUIRED: "false", SHARD_RESULT: "skipped" },
|
||||
}),
|
||||
).resolves.toMatchObject({ stderr: "" });
|
||||
});
|
||||
|
||||
it("keeps diagnosis available after merge failure and publishes only complete successful history", async () => {
|
||||
const steps = (await workflow()).test!.steps;
|
||||
const diagnosis = steps.find((step) => step.with?.name === "test-results");
|
||||
expect(diagnosis?.if).toContain("!cancelled()");
|
||||
expect(diagnosis?.if).not.toContain("success()");
|
||||
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 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 () => {
|
||||
const jobs = await workflow();
|
||||
const scripts = z
|
||||
.object({ scripts: z.record(z.string(), z.string()) })
|
||||
.parse(
|
||||
JSON.parse(
|
||||
await readFile(
|
||||
new URL("../../../package.json", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
).scripts;
|
||||
expect(
|
||||
jobs.docs.steps.some((step) => step.run === "npm run docs:check"),
|
||||
).toBe(true);
|
||||
expect(scripts["docs:check"]).toContain(
|
||||
"tests/conformance/readmeConsistency.test.ts",
|
||||
);
|
||||
const producer = jobs.static.steps.find(
|
||||
(step) => step.run === "npm run test:python",
|
||||
);
|
||||
expect(producer?.if).toBe("needs.changes.outputs.code == 'true'");
|
||||
expect(scripts["test:python"]).toContain(
|
||||
"bridge/native/test_rea_lldb_tracer.py",
|
||||
);
|
||||
});
|
||||
|
||||
it("exports portable timing history and removes it on a failed, partial, or invalid rerun", async () => {
|
||||
const root = await createTestTempDirectory("rea-ci-report-");
|
||||
const summary = join(root, "summary.md");
|
||||
const history = join(root, ".cache/ci-test-history/test-results.json");
|
||||
const report = {
|
||||
version: 1,
|
||||
success: true,
|
||||
files: [
|
||||
{
|
||||
name: join(root, "tests/slow.test.ts"),
|
||||
durationMs: 100,
|
||||
phases: {
|
||||
execution: 20,
|
||||
preparation: 20,
|
||||
environment: 10,
|
||||
imports: 40,
|
||||
setup: 10,
|
||||
},
|
||||
},
|
||||
{ name: join(root, "tests/fast.test.ts"), durationMs: 10 },
|
||||
],
|
||||
};
|
||||
const run = async (value: unknown, shards = "success", merge = "success") => {
|
||||
await writeFile(join(root, "test-timings.json"), JSON.stringify(value));
|
||||
await writeFile(summary, "");
|
||||
return execute(process.execPath, [fileURLToPath(script)], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_STEP_SUMMARY: summary,
|
||||
SHARD_RESULT: shards,
|
||||
MERGE_RESULT: merge,
|
||||
},
|
||||
});
|
||||
};
|
||||
await run(report);
|
||||
const contents = await readFile(history, "utf8");
|
||||
expect(contents).not.toContain("phases");
|
||||
expect(contents).not.toContain("startTime");
|
||||
expect(contents).not.toContain(root);
|
||||
expect(
|
||||
parseTestDurations(contents, resolve(root, "different-checkout")),
|
||||
).toEqual(
|
||||
new Map([
|
||||
["tests/slow.test.ts", 100],
|
||||
["tests/fast.test.ts", 10],
|
||||
]),
|
||||
);
|
||||
for (const [value, shards, merge] of [
|
||||
[{ ...report, success: false }, "failure", "failure"],
|
||||
[report, "cancelled", "success"],
|
||||
[report, "success", "failure"],
|
||||
] as const) {
|
||||
await run(report);
|
||||
await run(value, shards, merge);
|
||||
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await readFile(summary, "utf8")).toContain("diagnostic only");
|
||||
}
|
||||
await run(report);
|
||||
await expect(
|
||||
run({
|
||||
...report,
|
||||
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,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -37,6 +37,22 @@ const getClients = (home: string) =>
|
||||
);
|
||||
|
||||
describe("additional client configuration dialects", () => {
|
||||
it("treats an empty XDG config home as unset for OpenCode setup", async () => {
|
||||
const home = await createTestTempDirectory("rea-opencode-empty-xdg-");
|
||||
const client = supportedClients(home, "linux", {
|
||||
XDG_CONFIG_HOME: "",
|
||||
}).find(({ name }) => name === "opencode");
|
||||
const expectedPath = join(home, ".config/opencode/opencode.json");
|
||||
if (client === undefined) throw new Error("missing opencode client");
|
||||
|
||||
expect(client.configPath).toBe(expectedPath);
|
||||
expect(client.configPaths).toContain(expectedPath);
|
||||
expect(
|
||||
await configureClientConfiguration(client, {}, command),
|
||||
).toMatchObject({ status: "configured" });
|
||||
expect(await readFile(expectedPath, "utf8")).toContain('"mcp"');
|
||||
});
|
||||
|
||||
it.each([
|
||||
"opencode",
|
||||
"antigravity",
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import {
|
||||
chmod,
|
||||
copyFile,
|
||||
lstat,
|
||||
mkdir,
|
||||
@@ -21,6 +22,7 @@ import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
|
||||
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { readConfigurationFile } from "../../../src/application/ClientConfigurationFiles.js";
|
||||
import {
|
||||
detectClients,
|
||||
systemSetupHost,
|
||||
@@ -63,10 +65,13 @@ describe("client configuration filesystem lifecycle", () => {
|
||||
"commandcode",
|
||||
"qwen_code",
|
||||
"vscode",
|
||||
"trae",
|
||||
"grok_build",
|
||||
"omp",
|
||||
"pi",
|
||||
"hermes",
|
||||
"qoder",
|
||||
"zcode",
|
||||
"dsh",
|
||||
"grok_bot",
|
||||
]);
|
||||
@@ -1526,6 +1531,68 @@ describe("client configuration filesystem removal", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("removes emptied skill directories and keeps ones with user files", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-skill-dirs-");
|
||||
roots.push(home);
|
||||
const shared = join(home, ".agents/skills/reverse-engineer-anything");
|
||||
const claude = join(home, ".claude/skills/reverse-engineer-anything");
|
||||
for (const root of [shared, claude]) {
|
||||
await mkdir(join(root, "references"), { recursive: true });
|
||||
await writeFile(join(root, "SKILL.md"), ownedSkillManifest);
|
||||
await writeFile(
|
||||
join(root, "references/evidence-workflows.md"),
|
||||
"managed",
|
||||
);
|
||||
}
|
||||
await writeFile(join(claude, "notes.md"), "user");
|
||||
|
||||
const result = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, undefined, {
|
||||
HOME: home,
|
||||
CLAUDE_CONFIG_DIR: join(home, ".claude"),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("complete");
|
||||
await expect(lstat(shared)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(lstat(join(claude, "references"))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
expect(await readFile(join(claude, "notes.md"), "utf8")).toBe("user");
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"reports an emptied skill directory that cannot be removed",
|
||||
async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-skill-perm-");
|
||||
roots.push(home);
|
||||
const parent = join(home, ".agents/skills");
|
||||
const root = join(parent, "reverse-engineer-anything");
|
||||
await mkdir(join(root, "references"), { recursive: true });
|
||||
await writeFile(join(root, "SKILL.md"), ownedSkillManifest);
|
||||
await chmod(parent, 0o555);
|
||||
try {
|
||||
const result = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, undefined, { HOME: home }),
|
||||
);
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "skill",
|
||||
status: "failed",
|
||||
detail: expect.stringContaining(
|
||||
`Managed skill directory could not be removed: ${root}.`,
|
||||
),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await chmod(parent, 0o755);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("removes an owned entry through a symlink without replacing it", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-symlink-");
|
||||
roots.push(home);
|
||||
@@ -1593,6 +1660,37 @@ describe("uninstall configuration preflight", () => {
|
||||
expect(await readFile(config, "utf8")).toBe("not-json");
|
||||
});
|
||||
|
||||
it.each([
|
||||
['{"mcpServers":null,"keep":1}', '"mcpServers" must be an object'],
|
||||
["[]", "The configuration root must be an object"],
|
||||
['{"mcpServers":"x"}', '"mcpServers" must be an object'],
|
||||
])(
|
||||
"names the structural problem in valid JSON %s",
|
||||
async (content, problem) => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-shape-");
|
||||
roots.push(home);
|
||||
const config = join(home, ".cursor/mcp.json");
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
await writeFile(config, content);
|
||||
expect(await readConfigurationFile(config, "json")).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "malformed",
|
||||
detail: `Configuration ${config} is malformed: ${problem}`,
|
||||
},
|
||||
});
|
||||
const result = await runUninstall(false, systemUninstallHost(home));
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual({
|
||||
name: "cursor",
|
||||
status: "failed",
|
||||
detail: `Configuration was not changed: ${problem}. Repair it, then rerun uninstall.`,
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(content);
|
||||
await expect(readFile(`${config}.rea.backup`, "utf8")).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it("stops before any removal when one client configuration is malformed", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-stop-");
|
||||
roots.push(home);
|
||||
|
||||
@@ -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"),
|
||||
});
|
||||
});
|
||||
@@ -39,24 +39,27 @@ const bundle = (result = true) =>
|
||||
),
|
||||
]);
|
||||
|
||||
it("returns import cancellation before inspecting a selected path", async () => {
|
||||
const root = await createTestTempDirectory("rea-import-pre-cancel-");
|
||||
const controller = new AbortController();
|
||||
controller.abort(new Error("cancel before import"));
|
||||
expect(
|
||||
await readImmutableEvidenceBundle(
|
||||
join(root, "missing.json"),
|
||||
controller.signal,
|
||||
),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "import_evidence_bundle",
|
||||
},
|
||||
});
|
||||
expect(await readdir(root)).toEqual([]);
|
||||
});
|
||||
it.each([
|
||||
["immutable", readImmutableEvidenceBundle],
|
||||
["mutable", readEvidenceBundle],
|
||||
] as const)(
|
||||
"cancels a %s bundle read before opening its selected path",
|
||||
async (_, read) => {
|
||||
const root = await createTestTempDirectory("rea-bundle-pre-cancel-");
|
||||
const controller = new AbortController();
|
||||
controller.abort(new Error("cancel before bundle read"));
|
||||
expect(
|
||||
await read(join(root, "missing.json"), controller.signal),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "import_evidence_bundle",
|
||||
},
|
||||
});
|
||||
expect(await readdir(root)).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the failed-close owner when import is also cancelled", async () => {
|
||||
const root = await createTestTempDirectory("rea-import-cancel-cleanup-");
|
||||
@@ -431,21 +434,8 @@ describe("evidence bundle filesystem adapter", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("names the failed bundle constraint for a single record or schema mismatch", async () => {
|
||||
it("names schema mismatches that prevent bundle parsing", async () => {
|
||||
const directory = await createTestTempDirectory("rea-evidence-");
|
||||
const record = bundle().records[0];
|
||||
const single = join(directory, "record.json");
|
||||
await writeFile(single, JSON.stringify(record));
|
||||
expect(await readEvidenceBundle(single)).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "EvidenceIntegrityError",
|
||||
userMessage: expect.stringContaining(
|
||||
`this JSON is one Evidence record (${String(record?.evidence_id)})`,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const partial = join(directory, "partial.json");
|
||||
await writeFile(partial, JSON.stringify({ evidence_id: "typo" }));
|
||||
const rejected = await readEvidenceBundle(partial);
|
||||
@@ -474,3 +464,38 @@ describe("evidence bundle filesystem adapter", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("standalone Evidence bundle inputs", () => {
|
||||
it("classifies a record only after authenticating it", async () => {
|
||||
const directory = await createTestTempDirectory("rea-evidence-");
|
||||
const record = bundle().records[0];
|
||||
const single = join(directory, "record.json");
|
||||
await writeFile(single, JSON.stringify(record));
|
||||
expect(await readEvidenceBundle(single)).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "EvidenceFileError",
|
||||
reason: "wrong-kind",
|
||||
path: single,
|
||||
userMessage: expect.stringContaining(
|
||||
`this JSON is one Evidence record (${String(record?.evidence_id)})`,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const tamperedRecord = join(directory, "tampered-record.json");
|
||||
await writeFile(
|
||||
tamperedRecord,
|
||||
JSON.stringify({ ...record, normalized_result: "changed" }),
|
||||
);
|
||||
expect(await readEvidenceBundle(tamperedRecord)).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "EvidenceIntegrityError",
|
||||
userMessage: expect.stringContaining(
|
||||
"does not match the bundle schema",
|
||||
),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,89 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
inspectGhidraInstallation,
|
||||
ghidraInstallationDiagnostics,
|
||||
} from "../../../src/ghidra/GhidraInstallation.js";
|
||||
import { SUPPORTED_GHIDRA_VERSION } from "../../../src/ghidra/GhidraInstallationPolicy.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const { mockSpawnSync } = vi.hoisted(() => ({ mockSpawnSync: vi.fn() }));
|
||||
|
||||
vi.mock("node:child_process", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("node:child_process")>()),
|
||||
spawnSync: mockSpawnSync,
|
||||
}));
|
||||
|
||||
afterEach(() => mockSpawnSync.mockReset());
|
||||
|
||||
it.each([
|
||||
{ major: 17, fullJdk: true, vmName: "Java HotSpot(TM) 64-Bit Server VM" },
|
||||
{ major: 21, fullJdk: true, vmName: "Eclipse OpenJ9 VM" },
|
||||
{ major: 21, fullJdk: false, vmName: undefined },
|
||||
])(
|
||||
"preserves the reported Unicode Java home and classifies JDK $major (full JDK: $fullJdk)",
|
||||
async ({ major, fullJdk, vmName }) => {
|
||||
const root = await createTestTempDirectory("rea-java-probe-");
|
||||
const configuredHome = join(root, "selected-jdk");
|
||||
const reportedHome = join(root, "Réa逆向", `JDK ${String(major)}`);
|
||||
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`,
|
||||
);
|
||||
if (fullJdk) {
|
||||
await mkdir(join(reportedHome, "bin"), { recursive: true });
|
||||
await writeFile(
|
||||
join(
|
||||
reportedHome,
|
||||
"bin",
|
||||
process.platform === "win32" ? "javac.exe" : "javac",
|
||||
),
|
||||
"compiler presence fixture",
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
}
|
||||
const version = `${String(major)}.0.11`;
|
||||
mockSpawnSync.mockReturnValue({
|
||||
stdout: "",
|
||||
stderr: ` java.version = ${version}\n java.home = ${reportedHome}\n sun.arch.data.model = 64\n${vmName === undefined ? "" : ` java.vm.name = ${vmName}\n`}`,
|
||||
status: 0,
|
||||
});
|
||||
|
||||
const inspection = inspectGhidraInstallation({
|
||||
environment: {},
|
||||
installDir,
|
||||
javaHome: configuredHome,
|
||||
});
|
||||
|
||||
expect(inspection.javaHome).toBe(reportedHome);
|
||||
expect(inspection.javaVersion).toBe(version);
|
||||
expect(inspection.javaVmName).toBe(vmName);
|
||||
expect(ghidraInstallationDiagnostics(inspection).java_vm_name).toBe(
|
||||
vmName ?? null,
|
||||
);
|
||||
expect(inspection.checks.find(({ name }) => name === "java")).toMatchObject(
|
||||
{
|
||||
status: fullJdk ? "passed" : "failed",
|
||||
detail: expect.stringContaining(fullJdk ? "; JDK;" : "; runtime only;"),
|
||||
},
|
||||
);
|
||||
expect(mockSpawnSync).toHaveBeenCalledExactlyOnceWith(
|
||||
join(
|
||||
configuredHome,
|
||||
"bin",
|
||||
process.platform === "win32" ? "java.exe" : "java",
|
||||
),
|
||||
expect.arrayContaining([
|
||||
"-Dstdout.encoding=UTF-8",
|
||||
"-Dstderr.encoding=UTF-8",
|
||||
"-Dsun.stdout.encoding=UTF-8",
|
||||
"-Dsun.stderr.encoding=UTF-8",
|
||||
]),
|
||||
expect.objectContaining({ encoding: "utf8" }),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -214,6 +214,34 @@ describe("HarmonyOS packaging boundaries", () => {
|
||||
});
|
||||
|
||||
describe("HarmonyOS inventory coverage", () => {
|
||||
it("keeps a case-colliding inventory partial in the application projection", async () => {
|
||||
const path = await writeApplicationZip(
|
||||
"rea-harmony-case-collision-",
|
||||
"Fixture.hap",
|
||||
[
|
||||
{ path: "module.json", content: '{"module":{}}' },
|
||||
{ path: "MODULE.JSON", content: '{"module":{}}' },
|
||||
],
|
||||
);
|
||||
const inventory = await inventoryApplicationPackage(path);
|
||||
expect(inventory.normalized_result).toMatchObject({
|
||||
coverage_status: "partial",
|
||||
});
|
||||
|
||||
const projection = requireDeterministicProjection(
|
||||
projectHarmonyApplicationEvidence,
|
||||
inventory,
|
||||
harmonyApplicationProjectionResultSchema,
|
||||
);
|
||||
expect(projection.coverage).toEqual({
|
||||
status: "partial",
|
||||
inventory_complete: true,
|
||||
});
|
||||
expect(projection.limitations).toContain(
|
||||
"Source inventory coverage is partial; absence is unknown.",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(ZIP_PACKAGE_FORMATS)(
|
||||
"retains archive identity and ZIP coverage for %s",
|
||||
async (format) => {
|
||||
|
||||
@@ -6,9 +6,15 @@ import { parse as parseYaml } from "yaml";
|
||||
|
||||
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
|
||||
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import {
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { supportedClients } from "../../../src/application/SupportedClients.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import {
|
||||
runUninstall,
|
||||
systemUninstallHost,
|
||||
} from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
|
||||
|
||||
@@ -90,18 +96,75 @@ describe("Hermes configuration paths", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes YAML registration", () => {
|
||||
const hermesClient = async () => {
|
||||
const home = await createTestTempDirectory("rea-hermes-");
|
||||
const client = supportedClients(home, process.platform, {}).find(
|
||||
({ name }) => name === "hermes",
|
||||
);
|
||||
if (client?.markerPath === undefined)
|
||||
throw new Error("missing Hermes client");
|
||||
await mkdir(client.markerPath, { recursive: true });
|
||||
return { home, client };
|
||||
};
|
||||
const hermesClient = async () => {
|
||||
const home = await createTestTempDirectory("rea-hermes-");
|
||||
const client = supportedClients(home, process.platform, {}).find(
|
||||
({ name }) => name === "hermes",
|
||||
);
|
||||
if (client?.markerPath === undefined)
|
||||
throw new Error("missing Hermes client");
|
||||
await mkdir(client.markerPath, { recursive: true });
|
||||
return { home, client };
|
||||
};
|
||||
|
||||
describe("Hermes YAML shape diagnostics", () => {
|
||||
it.each(
|
||||
[
|
||||
"!!set {rea: null}",
|
||||
"!!omap [{rea: {command: rea, args: [mcp]}}]",
|
||||
"!!timestamp 2001-12-15",
|
||||
"!!binary cmVh",
|
||||
].flatMap((value) => [
|
||||
{
|
||||
original: `${value}\n`,
|
||||
problem: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
original: `mcp_servers: ${value}\n`,
|
||||
problem: '"mcp_servers" must be an object',
|
||||
},
|
||||
]),
|
||||
)(
|
||||
"blocks setup and uninstall before changes for tagged non-record YAML: $original",
|
||||
async ({ original, problem }) => {
|
||||
const { home, client } = await hermesClient();
|
||||
const cursor = join(home, ".cursor", "mcp.json");
|
||||
const cursorOriginal =
|
||||
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}';
|
||||
await mkdir(join(home, ".cursor"));
|
||||
await writeFile(cursor, cursorOriginal);
|
||||
await writeFile(client.configPath, original);
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, command),
|
||||
).toMatchObject({
|
||||
status: "invalid",
|
||||
remediation: `Configuration ${client.configPath} is malformed: ${problem}`,
|
||||
});
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
const result = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, undefined, {}),
|
||||
);
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual({
|
||||
name: "hermes",
|
||||
status: "failed",
|
||||
detail: `Configuration was not changed: ${problem}. Repair it, then rerun uninstall.`,
|
||||
});
|
||||
expect(await readFile(client.configPath, "utf8")).toBe(original);
|
||||
expect(await readFile(cursor, "utf8")).toBe(cursorOriginal);
|
||||
await expect(
|
||||
readFile(`${client.configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
await expect(readFile(`${cursor}.rea.backup`, "utf8")).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Hermes YAML registration", () => {
|
||||
it("writes mcp_servers, preserves comments, reads back, and uninstalls", async () => {
|
||||
const { home, client } = await hermesClient();
|
||||
await writeFile(
|
||||
|
||||
@@ -11,12 +11,26 @@ 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";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
// install.sh:fail_node_version emits this recovery block verbatim. The fake
|
||||
// `uname` in createFixture reports `x86_64` / `Linux`, so the host labels
|
||||
// resolve to `linux/x64`.
|
||||
const UNSUPPORTED_NODE_RECOVERY_LINUX_X64 =
|
||||
"REA installation failed: Node.js 20.0.0 is unsupported.\n" +
|
||||
"\n" +
|
||||
"REA requires Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+. Install one via:\n" +
|
||||
" nvm: nvm install 24 && nvm use 24 (https://github.com/nvm-sh/nvm)\n" +
|
||||
" fnm: fnm install 24 && fnm use 24 (https://github.com/Schniz/fnm)\n" +
|
||||
" Direct download for linux/x64:\n" +
|
||||
" https://nodejs.org/dist/latest-v24.x/ (grab the linux-x64 tarball)\n" +
|
||||
"Then rerun this installer.\n";
|
||||
|
||||
describe("curl installer scenarios", { timeout: 20_000 }, () => {
|
||||
it("installs only a pinned REA CLI with closed stdin", async () => {
|
||||
const fixture = await createFixture();
|
||||
@@ -87,7 +101,7 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
|
||||
"unsupported Node",
|
||||
["--version", "0.3.0"],
|
||||
{ FAKE_NODE_VERSION: "20.0.0" },
|
||||
"REA installation failed: Node.js 20.0.0 is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+.\n",
|
||||
UNSUPPORTED_NODE_RECOVERY_LINUX_X64,
|
||||
],
|
||||
[
|
||||
"unreadable Node version",
|
||||
@@ -172,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();
|
||||
@@ -321,13 +398,18 @@ describe("native macOS installer", { timeout: 20_000 }, () => {
|
||||
});
|
||||
|
||||
describe("installer semantic version parsing", { timeout: 20_000 }, () => {
|
||||
it.each(["1.2.3-01"])(
|
||||
it.each([
|
||||
"1.2.3-01",
|
||||
"1.2.3-$(printf unexpected)",
|
||||
'1.2.3-"; printf unexpected; #',
|
||||
])(
|
||||
"rejects malformed semantic versions before invoking npm: %s",
|
||||
async (version) => {
|
||||
const fixture = await createFixture();
|
||||
await expect(
|
||||
runInstaller(fixture, ["--version", version, "--dry-run"]),
|
||||
).rejects.toMatchObject({
|
||||
stdout: "",
|
||||
stderr:
|
||||
"REA installation failed: version must be an exact semantic version.\n",
|
||||
});
|
||||
@@ -415,6 +497,7 @@ interface InstallerFixture {
|
||||
readonly temporary: string;
|
||||
readonly npmLog: string;
|
||||
readonly reaLog: string;
|
||||
readonly installerStderrLog: string;
|
||||
}
|
||||
|
||||
const getProcessOutput = (
|
||||
@@ -438,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(
|
||||
@@ -489,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> => {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
@@ -10,6 +9,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { analyzeInterfaceBuilderBundle } from "../../../src/artifacts/apple/InterfaceBuilderAnalysis.js";
|
||||
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
|
||||
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { xcodeIbtoolAvailable } from "../../fixtures/ibtool.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
|
||||
@@ -913,7 +913,7 @@ describe("bounded Interface Builder archive decoding", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "darwin" || !existsSync("/usr/bin/ibtool"))(
|
||||
it.skipIf(!xcodeIbtoolAvailable)(
|
||||
"decodes an Xcode-compiled storyboard NIB and recovers its UI routes",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-ib-compiled-test-");
|
||||
@@ -992,8 +992,8 @@ describe("bounded Interface Builder archive decoding", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("compiled UIKit NIB connections", () => {
|
||||
it("projects UIKit runtime outlet and event connections", async () => {
|
||||
describe("NIBArchive UIKit event connections", () => {
|
||||
it("projects a runtime event connection and its event mask", async () => {
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
const bundle = join(root, "Example.app");
|
||||
await mkdir(bundle, { recursive: true });
|
||||
@@ -1005,7 +1005,6 @@ describe("compiled UIKit NIB connections", () => {
|
||||
"UIClassSwapper",
|
||||
"UIButton",
|
||||
"UIRuntimeEventConnection",
|
||||
"UIRuntimeOutletConnection",
|
||||
"NSString",
|
||||
],
|
||||
objects: [
|
||||
@@ -1021,18 +1020,10 @@ describe("compiled UIKit NIB connections", () => {
|
||||
UIEventMask: 64,
|
||||
},
|
||||
},
|
||||
{
|
||||
classIndex: 4,
|
||||
values: {
|
||||
UISource: { ref: 1 },
|
||||
UIDestination: { ref: 2 },
|
||||
UILabel: { ref: 8 },
|
||||
},
|
||||
},
|
||||
{ classIndex: 5, values: { "NS.bytes": "IBFilesOwner" } },
|
||||
{ classIndex: 5, values: { "NS.bytes": "BuildCell" } },
|
||||
{ classIndex: 5, values: { "NS.bytes": "buildTapped:" } },
|
||||
{ classIndex: 5, values: { "NS.bytes": "buildButton" } },
|
||||
{ classIndex: 2, values: {} },
|
||||
{ classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } },
|
||||
{ classIndex: 4, values: { "NS.bytes": "BuildCell" } },
|
||||
{ classIndex: 4, values: { "NS.bytes": "buildTapped:" } },
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -1062,16 +1053,6 @@ describe("compiled UIKit NIB connections", () => {
|
||||
.filter(({ from }) => from === action?.id)
|
||||
.map(({ to }) => named(to)),
|
||||
).toEqual(expect.arrayContaining(["BuildCell"]));
|
||||
const outlet = analysis.graph.nodes.find(({ kind }) => kind === "outlet");
|
||||
expect(outlet?.name).toBe("buildButton");
|
||||
expect(
|
||||
analysis.graph.edges
|
||||
.filter(
|
||||
({ relation, from }) =>
|
||||
relation === "outlet_to" && from === outlet?.id,
|
||||
)
|
||||
.map(({ to }) => named(to)),
|
||||
).toEqual(["UIButton"]);
|
||||
expect(
|
||||
analysis.graph.nodes.find(({ name }) => name === "IBFilesOwner")?.kind,
|
||||
).toBe("placeholder");
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user