Merge remote-tracking branch 'origin/main' into feat/claude-code-plugin
This commit is contained in:
@@ -13,32 +13,56 @@ 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";',
|
||||
'import "./explicit.js";',
|
||||
'import "./exact.js";',
|
||||
'import "./actual.cjs?cache=1";',
|
||||
'import fallback from "empty-main";',
|
||||
'import "nested-main";',
|
||||
'import "file-only";',
|
||||
'import "ancestor-empty";',
|
||||
'import "ancestor-blocked";',
|
||||
'import "ancestor-sub/parser";',
|
||||
"void fallback;",
|
||||
].join("\n"),
|
||||
"esm/extensionless.js": "module.exports = 1;",
|
||||
"esm/directory/index.js": "module.exports = 2;",
|
||||
"esm/explicit.js.js": "module.exports = 3;",
|
||||
"esm/exact.js": "module.exports = 4;",
|
||||
"esm/actual.cjs": "module.exports = 5;",
|
||||
"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");',
|
||||
'require("empty-main");',
|
||||
'require("nested-main");',
|
||||
'require("file-only");',
|
||||
'require("ancestor-empty");',
|
||||
'require("ancestor-blocked");',
|
||||
'require("ancestor-sub/parser");',
|
||||
].join("\n"),
|
||||
"cjs/directory/index.cjs": "module.exports = 6;",
|
||||
"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.
|
||||
@@ -50,25 +74,38 @@ const createModuleLookupFixture = async () => {
|
||||
main: "other",
|
||||
}),
|
||||
"node_modules/nested-main/sub/other.js": "module.exports = 99;",
|
||||
"runtime-control.mjs": [
|
||||
'const specifiers = ["./esm/extensionless", "./esm/directory", "./esm/explicit.js", "./esm/exact.js", "empty-main", "nested-main"];',
|
||||
"node_modules/file-only.js": "module.exports = 7;",
|
||||
"node_modules/ancestor-empty/index.js": "module.exports = 8;",
|
||||
"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 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"),
|
||||
"runtime-control.cjs": [
|
||||
'const specifiers = ["./cjs/extensionless", "./cjs/feature", "./cjs/feature.cjs", "./cjs/default-js", "./cjs/default-json", "empty-main", "nested-main"];',
|
||||
"cjs/runtime-control.cjs": [
|
||||
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./module-only", "./valid-directory", "./default-js", "./default-json", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
|
||||
"const 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));",
|
||||
].join("\n"),
|
||||
});
|
||||
for (const directory of ["esm", "cjs"])
|
||||
await writeFixtureFiles(root, {
|
||||
[`${directory}/node_modules/ancestor-empty/package.json`]: JSON.stringify(
|
||||
{ main: "" },
|
||||
),
|
||||
[`${directory}/node_modules/ancestor-blocked/package.json`]:
|
||||
JSON.stringify({ main: "missing" }),
|
||||
[`${directory}/node_modules/ancestor-sub/package.json`]: "{}",
|
||||
});
|
||||
return root;
|
||||
};
|
||||
|
||||
@@ -77,11 +114,11 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
async (surface, { cli }) => {
|
||||
const root = await createModuleLookupFixture();
|
||||
const [esmControl, cjsControl] = await Promise.all([
|
||||
execute(process.execPath, ["runtime-control.mjs"], {
|
||||
execute(process.execPath, ["esm/runtime-control.mjs"], {
|
||||
cwd: root,
|
||||
timeout: 5_000,
|
||||
}),
|
||||
execute(process.execPath, ["runtime-control.cjs"], {
|
||||
execute(process.execPath, ["cjs/runtime-control.cjs"], {
|
||||
cwd: root,
|
||||
timeout: 5_000,
|
||||
}),
|
||||
@@ -90,48 +127,74 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
readonly value?: unknown;
|
||||
}>;
|
||||
const cjsResults = JSON.parse(cjsControl.stdout) as Array<{
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
readonly value?: unknown;
|
||||
}>;
|
||||
expect(esmResults).toEqual([
|
||||
{
|
||||
specifier: "./esm/extensionless",
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./esm/directory",
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "./esm/explicit.js",
|
||||
specifier: "./explicit.js",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./esm/exact.js", ok: true },
|
||||
{ specifier: "empty-main", ok: true },
|
||||
{ specifier: "./exact.js", ok: true, value: 4 },
|
||||
{ specifier: "./actual.cjs?cache=1", ok: true, value: 5 },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-empty", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{
|
||||
specifier: "ancestor-blocked",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "ancestor-sub/parser",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
]);
|
||||
expect(cjsResults).toEqual([
|
||||
{
|
||||
specifier: "./cjs/extensionless",
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./cjs/feature",
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./cjs/feature.cjs", ok: true },
|
||||
{ specifier: "./cjs/default-js", ok: true },
|
||||
{ specifier: "./cjs/default-json", ok: true },
|
||||
{ specifier: "empty-main", ok: true },
|
||||
{
|
||||
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 },
|
||||
]);
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
@@ -140,16 +203,45 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
["import", "./directory", null, "not-found"],
|
||||
["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"],
|
||||
["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"],
|
||||
["require", "empty-main", "node_modules/empty-main/index.js", "resolved"],
|
||||
["require", "nested-main", null, "not-found"],
|
||||
["require", "file-only", "node_modules/file-only.js", "resolved"],
|
||||
[
|
||||
"require",
|
||||
"ancestor-empty",
|
||||
"node_modules/ancestor-empty/index.js",
|
||||
"resolved",
|
||||
],
|
||||
["require", "ancestor-blocked", null, "not-found"],
|
||||
[
|
||||
"require",
|
||||
"ancestor-sub/parser",
|
||||
"node_modules/ancestor-sub/parser.js",
|
||||
"resolved",
|
||||
],
|
||||
] as const;
|
||||
|
||||
for (const [kind, specifier, resolvedPath, status] of expectations)
|
||||
|
||||
@@ -21,12 +21,19 @@ const fixturePath = fileURLToPath(
|
||||
new URL("../../fixtures/fakeLauncher.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
const expectAvailableToolInventory = async (client: Client) => {
|
||||
const listed = await client.listTools();
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
const expectAvailableToolInventory = async (
|
||||
client: Client,
|
||||
listed: Awaited<ReturnType<Client["listTools"]>>,
|
||||
) => {
|
||||
const binarySession = listed.tools.find(
|
||||
({ name }) => name === "binary_session",
|
||||
);
|
||||
if (binarySession === undefined)
|
||||
throw new Error("The compiled catalog omitted binary_session");
|
||||
const status = await client.callTool(
|
||||
{ name: "binary_session", arguments: {} },
|
||||
{ toolDefinition: binarySession },
|
||||
);
|
||||
expect(status.isError).not.toBe(true);
|
||||
const inventory = z
|
||||
.object({
|
||||
@@ -164,6 +171,9 @@ describe("production stdio runtime", () => {
|
||||
15_000,
|
||||
);
|
||||
|
||||
// Use the suite's bounded acceptance deadline, including its coverage allowance.
|
||||
// This cold-start workflow computes the growing catalog's schema digests; it
|
||||
// verifies catalog and lifecycle behavior, not a 15-second performance target.
|
||||
it("serves the compiled catalog without an initial target or fatal record", async () => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
@@ -183,7 +193,10 @@ describe("production stdio runtime", () => {
|
||||
try {
|
||||
await client.connect(transport);
|
||||
// Keep catalog parity independent of initial target/provider startup.
|
||||
const status = await expectAvailableToolInventory(client);
|
||||
// Validate each called tool against its advertised definition without
|
||||
// asking the SDK to compile every unrelated output schema in the catalog.
|
||||
const listed = await client.listTools();
|
||||
const status = await expectAvailableToolInventory(client, listed);
|
||||
expect(
|
||||
z
|
||||
.object({ result: z.object({ open: z.boolean() }) })
|
||||
@@ -191,10 +204,15 @@ describe("production stdio runtime", () => {
|
||||
).toEqual({ open: false });
|
||||
// Closing the empty session produces a structured lifecycle record,
|
||||
// making the fatal-record check observable without launching a provider.
|
||||
const closed = await client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
const closeBinary = listed.tools.find(
|
||||
({ name }) => name === "close_binary",
|
||||
);
|
||||
if (closeBinary === undefined)
|
||||
throw new Error("The compiled catalog omitted close_binary");
|
||||
const closed = await client.callTool(
|
||||
{ name: "close_binary", arguments: {} },
|
||||
{ toolDefinition: closeBinary },
|
||||
);
|
||||
expect(closed.isError).not.toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
@@ -221,10 +239,7 @@ describe("production stdio runtime", () => {
|
||||
record.level >= 50,
|
||||
);
|
||||
expect(fatal).toEqual([]);
|
||||
// Full catalog discovery and first-call SDK schema compilation take about
|
||||
// 8–9 seconds on one local CPU; the 15-second budget repeatedly expired in
|
||||
// parallel CI shards. Keep a finite budget for the complete workflow.
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
it.runIf(process.platform === "darwin")(
|
||||
"serves a database-kind initial target without a fatal record on macOS",
|
||||
|
||||
@@ -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";
|
||||
@@ -45,13 +46,13 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
source_name: "original.ts",
|
||||
map_path: "bundle.js.map",
|
||||
}),
|
||||
properties: {
|
||||
properties: expect.objectContaining({
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
source_name_available: true,
|
||||
content_available: true,
|
||||
content_sha256: originalDigest,
|
||||
},
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({ sha256: mapDigest }),
|
||||
}),
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect } from "vitest";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
createGoBinaryByteStringFixture,
|
||||
createGoBinaryDiagnosticFixtures,
|
||||
createGoBinaryFixture,
|
||||
createGoBinaryPathFailureFixture,
|
||||
GO_MODULE_TEXT,
|
||||
} from "../fixtures/go/image.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
for (const expectedErrno of ["ELOOP", "ENAMETOOLONG"] as const) {
|
||||
cliTest.skipIf(expectedErrno === "ELOOP" && process.platform === "win32")(
|
||||
`reports native ${expectedErrno} path failure as invalid selected-path input through the public Go CLI`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-path-failure-");
|
||||
const { path, errno } = await createGoBinaryPathFailureFixture(
|
||||
root,
|
||||
expectedErrno,
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "inspect_go_binary",
|
||||
issues: [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(errno),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.json).toMatchObject({
|
||||
details: { issues: [{ message: expect.stringContaining(path) }] },
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"preserves invalid embedded Go text bytes through the public CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-byte-strings-");
|
||||
const path = join(root, "byte-strings.elf");
|
||||
const fixture = createGoBinaryByteStringFixture();
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
expect(evidence.normalized_result.build_info).toEqual(
|
||||
fixture.expectedBuildInfo,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
for (const fixture of createGoBinaryDiagnosticFixtures()) {
|
||||
cliTest(
|
||||
`reports ${fixture.code} for ${fixture.name} through the public Go CLI`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-mz-");
|
||||
const path = join(root, `${fixture.name}.exe`);
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: fixture.code,
|
||||
details: {
|
||||
...fixture.details,
|
||||
...(fixture.code === "unsupported_target" ? { path } : {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"reports a readable unsupported carrier through the public Go CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-");
|
||||
const path = join(root, "text.bin");
|
||||
await writeFile(path, "This is not an executable container.");
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "unsupported_target",
|
||||
details: { operation: "inspect_go_binary", path },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
for (const format of ["elf", "pe", "macho"] as const) {
|
||||
for (const encoding of ["inline", "pointer"] as const) {
|
||||
cliTest(
|
||||
`inspects authored ${format} ${encoding} build metadata through the compiled CLI`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-");
|
||||
const fixture = createGoBinaryFixture({ format, encoding });
|
||||
const path = join(root, "application.bin");
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", "application.bin", "--json"],
|
||||
cwd: root,
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
expect(evidence.raw_result).toBeNull();
|
||||
expect(evidence.subject?.local_path).toBe(path);
|
||||
expect(evidence.subject?.digest.sha256).toBe(
|
||||
createHash("sha256").update(fixture.bytes).digest("hex"),
|
||||
);
|
||||
const report = evidence.normalized_result;
|
||||
expect(report).toMatchObject({
|
||||
format,
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
artifact: { path, bytes: fixture.bytes.length },
|
||||
});
|
||||
expect(report.build_info).toMatchObject({
|
||||
header_offset: fixture.headerOffset,
|
||||
encoding,
|
||||
go_version: "go1.26.0",
|
||||
module_text: GO_MODULE_TEXT,
|
||||
module_bytes_base64: fixture.moduleBytes.toString("base64"),
|
||||
module: {
|
||||
path: "example.com/tool/cmd/tool",
|
||||
main: {
|
||||
path: "example.com/tool",
|
||||
version: "(devel)",
|
||||
sum: "",
|
||||
replacement: null,
|
||||
},
|
||||
dependencies: [
|
||||
{
|
||||
path: "example.com/dependency",
|
||||
version: "v1.2.3",
|
||||
sum: "h1:sample",
|
||||
replacement: { path: "../dependency", version: "", sum: "" },
|
||||
},
|
||||
],
|
||||
complete: true,
|
||||
unparsed_lines: [],
|
||||
},
|
||||
});
|
||||
expect(report.build_info?.module.settings).toContainEqual({
|
||||
key: "-ldflags",
|
||||
value: "-s -w",
|
||||
});
|
||||
if (report.build_info === null)
|
||||
throw new Error("Fixture build metadata must be present");
|
||||
const version = report.build_info.version_location;
|
||||
const module = report.build_info.module_location;
|
||||
expect(
|
||||
fixture.bytes
|
||||
.subarray(version.offset, version.offset + version.bytes)
|
||||
.toString("utf8"),
|
||||
).toBe(report.build_info.go_version);
|
||||
expect(
|
||||
fixture.bytes.subarray(module.offset, module.offset + module.bytes),
|
||||
).toEqual(Buffer.from(report.build_info.module_bytes_base64, "base64"));
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
cliTest("preserves MIPS identity in Go CLI Evidence", async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-mips-");
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes.writeUInt16LE(8, 18); // ELF EM_MIPS.
|
||||
const path = join(root, "application.elf");
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
expect(evidence.subject?.architecture).toBe("mips");
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
architecture: "mips",
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
});
|
||||
});
|
||||
|
||||
cliTest(
|
||||
"reports missing build information as unknown and preserves unsupported carriers distinctly",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-");
|
||||
const path = join(root, "metadata-free.elf");
|
||||
await writeFile(path, createGoBinaryFixture({ omitBuildInfo: true }).bytes);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
const report = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
).normalized_result;
|
||||
expect(report.build_info).toBeNull();
|
||||
expect(report.limitations.join(" ")).toContain(
|
||||
"does not establish that the binary is not Go",
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -230,3 +230,70 @@ cliTest.for(["null", "caller-value", "[caller-value]"])(
|
||||
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(initial);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for([
|
||||
{
|
||||
label: "group-owned rows",
|
||||
patch: `- id: tools
|
||||
insert:
|
||||
- id: other
|
||||
name: caller-plugin
|
||||
- id: rea-mcp
|
||||
name: '@deepseek-ai/dsh-mcp-client'
|
||||
config: {serverName: rea, transport: stdio, command: stale, args: [mcp]}
|
||||
`,
|
||||
remediation: "group with unknown activity",
|
||||
removal: "removed",
|
||||
},
|
||||
{
|
||||
label: "expression-backed inserts",
|
||||
patch: "- insert: !!js process.env.DSH_ROWS\n",
|
||||
remediation: "unknown structure",
|
||||
removal: "retained",
|
||||
},
|
||||
])(
|
||||
"DSH CLI rejects setup and preserves ownership for $label",
|
||||
async ({ patch, remediation, removal }, { cli }) => {
|
||||
const home = await createTestTempDirectory("rea-dsh-ownership-");
|
||||
const profile = join(home, ".dsh");
|
||||
const config = join(profile, "cordis.patch.yml");
|
||||
await mkdir(profile);
|
||||
await writeFile(config, patch);
|
||||
const run = (args: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: [...args, "--json"],
|
||||
cwd: home,
|
||||
environment: { HOME: home, USERPROFILE: home, DSH_HOME: profile },
|
||||
});
|
||||
const setup = await run(["setup", "--client", "dsh", "--yes"]);
|
||||
expect(setup.exitCode).not.toBe(0);
|
||||
expect(setup.json).toMatchObject({
|
||||
status: "needs_human",
|
||||
appliedActions: [],
|
||||
remediation: expect.stringContaining(remediation),
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(patch);
|
||||
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
const uninstall = await run(["uninstall"]);
|
||||
expect(uninstall.exitCode).toBe(0);
|
||||
expect(uninstall.json).toMatchObject({
|
||||
status: "complete",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "dsh", status: removal }),
|
||||
]),
|
||||
});
|
||||
if (removal === "removed") {
|
||||
expect(parse(await readFile(config, "utf8"))).toEqual([
|
||||
{ id: "tools", insert: [{ id: "other", name: "caller-plugin" }] },
|
||||
]);
|
||||
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(patch);
|
||||
} else {
|
||||
expect(await readFile(config, "utf8")).toBe(patch);
|
||||
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { PwntoolsLayoutProvider } from "../../../src/native/pwntools/PwntoolsLayoutProvider.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
// Exercise the decoder's launch/cleanup contract independently of the host's
|
||||
// process table. The interpreter has exec'd over its caller-selected wrapper.
|
||||
it
|
||||
.runIf(process.platform === "linux" && process.arch === "x64")
|
||||
.each(["owned", "wrong-token", "wrong-parent"] as const)(
|
||||
"cancels an exec wrapper only with current ownership: %s",
|
||||
async (identity) => {
|
||||
const { root } = await createTestWorkspace("rea-pwntools-wrapper-");
|
||||
onTestFinished(() => removeTestWorkspace(root));
|
||||
const path = join(root, "input");
|
||||
await writeFile(path, "source-owned-seam-bytes");
|
||||
const controller = new AbortController();
|
||||
class DecoderProcess extends EventEmitter {
|
||||
readonly pid = 41234;
|
||||
readonly stdout = new PassThrough();
|
||||
readonly stderr = new PassThrough();
|
||||
exitCode: number | null = null;
|
||||
signalCode: NodeJS.Signals | null = null;
|
||||
kill(): boolean {
|
||||
throw new Error("Cleanup must validate ownership before signaling");
|
||||
}
|
||||
}
|
||||
const child = new DecoderProcess();
|
||||
let live = true;
|
||||
const signalGroup = vi.fn(() => {
|
||||
live = false;
|
||||
child.signalCode = "SIGTERM";
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit("exit", null, "SIGTERM");
|
||||
child.emit("close", null, "SIGTERM");
|
||||
});
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
async (spawn) => {
|
||||
const ownership = {
|
||||
runId: spawn.runId,
|
||||
leaderPid: child.pid,
|
||||
processGroupId: child.pid,
|
||||
expectedParentPid: process.pid,
|
||||
...(spawn.expectedCommand === null
|
||||
? {}
|
||||
: { expectedCommand: spawn.expectedCommand ?? spawn.command }),
|
||||
};
|
||||
setImmediate(() => controller.abort());
|
||||
return {
|
||||
process: child,
|
||||
ownership,
|
||||
cleanup: () =>
|
||||
cleanupOwnedProcessGroup(ownership, {
|
||||
listProcesses: async () =>
|
||||
live
|
||||
? [
|
||||
{
|
||||
pid: child.pid,
|
||||
parentPid:
|
||||
identity === "wrong-parent"
|
||||
? process.pid + 1
|
||||
: process.pid,
|
||||
processGroupId: child.pid,
|
||||
state: "S",
|
||||
command:
|
||||
"/selected/python -I bridge/pwntools/layout.py",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
environment: async () => ({
|
||||
REA_PROCESS_RUN_ID:
|
||||
identity === "wrong-token" ? "another-run" : spawn.runId,
|
||||
}),
|
||||
signalGroup,
|
||||
}),
|
||||
};
|
||||
},
|
||||
);
|
||||
const result = await provider.inspect(
|
||||
{ path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error:
|
||||
identity === "owned"
|
||||
? { _tag: "AnalysisCancelledError" }
|
||||
: { _tag: "ProviderAdapterError", cleanupIncomplete: true },
|
||||
});
|
||||
expect(signalGroup).toHaveBeenCalledTimes(identity === "owned" ? 1 : 0);
|
||||
},
|
||||
);
|
||||
@@ -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 }),
|
||||
]);
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -1161,58 +1161,73 @@ describe("source-map output admission", () => {
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ localOrigin: "http://[::1]:1", expectedStatus: "included" },
|
||||
{ localOrigin: "http://127.0.0.1:9222", expectedStatus: "partial" },
|
||||
])(
|
||||
"admits a maximum-size map set according to its actual output at $localOrigin",
|
||||
async ({ localOrigin, expectedStatus }) => {
|
||||
const mapUrl = `${localOrigin}/m`;
|
||||
const requests = Array.from({ length: 50_000 }, (_, index) => ({
|
||||
...request,
|
||||
scriptKey: `scr_${index.toString(16).padStart(64, "0")}`,
|
||||
declaredUrl: mapUrl,
|
||||
fetchUrl: mapUrl,
|
||||
}));
|
||||
const map = JSON.stringify({
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["x"],
|
||||
mappings: "AAAA",
|
||||
});
|
||||
const result = await fetchWebSourceMaps(
|
||||
requests,
|
||||
input({ allowed_origins: [localOrigin] }),
|
||||
undefined,
|
||||
{
|
||||
timeoutMs: 120_000,
|
||||
fetch: () => Promise.resolve(new Response(map, { status: 200 })),
|
||||
},
|
||||
);
|
||||
describe("source-map set output admission", () => {
|
||||
it("admits a maximum-size map set according to its serialized output size", async () => {
|
||||
const localOrigin = "http://127.0.0.1:9222";
|
||||
const mapUrl = `${localOrigin}/m`;
|
||||
const requests = Array.from({ length: 50_000 }, (_, index) => ({
|
||||
...request,
|
||||
scriptKey: `scr_${index.toString(16).padStart(64, "0")}`,
|
||||
declaredUrl: mapUrl,
|
||||
fetchUrl: mapUrl,
|
||||
}));
|
||||
const map = JSON.stringify({
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["x"],
|
||||
mappings: "AAAA",
|
||||
});
|
||||
const result = await fetchWebSourceMaps(
|
||||
requests,
|
||||
input({ allowed_origins: [localOrigin] }),
|
||||
undefined,
|
||||
{
|
||||
timeoutMs: 120_000,
|
||||
fetch: () => Promise.resolve(new Response(map, { status: 200 })),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.status).toBe(expectedStatus);
|
||||
if (expectedStatus === "included") {
|
||||
expect(result.limitation).toBeUndefined();
|
||||
expect(result.items).toHaveLength(requests.length);
|
||||
} else {
|
||||
expect(result.items.length).toBeLessThan(requests.length);
|
||||
expect(result.limitation).toContain(
|
||||
`${String(requests.length - result.items.length)} requested maps`,
|
||||
);
|
||||
expect(
|
||||
(Buffer.byteLength(JSON.stringify(result.items[0])) + 1) *
|
||||
requests.length,
|
||||
).toBeGreaterThan(32 * 1_024 * 1_024);
|
||||
}
|
||||
expect(result.processed).toBe(result.items.length);
|
||||
expect(result.requested).toBe(requests.length);
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(
|
||||
32 * 1_024 * 1_024,
|
||||
const outputLimitBytes = 32 * 1_024 * 1_024;
|
||||
const itemSizes = new Set(
|
||||
result.items.map((item) => Buffer.byteLength(JSON.stringify(item))),
|
||||
);
|
||||
expect(itemSizes.size).toBe(1);
|
||||
const firstItem = result.items[0];
|
||||
if (firstItem === undefined) throw new Error("no source map was admitted");
|
||||
const itemBytes = Buffer.byteLength(JSON.stringify(firstItem));
|
||||
const completeEnvelope = JSON.stringify({
|
||||
...result,
|
||||
status: "included",
|
||||
processed: requests.length,
|
||||
items: [],
|
||||
limitation: undefined,
|
||||
});
|
||||
const projectedCompleteBytes =
|
||||
Buffer.byteLength(completeEnvelope) +
|
||||
itemBytes * requests.length +
|
||||
requests.length -
|
||||
1;
|
||||
const completeOutputFits = projectedCompleteBytes <= outputLimitBytes;
|
||||
|
||||
expect(result.status).toBe(completeOutputFits ? "included" : "partial");
|
||||
if (completeOutputFits) {
|
||||
expect(result.limitation).toBeUndefined();
|
||||
expect(result.items).toHaveLength(requests.length);
|
||||
} else {
|
||||
expect(result.items.length).toBeLessThan(requests.length);
|
||||
expect(result.limitation).toContain(
|
||||
`${String(requests.length - result.items.length)} requested maps`,
|
||||
);
|
||||
},
|
||||
120_000,
|
||||
);
|
||||
expect(projectedCompleteBytes).toBeGreaterThan(outputLimitBytes);
|
||||
}
|
||||
expect(result.processed).toBe(result.items.length);
|
||||
expect(result.requested).toBe(requests.length);
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(
|
||||
outputLimitBytes,
|
||||
);
|
||||
}, 120_000);
|
||||
|
||||
it("reserves large failure contexts and reports unprocessed requests as unknown", async () => {
|
||||
const largeDeclaredUrl = `${origin}/${"u".repeat(8 * 1_024 * 1_024)}`;
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -44,15 +44,20 @@ describe.skipIf(process.platform !== "darwin")(
|
||||
});
|
||||
|
||||
cliTest("rejects a symbol spanning lines as input", async ({ cli }) => {
|
||||
const missingTarget = join(
|
||||
await createTestTempDirectory("rea-demangle-invalid-input-"),
|
||||
"absent",
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"demangle-swift",
|
||||
await evidenceTarget(),
|
||||
missingTarget,
|
||||
"$s4main3FooV",
|
||||
"$s4main\n3FooV",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({ code: "VALIDATION_ERROR" });
|
||||
|
||||
@@ -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-");
|
||||
|
||||
@@ -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,7 +11,32 @@ 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([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["legacy CP437", Buffer.from([0x82, 0x2e, 0x74, 0x78, 0x74]), false, "é.txt"],
|
||||
|
||||
@@ -245,6 +245,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");
|
||||
|
||||
@@ -12,7 +12,10 @@ import {
|
||||
|
||||
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 {
|
||||
clientSkillDirectories,
|
||||
supportedClients,
|
||||
@@ -398,18 +401,134 @@ describe("DeepSeek Harness repair boundaries", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses a group-targeted insertion whose applicability is unknown", async () => {
|
||||
it("keeps group-targeted ownership for uninstall while setup rejects unknown activity", async () => {
|
||||
const { home, client } = await harnessClient();
|
||||
const initial = stringifyYaml([
|
||||
{ id: "missing-group", insert: [canonicalEntry()] },
|
||||
{
|
||||
id: "tools",
|
||||
insert: [
|
||||
canonicalEntry(),
|
||||
{ id: "foreign-peer", name: "caller-plugin", config: { keep: true } },
|
||||
],
|
||||
},
|
||||
]);
|
||||
await writeFile(client.configPath, initial);
|
||||
expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
|
||||
{
|
||||
status: "invalid",
|
||||
remediation: expect.stringContaining("targets a group"),
|
||||
},
|
||||
);
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("failed");
|
||||
expect(await dshStatus(home)).not.toMatchObject({ state: "aligned" });
|
||||
expect(await dshStatus(home)).toMatchObject({
|
||||
state: "stale",
|
||||
command: [...command],
|
||||
});
|
||||
expect(await readFile(client.configPath, "utf8")).toBe(initial);
|
||||
const host = systemUninstallHost(home);
|
||||
expect(await host.inspectClient(client)).toBeUndefined();
|
||||
expect((await host.removeClient(client)).status).toBe("removed");
|
||||
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
|
||||
{
|
||||
id: "tools",
|
||||
insert: [
|
||||
{ id: "foreign-peer", name: "caller-plugin", config: { keep: true } },
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
|
||||
initial,
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks malformed literal patches but still uninstalls a known owned sibling", async () => {
|
||||
const { home, client } = await harnessClient();
|
||||
const initial = stringifyYaml([
|
||||
{ insert: [canonicalEntry()] },
|
||||
"foreign-invalid-row",
|
||||
]);
|
||||
await writeFile(client.configPath, initial);
|
||||
|
||||
expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
|
||||
{
|
||||
status: "invalid",
|
||||
remediation: expect.stringContaining("Malformed Cordis patches"),
|
||||
},
|
||||
);
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("failed");
|
||||
expect(await readFile(client.configPath, "utf8")).toBe(initial);
|
||||
|
||||
const host = systemUninstallHost(home);
|
||||
expect(await host.inspectClient(client)).toBeUndefined();
|
||||
expect((await host.removeClient(client)).status).toBe("removed");
|
||||
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
|
||||
"foreign-invalid-row",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["{ id: rea-mcp }", "7", "false", "''", "[null]"])(
|
||||
"blocks a non-list literal insert value %s before setup edits the file",
|
||||
async (insert) => {
|
||||
const { client } = await harnessClient();
|
||||
const initial = `- insert: ${insert}\n`;
|
||||
await writeFile(client.configPath, initial);
|
||||
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, command),
|
||||
).toMatchObject({
|
||||
status: "invalid",
|
||||
remediation: expect.stringContaining("Malformed Cordis patches"),
|
||||
});
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("failed");
|
||||
expect(await readFile(client.configPath, "utf8")).toBe(initial);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps Harness's null insert no-op editable", async () => {
|
||||
const { client } = await harnessClient();
|
||||
await writeFile(client.configPath, "- insert: null\n");
|
||||
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DeepSeek Harness expression-backed structure", () => {
|
||||
it.each([
|
||||
`- !!js process.env.DSH_PATCH\n`,
|
||||
`- insert: !!js process.env.DSH_ROWS\n`,
|
||||
`- insert: [!!js process.env.DSH_ROW]\n`,
|
||||
])(
|
||||
"retains dynamic insertion structure without appending or removing rows: %s",
|
||||
async (initial) => {
|
||||
const { home, client } = await harnessClient();
|
||||
await writeFile(client.configPath, initial);
|
||||
expect(await dshStatus(home)).toMatchObject({ state: "invalid" });
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, command),
|
||||
).toMatchObject({
|
||||
status: "invalid",
|
||||
remediation: expect.stringContaining("unknown structure"),
|
||||
});
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("failed");
|
||||
expect(await readFile(client.configPath, "utf8")).toBe(initial);
|
||||
const host = systemUninstallHost(home);
|
||||
expect((await host.removeClient(client)).status).toBe("retained");
|
||||
expect(await readFile(client.configPath, "utf8")).toBe(initial);
|
||||
await expect(
|
||||
readFile(`${client.configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("DeepSeek Harness registration state", () => {
|
||||
@@ -993,7 +1112,7 @@ describe("DeepSeek Harness alias targets", () => {
|
||||
const { client } = await harnessClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`- insert: &rows
|
||||
`- holder: &rows
|
||||
- id: other-tool
|
||||
name: other
|
||||
config:
|
||||
@@ -1015,7 +1134,7 @@ describe("DeepSeek Harness alias targets", () => {
|
||||
const text = await readFile(client.configPath, "utf8");
|
||||
expect(text).toContain("other-tool");
|
||||
expect(text).not.toContain("*rows");
|
||||
expect(text).not.toContain("stale-launcher");
|
||||
expect(text).toContain("stale-launcher");
|
||||
const patches = parseYaml(text) as { insert?: { id?: string }[] }[];
|
||||
expect(
|
||||
patches.flatMap(({ insert }) =>
|
||||
@@ -1063,11 +1182,11 @@ describe("DeepSeek Harness alias targets", () => {
|
||||
});
|
||||
|
||||
describe("DeepSeek Harness alias identity", () => {
|
||||
it("keeps unrelated rows when the insert list is anchored outside an operation", async () => {
|
||||
it("keeps unrelated rows when a valid insertion list is aliased", async () => {
|
||||
const { client } = await harnessClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`- &rows
|
||||
`- holder: &rows
|
||||
- id: other-tool
|
||||
name: other
|
||||
config:
|
||||
@@ -1107,7 +1226,8 @@ describe("DeepSeek Harness alias identity", () => {
|
||||
const { client } = await harnessClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`- &expr !!js process.env.TOKEN
|
||||
`- insert: []
|
||||
callerExpression: &expr !!js process.env.TOKEN
|
||||
- insert:
|
||||
- id: rea-mcp
|
||||
name: "@deepseek-ai/dsh-mcp-client"
|
||||
@@ -1137,7 +1257,8 @@ describe("DeepSeek Harness alias identity", () => {
|
||||
const { home, client } = await harnessClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`- &entryId rea-mcp
|
||||
`- insert: []
|
||||
holder: &entryId rea-mcp
|
||||
- insert:
|
||||
- id: *entryId
|
||||
name: "@deepseek-ai/dsh-mcp-client"
|
||||
@@ -1201,7 +1322,8 @@ describe("DeepSeek Harness alias cleanup", () => {
|
||||
const { home, client } = await harnessClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`- &expr !!js process.env.GHIDRA_INSTALL_DIR
|
||||
`- insert: []
|
||||
callerExpression: &expr !!js process.env.GHIDRA_INSTALL_DIR
|
||||
- insert:
|
||||
- id: rea-mcp
|
||||
name: "@deepseek-ai/dsh-mcp-client"
|
||||
@@ -1475,46 +1597,11 @@ describe("DeepSeek Harness alias anchors", () => {
|
||||
).toBe("unchanged");
|
||||
});
|
||||
|
||||
it("edits a root alias whose insert list is itself an alias", async () => {
|
||||
const { client } = await harnessClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`- &rows
|
||||
- id: other-tool
|
||||
name: other
|
||||
config:
|
||||
command: keep-me
|
||||
- id: rea-mcp
|
||||
name: "@deepseek-ai/dsh-mcp-client"
|
||||
config:
|
||||
serverName: rea
|
||||
transport: stdio
|
||||
command: stale-launcher
|
||||
args: [mcp]
|
||||
- holder: &op
|
||||
insert: *rows
|
||||
- *op
|
||||
`,
|
||||
);
|
||||
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const inserted = loadedInserts(await readFile(client.configPath, "utf8"));
|
||||
expect(inserted.filter((entry) => entry.id === "other-tool")).toHaveLength(
|
||||
1,
|
||||
);
|
||||
expect(inserted.filter((entry) => entry.id === "rea-mcp")).toHaveLength(1);
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("unchanged");
|
||||
});
|
||||
|
||||
it("drops a replayed root alias after its insert alias is emptied", async () => {
|
||||
const { home, client } = await harnessClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`- &rows
|
||||
`- holder: &rows
|
||||
- id: rea-mcp
|
||||
name: "@deepseek-ai/dsh-mcp-client"
|
||||
config:
|
||||
@@ -1866,7 +1953,7 @@ describe("DeepSeek Harness ownership and editability", () => {
|
||||
);
|
||||
const initial = yaml.toString();
|
||||
await writeFile(client.configPath, initial);
|
||||
expect(await dshStatus(home)).toMatchObject({ state: "invalid" });
|
||||
expect(await dshStatus(home)).toMatchObject({ state: "stale" });
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("failed");
|
||||
|
||||
@@ -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",
|
||||
),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,6 +17,19 @@ 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 +100,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",
|
||||
|
||||
@@ -42,7 +42,7 @@ describe("Webpack and Rspack runtime adapters", () => {
|
||||
expect(webpackEntry?.observations[0]?.properties).toMatchObject({
|
||||
bundler: "webpack",
|
||||
runtime_require_name: "__webpack_require__",
|
||||
runtime_module_cache_status: "observed",
|
||||
runtime_module_cache_status: "not-observed",
|
||||
entry_module_keys: ["10"],
|
||||
async_chunk_keys: ["lazy", "missing"],
|
||||
unknown_async_chunk_keys: 1,
|
||||
@@ -55,6 +55,7 @@ describe("Webpack and Rspack runtime adapters", () => {
|
||||
expect(rspackEntry?.observations[0]?.properties).toMatchObject({
|
||||
bundler: "rspack",
|
||||
runtime_require_name: "r",
|
||||
runtime_module_cache_status: "not-observed",
|
||||
entry_module_keys: ["src/entry.ts"],
|
||||
async_chunk_keys: ["model"],
|
||||
});
|
||||
@@ -156,7 +157,8 @@ const bundlerFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-bundler-adapters-");
|
||||
await writeFixtureFiles(root, {
|
||||
"renderer/chunks/runtime.js": `
|
||||
var __webpack_module_cache__ = {};
|
||||
// A cache-like name here is not evidence about either registration.
|
||||
const documentation = "__webpack_module_cache__";
|
||||
(globalThis["webpackChunkcustomPortal"] = globalThis["webpackChunkcustomPortal"] || []).push([
|
||||
["main"],
|
||||
{
|
||||
@@ -179,7 +181,11 @@ const bundlerFixture = async (): Promise<string> => {
|
||||
(globalThis["webpackChunkcustomPortal"] = globalThis["webpackChunkcustomPortal"] || []).push([
|
||||
["lazy"],
|
||||
{
|
||||
20: (module) => { module.exports = "lazy"; }
|
||||
20: (module) => {
|
||||
// A marker in a different registration must not be inherited.
|
||||
const documentation = "installedModules";
|
||||
module.exports = "lazy";
|
||||
}
|
||||
}
|
||||
]);
|
||||
(self.rspackChunkcustomPortal = self.rspackChunkcustomPortal || []).push([
|
||||
|
||||
+84
@@ -14,6 +14,90 @@ import {
|
||||
writeFixtureFiles,
|
||||
} from "../../../support/javascriptApplicationFixture.js";
|
||||
|
||||
describe("TypeScript source module loader semantics", () => {
|
||||
it("uses emitted TypeScript loader semantics without changing dynamic imports", async () => {
|
||||
const root = await createTestTempDirectory("rea-cts-module-loader-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": '{"type":"module"}',
|
||||
"main.cts": `
|
||||
import local = require("./local");
|
||||
import selected from "conditional";
|
||||
export { retained } from "conditional";
|
||||
void import("conditional");
|
||||
void local;
|
||||
void selected;
|
||||
`,
|
||||
"consumer.mts": `
|
||||
import local = require("./local");
|
||||
export { local };
|
||||
`,
|
||||
"local.js": "module.exports = 42;",
|
||||
"node_modules/conditional/package.json": JSON.stringify({
|
||||
exports: {
|
||||
".": {
|
||||
import: "./esm.mjs",
|
||||
require: "./cjs.cjs",
|
||||
},
|
||||
},
|
||||
}),
|
||||
"node_modules/conditional/esm.mjs": "export const retained = 'esm';",
|
||||
"node_modules/conditional/cjs.cjs": "exports.retained = 'cjs';",
|
||||
});
|
||||
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const localRequireEdge = (sourcePath: string) => {
|
||||
const source = findSourceModule(graph, sourcePath);
|
||||
return graph.edges.find(
|
||||
({ source_node_id, relation, properties }) =>
|
||||
source_node_id === source?.node_id &&
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "require" &&
|
||||
properties.specifier === "./local",
|
||||
);
|
||||
};
|
||||
|
||||
expect(
|
||||
findSourceModule(graph, "main.cts")?.observations[0]?.properties,
|
||||
).toMatchObject({ module_format: "commonjs" });
|
||||
expect(localRequireEdge("main.cts")).toMatchObject({
|
||||
properties: { resolved_path: "local.js", local_name: "local" },
|
||||
});
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "import",
|
||||
specifier: "conditional",
|
||||
resolvedPath: "node_modules/conditional/cjs.cjs",
|
||||
localName: "selected",
|
||||
}),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
findRelationshipEdge(graph, {
|
||||
kind: "re-export",
|
||||
specifier: "conditional",
|
||||
resolvedPath: "node_modules/conditional/cjs.cjs",
|
||||
}),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
properties.kind === "dynamic-import" &&
|
||||
properties.specifier === "conditional",
|
||||
),
|
||||
).toMatchObject({
|
||||
properties: {
|
||||
resolved_path: "node_modules/conditional/esm.mjs",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
findSourceModule(graph, "consumer.mts")?.observations[0]?.properties,
|
||||
).toMatchObject({ module_format: "esm" });
|
||||
expect(localRequireEdge("consumer.mts")).toMatchObject({
|
||||
properties: { resolved_path: "local.js", local_name: "local" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("CommonJS and ESM module relationships", () => {
|
||||
it("composes bindings, re-exports, dynamic imports, and JSON modules", async () => {
|
||||
const root = await moduleFixture();
|
||||
|
||||
@@ -79,7 +79,12 @@ for (const format of ["directory", "asar"] as const) {
|
||||
map_path: "app.js.map",
|
||||
resolution: { kind: "artifact-relative", path: "original.js" },
|
||||
},
|
||||
properties: { content_available: true },
|
||||
properties: expect.objectContaining({
|
||||
content_available: true,
|
||||
source_name_available: true,
|
||||
source_index: 0,
|
||||
declaration_index: 0,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -136,7 +136,6 @@ it.each([
|
||||
["a non-array sourcesContent value", { sourcesContent: "source" }],
|
||||
["a non-string, non-null source entry", { sourcesContent: [42] }],
|
||||
["a source-content array with the wrong length", { sourcesContent: [] }],
|
||||
["a non-string source name", { sources: [42] }],
|
||||
])(
|
||||
"reports %s as an invalid local source map",
|
||||
async (_description, content) => {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
|
||||
import { readJsonFile } from "../../../src/application/JsonFiles.js";
|
||||
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("retains and retries a JSON file owner after a persistent close failure", async () => {
|
||||
const root = await createTestTempDirectory("rea-json-file-owner-");
|
||||
const path = join(root, "input.json");
|
||||
await writeFile(path, '{"value":"retained"}');
|
||||
const resources = new ArtifactResourceScope();
|
||||
const closeFailure = new Error("injected persistent close failure");
|
||||
let attempts = 0;
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementation(async () => {
|
||||
attempts += 1;
|
||||
throw closeFailure;
|
||||
});
|
||||
let failure: unknown;
|
||||
try {
|
||||
try {
|
||||
await readJsonFile(path, undefined, resources);
|
||||
} catch (cause: unknown) {
|
||||
failure = cause;
|
||||
}
|
||||
expect(failure).toBeInstanceOf(RegularFileCleanupFailure);
|
||||
if (!(failure instanceof RegularFileCleanupFailure))
|
||||
throw new Error("Expected the failed file owner to remain visible");
|
||||
expect(failure.cleanupCause).toBe(closeFailure);
|
||||
expect(failure.outcome).toMatchObject({
|
||||
kind: "completed",
|
||||
value: { ok: true, value: { value: "retained" } },
|
||||
});
|
||||
expect(failure.owner.handle.fd).toBeGreaterThanOrEqual(0);
|
||||
expect(attempts).toBe(2);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
await resources.close();
|
||||
}
|
||||
if (!(failure instanceof RegularFileCleanupFailure))
|
||||
throw new Error("Expected the retained file owner");
|
||||
expect(failure.owner.handle.fd).toBe(-1);
|
||||
});
|
||||
|
||||
it("returns parsed JSON when a failed file close is recovered by the resource scope", async () => {
|
||||
const root = await createTestTempDirectory("rea-json-file-close-retry-");
|
||||
const path = join(root, "input.json");
|
||||
await writeFile(path, '{"value":"retained"}');
|
||||
const resources = new ArtifactResourceScope();
|
||||
const closeFailure = new Error("injected transient close failure");
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
let attempts = 0;
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
attempts += 1;
|
||||
if (attempts === 1) throw closeFailure;
|
||||
await originalClose.call(this);
|
||||
});
|
||||
try {
|
||||
const parsed = await readJsonFile(path, undefined, resources);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
expect(parsed.value).toEqual({ value: "retained" });
|
||||
expect(attempts).toBe(2);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
await resources.close();
|
||||
}
|
||||
});
|
||||
@@ -1,15 +1,22 @@
|
||||
import { 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 {
|
||||
captureProcessScenarioFile,
|
||||
compareProcessEvidenceFiles,
|
||||
projectProcessCliError,
|
||||
} from "../../../src/application/process/ProcessCli.js";
|
||||
import { JSON_BYTE_ORDER_MARK_MESSAGE } from "../../../src/application/Utf8JsonInput.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { holdFirstFileRead } from "../../support/holdFirstFileRead.js";
|
||||
|
||||
describe("process CLI input diagnostics", () => {
|
||||
describe("process CLI error projection", () => {
|
||||
it("preserves local diagnostics for unexpected process failures", () => {
|
||||
const projected = projectProcessCliError(
|
||||
new Error("SECRET internal failure /private/path"),
|
||||
@@ -22,7 +29,116 @@ describe("process CLI input diagnostics", () => {
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("stack");
|
||||
});
|
||||
});
|
||||
|
||||
describe("process CLI file cancellation", () => {
|
||||
it("projects pre-aborted file reads as cancellation", async () => {
|
||||
const root = await createTestTempDirectory("rea-process-cli-cancel-");
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
expect(
|
||||
await captureProcessScenarioFile(
|
||||
join(root, "missing-scenario.json"),
|
||||
process.env,
|
||||
controller.signal,
|
||||
),
|
||||
).toMatchObject({
|
||||
error: "Process command failed",
|
||||
code: "cancelled",
|
||||
category: "cancelled",
|
||||
details: { operation: "capture_process_scenario" },
|
||||
});
|
||||
expect(
|
||||
await compareProcessEvidenceFiles(
|
||||
join(root, "missing-left.json"),
|
||||
join(root, "missing-right.json"),
|
||||
join(root, "missing-trace.json"),
|
||||
controller.signal,
|
||||
),
|
||||
).toMatchObject({
|
||||
code: "cancelled",
|
||||
category: "cancelled",
|
||||
details: { operation: "compare_process_captures" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ workflow: "capture", input: "scenario" },
|
||||
{ workflow: "compare", input: "left" },
|
||||
{ workflow: "compare", input: "right" },
|
||||
{ workflow: "compare", input: "trace specification" },
|
||||
] as const)(
|
||||
"stops streamed $workflow $input reads after cancellation",
|
||||
async ({ workflow, input }) => {
|
||||
const root = await createTestTempDirectory("rea-process-cli-stream-");
|
||||
const paths = {
|
||||
scenario: join(root, "scenario.json"),
|
||||
left: join(root, "left.json"),
|
||||
right: join(root, "right.json"),
|
||||
trace: join(root, "trace.json"),
|
||||
};
|
||||
const evidence = JSON.stringify(processCaptureEvidence());
|
||||
const scenario = JSON.stringify({
|
||||
executable: process.execPath,
|
||||
arguments: [],
|
||||
});
|
||||
const traceSpecification = JSON.stringify(validTraceSpecification());
|
||||
const contentsByInput = {
|
||||
scenario: input === "scenario" ? stream(scenario) : scenario,
|
||||
left: input === "left" ? stream(evidence) : evidence,
|
||||
right: input === "right" ? stream(evidence) : evidence,
|
||||
trace:
|
||||
input === "trace specification"
|
||||
? stream(traceSpecification)
|
||||
: traceSpecification,
|
||||
};
|
||||
await Promise.all([
|
||||
writeFile(paths.scenario, contentsByInput.scenario),
|
||||
writeFile(paths.left, contentsByInput.left),
|
||||
writeFile(paths.right, contentsByInput.right),
|
||||
writeFile(paths.trace, contentsByInput.trace),
|
||||
]);
|
||||
const targetPath =
|
||||
paths[input === "trace specification" ? "trace" : input];
|
||||
const contents =
|
||||
contentsByInput[input === "trace specification" ? "trace" : input];
|
||||
const reader = await holdFirstFileRead(targetPath);
|
||||
onTestFinished(reader.release);
|
||||
const controller = new AbortController();
|
||||
try {
|
||||
const pending =
|
||||
workflow === "capture"
|
||||
? captureProcessScenarioFile(
|
||||
paths.scenario,
|
||||
process.env,
|
||||
controller.signal,
|
||||
)
|
||||
: compareProcessEvidenceFiles(
|
||||
paths.left,
|
||||
paths.right,
|
||||
paths.trace,
|
||||
controller.signal,
|
||||
);
|
||||
await reader.firstRead;
|
||||
controller.abort();
|
||||
reader.release();
|
||||
expect(await pending).toMatchObject({
|
||||
error: "Process command failed",
|
||||
code: "cancelled",
|
||||
category: "cancelled",
|
||||
});
|
||||
expect(reader.readCount).toBe(1);
|
||||
expect(reader.totalReadBytes).toBeLessThan(contents.length);
|
||||
} finally {
|
||||
controller.abort();
|
||||
reader.release();
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("process CLI input diagnostics", () => {
|
||||
it("projects missing, malformed JSON, and invalid scenario files", async () => {
|
||||
const root = await createTestTempDirectory("rea-process-cli-diagnostics-");
|
||||
const malformed = join(root, "malformed.json");
|
||||
@@ -78,6 +194,44 @@ describe("process CLI input diagnostics", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"preserves the open-file owner when close fails (cancelled: %s)",
|
||||
async (cancelDuringClose) => {
|
||||
const root = await createTestTempDirectory("rea-process-cli-cleanup-");
|
||||
const path = join(root, "scenario.json");
|
||||
await writeFile(path, JSON.stringify({ executable: process.execPath }));
|
||||
const controller = new AbortController();
|
||||
const cleanupCause = new Error("injected file close failure");
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementationOnce(async () => {
|
||||
if (cancelDuringClose) controller.abort();
|
||||
throw cleanupCause;
|
||||
});
|
||||
let failure: unknown;
|
||||
try {
|
||||
try {
|
||||
await captureProcessScenarioFile(
|
||||
path,
|
||||
process.env,
|
||||
cancelDuringClose ? controller.signal : undefined,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
failure = cause;
|
||||
}
|
||||
expect(failure).toBeInstanceOf(RegularFileCleanupFailure);
|
||||
if (!(failure instanceof RegularFileCleanupFailure))
|
||||
throw new Error("Expected the retained 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("names a leading byte-order mark instead of quoting it as a token", async () => {
|
||||
const path = join(
|
||||
await createTestTempDirectory("rea-process-cli-diagnostics-"),
|
||||
@@ -91,3 +245,40 @@ describe("process CLI input diagnostics", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const processCaptureEvidence = () =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
environment: {
|
||||
id: "fixture",
|
||||
platform: "fixture",
|
||||
architecture: "fixture",
|
||||
isolation: "process",
|
||||
},
|
||||
});
|
||||
|
||||
const stream = (json: string) => " ".repeat(8 * 1024 * 1024) + json;
|
||||
|
||||
const validTraceSpecification = () => ({
|
||||
events: [
|
||||
{
|
||||
id: "started",
|
||||
source: "lifecycle",
|
||||
exact: { state: "started" },
|
||||
},
|
||||
{
|
||||
id: "finished",
|
||||
source: "lifecycle",
|
||||
exact: { state: "finished" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [{ before: "started", after: "finished" }],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { access, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
const injectedFilesystemFailures = vi.hoisted(() => ({
|
||||
@@ -140,16 +141,17 @@ it.skipIf(process.platform === "win32").each([false, true])(
|
||||
"preserves extracted output when commit close fails (persistent: %s)",
|
||||
async (persistent) => {
|
||||
const root = await createTestTempDirectory("rea-extraction-commit-close-");
|
||||
const source = join(root, "source");
|
||||
const source = join(root, "source.zip");
|
||||
const output = join(root, "published");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "payload.txt"), "committed bytes");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("payload.txt", new TextReader("committed bytes"));
|
||||
await writeFile(source, await writer.close());
|
||||
const client = new ArtifactProvider(process.env).createClient({
|
||||
path: source,
|
||||
sourcePath: source,
|
||||
sha256: "0".repeat(64),
|
||||
kind: "archive",
|
||||
format: "asar",
|
||||
format: "zip",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
injectedFilesystemFailures.blockCloseRetries = false;
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
readSkillFile,
|
||||
skillDestinations,
|
||||
} from "../../../src/application/SetupSkill.js";
|
||||
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
|
||||
import { systemSetupHost } from "../../../src/application/SetupHost.js";
|
||||
import {
|
||||
runUninstall,
|
||||
@@ -67,7 +68,7 @@ const failFirstCloses = (path: string) => {
|
||||
};
|
||||
|
||||
describe("skill regular-file cleanup ownership", () => {
|
||||
it("keeps setup skill reads owned until setup host disposal", async () => {
|
||||
it("retains a failed setup skill read until setup host disposal", async () => {
|
||||
const home = await createTestTempDirectory("rea-setup-skill-close-");
|
||||
const [destination] = skillDestinations(home, []);
|
||||
if (destination === undefined) throw new Error("Shared skill root missing");
|
||||
@@ -81,7 +82,18 @@ describe("skill regular-file cleanup ownership", () => {
|
||||
);
|
||||
|
||||
try {
|
||||
expect(await host.skillNeedsInstall([])).toBe(true);
|
||||
const failure = await host.skillNeedsInstall([]).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(RegularFileCleanupFailure);
|
||||
expect(failure).toMatchObject({
|
||||
path: manifest,
|
||||
outcome: { kind: "completed" },
|
||||
cleanupCause: expect.objectContaining({
|
||||
message: "test holds the skill handle open",
|
||||
}),
|
||||
});
|
||||
expect(close.attempts.length).toBeGreaterThan(0);
|
||||
expect(new Set(close.attempts).size).toBe(1);
|
||||
const attemptsBeforeClose = close.attempts.length;
|
||||
@@ -147,7 +159,7 @@ describe("skill regular-file cleanup ownership", () => {
|
||||
});
|
||||
|
||||
describe("skill cleanup diagnostics", () => {
|
||||
it("preserves a doctor report and cleanup diagnostic when host close still fails", async () => {
|
||||
it("preserves read and host cleanup failures when doctor identity cannot complete", async () => {
|
||||
const home = await createTestTempDirectory("rea-doctor-skill-close-");
|
||||
const [destination] = skillDestinations(home, []);
|
||||
if (destination === undefined) throw new Error("Shared skill root missing");
|
||||
@@ -172,15 +184,23 @@ describe("skill cleanup diagnostics", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
const report = await runDoctorOwned(undefined, host, { skill: true });
|
||||
|
||||
expect(report.healthy).toBe(false);
|
||||
expect(report.identity?.skill.installed_version).toBeNull();
|
||||
expect(report.checks).toContainEqual(
|
||||
const failure = await runDoctorOwned(undefined, host, {
|
||||
skill: true,
|
||||
}).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(AggregateError);
|
||||
if (!(failure instanceof AggregateError))
|
||||
throw new Error("Doctor cleanup should preserve both failures");
|
||||
expect(failure.errors[0]).toBeInstanceOf(RegularFileCleanupFailure);
|
||||
expect(failure.errors[0]).toMatchObject({
|
||||
path: manifest,
|
||||
outcome: { kind: "completed" },
|
||||
});
|
||||
expect(failure.errors[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
name: "doctor-resource-cleanup",
|
||||
ok: false,
|
||||
detail: expect.stringContaining(manifest),
|
||||
message: expect.stringContaining(manifest),
|
||||
}),
|
||||
);
|
||||
expect(close.attempts.length).toBeGreaterThan(0);
|
||||
|
||||
@@ -32,7 +32,11 @@ import { SafeOutputTreeCreationFailure } from "../../../src/artifacts/SafeOutput
|
||||
import { selectScriptCapture } from "../../../src/browser/assets/ScriptCaptureAdapters.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { webScriptExportResultSchema } from "../../../src/domain/webScriptExport.js";
|
||||
import { PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION } from "../../../src/domain/browserNetworkEvidence.js";
|
||||
import {
|
||||
webScriptExportManifestSchema,
|
||||
webScriptExportResultSchema,
|
||||
} from "../../../src/domain/webScriptExport.js";
|
||||
import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import {
|
||||
@@ -70,6 +74,46 @@ const setup = async (capture: unknown = scriptCaptureEvidenceFixture()) => {
|
||||
return { root, input, resources };
|
||||
};
|
||||
|
||||
describe("empty URL component publication", () => {
|
||||
it("isolates empty query and fragment identities while retaining durable script bytes", async () => {
|
||||
const scripts = [
|
||||
{
|
||||
url: "https://fixture.test/ordinary.js",
|
||||
bytes: Buffer.from("export const ordinary = 1;"),
|
||||
},
|
||||
{
|
||||
url: "https://fixture.test/query.js?",
|
||||
bytes: Buffer.from("export const query = 2;"),
|
||||
},
|
||||
{
|
||||
url: "https://fixture.test/fragment.js#",
|
||||
bytes: Buffer.from("export const fragment = 3;"),
|
||||
},
|
||||
];
|
||||
const { input, resources } = await setup(scriptScenarioFixture(scripts));
|
||||
const exported = await exportWebScripts(input, resources);
|
||||
if (!exported.ok) throw exported.error;
|
||||
const result = webScriptExportResultSchema.parse(
|
||||
exported.value.normalized_result,
|
||||
);
|
||||
if (result.analysis_input === null)
|
||||
throw new Error("Missing analysis input");
|
||||
for (const [index, script] of result.scripts.entries()) {
|
||||
if (script.content.state !== "exported")
|
||||
throw new Error("Missing source bytes");
|
||||
expect(script.url).toBe(scripts[index]?.url);
|
||||
expect(script.content.layout).toBe(index === 0 ? "url-path" : "isolated");
|
||||
expect(
|
||||
await readFile(
|
||||
join(result.analysis_input.input_path, script.content.relative_path),
|
||||
),
|
||||
).toEqual(scripts[index]?.bytes);
|
||||
}
|
||||
const manifest = JSON.parse(await readFile(result.manifest.path, "utf8"));
|
||||
expect(manifest.scripts).toEqual(result.scripts);
|
||||
});
|
||||
});
|
||||
|
||||
describe("captured script publication boundary", () => {
|
||||
it("verifies durable bytes, manifest, capture identity, and existing module analysis", async () => {
|
||||
const capture = scriptScenarioFixture([
|
||||
@@ -137,43 +181,72 @@ describe("captured script publication boundary", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("links authenticated input Evidence and preserves binary and empty source bytes", async () => {
|
||||
it("links authenticated input Evidence", async () => {
|
||||
const { input, resources } = await setup();
|
||||
const result = await exportWebScripts(input, resources);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.evidence_links).toEqual([
|
||||
scriptCaptureEvidenceFixture().evidence_id,
|
||||
]);
|
||||
const binary = Buffer.from([255, 0, 254, 1]);
|
||||
const { input: binaryInput, resources: binaryResources } = await setup(
|
||||
scriptScenarioFixture([
|
||||
});
|
||||
|
||||
it.each([
|
||||
"playwright-response-body-bytes",
|
||||
"browser-decoded-response-bytes",
|
||||
] as const)(
|
||||
"preserves binary and empty response bytes and provenance for %s",
|
||||
async (representation) => {
|
||||
const binary = Buffer.from([255, 0, 254, 1]);
|
||||
const capture = scriptScenarioFixture([
|
||||
{ url: "https://fixture.test/binary.js", bytes: binary },
|
||||
{ url: "https://fixture.test/empty.js", bytes: Buffer.alloc(0) },
|
||||
]),
|
||||
);
|
||||
const binaryExport = await exportWebScripts(binaryInput, binaryResources);
|
||||
if (!binaryExport.ok) throw binaryExport.error;
|
||||
const parsed = webScriptExportResultSchema.parse(
|
||||
binaryExport.value.normalized_result,
|
||||
);
|
||||
const [first, second] = parsed.scripts;
|
||||
if (
|
||||
first?.content.state !== "exported" ||
|
||||
second?.content.state !== "exported" ||
|
||||
parsed.analysis_input === null
|
||||
)
|
||||
throw new Error("Missing exported bytes");
|
||||
expect(
|
||||
await readFile(
|
||||
join(parsed.analysis_input.input_path, first.content.relative_path),
|
||||
),
|
||||
).toEqual(binary);
|
||||
expect(
|
||||
await readFile(
|
||||
join(parsed.analysis_input.input_path, second.content.relative_path),
|
||||
),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
]);
|
||||
for (const event of capture.events.items) {
|
||||
if (event.kind === "network-content" && event.body.state === "captured")
|
||||
event.body.representation = representation;
|
||||
}
|
||||
const { input: binaryInput, resources: binaryResources } =
|
||||
await setup(capture);
|
||||
const binaryExport = await exportWebScripts(binaryInput, binaryResources);
|
||||
if (!binaryExport.ok) throw binaryExport.error;
|
||||
const parsed = webScriptExportResultSchema.parse(
|
||||
binaryExport.value.normalized_result,
|
||||
);
|
||||
const [first, second] = parsed.scripts;
|
||||
if (
|
||||
first?.content.state !== "exported" ||
|
||||
second?.content.state !== "exported" ||
|
||||
parsed.analysis_input === null
|
||||
)
|
||||
throw new Error("Missing exported bytes");
|
||||
expect(first.content.representation).toBe(representation);
|
||||
expect(second.content.representation).toBe(representation);
|
||||
expect(parsed.limitations).toContain(
|
||||
PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION,
|
||||
);
|
||||
const persisted = webScriptExportManifestSchema.parse(
|
||||
JSON.parse(await readFile(parsed.manifest.path, "utf8")),
|
||||
);
|
||||
expect(
|
||||
persisted.scripts.map(({ content }) =>
|
||||
content.state === "exported" ? content.representation : undefined,
|
||||
),
|
||||
).toEqual([representation, representation]);
|
||||
expect(persisted.limitations).toContain(
|
||||
PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION,
|
||||
);
|
||||
expect(
|
||||
await readFile(
|
||||
join(parsed.analysis_input.input_path, first.content.relative_path),
|
||||
),
|
||||
).toEqual(binary);
|
||||
expect(
|
||||
await readFile(
|
||||
join(parsed.analysis_input.input_path, second.content.relative_path),
|
||||
),
|
||||
).toHaveLength(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains missing sources in a manifest without inventing an analysis directory", async () => {
|
||||
const capture = scriptScenarioFixture();
|
||||
|
||||
@@ -199,3 +199,38 @@ describe("nested container family", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("package signature byte identity", () => {
|
||||
it.each([
|
||||
{ extension: "pkg", signature: "xar!", offset: 0, size: 4 },
|
||||
{ extension: "dmg", signature: "koly", offset: 0, size: 512 },
|
||||
])(
|
||||
"rejects high-bit aliases of $extension magic at both admission boundaries",
|
||||
async ({ extension, signature, offset, size }) => {
|
||||
const root = await createTestTempDirectory("rea-package-magic-");
|
||||
const path = join(root, `input.${extension}`);
|
||||
const bytes = Buffer.alloc(size);
|
||||
bytes.write(signature, offset, "ascii");
|
||||
await writeFile(path, bytes);
|
||||
expect(
|
||||
(await classifyAndHashRoot(path, false, await lstat(path))).format,
|
||||
).toBe(extension);
|
||||
expect(await parseBinaryTarget(path)).toMatchObject({
|
||||
ok: true,
|
||||
value: { format: extension },
|
||||
});
|
||||
for (let index = 0; index < signature.length; index += 1) {
|
||||
const changed = Buffer.from(bytes);
|
||||
changed[offset + index] = changed[offset + index]! | 0x80;
|
||||
await writeFile(path, changed);
|
||||
expect(
|
||||
(await classifyAndHashRoot(path, false, await lstat(path))).format,
|
||||
).toBe("file");
|
||||
expect(await parseBinaryTarget(path)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BinaryTargetError" },
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,595 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { readGoBinaryImage } from "../../../src/go/GoBinaryImage.js";
|
||||
import {
|
||||
createGoBinaryFixture,
|
||||
GO_MODULE_TEXT,
|
||||
} from "../../fixtures/go/image.js";
|
||||
|
||||
it.each([
|
||||
["elf", 32, "little"],
|
||||
["elf", 32, "big"],
|
||||
["elf", 64, "little"],
|
||||
["elf", 64, "big"],
|
||||
["pe", 32, "little"],
|
||||
["pe", 64, "little"],
|
||||
["macho", 32, "little"],
|
||||
["macho", 32, "big"],
|
||||
["macho", 64, "little"],
|
||||
["macho", 64, "big"],
|
||||
] as const)(
|
||||
"reads %s %d-bit %s inline build metadata",
|
||||
(format, bits, byteOrder) => {
|
||||
const fixture = createGoBinaryFixture({ format, bits, byteOrder });
|
||||
expect(readGoBinaryImage(fixture.bytes)).toMatchObject({
|
||||
format,
|
||||
bits,
|
||||
byte_order: byteOrder,
|
||||
build_info: {
|
||||
header_offset: fixture.headerOffset,
|
||||
encoding: "inline",
|
||||
go_version: "go1.26.0",
|
||||
module_text: GO_MODULE_TEXT,
|
||||
module_bytes_base64: fixture.moduleBytes.toString("base64"),
|
||||
version_location: { offset: fixture.versionOffset, bytes: 8 },
|
||||
module_location: {
|
||||
offset: fixture.moduleOffset,
|
||||
bytes: fixture.moduleBytes.length,
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"follows mapped pointers in legacy %s metadata",
|
||||
(format) => {
|
||||
const fixture = createGoBinaryFixture({
|
||||
format,
|
||||
encoding: "pointer",
|
||||
goVersion: "go1.17",
|
||||
});
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info).toMatchObject({
|
||||
encoding: "pointer",
|
||||
go_version: "go1.17",
|
||||
module_text: GO_MODULE_TEXT,
|
||||
version_location: { offset: fixture.versionOffset, bytes: 6 },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "macho"] as const)(
|
||||
"finds sectionless %s metadata in its writable data mapping",
|
||||
(format) => {
|
||||
const fixture = createGoBinaryFixture({ format, sectionless: true });
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info?.go_version).toBe(
|
||||
"go1.26.0",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not treat a code/overlay decoy or unaligned marker as Go metadata", () => {
|
||||
const absent = createGoBinaryFixture({ omitBuildInfo: true });
|
||||
const decoy = createGoBinaryFixture();
|
||||
decoy.bytes
|
||||
.subarray(decoy.headerOffset, decoy.headerOffset + 512)
|
||||
.copy(absent.bytes, 3072);
|
||||
expect(readGoBinaryImage(absent.bytes).build_info).toBeNull();
|
||||
const unaligned = createGoBinaryFixture({
|
||||
sectionless: true,
|
||||
omitBuildInfo: true,
|
||||
});
|
||||
decoy.bytes
|
||||
.subarray(decoy.headerOffset, decoy.headerOffset + 512)
|
||||
.copy(unaligned.bytes, 1025);
|
||||
expect(readGoBinaryImage(unaligned.bytes).build_info).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses mapped pointer lengths outside the file instead of rounding 64-bit addresses", () => {
|
||||
const fixture = createGoBinaryFixture({ encoding: "pointer" });
|
||||
fixture.bytes.writeBigUInt64LE(0x20000000000001n, 1536);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(
|
||||
/mapped|address/i,
|
||||
);
|
||||
const length = createGoBinaryFixture({ encoding: "pointer" });
|
||||
length.bytes.writeBigUInt64LE(0xffffffffffffffffn, 1544);
|
||||
expect(() => readGoBinaryImage(length.bytes)).toThrowError(/limit|length/i);
|
||||
});
|
||||
|
||||
it("refuses overlong or truncated varints before decoding or allocating strings", () => {
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes.fill(
|
||||
0xff,
|
||||
fixture.headerOffset + 32,
|
||||
fixture.headerOffset + 42,
|
||||
);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/varint/i);
|
||||
const truncated = createGoBinaryFixture();
|
||||
truncated.bytes.writeBigUInt64LE(33n, 256 + 64 * 2 + 32);
|
||||
truncated.bytes[truncated.headerOffset + 32] = 0x80;
|
||||
expect(() => readGoBinaryImage(truncated.bytes)).toThrowError(
|
||||
/truncated|range|varint/i,
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses invalid module framing and preserves BOMs without replacement decoding", () => {
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes[fixture.moduleOffset] = 0;
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/framing/i);
|
||||
const bom = createGoBinaryFixture({
|
||||
goVersion: "\ufeffgo1.26.0",
|
||||
moduleText: "\ufeffpath\tx\n",
|
||||
});
|
||||
expect(readGoBinaryImage(bom.bytes).build_info).toMatchObject({
|
||||
go_version: "\ufeffgo1.26.0",
|
||||
module_text: "\ufeffpath\tx\n",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects future encodings and invalid pointer widths explicitly", () => {
|
||||
const flags = createGoBinaryFixture();
|
||||
flags.bytes[flags.headerOffset + 15] = 0x82;
|
||||
expect(() => readGoBinaryImage(flags.bytes)).toThrowError(/flags/i);
|
||||
const width = createGoBinaryFixture({ encoding: "pointer" });
|
||||
width.bytes[width.headerOffset + 14] = 16;
|
||||
expect(() => readGoBinaryImage(width.bytes)).toThrowError(/pointer/i);
|
||||
});
|
||||
|
||||
it("preserves non-UTF8 compiler and module bytes without rejecting other observed metadata", () => {
|
||||
const version = createGoBinaryFixture();
|
||||
version.bytes[version.versionOffset] = 0xff;
|
||||
expect(readGoBinaryImage(version.bytes).build_info).toMatchObject({
|
||||
go_version: null,
|
||||
go_version_bytes_base64: version.bytes
|
||||
.subarray(version.versionOffset, version.versionOffset + 8)
|
||||
.toString("base64"),
|
||||
module_text: GO_MODULE_TEXT,
|
||||
});
|
||||
const module = createGoBinaryFixture({ moduleText: "build\t-tags=x\n" });
|
||||
module.bytes[module.moduleOffset + 16 + Buffer.byteLength("build\t-tags=")] =
|
||||
0xff;
|
||||
expect(readGoBinaryImage(module.bytes).build_info).toMatchObject({
|
||||
go_version: "go1.26.0",
|
||||
module_text: null,
|
||||
module_bytes_base64: module.bytes
|
||||
.subarray(
|
||||
module.moduleOffset,
|
||||
module.moduleOffset + module.moduleBytes.length,
|
||||
)
|
||||
.toString("base64"),
|
||||
});
|
||||
});
|
||||
|
||||
it.each([0, 4, 16])("ignores unused inline pointer width %s", (width) => {
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes[fixture.headerOffset + 14] = width;
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info?.go_version).toBe(
|
||||
"go1.26.0",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["pe", "macho"] as const)(
|
||||
"refuses ambiguous inline %s header mappings",
|
||||
(format) => {
|
||||
const fixture = createGoBinaryFixture({ format });
|
||||
if (format === "pe") {
|
||||
fixture.bytes.writeUInt16LE(2, 134);
|
||||
fixture.bytes.copy(fixture.bytes, 304, 264, 304);
|
||||
fixture.bytes.writeUInt32LE(512, 324);
|
||||
} else {
|
||||
fixture.bytes.writeUInt32LE(2, 16);
|
||||
fixture.bytes.writeUInt32LE(224, 20);
|
||||
fixture.bytes.writeUInt32LE(0x19, 184);
|
||||
fixture.bytes.writeUInt32LE(72, 188);
|
||||
fixture.bytes.write("__ALIAS", 192);
|
||||
fixture.bytes.writeBigUInt64LE(0x10000n, 208);
|
||||
fixture.bytes.writeBigUInt64LE(4096n, 216);
|
||||
fixture.bytes.writeBigUInt64LE(16n, 224);
|
||||
fixture.bytes.writeBigUInt64LE(4080n, 232);
|
||||
}
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/ambiguous/i);
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses a contradictory mapping that overlaps only inline string bytes", () => {
|
||||
const fixture = createGoBinaryFixture({ format: "pe" });
|
||||
fixture.bytes.writeUInt16LE(2, 134);
|
||||
fixture.bytes.copy(fixture.bytes, 304, 264, 304);
|
||||
fixture.bytes.writeUInt32LE(16, 312);
|
||||
fixture.bytes.writeUInt32LE(fixture.moduleOffset + 32, 316);
|
||||
fixture.bytes.writeUInt32LE(16, 320);
|
||||
fixture.bytes.writeUInt32LE(512, 324);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/ambiguous/i);
|
||||
});
|
||||
|
||||
it("ignores the endian flag for pointer-free strings in a big-endian image", () => {
|
||||
const fixture = createGoBinaryFixture({ byteOrder: "big" });
|
||||
fixture.bytes[fixture.headerOffset + 15] = 2;
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info?.go_version).toBe(
|
||||
"go1.26.0",
|
||||
);
|
||||
});
|
||||
|
||||
it("distinguishes unsupported containers from malformed recognized images", () => {
|
||||
expect(() =>
|
||||
readGoBinaryImage(Buffer.from([0xca, 0xfe, 0xba, 0xbe])),
|
||||
).toThrowError(/universal|fat/i);
|
||||
expect(() => readGoBinaryImage(Buffer.from("\x7fELF"))).toThrowError(
|
||||
/truncated/i,
|
||||
);
|
||||
const pe = createGoBinaryFixture({ format: "pe" });
|
||||
pe.bytes.writeUInt32LE(0xfffffff0, 60);
|
||||
expect(() => readGoBinaryImage(pe.bytes)).toThrowError(/range|truncated/i);
|
||||
});
|
||||
|
||||
it("rejects ELF header tables overlapping the native header", () => {
|
||||
const fixture = createGoBinaryFixture({ sectionless: true });
|
||||
fixture.bytes.writeBigUInt64LE(0n, 32);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(
|
||||
/header|overlap/i,
|
||||
);
|
||||
const declaredSize = createGoBinaryFixture();
|
||||
declaredSize.bytes.writeUInt16LE(8192, 52);
|
||||
expect(() => readGoBinaryImage(declaredSize.bytes)).toThrowError(
|
||||
/truncated|range/i,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects contradictory aliases when a metadata address maps to different file bytes", () => {
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes.writeUInt16LE(2, 56);
|
||||
fixture.bytes.writeUInt32LE(1, 184);
|
||||
fixture.bytes.writeUInt32LE(6, 188);
|
||||
fixture.bytes.writeBigUInt64LE(16n, 192);
|
||||
fixture.bytes.writeBigUInt64LE(0x10000n, 200);
|
||||
fixture.bytes.writeBigUInt64LE(4080n, 216);
|
||||
fixture.bytes.writeBigUInt64LE(4080n, 224);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/ambiguous/i);
|
||||
});
|
||||
|
||||
it.each(["pe", "elf"] as const)(
|
||||
"ignores a marker extending past the selected %s data boundary",
|
||||
(format) => {
|
||||
const fixture = createGoBinaryFixture({ format, omitBuildInfo: true });
|
||||
if (format === "pe") fixture.bytes.writeUInt32LE(2040, 264 + 8);
|
||||
else fixture.bytes.writeBigUInt64LE(2040n, 256 + 64 * 2 + 32);
|
||||
Buffer.from("ff20476f206275696c64696e663a", "hex").copy(
|
||||
fixture.bytes,
|
||||
3056,
|
||||
);
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([0n, 3n])(
|
||||
"rejects reserved extended ELF section counts containing %s",
|
||||
(count) => {
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes.writeUInt16LE(0, 60);
|
||||
fixture.bytes.writeBigUInt64LE(count, 256 + 32);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(
|
||||
/extended|section count/i,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["names", "programs"] as const)(
|
||||
"rejects extended ELF %s values below their reserved ranges",
|
||||
(field) => {
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes.writeUInt16LE(0xffff, field === "names" ? 62 : 56);
|
||||
fixture.bytes.writeUInt32LE(1, 256 + (field === "names" ? 40 : 44));
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/extended/i);
|
||||
},
|
||||
);
|
||||
|
||||
it("requires SHT_NULL for the initial section carrying extended ELF numbering", () => {
|
||||
const bytes = extendedElfFixture();
|
||||
bytes.writeUInt32LE(1, 4096 + 4);
|
||||
expect(() => readGoBinaryImage(bytes)).toThrowError(
|
||||
/initial|section zero|SHT_NULL/i,
|
||||
);
|
||||
});
|
||||
|
||||
it("reads a valid 65,536-entry ELF section table with an extended name-table index", () => {
|
||||
const bytes = extendedElfFixture();
|
||||
expect(readGoBinaryImage(bytes).build_info).toMatchObject({
|
||||
go_version: "go1.26.0",
|
||||
module_text: GO_MODULE_TEXT,
|
||||
});
|
||||
});
|
||||
|
||||
const extendedElfFixture = (): Buffer => {
|
||||
const fixture = createGoBinaryFixture();
|
||||
const tableOffset = 4096;
|
||||
const count = 65536;
|
||||
const bytes = Buffer.alloc(tableOffset + count * 64);
|
||||
fixture.bytes.copy(bytes);
|
||||
bytes.writeBigUInt64LE(BigInt(tableOffset), 40);
|
||||
bytes.writeUInt16LE(0, 60);
|
||||
bytes.writeUInt16LE(0xffff, 62);
|
||||
bytes.writeBigUInt64LE(BigInt(count), tableOffset + 32);
|
||||
bytes.writeUInt32LE(count - 1, tableOffset + 40);
|
||||
fixture.bytes.subarray(384, 448).copy(bytes, tableOffset + 64);
|
||||
fixture.bytes.subarray(320, 384).copy(bytes, tableOffset + (count - 1) * 64);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const legacyLayouts = [
|
||||
["elf", 32, "little"],
|
||||
["elf", 32, "big"],
|
||||
["elf", 64, "little"],
|
||||
["elf", 64, "big"],
|
||||
["pe", 32, "little"],
|
||||
["pe", 64, "little"],
|
||||
["macho", 32, "little"],
|
||||
["macho", 32, "big"],
|
||||
["macho", 64, "little"],
|
||||
["macho", 64, "big"],
|
||||
] as const;
|
||||
|
||||
it.each(legacyLayouts)(
|
||||
"reads moduleless legacy %s %d-bit %s metadata with a zero-filled module header",
|
||||
(format, bits, byteOrder) => {
|
||||
const fixture = zeroFilledModuleFixture(format, bits, byteOrder);
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info).toMatchObject({
|
||||
encoding: "pointer",
|
||||
go_version: "go1.17",
|
||||
module_text: "",
|
||||
module_bytes_base64: "",
|
||||
module_location: { offset: fixture.moduleField, bytes: 0 },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"recognizes a module header in a %s segment containing only zero-filled memory",
|
||||
(format) => {
|
||||
const fixture = zeroFilledModuleFixture(format, 64, "little", true);
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info).toMatchObject({
|
||||
go_version: "go1.17",
|
||||
module_text: "",
|
||||
module_location: { offset: fixture.moduleField, bytes: 0 },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"keeps unmapped and partial zero-filled %s module headers invalid",
|
||||
(format) => {
|
||||
const fixture = zeroFilledModuleFixture(format, 64, "little");
|
||||
fixture.bytes.writeBigUInt64LE(
|
||||
fixture.moduleAddress + 8n,
|
||||
fixture.moduleField,
|
||||
);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(
|
||||
/mapped|range/i,
|
||||
);
|
||||
fixture.bytes.writeBigUInt64LE(0x30000n, fixture.moduleField);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(
|
||||
/mapped|range/i,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"keeps compiler headers in zero-filled %s memory invalid",
|
||||
(format) => {
|
||||
const fixture = zeroFilledModuleFixture(format, 64, "little");
|
||||
fixture.bytes.writeBigUInt64LE(
|
||||
fixture.moduleAddress,
|
||||
fixture.headerOffset + 16,
|
||||
);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(
|
||||
/mapped|range/i,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"keeps nonempty string contents in zero-filled %s memory invalid",
|
||||
(format) => {
|
||||
const version = zeroFilledModuleFixture(format, 64, "little");
|
||||
version.bytes.writeBigUInt64LE(version.moduleAddress, 1536);
|
||||
expect(() => readGoBinaryImage(version.bytes)).toThrowError(
|
||||
/mapped|range/i,
|
||||
);
|
||||
const module = zeroFilledModuleFixture(format, 64, "little");
|
||||
module.bytes.writeBigUInt64LE(0x10000n + 1552n, module.moduleField);
|
||||
module.bytes.writeBigUInt64LE(module.moduleAddress, 1552);
|
||||
expect(() => readGoBinaryImage(module.bytes)).toThrowError(/mapped|range/i);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"rejects zero-filled %s extents overflowing the image address width",
|
||||
(format) => {
|
||||
const fixture = zeroFilledModuleFixture(format, 64, "little", true);
|
||||
if (format === "elf")
|
||||
fixture.bytes.writeBigUInt64LE(0xfffffffffffffff8n, 184 + 16);
|
||||
else if (format === "pe")
|
||||
fixture.bytes.writeBigUInt64LE(0xfffffffffffeffffn, 152 + 24);
|
||||
else fixture.bytes.writeBigUInt64LE(0xfffffffffffffff8n, 184 + 24);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(
|
||||
/overflow|addresses/i,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"ignores unused file offsets for %s memory with no file bytes",
|
||||
(format) => {
|
||||
const fixture = zeroFilledModuleFixture(format, 64, "little", true);
|
||||
if (format === "elf")
|
||||
fixture.bytes.writeBigUInt64LE(0xffffffffffffffffn, 184 + 8);
|
||||
else if (format === "pe") fixture.bytes.writeUInt32LE(0xffffffff, 304 + 20);
|
||||
else fixture.bytes.writeBigUInt64LE(0xffffffffffffffffn, 184 + 40);
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info?.go_version).toBe(
|
||||
"go1.17",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not treat Mach-O __PAGEZERO as a module string header", () => {
|
||||
const fixture = zeroFilledModuleFixture("macho", 64, "little", true);
|
||||
fixture.bytes.fill(0, 184 + 8, 184 + 24);
|
||||
fixture.bytes.write("__PAGEZERO", 184 + 8);
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/mapped|range/i);
|
||||
});
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"refuses file aliases overlapping only part of a zero-filled %s module header",
|
||||
(format) => {
|
||||
const fixture = zeroFilledModuleFixture(format, 64, "little");
|
||||
addLegacyMapping(fixture.bytes, format, {
|
||||
address: fixture.moduleAddress + 8n,
|
||||
fileOffset: 512,
|
||||
fileSize: 8,
|
||||
memorySize: 8,
|
||||
});
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/ambiguous/i);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["elf", "pe", "macho"] as const)(
|
||||
"refuses a file alias covering a zero-filled %s module header even when file bytes are zero",
|
||||
(format) => {
|
||||
const fixture = zeroFilledModuleFixture(format, 64, "little");
|
||||
addLegacyMapping(fixture.bytes, format, {
|
||||
address: fixture.moduleAddress,
|
||||
fileOffset: 512,
|
||||
fileSize: 16,
|
||||
memorySize: 16,
|
||||
});
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/ambiguous/i);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not infer PE zero-fill from raw padding beyond a smaller virtual size", () => {
|
||||
const fixture = createGoBinaryFixture({ format: "pe", encoding: "pointer" });
|
||||
fixture.bytes.writeUInt32LE(1024, 264 + 8);
|
||||
expect(readGoBinaryImage(fixture.bytes).build_info?.go_version).toBe(
|
||||
"go1.26.0",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["inline", "pointer"] as const)(
|
||||
"refuses zero-filled aliases overlapping only %s string bytes",
|
||||
(encoding) => {
|
||||
const fixture = createGoBinaryFixture({ format: "pe", encoding });
|
||||
addLegacyMapping(fixture.bytes, "pe", {
|
||||
address: 0x10000n + BigInt(fixture.moduleOffset + 32),
|
||||
fileOffset: 0,
|
||||
fileSize: 0,
|
||||
memorySize: 8,
|
||||
});
|
||||
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/ambiguous/i);
|
||||
},
|
||||
);
|
||||
|
||||
const zeroFilledModuleFixture = (
|
||||
format: "elf" | "pe" | "macho",
|
||||
bits: 32 | 64,
|
||||
byteOrder: "little" | "big",
|
||||
separateSegment = false,
|
||||
) => {
|
||||
const fixture = createGoBinaryFixture({
|
||||
format,
|
||||
bits,
|
||||
byteOrder,
|
||||
encoding: "pointer",
|
||||
goVersion: "go1.17",
|
||||
});
|
||||
const view = new DataView(
|
||||
fixture.bytes.buffer,
|
||||
fixture.bytes.byteOffset,
|
||||
fixture.bytes.byteLength,
|
||||
);
|
||||
const little = byteOrder === "little";
|
||||
const moduleAddress = separateSegment
|
||||
? 0x20000n
|
||||
: format === "pe"
|
||||
? 0x10c00n
|
||||
: 0x11000n;
|
||||
const moduleField = fixture.headerOffset + 16 + bits / 8;
|
||||
if (bits === 64) view.setBigUint64(moduleField, moduleAddress, little);
|
||||
else view.setUint32(moduleField, Number(moduleAddress), little);
|
||||
if (separateSegment) {
|
||||
addLegacyMapping(
|
||||
fixture.bytes,
|
||||
format,
|
||||
{ address: moduleAddress, fileOffset: 0, fileSize: 0, memorySize: 16 },
|
||||
{ bits, little },
|
||||
);
|
||||
} else if (format === "elf") {
|
||||
if (bits === 64) view.setBigUint64(168, 4112n, little);
|
||||
else view.setUint32(148, 4112, little);
|
||||
} else if (format === "pe") {
|
||||
view.setUint32(152 + (bits === 64 ? 112 : 96) + 8, 2064, little);
|
||||
} else if (bits === 64) {
|
||||
view.setBigUint64(32 + 32, 4112n, little);
|
||||
} else {
|
||||
view.setUint32(28 + 28, 4112, little);
|
||||
}
|
||||
return { ...fixture, moduleAddress, moduleField };
|
||||
};
|
||||
|
||||
const addLegacyMapping = (
|
||||
bytes: Buffer,
|
||||
format: "elf" | "pe" | "macho",
|
||||
{
|
||||
address,
|
||||
fileOffset,
|
||||
fileSize,
|
||||
memorySize,
|
||||
}: {
|
||||
address: bigint;
|
||||
fileOffset: number;
|
||||
fileSize: number;
|
||||
memorySize: number;
|
||||
},
|
||||
{ bits, little }: { bits: 32 | 64; little: boolean } = {
|
||||
bits: 64,
|
||||
little: true,
|
||||
},
|
||||
): void => {
|
||||
const wide = bits === 64;
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const u32 = (offset: number, value: number) =>
|
||||
view.setUint32(offset, value, little);
|
||||
const word = (offset: number, value: bigint) => {
|
||||
if (wide) view.setBigUint64(offset, value, little);
|
||||
else u32(offset, Number(value));
|
||||
};
|
||||
if (format === "elf") {
|
||||
view.setUint16(wide ? 56 : 44, 2, little);
|
||||
const entry = 128 + (wide ? 56 : 32);
|
||||
u32(entry, 1);
|
||||
u32(entry + (wide ? 4 : 24), 6);
|
||||
word(entry + (wide ? 8 : 4), BigInt(fileOffset));
|
||||
word(entry + (wide ? 16 : 8), address);
|
||||
word(entry + (wide ? 32 : 16), BigInt(fileSize));
|
||||
word(entry + (wide ? 40 : 20), BigInt(memorySize));
|
||||
} else if (format === "pe") {
|
||||
view.setUint16(134, 2, little);
|
||||
const entry = 152 + (wide ? 112 : 96) + 40;
|
||||
u32(entry + 8, memorySize);
|
||||
u32(entry + 12, Number(address - 0x10000n));
|
||||
u32(entry + 16, fileSize);
|
||||
u32(entry + 20, fileOffset);
|
||||
u32(entry + 36, 0xc0000040);
|
||||
} else {
|
||||
const entry = wide ? 32 + 72 + 80 : 28 + 56 + 68;
|
||||
const size = wide ? 72 : 56;
|
||||
u32(16, 2);
|
||||
u32(20, entry + size - (wide ? 32 : 28));
|
||||
u32(entry, wide ? 0x19 : 1);
|
||||
u32(entry + 4, size);
|
||||
bytes.write("__EXTRA", entry + 8);
|
||||
word(entry + 24, address);
|
||||
word(entry + (wide ? 32 : 28), BigInt(memorySize));
|
||||
word(entry + (wide ? 40 : 32), BigInt(fileOffset));
|
||||
word(entry + (wide ? 48 : 36), BigInt(fileSize));
|
||||
u32(entry + (wide ? 56 : 40), 3);
|
||||
u32(entry + (wide ? 60 : 44), 3);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { mappedFileOffset } from "../../../src/go/GoBinaryContainer.js";
|
||||
|
||||
const selected = { address: 100n, offset: 16, size: 64 };
|
||||
|
||||
it.each([
|
||||
{ address: 132n, offset: 4, size: 4 },
|
||||
{ address: 112n, offset: 4, size: 12 },
|
||||
])(
|
||||
"rejects a contradictory alias overlapping only part of the selected bytes",
|
||||
(alias) => {
|
||||
expect(() => mappedFileOffset([selected, alias], 120n, 24)).toThrowError(
|
||||
/ambiguous/i,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("accepts overlapping aliases that identify exactly the same file bytes", () => {
|
||||
expect(
|
||||
mappedFileOffset(
|
||||
[selected, { address: 132n, offset: 48, size: 4 }],
|
||||
120n,
|
||||
24,
|
||||
),
|
||||
).toBe(36);
|
||||
});
|
||||
|
||||
it("does not confuse adjacent mappings with overlapping byte spans", () => {
|
||||
const adjacent = { address: 164n, offset: 80, size: 32 };
|
||||
expect(mappedFileOffset([selected, adjacent], 140n, 24)).toBe(56);
|
||||
expect(mappedFileOffset([selected, adjacent], 164n, 0)).toBe(80);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ address: 132n, size: 4n },
|
||||
{ address: 112n, size: 12n },
|
||||
])(
|
||||
"rejects zero-fill aliases overlapping part of file-backed bytes",
|
||||
(zeroFill) => {
|
||||
expect(() =>
|
||||
mappedFileOffset([selected], 120n, 24, [zeroFill]),
|
||||
).toThrowError(/ambiguous/i);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps adjacent zero-filled memory outside the selected file span", () => {
|
||||
expect(
|
||||
mappedFileOffset([selected], 140n, 24, [{ address: 164n, size: 32n }]),
|
||||
).toBe(56);
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { writeFile, symlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../../../src/domain/analysisErrorCore.js";
|
||||
import {
|
||||
createGoBinaryDiagnosticFixtures,
|
||||
createGoBinaryFixture,
|
||||
} from "../../fixtures/go/image.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("distinguishes unsupported MZ carriers from damaged PE declarations", async () => {
|
||||
const root = await createTestTempDirectory("rea-go-mz-");
|
||||
for (const fixture of createGoBinaryDiagnosticFixtures()) {
|
||||
const path = join(root, `${fixture.name}.exe`);
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await new GoBinaryProvider().inspect({ path });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error).toBeInstanceOf(
|
||||
fixture.code === "unsupported_target"
|
||||
? AnalysisUnsupportedTargetError
|
||||
: AnalysisInputError,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([32, 64] as const)(
|
||||
"rejects advertised PE%d data directories outside the optional header",
|
||||
async (bits) => {
|
||||
const root = await createTestTempDirectory("rea-go-pe-directories-");
|
||||
const fixture = createGoBinaryFixture({ format: "pe", bits });
|
||||
fixture.bytes.writeUInt32LE(1, 152 + (bits === 64 ? 108 : 92));
|
||||
const path = join(root, `truncated-pe${String(bits)}.exe`);
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await new GoBinaryProvider().inspect({ path });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBeInstanceOf(AnalysisInputError);
|
||||
if (!(result.error instanceof AnalysisInputError)) throw result.error;
|
||||
expect(result.error.issues).toContainEqual(
|
||||
expect.objectContaining({ reason: "invalid_format" }),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([{ signature: [0xce, 0xc5] }, { signature: [0xcc, 0xd8] }])(
|
||||
"rejects high-bit lookalikes of Windows signatures %j",
|
||||
async ({ signature }) => {
|
||||
const root = await createTestTempDirectory("rea-go-pe-signature-");
|
||||
const fixture = createGoBinaryFixture({ format: "pe" });
|
||||
fixture.bytes.set(signature, 128);
|
||||
const path = join(root, "corrupt-signature.exe");
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await new GoBinaryProvider().inspect({ path });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisInputError);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the actual build-info byte guard as a resource failure", async () => {
|
||||
const fixture = createGoBinaryFixture();
|
||||
fixture.bytes.set([0x81, 0x80, 0x40], fixture.headerOffset + 32);
|
||||
const root = await createTestTempDirectory("rea-go-resource-");
|
||||
const path = join(root, "oversized-metadata.elf");
|
||||
await writeFile(path, fixture.bytes);
|
||||
const result = await new GoBinaryProvider().inspect({ path });
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok)
|
||||
throw new Error("Oversized embedded metadata must not succeed");
|
||||
expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
|
||||
if (!(result.error instanceof AnalysisResourceConstraintError))
|
||||
throw result.error;
|
||||
expect(result.error.reason).toContain(path);
|
||||
expect(result.error.reportedLimits).toEqual({
|
||||
boundary: "build-info",
|
||||
maximum_bytes: 1024 * 1024,
|
||||
});
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects a symlink without replacing its selected file identity",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-go-symlink-");
|
||||
const selected = join(root, "selected");
|
||||
const original = join(root, "original.elf");
|
||||
await writeFile(original, createGoBinaryFixture().bytes);
|
||||
await symlink(original, selected);
|
||||
const result = await new GoBinaryProvider().inspect({ path: selected });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisInputError);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,177 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
parseGoModuleBytes,
|
||||
parseGoModuleText,
|
||||
} from "../../../src/go/GoModuleText.js";
|
||||
|
||||
describe("Go producer module text", () => {
|
||||
it("preserves local replacements, empty fields and ordered duplicate build settings", () => {
|
||||
const parsed = parseGoModuleText(
|
||||
"path\texample.invalid/app\nmod\texample.invalid/app\t(devel)\t\ndep\texample.invalid/lib\tv1.2.3\th1:bytes\n=>\t../local lib\t\t\nbuild\tGOOS=linux\nbuild\tGOOS=custom\nbuild\t__proto__=kept\n",
|
||||
);
|
||||
expect(parsed).toMatchObject({
|
||||
path: "example.invalid/app",
|
||||
main: { version: "(devel)", sum: "" },
|
||||
dependencies: [
|
||||
{
|
||||
path: "example.invalid/lib",
|
||||
version: "v1.2.3",
|
||||
sum: "h1:bytes",
|
||||
replacement: { path: "../local lib", version: "", sum: "" },
|
||||
},
|
||||
],
|
||||
settings: [
|
||||
{ key: "GOOS", value: "linux" },
|
||||
{ key: "GOOS", value: "custom" },
|
||||
{ key: "__proto__", value: "kept" },
|
||||
],
|
||||
complete: true,
|
||||
unparsed_lines: [],
|
||||
unparsed_line_bytes_base64: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes Go quoting including byte, octal and Unicode escapes without JSON substitution", () => {
|
||||
const text =
|
||||
String.raw`build\t"key=quoted"="\a\v\xC3\xA9\303\251\u263a\U0001F680"`.replace(
|
||||
"\\t",
|
||||
"\t",
|
||||
) +
|
||||
"\n" +
|
||||
"build\traw=`a\rb`\n";
|
||||
expect(parseGoModuleText(text)).toMatchObject({
|
||||
settings: [
|
||||
{ key: "key=quoted", value: "\x07\x0béé☺🚀" },
|
||||
{ key: "raw", value: "ab" },
|
||||
],
|
||||
complete: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports unparsed records and malformed escaped bytes while retaining observed fields", () => {
|
||||
const text =
|
||||
'path\tapp\nmod\tapp\t(devel)\nbuild\tbad="\\xff"\nfuture\tdata\nbuild\tGOARCH=amd64';
|
||||
expect(parseGoModuleText(text)).toMatchObject({
|
||||
path: "app",
|
||||
main: { sum: null },
|
||||
settings: [],
|
||||
complete: false,
|
||||
unparsed_lines: [
|
||||
'build\tbad="\\xff"',
|
||||
"future\tdata",
|
||||
"build\tGOARCH=amd64",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not attach a replacement after a malformed module declaration", () => {
|
||||
const parsed = parseGoModuleText(
|
||||
"dep\tfirst\tv1\ndep\tmalformed\n=>\tlocal\t\t\n",
|
||||
);
|
||||
expect(parsed.dependencies).toEqual([
|
||||
{ path: "first", version: "v1", sum: null, replacement: null },
|
||||
]);
|
||||
expect(parsed.complete).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves duplicate singleton declarations as unknown instead of silently overwriting", () => {
|
||||
expect(
|
||||
parseGoModuleText(
|
||||
"path\tfirst\npath\tsecond\nmod\tfirst\tv1\nmod\tsecond\tv2\n",
|
||||
),
|
||||
).toMatchObject({
|
||||
path: "first",
|
||||
main: { path: "first", version: "v1" },
|
||||
unparsed_lines: ["path\tsecond", "mod\tsecond\tv2"],
|
||||
complete: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Go producer module bytes", () => {
|
||||
it("retains byte-valued producer settings and parses surrounding UTF-8 records", () => {
|
||||
const setting = Buffer.concat([
|
||||
Buffer.from("build\t-tags="),
|
||||
Buffer.from([0xff]),
|
||||
]);
|
||||
const trailing = Buffer.from([0xfe]);
|
||||
const parsed = parseGoModuleBytes(
|
||||
Buffer.concat([
|
||||
Buffer.from("path\tapp\nmod\tapp\t(devel)\t\nbuild\tGOOS=linux\n"),
|
||||
setting,
|
||||
Buffer.from("\nbuild\tGOARCH=amd64\n"),
|
||||
trailing,
|
||||
]),
|
||||
);
|
||||
expect(parsed).toEqual({
|
||||
path: "app",
|
||||
main: { path: "app", version: "(devel)", sum: "", replacement: null },
|
||||
dependencies: [],
|
||||
settings: [
|
||||
{ key: "GOOS", value: "linux" },
|
||||
{ key: "GOARCH", value: "amd64" },
|
||||
],
|
||||
unparsed_lines: [],
|
||||
unparsed_line_bytes_base64: [
|
||||
setting.toString("base64"),
|
||||
trailing.toString("base64"),
|
||||
],
|
||||
complete: false,
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["mod", "dep", "=>"])(
|
||||
"does not bind a replacement through an undecodable %s record",
|
||||
(record) => {
|
||||
const invalid = Buffer.concat([
|
||||
Buffer.from(`${record}\t`),
|
||||
Buffer.from([0xff]),
|
||||
Buffer.from("\tv2\t"),
|
||||
]);
|
||||
expect(
|
||||
parseGoModuleBytes(
|
||||
Buffer.concat([
|
||||
Buffer.from("dep\tfirst\tv1\n"),
|
||||
invalid,
|
||||
Buffer.from("\n=>\tlocal\t\t\n"),
|
||||
]),
|
||||
),
|
||||
).toMatchObject({
|
||||
dependencies: [
|
||||
{ path: "first", version: "v1", sum: null, replacement: null },
|
||||
],
|
||||
unparsed_lines: ["=>\tlocal\t\t"],
|
||||
unparsed_line_bytes_base64: [invalid.toString("base64")],
|
||||
complete: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["build\t-tags=", "future\t"])(
|
||||
"preserves replacement context through an undecodable %s record",
|
||||
(prefix) => {
|
||||
const invalid = Buffer.concat([Buffer.from(prefix), Buffer.from([0xff])]);
|
||||
expect(
|
||||
parseGoModuleBytes(
|
||||
Buffer.concat([
|
||||
Buffer.from("dep\tfirst\tv1\n"),
|
||||
invalid,
|
||||
Buffer.from("\n=>\tlocal\t\t\n"),
|
||||
]),
|
||||
),
|
||||
).toMatchObject({
|
||||
dependencies: [
|
||||
{
|
||||
path: "first",
|
||||
version: "v1",
|
||||
sum: null,
|
||||
replacement: { path: "local", version: "", sum: "" },
|
||||
},
|
||||
],
|
||||
unparsed_lines: [],
|
||||
unparsed_line_bytes_base64: [invalid.toString("base64")],
|
||||
complete: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -235,6 +235,68 @@ test("returns every target exposed by the selected Inspector endpoint inline", a
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ label: "omitted", attached: undefined, expected: null },
|
||||
{ label: "explicitly detached", attached: false, expected: false },
|
||||
] as const)(
|
||||
"preserves $label V8 attachment state through listing and observation",
|
||||
async ({ attached, expected }) => {
|
||||
const fixture = await runtimeFixture();
|
||||
const fake = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(fixture.entry).href,
|
||||
...(attached === undefined ? {} : { attached }),
|
||||
});
|
||||
try {
|
||||
const provider = new V8InspectorProvider();
|
||||
const listed = await provider.listTargets({
|
||||
inspector_endpoint: fake.endpoint,
|
||||
});
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets[0]?.attached).toBe(expected);
|
||||
if (expected === null)
|
||||
expect(
|
||||
listed.value.limitations.some((item) =>
|
||||
item.includes("attachment state"),
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const observed = await provider.observe(
|
||||
observeInput(fake.endpoint, fake.targetId, "node"),
|
||||
);
|
||||
if (!observed.ok) throw observed.error;
|
||||
expect(observed.value.target.attached).toBe(expected);
|
||||
if (expected === null)
|
||||
expect(
|
||||
observed.value.limitations.some((item) =>
|
||||
item.includes("attachment state"),
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
await fake.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("rejects a V8 target explicitly marked attached", async () => {
|
||||
const fixture = await runtimeFixture();
|
||||
const fake = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(fixture.entry).href,
|
||||
attached: true,
|
||||
});
|
||||
try {
|
||||
const result = await new V8InspectorProvider().observe(
|
||||
observeInput(fake.endpoint, fake.targetId, "node"),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "target_not_allowed" },
|
||||
});
|
||||
expect(fake.commands).toEqual([]);
|
||||
} finally {
|
||||
await fake.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("includes targets outside the old caller root filter", async () => {
|
||||
const fixture = await runtimeFixture();
|
||||
const outside = await temporaryFile("outside.js");
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
serializeEvidenceBundle,
|
||||
} from "../../../src/domain/evidenceBundle.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { holdFirstFileRead } from "../../support/holdFirstFileRead.js";
|
||||
|
||||
it("leaves the session unchanged after bundle comparison cancellation and permits a retry", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-compare-cancel-");
|
||||
const leftPath = join(root, "left.json");
|
||||
const rightPath = join(root, "right.json");
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const left = createEvidence(undefined, provider, {
|
||||
operation: "observation",
|
||||
parameters: { side: "left" },
|
||||
result: { side: "left" },
|
||||
});
|
||||
const right = createEvidence(undefined, provider, {
|
||||
operation: "observation",
|
||||
parameters: { side: "right" },
|
||||
result: { side: "right" },
|
||||
});
|
||||
const leftContents =
|
||||
" ".repeat(8 * 1024 * 1024) +
|
||||
serializeEvidenceBundle(createEvidenceBundle([left]));
|
||||
await Promise.all([
|
||||
// Just over the native-parse budget, without a large JSON tree.
|
||||
writeFile(leftPath, leftContents),
|
||||
writeFile(
|
||||
rightPath,
|
||||
serializeEvidenceBundle(createEvidenceBundle([right])),
|
||||
),
|
||||
]);
|
||||
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Bundle comparison must not start a binary provider");
|
||||
});
|
||||
const existing = createEvidence(undefined, provider, {
|
||||
operation: "existing_observation",
|
||||
parameters: {},
|
||||
result: { retained: true },
|
||||
});
|
||||
const recorded = session.recordEvidence(existing);
|
||||
if (!recorded.ok) throw recorded.error;
|
||||
const before = session.exportEvidenceBundle();
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({
|
||||
name: "bundle-comparison-cancellation",
|
||||
version: "1",
|
||||
});
|
||||
const controller = new AbortController();
|
||||
let releaseRead: (() => void) | undefined;
|
||||
onTestFinished(async () => {
|
||||
controller.abort();
|
||||
releaseRead?.();
|
||||
vi.restoreAllMocks();
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const reader = await holdFirstFileRead(leftPath);
|
||||
releaseRead = reader.release;
|
||||
|
||||
let resolveDispatched: (() => void) | undefined;
|
||||
const dispatched = new Promise<void>((resolve) => {
|
||||
resolveDispatched = resolve;
|
||||
});
|
||||
const send = clientTransport.send.bind(clientTransport);
|
||||
vi.spyOn(clientTransport, "send").mockImplementation(
|
||||
async (message, ...args) => {
|
||||
await send(message, ...args);
|
||||
if ("method" in message && message.method === "tools/call")
|
||||
resolveDispatched?.();
|
||||
},
|
||||
);
|
||||
let resolveCompleted: (() => void) | undefined;
|
||||
const completed = new Promise<void>((resolve) => {
|
||||
resolveCompleted = resolve;
|
||||
});
|
||||
let settledResult: unknown;
|
||||
const deliver = ToolResultDelivery.prototype.toCallToolResult;
|
||||
vi.spyOn(ToolResultDelivery.prototype, "toCallToolResult").mockImplementation(
|
||||
function (this: ToolResultDelivery, result, contract) {
|
||||
const reply = deliver.call(this, result, contract);
|
||||
if (contract.name === "compare_bundles") {
|
||||
settledResult = result;
|
||||
resolveCompleted?.();
|
||||
}
|
||||
return reply;
|
||||
},
|
||||
);
|
||||
|
||||
const args = {
|
||||
left_bundle_path: leftPath,
|
||||
right_bundle_path: rightPath,
|
||||
record_pairs: [
|
||||
{
|
||||
left_evidence_id: left.evidence_id,
|
||||
right_evidence_id: right.evidence_id,
|
||||
},
|
||||
],
|
||||
};
|
||||
const cancellation = client
|
||||
.callTool(
|
||||
{ name: "compare_bundles", arguments: args },
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then(
|
||||
() => "completed",
|
||||
(error: unknown) => error,
|
||||
);
|
||||
await dispatched;
|
||||
await reader.firstRead;
|
||||
await client.ping();
|
||||
controller.abort(new Error("SDK bundle comparison cancellation"));
|
||||
reader.release();
|
||||
expect(await cancellation).toMatchObject({
|
||||
message: expect.stringContaining("SDK bundle comparison cancellation"),
|
||||
});
|
||||
// Wait for the handler's delivered Result as well as the client's rejection.
|
||||
await completed;
|
||||
expect(settledResult).toMatchObject({
|
||||
ok: false,
|
||||
error: expect.any(AnalysisCancelledError),
|
||||
});
|
||||
expect(reader.readCount).toBe(1);
|
||||
expect(reader.totalReadBytes).toBeLessThan(leftContents.length);
|
||||
expect(session.exportEvidenceBundle()).toEqual(before);
|
||||
|
||||
await client.ping();
|
||||
const retry = await client.callTool({
|
||||
name: "compare_bundles",
|
||||
arguments: args,
|
||||
});
|
||||
expect(retry.isError, JSON.stringify(retry)).not.toBe(true);
|
||||
expect(retry.structuredContent).toMatchObject({
|
||||
normalized_result: { status: "changed" },
|
||||
});
|
||||
const after = session.exportEvidenceBundle();
|
||||
expect(after.unknowns).toEqual(before.unknowns);
|
||||
expect(after.records).toEqual(
|
||||
expect.arrayContaining([
|
||||
...before.records,
|
||||
left,
|
||||
right,
|
||||
expect.objectContaining({
|
||||
operation: "compare_bundles",
|
||||
evidence_links: [left.evidence_id, right.evidence_id],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
@@ -134,7 +134,9 @@ describe("bundle comparison MCP integration", () => {
|
||||
expect(result.isError).toBe(true);
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "evidence_integrity_mismatch",
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: { path: recordPath },
|
||||
message: expect.stringContaining(
|
||||
`this JSON is one Evidence record (${record.evidence_id})`,
|
||||
),
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createAnalysisExecution } from "../../../src/application/AnalysisProvid
|
||||
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisOutputError,
|
||||
} from "../../../src/domain/analysisErrorCore.js";
|
||||
import type { RelationshipCoverage } from "../../../src/domain/relationshipCoverage.js";
|
||||
@@ -178,6 +179,125 @@ describe("enhanced MCP tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("trace_call_path MCP outcome semantics", () => {
|
||||
it("reports an unreachable goal as unknown when relationship coverage is partial", async () => {
|
||||
const client = await connect({
|
||||
execute: async (name, arguments_) => {
|
||||
if (name === "procedure_address")
|
||||
return relationshipExecution(String(arguments_.procedure));
|
||||
if (name !== "procedure_callees")
|
||||
throw new Error(`Unexpected operation: ${name}`);
|
||||
return relationshipExecution([], [], {
|
||||
status: "partial",
|
||||
limitations: ["one or more callees may be missing"],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const trace = await client.callTool({
|
||||
name: "trace_call_path",
|
||||
arguments: { start: "0x1", goal: "0x2" },
|
||||
});
|
||||
expect(trace.isError).not.toBe(true);
|
||||
expect(trace.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
goal_status: "unknown",
|
||||
truncated: true,
|
||||
relationship_coverage: { "0x1": { status: "partial" } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an unreachable goal as unknown when an expansion fails", async () => {
|
||||
const client = await connect({
|
||||
execute: async (name, arguments_) => {
|
||||
if (name === "procedure_address")
|
||||
return relationshipExecution(String(arguments_.procedure));
|
||||
if (name !== "procedure_callees")
|
||||
throw new Error(`Unexpected operation: ${name}`);
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"fixture",
|
||||
name,
|
||||
"relationship read unavailable",
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const trace = await client.callTool({
|
||||
name: "trace_call_path",
|
||||
arguments: { start: "0x1", goal: "0x2" },
|
||||
});
|
||||
expect(trace.isError).not.toBe(true);
|
||||
expect(trace.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
goal_status: "unknown",
|
||||
failures: [{ address: "0x1" }],
|
||||
truncated: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an unreachable goal as absent after complete traversal", async () => {
|
||||
const client = await connect({
|
||||
execute: async (name, arguments_) => {
|
||||
if (name === "procedure_address")
|
||||
return relationshipExecution(String(arguments_.procedure));
|
||||
if (name !== "procedure_callees")
|
||||
throw new Error(`Unexpected operation: ${name}`);
|
||||
return relationshipExecution([], [], { status: "complete" });
|
||||
},
|
||||
});
|
||||
|
||||
const trace = await client.callTool({
|
||||
name: "trace_call_path",
|
||||
arguments: { start: "0x1", goal: "0x2" },
|
||||
});
|
||||
expect(trace.isError).not.toBe(true);
|
||||
expect(trace.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
goal_status: "not_reached",
|
||||
truncated: false,
|
||||
residual_unknowns: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("propagates cancellation during expansion without visiting another frontier", async () => {
|
||||
const controller = new AbortController();
|
||||
const calls: string[] = [];
|
||||
const client = await connect({
|
||||
execute: async (name, arguments_, options) => {
|
||||
calls.push(name);
|
||||
if (name === "procedure_address")
|
||||
return relationshipExecution(String(arguments_.procedure));
|
||||
if (name !== "procedure_callees")
|
||||
throw new Error(`Unexpected operation: ${name}`);
|
||||
controller.abort();
|
||||
if (options?.signal?.aborted !== true)
|
||||
throw new Error("provider request was not cancelled");
|
||||
return err(new AnalysisCancelledError(name));
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.callTool(
|
||||
{
|
||||
name: "trace_call_path",
|
||||
arguments: { start: "0x1", goal: "0x3" },
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
).rejects.toThrow();
|
||||
expect(calls).toEqual([
|
||||
"procedure_address",
|
||||
"procedure_address",
|
||||
"procedure_callees",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("enhanced MCP batches", () => {
|
||||
it("returns every batch item in caller order with its own result", async () => {
|
||||
const addresses = Array.from(
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
@@ -137,3 +138,121 @@ it("keeps the complete session unchanged after SDK import cancellation and permi
|
||||
);
|
||||
await client.ping();
|
||||
});
|
||||
|
||||
it("retains a failed import close in the server scope through SDK error projection", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-import-close-");
|
||||
const path = join(root, "bundle.json");
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Evidence import must not start a binary provider");
|
||||
});
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const existing = createEvidence(undefined, provider, {
|
||||
operation: "existing_observation",
|
||||
parameters: {},
|
||||
result: { retained: true },
|
||||
});
|
||||
const imported = createEvidence(undefined, provider, {
|
||||
operation: "imported_observation",
|
||||
parameters: {},
|
||||
result: { retained: "close failure" },
|
||||
});
|
||||
const recorded = session.recordEvidence(existing);
|
||||
if (!recorded.ok) throw recorded.error;
|
||||
await writeFile(path, JSON.stringify(createEvidenceBundle([imported])));
|
||||
|
||||
let allowClose = false;
|
||||
let retainedOwner: OwnedFileHandle | undefined;
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
retainedOwner ??= this;
|
||||
if (!allowClose) throw new Error("persistent file close failure");
|
||||
return originalClose.call(this);
|
||||
});
|
||||
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({
|
||||
name: "evidence-import-close-failure",
|
||||
version: "1",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
allowClose = true;
|
||||
close.mockRestore();
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const before = session.exportEvidenceBundle();
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle()).toEqual(before);
|
||||
expect(retainedOwner).toBeDefined();
|
||||
expect(retainedOwner?.handle.fd).toBeGreaterThanOrEqual(0);
|
||||
|
||||
await client.close();
|
||||
await expect(server.close()).rejects.toThrow("REA session cleanup failed");
|
||||
expect(retainedOwner?.handle.fd).toBeGreaterThanOrEqual(0);
|
||||
allowClose = true;
|
||||
close.mockRestore();
|
||||
await server.close();
|
||||
expect(retainedOwner?.handle.fd).toBe(-1);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("retries a transient import close failure before admitting the bundle", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-import-close-retry-");
|
||||
const path = join(root, "bundle.json");
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Evidence import must not start a binary provider");
|
||||
});
|
||||
const imported = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
operation: "imported_observation",
|
||||
parameters: {},
|
||||
result: { retained: "retry succeeded" },
|
||||
},
|
||||
);
|
||||
await writeFile(path, JSON.stringify(createEvidenceBundle([imported])));
|
||||
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementationOnce(async () => {
|
||||
throw new Error("one transient file close failure");
|
||||
});
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({
|
||||
name: "evidence-import-close-retry",
|
||||
version: "1",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
close.mockRestore();
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path },
|
||||
});
|
||||
close.mockRestore();
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toContainEqual(imported);
|
||||
await client.ping();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
|
||||
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
|
||||
import { LazyAnalysisProvider } from "../../../src/application/binary/LazyAnalysisProvider.js";
|
||||
import { parseConfig } from "../../../src/config/parseConfig.js";
|
||||
import { elf } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { GhidraClient } from "../../../src/ghidra/GhidraClient.js";
|
||||
import type { GhidraInstallationHost } from "../../../src/ghidra/GhidraInstallation.js";
|
||||
import type {
|
||||
GhidraLaunchSession,
|
||||
GhidraLauncher,
|
||||
} from "../../../src/ghidra/GhidraLauncher.js";
|
||||
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { waitForExit } from "../../support/process/processFixture.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../fixtures/fakeGhidra.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
type FixtureLaunch = {
|
||||
child: ChildProcess;
|
||||
runtimeRoot: string;
|
||||
endpointPath: string;
|
||||
};
|
||||
|
||||
class FixtureLauncher implements GhidraLauncher {
|
||||
readonly launches: FixtureLaunch[] = [];
|
||||
readonly requests: string[] = [];
|
||||
cleanupAllowed = true;
|
||||
cleanupAttempts = 0;
|
||||
|
||||
async launch(session: GhidraLaunchSession) {
|
||||
const projectRoot = join(session.runtimeRoot, "project");
|
||||
await mkdir(projectRoot, { recursive: true });
|
||||
const child = spawn(process.execPath, [fixturePath], {
|
||||
stdio: ["ignore", "pipe", "pipe", "ipc"],
|
||||
env: {
|
||||
...process.env,
|
||||
REA_GHIDRA_FIXTURE_CONFIG: JSON.stringify({
|
||||
endpointPath: session.endpointPath,
|
||||
token: session.token,
|
||||
runId: session.runId,
|
||||
providerVersion: session.providerVersion,
|
||||
profileDigest: session.profileDigest,
|
||||
targetSha256: session.targetSha256,
|
||||
transport: session.transport,
|
||||
}),
|
||||
},
|
||||
});
|
||||
this.launches.push({
|
||||
child,
|
||||
runtimeRoot: session.runtimeRoot,
|
||||
endpointPath: session.endpointPath,
|
||||
});
|
||||
child.on("message", (value: unknown) => {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"method" in value &&
|
||||
typeof value.method === "string"
|
||||
)
|
||||
this.requests.push(value.method);
|
||||
});
|
||||
return ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true as const,
|
||||
projectRoot,
|
||||
ghidraLogPath: join(session.runtimeRoot, "ghidra.log"),
|
||||
scriptLogPath: join(session.runtimeRoot, "script.log"),
|
||||
cleanup: async () => {
|
||||
this.cleanupAttempts += 1;
|
||||
if (!this.cleanupAllowed)
|
||||
return {
|
||||
cleaned: false as const,
|
||||
reason: "fixture cleanup is not yet confirmed",
|
||||
};
|
||||
const signaled = child.exitCode === null && child.signalCode === null;
|
||||
if (signaled) child.kill("SIGTERM");
|
||||
return (await waitForExit(child, 2_000))
|
||||
? { cleaned: true as const, signaled }
|
||||
: { cleaned: false as const, reason: "fixture child did not exit" };
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const installationHost: GhidraInstallationHost = {
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
readText: () => "application.version=12.1.4\n",
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/fixture/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
};
|
||||
|
||||
// Only installation discovery and the Java bridge are simulated. Requests use
|
||||
// the production client, real child/socket and public MCP session routing.
|
||||
const connectGhidra = async () => {
|
||||
const directory = await createTestTempDirectory("rea-ghidra-reopen-");
|
||||
const target = join(directory, "target.elf");
|
||||
const source = elf(2, 1, 62);
|
||||
await writeFile(target, source);
|
||||
const config = parseConfig({
|
||||
GHIDRA_INSTALL_DIR: "/fixture/ghidra_12.1.4_PUBLIC",
|
||||
});
|
||||
if (!config.ok) throw config.error;
|
||||
const launcher = new FixtureLauncher();
|
||||
const clients: GhidraClient[] = [];
|
||||
const provider = new GhidraProvider(
|
||||
config.value,
|
||||
silentLogger,
|
||||
{},
|
||||
installationHost,
|
||||
(options) => {
|
||||
const client = new GhidraClient({
|
||||
...options,
|
||||
launcher,
|
||||
platform: process.platform,
|
||||
startupTimeoutMs: 5_000,
|
||||
});
|
||||
clients.push(client);
|
||||
return client;
|
||||
},
|
||||
);
|
||||
const lazy = new LazyAnalysisProvider({
|
||||
identity: provider.identity(),
|
||||
capabilities: provider.capabilities(),
|
||||
load: () => Promise.resolve(provider),
|
||||
});
|
||||
const session = composeBinarySession(
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
identity: () => provider.identity(),
|
||||
capabilities: () => provider.capabilities(),
|
||||
inspectAvailability: () => provider.inspectAvailability(),
|
||||
inspectTargetSupport: (value) => provider.inspectTargetSupport(value),
|
||||
resolveAnalysisProfile: (value, options) =>
|
||||
provider.resolveAnalysisProfile(value, options),
|
||||
createClient: (value, profile, context) =>
|
||||
lazy.createClient(value, profile, context),
|
||||
},
|
||||
]),
|
||||
);
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ logger: silentLogger },
|
||||
);
|
||||
const mcp = new Client({ name: "ghidra-reopen", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const close = async () => {
|
||||
launcher.cleanupAllowed = true;
|
||||
await Promise.allSettled([mcp.close(), server.close()]);
|
||||
const closed = await session.close();
|
||||
try {
|
||||
for (const client of clients)
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
expect(closed.ok).toBe(true);
|
||||
} finally {
|
||||
for (const { child } of launcher.launches) {
|
||||
if (child.exitCode === null && child.signalCode === null)
|
||||
child.kill("SIGTERM");
|
||||
expect(await waitForExit(child, 2_000)).toBe(true);
|
||||
}
|
||||
}
|
||||
for (const launched of launcher.launches) await expectReleased(launched);
|
||||
expect(await readFile(target)).toEqual(source);
|
||||
};
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await mcp.connect(clientTransport);
|
||||
} catch (cause) {
|
||||
await close();
|
||||
throw cause;
|
||||
}
|
||||
return {
|
||||
clients,
|
||||
launcher,
|
||||
close,
|
||||
open: () =>
|
||||
mcp.callTool({ name: "open_binary", arguments: { path: target } }),
|
||||
query: (addressSuffix: number) =>
|
||||
mcp.callTool({
|
||||
name: "list_strings",
|
||||
arguments: { address: `0x200${addressSuffix}` },
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const firstLaunch = (launcher: FixtureLauncher): FixtureLaunch => {
|
||||
const first = launcher.launches[0];
|
||||
if (first === undefined) throw new Error("Expected a running Ghidra fixture");
|
||||
return first;
|
||||
};
|
||||
|
||||
const expectReleased = async ({
|
||||
child,
|
||||
runtimeRoot,
|
||||
endpointPath,
|
||||
}: FixtureLaunch) => {
|
||||
expect(await waitForExit(child, 2_000)).toBe(true);
|
||||
await expect(access(runtimeRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(access(endpointPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
};
|
||||
|
||||
const disconnect = async (
|
||||
child: ChildProcess,
|
||||
client: GhidraClient | undefined,
|
||||
) => {
|
||||
if (client === undefined)
|
||||
throw new Error("Expected a connected Ghidra client");
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
child.off("message", received);
|
||||
reject(new Error("Fixture did not acknowledge socket disconnection"));
|
||||
}, 2_000);
|
||||
const received = (message: unknown) => {
|
||||
if (
|
||||
typeof message !== "object" ||
|
||||
message === null ||
|
||||
!("event" in message) ||
|
||||
message.event !== "disconnected"
|
||||
)
|
||||
return;
|
||||
clearTimeout(timer);
|
||||
child.off("message", received);
|
||||
resolve();
|
||||
};
|
||||
child.on("message", received);
|
||||
child.send("disconnect");
|
||||
});
|
||||
await expect
|
||||
.poll(async () => (await client.ping({ timeoutMs: 200 })).ok)
|
||||
.toBe(false);
|
||||
expect(child.exitCode).toBeNull();
|
||||
expect(child.signalCode).toBeNull();
|
||||
};
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"Ghidra MCP session recovery over Unix sockets",
|
||||
() => {
|
||||
it("keeps open lazy, reuses a live child, and replaces an exited child on reopen", async () => {
|
||||
const harness = await connectGhidra();
|
||||
try {
|
||||
expect((await harness.open()).isError).not.toBe(true);
|
||||
expect((await harness.open()).isError).not.toBe(true);
|
||||
expect(harness.clients).toHaveLength(0);
|
||||
expect(harness.launcher.launches).toHaveLength(0);
|
||||
expect((await harness.query(1)).isError).not.toBe(true);
|
||||
const old = firstLaunch(harness.launcher);
|
||||
expect((await harness.open()).isError).not.toBe(true);
|
||||
expect((await harness.query(2)).isError).not.toBe(true);
|
||||
expect(harness.launcher.launches).toHaveLength(1);
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
harness.launcher.requests.filter(
|
||||
(method) => method === "list_strings",
|
||||
).length,
|
||||
)
|
||||
.toBe(2);
|
||||
expect(old.child.kill("SIGTERM")).toBe(true);
|
||||
expect(await waitForExit(old.child, 2_000)).toBe(true);
|
||||
expect(old.child.signalCode).toBe("SIGTERM");
|
||||
expect((await harness.open()).isError).not.toBe(true);
|
||||
await expectReleased(old);
|
||||
expect(harness.clients).toHaveLength(1);
|
||||
expect(harness.launcher.launches).toHaveLength(1);
|
||||
expect((await harness.query(3)).isError).not.toBe(true);
|
||||
expect(harness.clients).toHaveLength(2);
|
||||
expect(harness.launcher.launches).toHaveLength(2);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("retires a disconnected live child before lazily starting a replacement", async () => {
|
||||
const harness = await connectGhidra();
|
||||
try {
|
||||
expect((await harness.open()).isError).not.toBe(true);
|
||||
expect((await harness.query(1)).isError).not.toBe(true);
|
||||
const old = firstLaunch(harness.launcher);
|
||||
await disconnect(old.child, harness.clients[0]);
|
||||
expect((await harness.open()).isError).not.toBe(true);
|
||||
await expectReleased(old);
|
||||
expect(harness.clients).toHaveLength(1);
|
||||
expect(harness.launcher.launches).toHaveLength(1);
|
||||
expect((await harness.query(2)).isError).not.toBe(true);
|
||||
expect(harness.clients).toHaveLength(2);
|
||||
expect(harness.launcher.launches).toHaveLength(2);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains failed cleanup and refuses replacement until cleanup can be retried", async () => {
|
||||
const harness = await connectGhidra();
|
||||
try {
|
||||
expect((await harness.open()).isError).not.toBe(true);
|
||||
expect((await harness.query(1)).isError).not.toBe(true);
|
||||
const old = firstLaunch(harness.launcher);
|
||||
await disconnect(old.child, harness.clients[0]);
|
||||
harness.launcher.cleanupAllowed = false;
|
||||
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
||||
expect(parseMcpToolError(await harness.open())).toMatchObject({
|
||||
error: { code: "cleanup_incomplete" },
|
||||
});
|
||||
expect(harness.launcher.cleanupAttempts).toBe(attempt);
|
||||
expect(harness.clients).toHaveLength(1);
|
||||
expect(harness.launcher.launches).toHaveLength(1);
|
||||
expect(old.child.exitCode).toBeNull();
|
||||
expect(old.child.signalCode).toBeNull();
|
||||
await access(old.runtimeRoot);
|
||||
}
|
||||
harness.launcher.cleanupAllowed = true;
|
||||
expect((await harness.open()).isError).not.toBe(true);
|
||||
await expectReleased(old);
|
||||
expect(harness.launcher.cleanupAttempts).toBe(3);
|
||||
expect(harness.clients).toHaveLength(1);
|
||||
expect(harness.launcher.launches).toHaveLength(1);
|
||||
expect((await harness.query(2)).isError).not.toBe(true);
|
||||
expect(harness.clients).toHaveLength(2);
|
||||
expect(harness.launcher.launches).toHaveLength(2);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,285 @@
|
||||
import type { Client } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
|
||||
import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
createCacheProvider,
|
||||
createDeferred,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import {
|
||||
createGoBinaryByteStringFixture,
|
||||
createGoBinaryDiagnosticFixtures,
|
||||
createGoBinaryFixture,
|
||||
createGoBinaryPathFailureFixture,
|
||||
} from "../../fixtures/go/image.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { mcpTest } from "../../support/mcp/mcpFixture.js";
|
||||
|
||||
const goMcpTest = mcpTest.extend<{
|
||||
go: {
|
||||
client: Client;
|
||||
session: ReturnType<typeof createTestBinarySession>;
|
||||
};
|
||||
}>({
|
||||
go: async ({ mcp }, use) => {
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Go metadata must not start a deep provider");
|
||||
});
|
||||
try {
|
||||
const client = await mcp.connect(
|
||||
createServer({ kind: "session", session }),
|
||||
);
|
||||
await use({ client, session });
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
mcpTest(
|
||||
"retains MIPS identity and in-flight Go inspection in the saved session snapshot",
|
||||
async ({ mcp }) => {
|
||||
const root = await createTestTempDirectory("rea-go-mcp-close-");
|
||||
const path = join(root, "application");
|
||||
const snapshotPath = join(root, "analysis.json");
|
||||
const fixture = createGoBinaryFixture({ bits: 32, byteOrder: "big" });
|
||||
fixture.bytes.writeUInt16BE(8, 18); // ELF EM_MIPS.
|
||||
await writeFile(path, fixture.bytes);
|
||||
const entered = createDeferred<void>();
|
||||
const release = createDeferred<void>();
|
||||
const closeStarted = createDeferred<void>();
|
||||
const provider = new GoBinaryProvider();
|
||||
const session = createTestBinarySession(createCacheProvider([]));
|
||||
const service = new GoBinaryService({
|
||||
identity: provider.identity,
|
||||
inspect: async (input, options) => {
|
||||
const result = await provider.inspect(input, options);
|
||||
entered.resolve();
|
||||
await release.promise;
|
||||
return result;
|
||||
},
|
||||
});
|
||||
try {
|
||||
const client = await mcp.connect(
|
||||
createServer({ kind: "session", session }, { goBinary: service }),
|
||||
);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
|
||||
client.setNotificationHandler("notifications/progress", () => {
|
||||
closeStarted.resolve();
|
||||
});
|
||||
const inspection = client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path },
|
||||
});
|
||||
await entered.promise;
|
||||
const closing = client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: { snapshot_path: snapshotPath },
|
||||
_meta: { progressToken: "go-close-race" },
|
||||
});
|
||||
await closeStarted.promise;
|
||||
release.resolve();
|
||||
const inspected = await inspection;
|
||||
expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
inspected.structuredContent,
|
||||
);
|
||||
expect(evidence.subject?.architecture).toBe("mips");
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
architecture: "mips",
|
||||
bits: 32,
|
||||
byte_order: "big",
|
||||
});
|
||||
const closed = await closing;
|
||||
expect(closed.isError, JSON.stringify(closed.content)).not.toBe(true);
|
||||
const snapshot = await readAnalysisSnapshot(snapshotPath);
|
||||
if (!snapshot.ok) throw snapshot.error;
|
||||
expect(snapshot.value.evidence_bundle.records).toContainEqual(evidence);
|
||||
expect(session.evidenceById(evidence.evidence_id)).toBeUndefined();
|
||||
} finally {
|
||||
release.resolve();
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
for (const expectedErrno of ["ELOOP", "ENAMETOOLONG"] as const) {
|
||||
goMcpTest.skipIf(expectedErrno === "ELOOP" && process.platform === "win32")(
|
||||
`reports native ${expectedErrno} path failure as invalid selected-path input through Go MCP`,
|
||||
async ({ go: { client } }) => {
|
||||
const root = await createTestTempDirectory("rea-go-mcp-path-failure-");
|
||||
const { path, errno } = await createGoBinaryPathFailureFixture(
|
||||
root,
|
||||
expectedErrno,
|
||||
);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path },
|
||||
});
|
||||
const diagnostic = parseMcpToolError(response);
|
||||
expect(diagnostic.error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "inspect_go_binary",
|
||||
issues: [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(errno),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(diagnostic.error.details).toMatchObject({
|
||||
issues: [{ message: expect.stringContaining(path) }],
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
goMcpTest(
|
||||
"preserves invalid embedded Go text bytes through MCP",
|
||||
async ({ go: { client, session } }) => {
|
||||
const root = await createTestTempDirectory("rea-go-mcp-byte-strings-");
|
||||
const path = join(root, "byte-strings.elf");
|
||||
const fixture = createGoBinaryByteStringFixture();
|
||||
await writeFile(path, fixture.bytes);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
expect(evidence.normalized_result.build_info).toEqual(
|
||||
fixture.expectedBuildInfo,
|
||||
);
|
||||
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
|
||||
},
|
||||
);
|
||||
|
||||
goMcpTest(
|
||||
"distinguishes unsupported MZ carriers from malformed PE through MCP",
|
||||
async ({ go: { client } }) => {
|
||||
const root = await createTestTempDirectory("rea-go-mcp-mz-");
|
||||
for (const fixture of createGoBinaryDiagnosticFixtures()) {
|
||||
const path = join(root, `${fixture.name}.exe`);
|
||||
await writeFile(path, fixture.bytes);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response)).toMatchObject({
|
||||
error: {
|
||||
code: fixture.code,
|
||||
details: {
|
||||
...fixture.details,
|
||||
...(fixture.code === "unsupported_target" ? { path } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
goMcpTest(
|
||||
"advertises valid schemas and inspects real file bytes through MCP without an active target",
|
||||
async ({ go: { client, session } }) => {
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
const availability = expandToolAvailability(
|
||||
toolContract("binary_session").outputSchema.parse(
|
||||
status.structuredContent,
|
||||
).result.tool_availability,
|
||||
);
|
||||
expect(availability).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "inspect_go_binary",
|
||||
available: true,
|
||||
reason: "available",
|
||||
}),
|
||||
);
|
||||
const advertised = (await client.listTools()).tools.find(
|
||||
(tool) => tool.name === "inspect_go_binary",
|
||||
);
|
||||
if (advertised?.outputSchema === undefined)
|
||||
throw new Error("Go metadata must publish both schemas");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = advertised.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = advertised.outputSchema;
|
||||
expect(ajv.validateSchema(inputSchema)).toBe(true);
|
||||
expect(ajv.validateSchema(outputSchema)).toBe(true);
|
||||
expect(
|
||||
ajv.validate(inputSchema, { path: "/artifacts/program", execute: true }),
|
||||
).toBe(false);
|
||||
expect(ajv.validate(inputSchema, { path: "/artifacts/\0program" })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(advertised.annotations).toMatchObject({
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
});
|
||||
const root = await createTestTempDirectory("rea-go-mcp-");
|
||||
const path = join(root, "application");
|
||||
const fixture = createGoBinaryFixture({
|
||||
moduleText: "path\texample.com/tool\nnew-record\tfuture\n",
|
||||
});
|
||||
await writeFile(path, fixture.bytes);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(
|
||||
ajv.validate(outputSchema, response.structuredContent),
|
||||
JSON.stringify(ajv.errors),
|
||||
).toBe(true);
|
||||
const parsed = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
const evidence = parseEvidence(parsed);
|
||||
expect(evidence.confidence).toBe("observed");
|
||||
expect(parsed.normalized_result.build_info?.module).toMatchObject({
|
||||
path: "example.com/tool",
|
||||
complete: false,
|
||||
unparsed_lines: ["new-record\tfuture"],
|
||||
});
|
||||
expect(evidence.limitations.join(" ")).toContain(
|
||||
"could not be parsed completely",
|
||||
);
|
||||
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
|
||||
const invalid = await client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path: "relative.bin" },
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
expect(parseMcpToolError(invalid)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: { issues: [{ path: ["path"], reason: "invalid_format" }] },
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -5,7 +5,11 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisClient,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import type { AnalysisProfileCommitment } from "../../../src/domain/analysisProfile.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
|
||||
import { PROCESS_CAPTURE_REFERENCE } from "../../../src/contracts/investigationExamples.js";
|
||||
@@ -29,26 +33,33 @@ afterEach(async () => {
|
||||
describe("guided prompt completion from live analysis", () => {
|
||||
it("reads live documents and complete procedures without ambiguous names", async () => {
|
||||
const requests: Array<Readonly<Record<string, unknown>>> = [];
|
||||
const session = createTestBinarySession(() => client(requests), {
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(
|
||||
{
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
},
|
||||
{ fixture: true },
|
||||
),
|
||||
}),
|
||||
),
|
||||
});
|
||||
const session = createTestBinarySession(
|
||||
(_target, profile) => client(requests, profile),
|
||||
{
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(
|
||||
{
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
},
|
||||
{ fixture: true },
|
||||
),
|
||||
}),
|
||||
),
|
||||
},
|
||||
);
|
||||
directory = await createTestTempDirectory("rea-prompt-completion-");
|
||||
const target = join(directory, "fixture.hop");
|
||||
await writeFile(target, "fixture");
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
const completion = createPromptCompletionSource(session, session);
|
||||
expect(await completion.complete("document", "app")).toEqual([]);
|
||||
expect(await completion.complete("procedure", "")).toEqual([]);
|
||||
const warmed = await session.execute("list_documents", {});
|
||||
if (!warmed.ok) throw warmed.error;
|
||||
|
||||
expect(await completion.complete("document", "app")).toEqual([
|
||||
"App",
|
||||
@@ -269,14 +280,23 @@ const fixtureEnvironment = {
|
||||
|
||||
const client = (
|
||||
requests: Array<Readonly<Record<string, unknown>>>,
|
||||
): AnalysisClient => ({
|
||||
execute(operation, parameters) {
|
||||
analysisProfile?: AnalysisProfileCommitment,
|
||||
): AnalysisClient => {
|
||||
const observe = (value: unknown) =>
|
||||
resultOk(
|
||||
createAnalysisExecution(
|
||||
value,
|
||||
analysisProfile?.provider ?? fixtureProvider,
|
||||
analysisProfile === undefined ? {} : { analysisProfile },
|
||||
),
|
||||
);
|
||||
const execute: AnalysisClient["execute"] = (operation, parameters) => {
|
||||
if (operation === "list_documents")
|
||||
return Promise.resolve(observed(["AppTests", "App", "App"]));
|
||||
return Promise.resolve(observe(["AppTests", "App", "App"]));
|
||||
if (operation === "list_procedures") {
|
||||
requests.push(parameters);
|
||||
return Promise.resolve(
|
||||
observed([
|
||||
observe([
|
||||
{ address: "0x1000", value: "duplicate" },
|
||||
{ address: "0x2000", value: "unique" },
|
||||
{ address: "0x3000", value: "duplicate" },
|
||||
@@ -284,7 +304,11 @@ const client = (
|
||||
]),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
});
|
||||
return Promise.resolve(observe(null));
|
||||
};
|
||||
return {
|
||||
execute,
|
||||
executeIfReady: execute,
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -11,7 +11,22 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisClient,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import type {
|
||||
AnalysisProvider,
|
||||
AnalysisProviderCandidate,
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
|
||||
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import {
|
||||
createCacheProvider,
|
||||
createTestBinarySession,
|
||||
@@ -304,6 +319,67 @@ describe("guided prompt completion registry", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("guided prompt completion avoids cold startup and cancels warm lookup on close", async () => {
|
||||
const directory = await createTestTempDirectory("rea-prompt-warm-only-");
|
||||
temporaryDirectories.push(directory);
|
||||
const target = join(directory, "target.hop");
|
||||
await writeFile(target, "fixture target");
|
||||
const fixture = await createWarmCompletionFixture(target);
|
||||
const { client } = fixture;
|
||||
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: target },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
expect(fixture.childrenCreated()).toBe(0);
|
||||
expect(await complete(client, "document", "")).toEqual([]);
|
||||
expect(await complete(client, "procedure", "")).toEqual([]);
|
||||
expect(fixture.childrenCreated()).toBe(0);
|
||||
|
||||
const startup = fixture.holdStartup();
|
||||
const warming = client.callTool({ name: "list_documents", arguments: {} });
|
||||
await startup.started;
|
||||
expect(await complete(client, "document", "")).toEqual([]);
|
||||
expect(await complete(client, "procedure", "")).toEqual([]);
|
||||
expect(fixture.childrenCreated()).toBe(1);
|
||||
startup.finish();
|
||||
const warmed = await warming;
|
||||
expect(warmed.isError, JSON.stringify(warmed)).not.toBe(true);
|
||||
expect(fixture.childrenCreated()).toBe(1);
|
||||
expect(await complete(client, "document", "fixture")).toEqual([
|
||||
"fixture-document",
|
||||
]);
|
||||
|
||||
const cancellation = fixture.holdCompletion();
|
||||
const controller = new AbortController();
|
||||
const cancelled = client.complete(
|
||||
{
|
||||
ref: { type: "ref/prompt", name: "investigate_feature" },
|
||||
argument: { name: "document", value: "" },
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
await cancellation.started;
|
||||
controller.abort();
|
||||
await expect(cancelled).rejects.toThrow();
|
||||
await cancellation.aborted;
|
||||
|
||||
const lifecycle = fixture.holdCompletion();
|
||||
const pending = client.complete({
|
||||
ref: { type: "ref/prompt", name: "investigate_feature" },
|
||||
argument: { name: "document", value: "" },
|
||||
});
|
||||
await lifecycle.started;
|
||||
const closed = await client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
expect(closed.isError).not.toBe(true);
|
||||
await lifecycle.aborted;
|
||||
expect((await pending).completion.values).toEqual([]);
|
||||
}, 10_000);
|
||||
|
||||
describe("guided prompt completion lifecycle", () => {
|
||||
it("survives a cancelled completion and ignores its late result", async () => {
|
||||
let calls = 0;
|
||||
@@ -410,6 +486,181 @@ describe("guided prompt completion lifecycle", () => {
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
const createWarmCompletionFixture = async (target: string) => {
|
||||
const identity = {
|
||||
id: "deep-fixture",
|
||||
name: "Deep fixture provider",
|
||||
version: "1",
|
||||
};
|
||||
const analysisProfile = createAnalysisProfile(identity, { fixture: true });
|
||||
const observeCompletion = (result: JsonValue) =>
|
||||
resultOk(createAnalysisExecution(result, identity, { analysisProfile }));
|
||||
let childrenCreated = 0;
|
||||
let ready = false;
|
||||
let startupGate:
|
||||
| {
|
||||
readonly started: () => void;
|
||||
readonly release: Promise<void>;
|
||||
}
|
||||
| undefined;
|
||||
let completionGate:
|
||||
| {
|
||||
readonly started: () => void;
|
||||
readonly aborted: () => void;
|
||||
}
|
||||
| undefined;
|
||||
const deep = deepProvider(identity, {
|
||||
createClient() {
|
||||
childrenCreated += 1;
|
||||
return {
|
||||
execute: async (operation) => {
|
||||
if (operation !== "health") {
|
||||
const gate = startupGate;
|
||||
if (gate !== undefined) {
|
||||
startupGate = undefined;
|
||||
gate.started();
|
||||
await gate.release;
|
||||
}
|
||||
ready = true;
|
||||
}
|
||||
return observeCompletion(
|
||||
operation === "list_documents"
|
||||
? ["fixture-document"]
|
||||
: operation === "list_procedures"
|
||||
? [{ address: "0x1000", value: "fixture-procedure" }]
|
||||
: null,
|
||||
);
|
||||
},
|
||||
executeIfReady(operation, _parameters, options) {
|
||||
if (
|
||||
!ready ||
|
||||
(operation !== "list_documents" && operation !== "list_procedures")
|
||||
)
|
||||
return Promise.resolve(undefined);
|
||||
const gate = completionGate;
|
||||
if (gate === undefined)
|
||||
return Promise.resolve(
|
||||
observeCompletion(
|
||||
operation === "list_documents"
|
||||
? ["fixture-document"]
|
||||
: [{ address: "0x1000", value: "fixture-procedure" }],
|
||||
),
|
||||
);
|
||||
completionGate = undefined;
|
||||
gate.started();
|
||||
return new Promise((resolve) => {
|
||||
const signal = options?.signal;
|
||||
const cancel = (): void => {
|
||||
gate.aborted();
|
||||
resolve(err(new AnalysisCancelledError(operation)));
|
||||
};
|
||||
if (signal?.aborted === true) cancel();
|
||||
else signal?.addEventListener("abort", cancel, { once: true });
|
||||
});
|
||||
},
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
};
|
||||
},
|
||||
});
|
||||
const auxiliaryIdentity: ProviderIdentity = {
|
||||
id: "aux-fixture",
|
||||
name: "Aux fixture",
|
||||
version: "1",
|
||||
};
|
||||
const auxiliary: AnalysisProvider = {
|
||||
identity: () => auxiliaryIdentity,
|
||||
capabilities: () => [
|
||||
promptCapability(auxiliaryIdentity, "inspect_artifact"),
|
||||
],
|
||||
createClient: () => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
}),
|
||||
};
|
||||
const session = composeBinarySession(new AnalysisProviderRegistry([deep]), [
|
||||
auxiliary,
|
||||
]);
|
||||
const client = await connect(createServer({ kind: "session", session }));
|
||||
resources.push(session);
|
||||
return {
|
||||
client,
|
||||
childrenCreated: () => childrenCreated,
|
||||
holdStartup: () => {
|
||||
let started = (): void => undefined;
|
||||
let finish = (): void => undefined;
|
||||
const observedStart = new Promise<void>((resolve) => {
|
||||
started = resolve;
|
||||
});
|
||||
const release = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
startupGate = { started, release };
|
||||
return { started: observedStart, finish };
|
||||
},
|
||||
holdCompletion: () => {
|
||||
let started = (): void => undefined;
|
||||
let aborted = (): void => undefined;
|
||||
const observedStart = new Promise<void>((resolve) => {
|
||||
started = resolve;
|
||||
});
|
||||
const observedAbort = new Promise<void>((resolve) => {
|
||||
aborted = resolve;
|
||||
});
|
||||
completionGate = { started, aborted };
|
||||
return { started: observedStart, aborted: observedAbort };
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const deepProvider = (
|
||||
identity: Parameters<typeof createAnalysisProfile>[0],
|
||||
options: {
|
||||
readonly createClient: AnalysisProviderCandidate["createClient"];
|
||||
},
|
||||
): AnalysisProviderCandidate => ({
|
||||
identity: () => identity,
|
||||
capabilities: () => [
|
||||
promptCapability(identity, "list_documents"),
|
||||
promptCapability(identity, "list_procedures"),
|
||||
],
|
||||
inspectAvailability: () => ({
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: {},
|
||||
}),
|
||||
inspectTargetSupport: () => ({
|
||||
status: "supported",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: {},
|
||||
}),
|
||||
resolveAnalysisProfile: async () =>
|
||||
ok({ profile: createAnalysisProfile(identity, { fixture: true }) }),
|
||||
createClient: options.createClient,
|
||||
});
|
||||
|
||||
const promptCapability = (
|
||||
provider: ProviderIdentity,
|
||||
operation: CapabilityDescriptor["operation"],
|
||||
): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation,
|
||||
available: true,
|
||||
reason: null,
|
||||
cachePolicy: "live",
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const fixtureProvider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
|
||||
const fixtureSession = (
|
||||
@@ -461,6 +712,22 @@ const lifecycleClient = (
|
||||
}
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
executeIfReady(operation, parameters) {
|
||||
if (operation === "list_documents")
|
||||
return Promise.resolve(observed([`${target}-document`]));
|
||||
if (operation === "list_procedures") {
|
||||
requests.push(parameters);
|
||||
return Promise.resolve(
|
||||
observed([
|
||||
{
|
||||
address: target === "first" ? "0x1000" : "0x2000",
|
||||
value: `${target}-procedure`,
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
},
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
});
|
||||
|
||||
|
||||
@@ -19,13 +19,30 @@ interface ToolSchemas {
|
||||
}
|
||||
|
||||
function schemaErrors(tools: readonly ToolSchemas[]): string[] {
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
// Reuse Ajv's meta-schema validators, then clear each root's reference
|
||||
// namespace, including nested IDs, before validating the next schema.
|
||||
const ajv = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
addUsedSchema: false,
|
||||
});
|
||||
return tools.flatMap((tool) =>
|
||||
["inputSchema", "outputSchema"].flatMap((kind) => {
|
||||
const schema =
|
||||
kind === "inputSchema" ? tool.inputSchema : tool.outputSchema;
|
||||
if (schema === undefined || ajv.validateSchema(schema)) return [];
|
||||
return [`${tool.name}.${kind}: ${ajv.errorsText(ajv.errors)}`];
|
||||
if (schema === undefined) return [];
|
||||
try {
|
||||
if (!ajv.validateSchema(schema))
|
||||
return [`${tool.name}.${kind}: ${ajv.errorsText(ajv.errors)}`];
|
||||
ajv.compile(schema);
|
||||
return [];
|
||||
} catch (cause: unknown) {
|
||||
return [
|
||||
`${tool.name}.${kind}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
];
|
||||
} finally {
|
||||
ajv.removeSchema();
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -628,6 +645,69 @@ it("ships nonrecursive input and output schemas in the generated catalog", () =>
|
||||
expect(recursiveReferences(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects unresolved output-schema references even for uncalled tools", () => {
|
||||
const errors = schemaErrors([
|
||||
{
|
||||
name: "dangling",
|
||||
inputSchema: { type: "object" },
|
||||
outputSchema: { $ref: "#/$defs/missing" },
|
||||
},
|
||||
]);
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]).toContain("dangling.outputSchema");
|
||||
});
|
||||
|
||||
it("validates each tool independently when output schema IDs repeat", () => {
|
||||
const outputSchema = { $id: "urn:rea:test:shared-output", type: "string" };
|
||||
const errors = schemaErrors([
|
||||
{ name: "first", inputSchema: { type: "object" }, outputSchema },
|
||||
{
|
||||
name: "second",
|
||||
inputSchema: { type: "object" },
|
||||
outputSchema: { ...outputSchema },
|
||||
},
|
||||
{
|
||||
name: "broken",
|
||||
inputSchema: { type: "object" },
|
||||
outputSchema: { $id: outputSchema.$id, $ref: "#/$defs/missing" },
|
||||
},
|
||||
]);
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]).toContain("broken.outputSchema");
|
||||
expect(errors[0]).toContain("missing");
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"rejects references to another tool's nested IDs (earlier compilation fails: %s)",
|
||||
(invalidPrevious) => {
|
||||
const nestedId = "urn:rea:test:nested-output";
|
||||
const errors = schemaErrors([
|
||||
{
|
||||
name: "first",
|
||||
inputSchema: { type: "object" },
|
||||
outputSchema: {
|
||||
$defs: { shared: { $id: nestedId, type: "string" } },
|
||||
...(invalidPrevious ? { pattern: "[" } : {}),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "broken",
|
||||
inputSchema: { type: "object" },
|
||||
outputSchema: {
|
||||
$ref: nestedId,
|
||||
$defs: { shared: { type: "number" } },
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(errors).toHaveLength(invalidPrevious ? 2 : 1);
|
||||
const brokenErrors = errors.filter((error) =>
|
||||
error.startsWith("broken.outputSchema:"),
|
||||
);
|
||||
expect(brokenErrors).toHaveLength(1);
|
||||
expect(brokenErrors[0]).toContain(nestedId);
|
||||
},
|
||||
);
|
||||
|
||||
it("distinguishes recursive references from shared definitions", () => {
|
||||
const diamond = {
|
||||
type: "object",
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { chmod, mkdir, readFile, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { AdbProvider } from "../../../src/adb/AdbProvider.js";
|
||||
import { adbResultSchemas } from "../../../src/domain/adb/adbDeviceAnalysis.js";
|
||||
import {
|
||||
ADB_DIRECTORY_BATCH_SCRIPT,
|
||||
parseAdbDirectoryListing,
|
||||
} from "../../../src/adb/AdbDirectoryListing.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const itPosix = it.skipIf(process.platform === "win32");
|
||||
|
||||
// AOSP Toybox stat's documented %A/%U/%G/%s/%y conversions are fixed-format
|
||||
// metadata fields. This shim models those fields from host lstat data; it does
|
||||
// not claim to exercise an Android device's Toybox binary.
|
||||
const statShim = String.raw`#!${process.execPath}
|
||||
const fs = require('node:fs');
|
||||
const args = process.argv.slice(2);
|
||||
fs.appendFileSync(process.env.STAT_CALLS, args.slice(2).length + '\n');
|
||||
const fail = process.env.STAT_FAIL_PATH;
|
||||
for (const path of args.slice(2)) {
|
||||
if (path === fail) {
|
||||
process.stdout.write('-rw-r--r--|1000|1000|1|2026-10-12 00:00:00\n');
|
||||
process.exit(1);
|
||||
}
|
||||
const stat = fs.lstatSync(path);
|
||||
const kind = stat.isSymbolicLink() ? 'l' : stat.isDirectory() ? 'd' : '-';
|
||||
const permissions = kind + 'rw-r--r--';
|
||||
process.stdout.write(permissions + '|1000|1000|' + stat.size + '|2026-10-12 00:00:00\n');
|
||||
}`;
|
||||
|
||||
const readlinkShim = String.raw`#!${process.execPath}
|
||||
const fs = require('node:fs');
|
||||
fs.appendFileSync(process.env.READLINK_CALLS, 'called\n');
|
||||
process.stdout.write(fs.readlinkSync(process.argv[3]));
|
||||
`;
|
||||
|
||||
const makeTool = async (directory: string, name: string, contents: string) => {
|
||||
const path = join(directory, name);
|
||||
await writeFile(path, contents);
|
||||
await chmod(path, 0o755);
|
||||
return path;
|
||||
};
|
||||
|
||||
const shellQuote = (value: string): string =>
|
||||
"'" + value.replaceAll("'", "'\\''") + "'";
|
||||
|
||||
const makeFakeAdb = async (
|
||||
directory: string,
|
||||
toolDirectory: string,
|
||||
calls: string,
|
||||
linkCalls: string,
|
||||
) => {
|
||||
const path = join(directory, "fakeadb");
|
||||
await writeFile(
|
||||
path,
|
||||
`#!/bin/sh
|
||||
if [ "$1" = version ]; then
|
||||
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' "$0"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$1" = -s ]; then shift 2; fi
|
||||
[ "$1" = shell ] || exit 90
|
||||
shift
|
||||
export PATH=${shellQuote(`${toolDirectory}:` + (process.env.PATH ?? ""))}
|
||||
export STAT_CALLS=${shellQuote(calls)}
|
||||
export READLINK_CALLS=${shellQuote(linkCalls)}
|
||||
exec /bin/sh -c "$*"
|
||||
`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
await chmod(path, 0o755);
|
||||
return path;
|
||||
};
|
||||
|
||||
const makeRawOutputFakeAdb = async (
|
||||
directory: string,
|
||||
rawOutput: Buffer,
|
||||
): Promise<string> => {
|
||||
const path = join(directory, "fakeadb-raw-output");
|
||||
const encoded = rawOutput.toString("base64");
|
||||
await writeFile(
|
||||
path,
|
||||
`#!/bin/sh
|
||||
if [ "$1" = version ]; then
|
||||
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' "$0"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$1" = -s ]; then shift 2; fi
|
||||
[ "$1" = shell ] || exit 90
|
||||
exec ${shellQuote(process.execPath)} -e 'process.stdout.write(Buffer.from("${encoded}", "base64"))'
|
||||
`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
await chmod(path, 0o755);
|
||||
return path;
|
||||
};
|
||||
|
||||
const runScript = async (
|
||||
script: string,
|
||||
paths: readonly string[],
|
||||
environment: NodeJS.ProcessEnv,
|
||||
) => {
|
||||
const { stdout } = await execFileAsync(
|
||||
"/bin/sh",
|
||||
["-c", script, "rea-list-directory", ...paths],
|
||||
{ encoding: "buffer", env: environment, maxBuffer: 64 * 1024 },
|
||||
);
|
||||
return stdout;
|
||||
};
|
||||
|
||||
itPosix(
|
||||
"lists adversarial names through the complete adb provider command",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-adb-directory-listing-");
|
||||
const bin = join(root, "bin");
|
||||
const deviceDirectory = join(root, "device dir ' $");
|
||||
await mkdir(bin);
|
||||
await mkdir(deviceDirectory);
|
||||
const calls = join(root, "stat-calls");
|
||||
const linkCalls = join(root, "readlink-calls");
|
||||
await writeFile(calls, "");
|
||||
await writeFile(linkCalls, "");
|
||||
await makeTool(bin, "stat", statShim);
|
||||
await makeTool(bin, "readlink", readlinkShim);
|
||||
|
||||
const names = [
|
||||
"line\nbreak",
|
||||
"arrow -> tick` quote' space",
|
||||
"carriage\r雪",
|
||||
"tail\n",
|
||||
".hidden",
|
||||
];
|
||||
const paths: string[] = [];
|
||||
for (const name of names) {
|
||||
const path = join(deviceDirectory, name);
|
||||
await writeFile(path, "x");
|
||||
paths.push(path);
|
||||
}
|
||||
const nested = join(deviceDirectory, "nested");
|
||||
await mkdir(nested);
|
||||
await writeFile(join(nested, "ghost"), "not a direct child");
|
||||
paths.push(nested);
|
||||
const target = "target -> `quoted'\n雪\n";
|
||||
const link = join(deviceDirectory, "link\nname");
|
||||
await symlink(target, link);
|
||||
paths.push(link);
|
||||
const binary = await makeFakeAdb(root, bin, calls, linkCalls);
|
||||
|
||||
const execution = await new AdbProvider({
|
||||
environment: { REA_ADB_PATH: binary },
|
||||
}).execute({
|
||||
operation: "list_adb_directory",
|
||||
input: { serial: "test-device", device_path: deviceDirectory },
|
||||
});
|
||||
if (!execution.ok) throw execution.error;
|
||||
const result = adbResultSchemas.list_adb_directory.parse(
|
||||
execution.value.result,
|
||||
);
|
||||
expect(result.device_path).toBe(deviceDirectory);
|
||||
expect(result.unparsed_lines).toEqual([]);
|
||||
expect(result.coverage).toBe("complete");
|
||||
expect(result.entries.map((entry) => entry.name).sort()).toEqual(
|
||||
[...names, "nested", "link\nname"].sort(),
|
||||
);
|
||||
expect(
|
||||
result.entries.find((entry) => entry.name === "link\nname"),
|
||||
).toMatchObject({
|
||||
kind: "symlink",
|
||||
bytes: expect.any(Number),
|
||||
link_target: target,
|
||||
});
|
||||
expect(
|
||||
result.entries.filter((entry) => entry.kind !== "symlink"),
|
||||
).toHaveLength(names.length + 1);
|
||||
expect(
|
||||
result.entries.some((entry) => entry.name === "." || entry.name === ".."),
|
||||
).toBe(false);
|
||||
expect((await readFile(calls, "utf8")).trim().split("\n")).toEqual([
|
||||
String(paths.length),
|
||||
]);
|
||||
expect((await readFile(linkCalls, "utf8")).trim().split("\n")).toEqual([
|
||||
"called",
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
itPosix(
|
||||
"discards a failed stat batch instead of pairing shortened rows with later names",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-adb-directory-stat-failure-",
|
||||
);
|
||||
const bin = join(root, "bin");
|
||||
await mkdir(bin);
|
||||
const calls = join(root, "stat-calls");
|
||||
const linkCalls = join(root, "readlink-calls");
|
||||
await writeFile(calls, "");
|
||||
await writeFile(linkCalls, "");
|
||||
await makeTool(bin, "stat", statShim);
|
||||
await makeTool(bin, "readlink", readlinkShim);
|
||||
const first = join(root, "first");
|
||||
const omitted = join(root, "omitted");
|
||||
const last = join(root, "last");
|
||||
await Promise.all(
|
||||
[first, omitted, last].map((path) => writeFile(path, "x")),
|
||||
);
|
||||
|
||||
const output = await runScript(
|
||||
ADB_DIRECTORY_BATCH_SCRIPT,
|
||||
[first, omitted, last],
|
||||
{
|
||||
...process.env,
|
||||
PATH: `${bin}:${process.env.PATH ?? ""}`,
|
||||
STAT_CALLS: calls,
|
||||
READLINK_CALLS: linkCalls,
|
||||
STAT_FAIL_PATH: omitted,
|
||||
},
|
||||
).catch((cause: unknown) => {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"stdout" in cause &&
|
||||
Buffer.isBuffer(cause.stdout)
|
||||
)
|
||||
return cause.stdout;
|
||||
throw cause;
|
||||
});
|
||||
expect(parseAdbDirectoryListing(output)).toEqual({
|
||||
entries: [],
|
||||
unparsedLines: [],
|
||||
});
|
||||
expect((await readFile(calls, "utf8")).trim()).toBe("3");
|
||||
},
|
||||
);
|
||||
|
||||
itPosix(
|
||||
"preserves distinct invalid UTF-8 filenames as partial evidence",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-adb-directory-invalid-utf8-",
|
||||
);
|
||||
const deviceDirectory = join(root, "device");
|
||||
await mkdir(deviceDirectory);
|
||||
const invalidNames = [Buffer.from([0xff]), Buffer.from([0xfe])];
|
||||
|
||||
// macOS rejects raw invalid-UTF-8 path bytes with EILSEQ, so fake adb
|
||||
// returns the exact producer bytes while U+FFFD remains a valid record.
|
||||
const metadata = Buffer.from(
|
||||
"-rw-r--r--|1000|1000|1|2026-10-12 00:00:00\0",
|
||||
);
|
||||
const records = [
|
||||
...invalidNames.map((name) =>
|
||||
Buffer.concat([metadata, name, Buffer.from("\0\0")]),
|
||||
),
|
||||
Buffer.concat([metadata, Buffer.from("\ufffd"), Buffer.from("\0\0")]),
|
||||
];
|
||||
const rawOutput = Buffer.concat(records);
|
||||
const binary = await makeRawOutputFakeAdb(root, rawOutput);
|
||||
const execution = await new AdbProvider({
|
||||
environment: { REA_ADB_PATH: binary },
|
||||
}).execute({
|
||||
operation: "list_adb_directory",
|
||||
input: { serial: "test-device", device_path: deviceDirectory },
|
||||
});
|
||||
if (!execution.ok) throw execution.error;
|
||||
const result = adbResultSchemas.list_adb_directory.parse(
|
||||
execution.value.result,
|
||||
);
|
||||
|
||||
expect(result.entries.map((entry) => entry.name)).toEqual(["\ufffd"]);
|
||||
expect(result.coverage).toBe("partial");
|
||||
expect(result.unparsed_lines).toHaveLength(2);
|
||||
for (const invalidName of invalidNames) {
|
||||
const malformedRecord = Buffer.concat([
|
||||
metadata,
|
||||
invalidName,
|
||||
Buffer.from("\0\0"),
|
||||
]).toString("hex");
|
||||
expect(
|
||||
result.unparsed_lines.some((line) => line.includes(malformedRecord)),
|
||||
).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -875,6 +875,38 @@ it.skipIf(!onDarwin)(
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual({
|
||||
argvDecoyIgnored: true,
|
||||
readableEnvironmentWithoutToken: {
|
||||
runId: null,
|
||||
environmentEntryCount: 1,
|
||||
},
|
||||
restrictedReadableEnvironmentWithoutToken: {
|
||||
state: "readable",
|
||||
reason: null,
|
||||
},
|
||||
restrictedEmptyEnvironment: {
|
||||
state: "unavailable",
|
||||
reason: "restricted_process_environment_withheld",
|
||||
},
|
||||
platformEmptyEnvironment: {
|
||||
state: "unavailable",
|
||||
reason: "platform_binary_environment_withheld",
|
||||
},
|
||||
restrictedUnavailableEnvironment: {
|
||||
state: "unavailable",
|
||||
reason: "restricted_process_environment_withheld",
|
||||
},
|
||||
restrictedAmbiguousEnvironment: {
|
||||
state: "unavailable",
|
||||
reason: "restricted_process_environment_withheld",
|
||||
},
|
||||
ordinaryAmbiguousEnvironment: {
|
||||
state: "unavailable",
|
||||
reason: "ambiguous_environment_boundary",
|
||||
},
|
||||
ordinaryUnavailableEnvironment: {
|
||||
state: "unavailable",
|
||||
reason: "environment_unavailable",
|
||||
},
|
||||
alternatePaddingRead: true,
|
||||
appleVectorTokenFailsClosed: true,
|
||||
clearedAppleVectorTokenFailsClosed: true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { access, stat } from "node:fs/promises";
|
||||
import { access, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -57,7 +58,8 @@ describe("provider process runtime and wait primitives", () => {
|
||||
parent: tmpdir(),
|
||||
prefix: "rea-provider-test-",
|
||||
});
|
||||
expect((await stat(runtime.path)).mode & 0o777).toBe(0o700);
|
||||
expect((await stat(runtime.path)).mode & 0o077).toBe(0);
|
||||
await writeFile(join(runtime.path, "owned-scratch"), "fixture");
|
||||
|
||||
const first = runtime.close();
|
||||
const second = runtime.close();
|
||||
|
||||
@@ -150,6 +150,26 @@ afterEach(async () => {
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
});
|
||||
|
||||
describe("GhidraClient ready-only dispatch", () => {
|
||||
it("does not start cold and preserves the normal result once ready", async () => {
|
||||
const launcher = new FixtureLauncher();
|
||||
const client = clientFor(launcher);
|
||||
|
||||
await expect(client.callToolIfReady("list_strings", {})).resolves.toBe(
|
||||
undefined,
|
||||
);
|
||||
expect(launcher.processes).toEqual([]);
|
||||
|
||||
const started = await client.start();
|
||||
if (!started.ok) throw started.error;
|
||||
await expect(client.callToolIfReady("list_strings", {})).resolves.toEqual({
|
||||
ok: true,
|
||||
value: [expect.objectContaining({ value: "fixture value" })],
|
||||
});
|
||||
expect(launcher.processes).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("reports unknown startup work and stops notifications when cancellation releases the process", async () => {
|
||||
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
|
||||
const launcher = new FixtureLauncher("silent");
|
||||
@@ -232,6 +252,7 @@ describe("GhidraClient captured source snapshot", () => {
|
||||
if (!started.ok) throw started.error;
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockRejectedValueOnce(new Error("snapshot descriptor close failed"))
|
||||
.mockRejectedValueOnce(new Error("snapshot descriptor close failed"));
|
||||
try {
|
||||
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
|
||||
@@ -240,11 +261,19 @@ describe("GhidraClient captured source snapshot", () => {
|
||||
});
|
||||
const owner = close.mock.contexts[0];
|
||||
expect(owner).toBeInstanceOf(OwnedFileHandle);
|
||||
await expect(client.close()).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
expect(client.operationHealthSnapshot()).toMatchObject({
|
||||
state: "unknown",
|
||||
});
|
||||
const closed = await client.close();
|
||||
if (!closed.ok) throw closed.error;
|
||||
expect(client.operationHealthSnapshot()).toBeUndefined();
|
||||
expect(
|
||||
close.mock.contexts.filter((context) => context === owner),
|
||||
).toHaveLength(2);
|
||||
).toHaveLength(3);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
}
|
||||
@@ -591,11 +620,15 @@ describe("GhidraClient runtime removal failures", () => {
|
||||
},
|
||||
});
|
||||
await expect(access(runtimeRoot)).resolves.toBeUndefined();
|
||||
expect(client.operationHealthSnapshot()).toMatchObject({
|
||||
state: "unknown",
|
||||
});
|
||||
} finally {
|
||||
await chmod(runtimeRoot, 0o700);
|
||||
}
|
||||
|
||||
await expect(client.close()).resolves.toEqual({ ok: true, value: null });
|
||||
expect(client.operationHealthSnapshot()).toBeUndefined();
|
||||
await expect(access(runtimeRoot)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
@@ -626,16 +659,21 @@ describe("GhidraClient cleanup and diagnostics", () => {
|
||||
const client = clientFor(launcher, {
|
||||
runId: "11111111-1111-4111-8111-111111111111",
|
||||
});
|
||||
expect(client.operationHealthSnapshot()).toBeUndefined();
|
||||
await expect(client.start()).resolves.toMatchObject({ ok: true });
|
||||
expect(client.operationHealthSnapshot()).toBeUndefined();
|
||||
const child = await launcher.started;
|
||||
|
||||
await client.close();
|
||||
|
||||
expect(client.operationHealthSnapshot()).toBeUndefined();
|
||||
expect(client.diagnostics()).toMatchObject({
|
||||
runtime_root: launcher.runtimeRoots[0],
|
||||
transport: HOST_TRANSPORT,
|
||||
endpoint_path: launcher.endpointPaths[0],
|
||||
project_root: join(launcher.runtimeRoots[0] ?? "", "project"),
|
||||
process_id: expect.any(Number),
|
||||
exit_code: child.exitCode,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
});
|
||||
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
|
||||
|
||||
@@ -165,10 +165,12 @@ describe("Hopper bridge launcher selection", () => {
|
||||
|
||||
it("launches Hopper helpers with the caller-selected environment without restoring ambient values", async () => {
|
||||
const directory = await createTestTempDirectory("rea-hopper-selected-env-");
|
||||
const targetPath = join(directory, "target");
|
||||
await writeFile(targetPath, "fixture target");
|
||||
const launcher = new HopperApplicationLauncher({
|
||||
environment: { REA_SELECTED_VALUE: "caller-value" },
|
||||
launcherPath: process.execPath,
|
||||
targetPath: join(directory, "target"),
|
||||
targetPath,
|
||||
targetKind: "executable",
|
||||
loaderArgs: [
|
||||
"-e",
|
||||
|
||||
@@ -107,7 +107,7 @@ const failedStartup = async (launcher: RetryCleanupLauncher) => {
|
||||
error: {
|
||||
_tag: "ProviderAdapterError",
|
||||
cleanupIncomplete: true,
|
||||
cause: { _tag: "HopperTimeoutError" },
|
||||
cause: { cause: { _tag: "HopperTimeoutError" } },
|
||||
},
|
||||
});
|
||||
const session = launcher.sessions[0];
|
||||
@@ -233,7 +233,7 @@ it("blocks a fresh launch while cleanup remains unverified", async () => {
|
||||
ok: false,
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
cause: { _tag: "HopperTimeoutError" },
|
||||
cause: { cause: { _tag: "HopperTimeoutError" } },
|
||||
diagnostics: { primary_error: { code: "provider_timeout" } },
|
||||
},
|
||||
});
|
||||
@@ -263,7 +263,7 @@ it("preserves failed startup state through a blocked retry until cleanup succeed
|
||||
error: {
|
||||
_tag: "ProviderAdapterError",
|
||||
cleanupIncomplete: true,
|
||||
cause: { _tag: "HopperTimeoutError" },
|
||||
cause: { cause: { _tag: "HopperTimeoutError" } },
|
||||
},
|
||||
});
|
||||
// ...but must not wipe the failed-startup state: the client still
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { access } from "node:fs/promises";
|
||||
import { access, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { AnalysisError } from "../../../../src/domain/analysisErrorBase.js";
|
||||
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
@@ -67,17 +70,23 @@ const trackFailedHelperClient = (
|
||||
const projectPrimaryStartupFailure = (error: AnalysisError) => {
|
||||
if (!error.cleanupIncomplete) return projectAnalysisError(error);
|
||||
expect(projectAnalysisError(error).code).toBe("cleanup_incomplete");
|
||||
const primary = error.cause;
|
||||
const cause = error.cause;
|
||||
if (!(cause instanceof AggregateError))
|
||||
throw new Error("Cleanup failure did not retain its aggregate causes");
|
||||
const primary = cause.cause;
|
||||
if (!(primary instanceof AnalysisError))
|
||||
throw new Error("Cleanup failure lost its typed startup cause");
|
||||
return projectAnalysisError(primary);
|
||||
};
|
||||
|
||||
it("does not equate an owned native helper exit with an external GUI exit", async () => {
|
||||
const directory = await createTestTempDirectory("rea-hopper-helper-failure-");
|
||||
const targetPath = join(directory, "target");
|
||||
await writeFile(targetPath, "fixture target");
|
||||
const launcher = new HopperApplicationLauncher({
|
||||
environment: {},
|
||||
launcherPath: process.execPath,
|
||||
targetPath: "/target",
|
||||
targetPath,
|
||||
targetKind: "executable",
|
||||
loaderArgs: [
|
||||
"-e",
|
||||
@@ -91,7 +100,10 @@ it("does not equate an owned native helper exit with an external GUI exit", asyn
|
||||
const result = await client.start();
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true, cause: { _tag: "HopperStartError" } },
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
cause: { cause: { _tag: "HopperStartError" } },
|
||||
},
|
||||
});
|
||||
if (result.ok) throw new Error("Expected the native helper to fail");
|
||||
expect(projectPrimaryStartupFailure(result.error)).toMatchObject({
|
||||
@@ -140,7 +152,10 @@ it.each(["exit", "signal", "exit75"] as const)(
|
||||
const result = await client.start();
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true, cause: { _tag: "HopperStartError" } },
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
cause: { cause: { _tag: "HopperStartError" } },
|
||||
},
|
||||
});
|
||||
if (result.ok) throw new Error("Expected the launcher to fail");
|
||||
const projected = projectPrimaryStartupFailure(result.error);
|
||||
|
||||
@@ -15,6 +15,26 @@ import {
|
||||
} from "./hopperClient.fixture.js";
|
||||
|
||||
describe("HopperClient protocol", () => {
|
||||
it("does not start cold and preserves normal dispatch once ready", async () => {
|
||||
const launcher = new FixtureLauncher();
|
||||
const client = new HopperClient({ launcher, startupTimeoutMs: 1_000 });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.callToolIfReady("echo", { label: "cold" }),
|
||||
).resolves.toBe(undefined);
|
||||
expect(launcher.processes).toEqual([]);
|
||||
|
||||
const started = await client.start();
|
||||
if (!started.ok) throw started.error;
|
||||
await expect(
|
||||
client.callToolIfReady("echo", { label: "warm" }),
|
||||
).resolves.toEqual({ ok: true, value: { label: "warm" } });
|
||||
expect(launcher.processes).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("sanitizes unexpected owned-cleanup exceptions", () => {
|
||||
expect(
|
||||
providerCleanupFailure(
|
||||
|
||||
@@ -209,7 +209,7 @@ it("preserves missing callgraph coverage through direct, graph, and trace workfl
|
||||
});
|
||||
if (!trace.ok) throw trace.error;
|
||||
expect(trace.value).toMatchObject({
|
||||
goal_status: "not_reached",
|
||||
goal_status: "unknown",
|
||||
edges: [],
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("callgraph was unavailable"),
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { truncate, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { ArtifactResourceScope } from "../../../../src/artifacts/ArtifactResourceScope.js";
|
||||
import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js";
|
||||
|
||||
import {
|
||||
compareManagedMembersEvidenceValidated,
|
||||
@@ -19,6 +21,11 @@ import { compareManagedMembersInputSchema } from "../../../../src/domain/managed
|
||||
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { managedPeFixtureTarget } from "../../../../src/dotnet/ManagedPe.fixture.js";
|
||||
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
|
||||
import {
|
||||
MAX_MANAGED_SNAPSHOT_BYTES,
|
||||
readManagedSnapshot,
|
||||
} from "../../../../src/dotnet/ManagedSnapshot.js";
|
||||
import * as boundedFileBytes from "../../../../src/process/BoundedFileBytes.js";
|
||||
|
||||
it.each([
|
||||
["accessibility", 6, 0x0011],
|
||||
@@ -184,6 +191,14 @@ describe("managed member comparison path workflow", () => {
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
});
|
||||
expect(result.value.parameters).toMatchObject({
|
||||
left_path: leftPath,
|
||||
right_path: rightPath,
|
||||
});
|
||||
expect(result.value.locations).toEqual([
|
||||
{ kind: "artifact-path", path: leftPath },
|
||||
{ kind: "artifact-path", path: rightPath },
|
||||
]);
|
||||
expect(
|
||||
managedMemberComparisonResultSchema.parse(result.value.normalized_result)
|
||||
.matching.exact_il_signature,
|
||||
@@ -205,7 +220,179 @@ describe("managed member comparison path workflow", () => {
|
||||
details: { path: expect.stringContaining("missing.dll") },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed comparison post-admission read failures", () => {
|
||||
it.each([
|
||||
["left", "disappearance", "ENOENT"],
|
||||
["left", "permission denial", "EACCES"],
|
||||
["right", "disappearance", "ENOENT"],
|
||||
["right", "permission denial", "EACCES"],
|
||||
])(
|
||||
"classifies a %s-side %s during the post-resolution read",
|
||||
async (side, _name, code) => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-read-failure-",
|
||||
);
|
||||
const leftPath = join(directory, "left.dll");
|
||||
const rightPath = join(directory, "right.dll");
|
||||
await writeFile(leftPath, buildManagedPeFixture());
|
||||
await writeFile(rightPath, buildManagedPeFixture());
|
||||
|
||||
const result = await compareManagedMemberPaths(
|
||||
{ leftPath, rightPath },
|
||||
{
|
||||
resolveTarget: parseBinaryTarget,
|
||||
readSnapshot: async (path, operation, options) => {
|
||||
if (path === (side === "left" ? leftPath : rightPath)) {
|
||||
const failure = Object.assign(new Error(`read failed: ${code}`), {
|
||||
code,
|
||||
});
|
||||
throw failure;
|
||||
}
|
||||
return readManagedSnapshot(path, operation, options);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("BinaryTargetError");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
details: { path: side === "left" ? leftPath : rightPath },
|
||||
});
|
||||
if (side === "right")
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
operation: "inspect_managed_members",
|
||||
subject: {
|
||||
local_path: leftPath,
|
||||
digest: { sha256: expect.stringMatching(/^[0-9a-f]{64}$/u) },
|
||||
},
|
||||
});
|
||||
else expect(result.error.partialObservation).toBeUndefined();
|
||||
if (code === "EACCES")
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "access_denied",
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("managed comparison snapshot admission and cleanup", () => {
|
||||
it("rejects a sparse oversized snapshot through the default reader before reading it", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-oversized-snapshot-",
|
||||
);
|
||||
const leftPath = join(directory, "oversized.dll");
|
||||
const rightPath = join(directory, "right.dll");
|
||||
const fixture = buildManagedPeFixture();
|
||||
await writeFile(leftPath, Buffer.alloc(0));
|
||||
await truncate(leftPath, MAX_MANAGED_SNAPSHOT_BYTES + 1);
|
||||
await writeFile(rightPath, fixture);
|
||||
const template = managedPeFixtureTarget(fixture);
|
||||
const read = vi.spyOn(boundedFileBytes, "readBoundedFileBytes");
|
||||
try {
|
||||
const result = await compareManagedMemberPaths(
|
||||
{ leftPath, rightPath },
|
||||
{
|
||||
resolveTarget: async (path) => ({
|
||||
ok: true,
|
||||
value: { ...template, path },
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
operation: "compare_managed_members",
|
||||
reportedLimits: {
|
||||
max_snapshot_bytes: MAX_MANAGED_SNAPSHOT_BYTES,
|
||||
},
|
||||
});
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("retries a transient snapshot close failure through the same resource owner", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-compare-close-",
|
||||
);
|
||||
const leftPath = join(directory, "left.dll");
|
||||
const rightPath = join(directory, "right.dll");
|
||||
await writeFile(leftPath, buildManagedPeFixture());
|
||||
await writeFile(rightPath, buildManagedPeFixture());
|
||||
const resources = new ArtifactResourceScope();
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
const owners: OwnedFileHandle[] = [];
|
||||
let attempts = 0;
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
owners.push(this);
|
||||
attempts += 1;
|
||||
if (attempts === 1) throw new Error("injected transient close failure");
|
||||
await originalClose.call(this);
|
||||
});
|
||||
try {
|
||||
const result = await compareManagedMemberPaths(
|
||||
{ leftPath, rightPath },
|
||||
{},
|
||||
resources,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(owners[0]).toBe(owners[1]);
|
||||
expect(attempts).toBe(3);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
await resources.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("projects persistent snapshot cleanup failure and retains its exact owner", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-compare-cleanup-",
|
||||
);
|
||||
const leftPath = join(directory, "left.dll");
|
||||
const rightPath = join(directory, "right.dll");
|
||||
await writeFile(leftPath, buildManagedPeFixture());
|
||||
await writeFile(rightPath, buildManagedPeFixture());
|
||||
const resources = new ArtifactResourceScope();
|
||||
const cleanupCause = new Error("injected persistent close failure");
|
||||
const owners: OwnedFileHandle[] = [];
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
owners.push(this);
|
||||
throw cleanupCause;
|
||||
});
|
||||
let result: Awaited<ReturnType<typeof compareManagedMemberPaths>>;
|
||||
try {
|
||||
result = await compareManagedMemberPaths(
|
||||
{ leftPath, rightPath },
|
||||
{},
|
||||
resources,
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { cleanup: "incomplete", resources: [leftPath] },
|
||||
});
|
||||
expect(owners[0]).toBe(owners[1]);
|
||||
expect(owners[0]?.handle.fd).toBeGreaterThanOrEqual(0);
|
||||
} finally {
|
||||
close.mockRestore();
|
||||
await resources.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed comparison target identity", () => {
|
||||
it("rejects a file that changes after target identity is resolved", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-compare-race-",
|
||||
@@ -227,7 +414,6 @@ describe("managed member comparison path workflow", () => {
|
||||
await writeFile(path, replacement);
|
||||
return target;
|
||||
},
|
||||
readBytes: (path) => readFile(path),
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { truncate, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
@@ -15,6 +15,180 @@ import {
|
||||
} from "../../../../src/domain/managed/managedArtifact.js";
|
||||
import { ManagedStaticProvider } from "../../../../src/dotnet/ManagedStaticProvider.js";
|
||||
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
|
||||
import {
|
||||
MAX_MANAGED_SNAPSHOT_BYTES,
|
||||
readManagedSnapshot,
|
||||
} from "../../../../src/dotnet/ManagedSnapshot.js";
|
||||
import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { ArtifactResourceScope } from "../../../../src/artifacts/ArtifactResourceScope.js";
|
||||
import { RegularFileCleanupFailure } from "../../../../src/application/RegularFileRead.js";
|
||||
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
|
||||
import * as boundedFileBytes from "../../../../src/process/BoundedFileBytes.js";
|
||||
|
||||
describe("managed static snapshot capacity failure", () => {
|
||||
it("preserves a typed capacity failure when closing the admitted file also fails", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-capacity-cleanup-",
|
||||
);
|
||||
const path = join(directory, "sparse.exe");
|
||||
await writeFile(path, Buffer.alloc(0));
|
||||
await truncate(path, MAX_MANAGED_SNAPSHOT_BYTES + 1);
|
||||
const resources = new ArtifactResourceScope();
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
let permitClose = false;
|
||||
const owners: OwnedFileHandle[] = [];
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
owners.push(this);
|
||||
if (!permitClose) throw new Error("fixture handle close failure");
|
||||
await originalClose.call(this);
|
||||
});
|
||||
try {
|
||||
const failure = await readManagedSnapshot(
|
||||
path,
|
||||
"inspect_managed_artifact",
|
||||
{
|
||||
resources,
|
||||
},
|
||||
).catch((cause: unknown) => cause);
|
||||
|
||||
expect(failure).toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
cleanupResources: [path],
|
||||
diagnostics: { primary_error: { code: "resource_constraint" } },
|
||||
});
|
||||
expect(owners.length).toBeGreaterThan(0);
|
||||
expect(owners.every((owner) => owner === owners[0])).toBe(true);
|
||||
|
||||
permitClose = true;
|
||||
await resources.close();
|
||||
} finally {
|
||||
permitClose = true;
|
||||
await resources.close();
|
||||
close.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed static snapshot cancellation", () => {
|
||||
it("preserves cancellation when snapshot cleanup also fails", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-cancel-cleanup-",
|
||||
);
|
||||
const path = join(directory, "fixture.exe");
|
||||
await writeFile(path, buildManagedPeFixture());
|
||||
const parsed = await parseBinaryTarget(path);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
const client = new ManagedStaticProvider().createClient(parsed.value);
|
||||
const controller = new AbortController();
|
||||
const originalRead = boundedFileBytes.readBoundedFileBytes;
|
||||
const read = vi
|
||||
.spyOn(boundedFileBytes, "readBoundedFileBytes")
|
||||
.mockImplementation(async (...arguments_) => {
|
||||
controller.abort(new Error("fixture cancellation"));
|
||||
return originalRead(...arguments_);
|
||||
});
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
let permitClose = false;
|
||||
const owners: OwnedFileHandle[] = [];
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
owners.push(this);
|
||||
if (!permitClose) throw new Error("fixture handle close failure");
|
||||
await originalClose.call(this);
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await client.execute(
|
||||
"inspect_managed_artifact",
|
||||
{},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: { code: "cancelled" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(result.error.cause).toBeInstanceOf(AggregateError);
|
||||
if (!(result.error.cause instanceof AggregateError)) return;
|
||||
const cleanupError = result.error.cause.errors[1];
|
||||
expect(cleanupError).toBeInstanceOf(Error);
|
||||
if (!(cleanupError instanceof Error)) return;
|
||||
expect(cleanupError.cause).toBeInstanceOf(RegularFileCleanupFailure);
|
||||
if (!(cleanupError.cause instanceof RegularFileCleanupFailure)) return;
|
||||
expect(cleanupError.cause.owner).toBe(owners[0]);
|
||||
expect(owners[0]?.handle.fd).toBeGreaterThanOrEqual(0);
|
||||
|
||||
permitClose = true;
|
||||
expect(await client.close()).toMatchObject({ ok: true });
|
||||
expect(owners.every((owner) => owner === owners[0])).toBe(true);
|
||||
} finally {
|
||||
permitClose = true;
|
||||
await client.close();
|
||||
close.mockRestore();
|
||||
read.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed static file ownership", () => {
|
||||
it("retains the same failed file owner, blocks reads, and retries it on client close", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-close-");
|
||||
const bytes = buildManagedPeFixture();
|
||||
const path = join(directory, "fixture.exe");
|
||||
await writeFile(path, bytes);
|
||||
const parsed = await parseBinaryTarget(path);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
const client = new ManagedStaticProvider().createClient(parsed.value);
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
const owners: OwnedFileHandle[] = [];
|
||||
let permitClose = false;
|
||||
const close = vi
|
||||
.spyOn(OwnedFileHandle.prototype, "close")
|
||||
.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
owners.push(this);
|
||||
if (!permitClose) throw new Error("fixture handle close failure");
|
||||
await originalClose.call(this);
|
||||
});
|
||||
try {
|
||||
const failed = await client.execute("inspect_managed_artifact", {});
|
||||
expect(failed).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
cleanupResources: [path],
|
||||
},
|
||||
});
|
||||
|
||||
const blocked = await client.execute("inspect_managed_artifact", {});
|
||||
expect(blocked).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
cleanupResources: [path],
|
||||
},
|
||||
});
|
||||
expect(owners).toHaveLength(3);
|
||||
expect(owners.every((owner) => owner === owners[0])).toBe(true);
|
||||
|
||||
permitClose = true;
|
||||
expect(await client.close()).toMatchObject({ ok: true });
|
||||
expect(owners).toHaveLength(4);
|
||||
expect(owners.every((owner) => owner === owners[0])).toBe(true);
|
||||
} finally {
|
||||
permitClose = true;
|
||||
await client.close();
|
||||
close.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed static provider path boundary", () => {
|
||||
it("executes as a read-only auxiliary provider with digest, cancellation, and format boundaries", async () => {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
@@ -13,12 +13,10 @@ import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
|
||||
describe("artifact extraction identity", () => {
|
||||
it("uses code-point order for path-independent extraction identities", async () => {
|
||||
const root = await createTestTempDirectory("rea-extract-order-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
for (const name of ["ä.js", "a.js", "Z.js"])
|
||||
await writeFile(join(source, name), `${name}\n`);
|
||||
const source = join(root, "source.zip");
|
||||
await writeOrderedZip(source, ["ä.js", "a.js", "Z.js"]);
|
||||
const result = await new ArtifactProvider(process.env)
|
||||
.createClient(directoryTarget(source))
|
||||
.createClient(archiveTarget(source))
|
||||
.execute(
|
||||
"extract_artifact",
|
||||
artifactExtractionExecutionSchema.parse({
|
||||
@@ -36,10 +34,10 @@ describe("artifact extraction identity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const directoryTarget = (path: string): BinaryTarget => ({
|
||||
const archiveTarget = (path: string): BinaryTarget => ({
|
||||
path,
|
||||
sourcePath: path,
|
||||
sha256: "0".repeat(64),
|
||||
kind: "archive",
|
||||
format: "asar",
|
||||
format: "zip",
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ it("does not attribute the first universal slice's UUID and segments to the sele
|
||||
const universal = new NativeFixtureRunner({
|
||||
"otool:-h": `${singleSlice}\n${singleSlice}`,
|
||||
dwarfdump:
|
||||
"UUID: AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA (x86_64) fixture\nUUID: 01234567-89AB-CDEF-0123-456789ABCDEF (arm64) fixture\n",
|
||||
"UUID: AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA (x86_64) /owned/universal\nUUID: 01234567-89AB-CDEF-0123-456789ABCDEF (arm64) /owned/universal\n",
|
||||
});
|
||||
const client = new NativeMacOSProvider(
|
||||
{},
|
||||
@@ -73,7 +73,7 @@ it.each([
|
||||
.join("\n");
|
||||
const fixtures = new NativeFixtureRunner({
|
||||
lipo,
|
||||
dwarfdump: `UUID: 01234567-89AB-CDEF-0123-456789ABCDEF (${dyldArchitecture}) fixture\n`,
|
||||
dwarfdump: `UUID: 01234567-89AB-CDEF-0123-456789ABCDEF (${dyldArchitecture}) /owned/universal\n`,
|
||||
});
|
||||
const client = new NativeMacOSProvider(
|
||||
{},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisProvider,
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisClient,
|
||||
type AnalysisProvider,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
@@ -374,7 +375,7 @@ describe("evidence metadata imports and snapshot cache", () => {
|
||||
ok: false,
|
||||
error: {
|
||||
message: expect.stringContaining(
|
||||
"Analysis snapshots are unavailable after analysis metadata mutations",
|
||||
"Analysis snapshots are unavailable because analysis metadata may have changed",
|
||||
),
|
||||
},
|
||||
});
|
||||
@@ -408,6 +409,108 @@ describe("evidence metadata imports and snapshot cache", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("snapshot invalidation at mutation dispatch", () => {
|
||||
it.each(["provider failure", "invalid reply identity"] as const)(
|
||||
"does not replay metadata after a write followed by %s",
|
||||
async (failure) => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const provider = createCacheProvider([]);
|
||||
let name = "before";
|
||||
provider.createClient = () => ({
|
||||
execute: (operation) => {
|
||||
if (operation === "health") return Promise.resolve(ok(null));
|
||||
if (operation === "address_name") return Promise.resolve(ok(name));
|
||||
if (operation !== "set_address_name")
|
||||
throw new Error(`Unexpected operation: ${operation}`);
|
||||
name = "after";
|
||||
return Promise.resolve(
|
||||
failure === "provider failure"
|
||||
? err(new ProviderAdapterError("fixture", operation))
|
||||
: resultOk(
|
||||
createAnalysisExecution(true, {
|
||||
id: "wrong",
|
||||
name: "Wrong",
|
||||
version: "1",
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
});
|
||||
const session = createTestBinarySession(provider);
|
||||
try {
|
||||
const opened = await session.open(target);
|
||||
if (!opened.ok) throw opened.error;
|
||||
const parameters = { address: "0x1000", document: "first" };
|
||||
const before = await session.execute("address_name", parameters);
|
||||
if (!before.ok) throw before.error;
|
||||
expect(before.value.result).toBe("before");
|
||||
const baseline = session.exportAnalysisSnapshot();
|
||||
if (!baseline.ok) throw baseline.error;
|
||||
|
||||
const written = await session.execute("set_address_name", {
|
||||
...parameters,
|
||||
name: "after",
|
||||
});
|
||||
expect(written).toMatchObject({ ok: false });
|
||||
const after = await session.execute("address_name", parameters);
|
||||
if (!after.ok) throw after.error;
|
||||
expect(after.value.result).toBe("after");
|
||||
expect(session.exportAnalysisSnapshot()).toMatchObject({ ok: false });
|
||||
expect(session.importAnalysisSnapshot(baseline.value)).toMatchObject({
|
||||
ok: false,
|
||||
});
|
||||
} finally {
|
||||
expect(await session.close()).toEqual({ ok: true, value: null });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("stops replay while a dispatched write is still awaiting its reply", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const provider = createCacheProvider([]);
|
||||
const started = createDeferred<void>();
|
||||
const reply = createDeferred<ReturnType<typeof ok>>();
|
||||
let name = "before";
|
||||
provider.createClient = () => ({
|
||||
execute: (operation) => {
|
||||
if (operation === "health") return Promise.resolve(ok(null));
|
||||
if (operation === "address_name") return Promise.resolve(ok(name));
|
||||
if (operation !== "set_address_name")
|
||||
throw new Error(`Unexpected operation: ${operation}`);
|
||||
name = "after";
|
||||
started.resolve();
|
||||
return reply.promise;
|
||||
},
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
});
|
||||
const session = createTestBinarySession(provider);
|
||||
try {
|
||||
const opened = await session.open(target);
|
||||
if (!opened.ok) throw opened.error;
|
||||
const parameters = { address: "0x1000", document: "first" };
|
||||
const before = await session.execute("address_name", parameters);
|
||||
if (!before.ok) throw before.error;
|
||||
const writing = session.execute("set_address_name", {
|
||||
...parameters,
|
||||
name: "after",
|
||||
});
|
||||
await started.promise;
|
||||
try {
|
||||
const during = await session.execute("address_name", parameters);
|
||||
if (!during.ok) throw during.error;
|
||||
expect(during.value.result).toBe("after");
|
||||
expect(session.exportAnalysisSnapshot()).toMatchObject({ ok: false });
|
||||
} finally {
|
||||
reply.resolve(ok(true));
|
||||
expect(await writing).toMatchObject({ ok: true });
|
||||
}
|
||||
} finally {
|
||||
expect(await session.close()).toEqual({ ok: true, value: null });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("replay of exact immutable calls", () => {
|
||||
it("replays exact immutable calls from a matching provider-neutral snapshot", async () => {
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
|
||||
@@ -507,6 +507,50 @@ describe("managed application graph token scope", () => {
|
||||
"token scope SHA-256",
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"module identity absent",
|
||||
"module MVID unknown",
|
||||
"token scope MVID unknown",
|
||||
] as const)("rejects inconsistent identity when %s", (variant) => {
|
||||
const { memberEvidence, boundaryEvidence } = createManagedInteropEvidence();
|
||||
const members = managedMemberInspectionSchema.parse(
|
||||
parseEvidence(memberEvidence).normalized_result,
|
||||
);
|
||||
if (members.module === null || members.module.mvid === null)
|
||||
throw new Error("Expected fixture module identity and MVID");
|
||||
const module =
|
||||
variant === "module identity absent"
|
||||
? null
|
||||
: variant === "module MVID unknown"
|
||||
? { ...members.module, mvid: null }
|
||||
: members.module;
|
||||
const identity_scope =
|
||||
variant === "token scope MVID unknown"
|
||||
? { ...members.identity_scope, requires_mvid: null }
|
||||
: members.identity_scope;
|
||||
const inconsistentMembers = createEvidence(
|
||||
undefined,
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
{
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: { ...members, module, identity_scope },
|
||||
rawResult: null,
|
||||
limitations: members.limitations,
|
||||
},
|
||||
);
|
||||
|
||||
const projected = projectManagedApplicationGraphEvidence({
|
||||
managed_members: inconsistentMembers,
|
||||
managed_native_boundaries: boundaryEvidence,
|
||||
});
|
||||
|
||||
expect(projected.ok).toBe(false);
|
||||
if (projected.ok)
|
||||
throw new Error("An inconsistent token scope was accepted");
|
||||
expect(JSON.stringify(projected.error)).toContain("token scope MVID");
|
||||
});
|
||||
});
|
||||
|
||||
describe("unknown managed application graph token scope", () => {
|
||||
|
||||
@@ -219,7 +219,11 @@ describe("managed one-shot cleanup outcomes", () => {
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.cause).toBe(primaryError);
|
||||
expect(result.error.cause).toBeInstanceOf(AggregateError);
|
||||
expect(result.error.cause).toMatchObject({
|
||||
cause: primaryError,
|
||||
errors: [primaryError, cleanupError],
|
||||
});
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
|
||||
+3
-1
@@ -101,7 +101,9 @@ export const targets = (
|
||||
type: "page",
|
||||
title: "Electron application",
|
||||
url: options.electronFileUrl,
|
||||
attached: false,
|
||||
...(options.omitElectronTargetAttachmentState === true
|
||||
? {}
|
||||
: { attached: false }),
|
||||
...(options.omitTargetWebSocket === true
|
||||
? {}
|
||||
: {
|
||||
|
||||
+2
@@ -114,6 +114,8 @@ export interface FakeOptions {
|
||||
readonly webMcpChildRecoversAfterTransient?: boolean;
|
||||
readonly webMcpChildNavigatesAllowed?: boolean;
|
||||
readonly electronFileUrl?: string;
|
||||
/** Omit attached from the Electron page's HTTP discovery target. */
|
||||
readonly omitElectronTargetAttachmentState?: boolean;
|
||||
readonly duplicateElectronInventory?: boolean;
|
||||
readonly electronInventoryCount?: number;
|
||||
readonly urlShapedAllowedTitle?:
|
||||
|
||||
Vendored
+8
@@ -31,7 +31,10 @@ if (mode === "exit") process.exit(73);
|
||||
if (mode === "silent") setInterval(() => undefined, 1_000);
|
||||
else {
|
||||
await rm(endpointPath, { force: true });
|
||||
const sockets = new Set();
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
socket.once("close", () => sockets.delete(socket));
|
||||
socket.setEncoding("utf8");
|
||||
const state = {
|
||||
buffer: { value: "" },
|
||||
@@ -45,6 +48,11 @@ else {
|
||||
};
|
||||
socket.on("data", (chunk) => onSocketData(socket, server, chunk, state));
|
||||
});
|
||||
process.on("message", (message) => {
|
||||
if (message !== "disconnect") return;
|
||||
for (const socket of sockets) socket.destroy();
|
||||
process.send?.({ event: "disconnected" });
|
||||
});
|
||||
if (transport === "unix-socket") server.listen(endpointPath);
|
||||
else {
|
||||
server.listen(0, "127.0.0.1", async () => {
|
||||
|
||||
Vendored
+355
@@ -0,0 +1,355 @@
|
||||
import { dosMz } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { lstat, symlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
/** Actual filesystem paths that fail before Go artifact acquisition begins. */
|
||||
export const createGoBinaryPathFailureFixture = async (
|
||||
root: string,
|
||||
expectedErrno: "ELOOP" | "ENAMETOOLONG",
|
||||
): Promise<{ path: string; errno: string }> => {
|
||||
let path = join(root, "a".repeat(256));
|
||||
if (expectedErrno === "ELOOP") {
|
||||
const loop = join(root, "loop");
|
||||
await symlink(loop, loop, "dir");
|
||||
path = join(loop, "application");
|
||||
}
|
||||
try {
|
||||
await lstat(path);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
!(cause instanceof Error) ||
|
||||
!("code" in cause) ||
|
||||
typeof cause.code !== "string"
|
||||
)
|
||||
throw cause;
|
||||
if (
|
||||
(expectedErrno === "ELOOP" || process.platform === "linux") &&
|
||||
cause.code !== expectedErrno
|
||||
)
|
||||
throw new Error(
|
||||
`Path fixture expected ${expectedErrno}, but native lstat returned ${cause.code}.`,
|
||||
{ cause },
|
||||
);
|
||||
return { path, errno: cause.code };
|
||||
}
|
||||
throw new Error(`Expected native lstat to reject path fixture: ${path}`);
|
||||
};
|
||||
|
||||
/** Producer-shaped Go metadata used for portable binary format regressions. */
|
||||
export const GO_MODULE_TEXT =
|
||||
"path\texample.com/tool/cmd/tool\n" +
|
||||
"mod\texample.com/tool\t(devel)\t\n" +
|
||||
"dep\texample.com/dependency\tv1.2.3\th1:sample\n" +
|
||||
"=>\t../dependency\t\t\n" +
|
||||
"build\t-compiler=gc\n" +
|
||||
"build\tGOOS=linux\n" +
|
||||
'build\t-ldflags="-s -w"\n';
|
||||
|
||||
const MODULE_START = Buffer.from("3077af0c9274080241e1c107e6d618e6", "hex");
|
||||
const MODULE_END = Buffer.from("f932433186182072008242104116d8f2", "hex");
|
||||
|
||||
/** Build an authored, file-backed ELF/PE/Mach-O image without executing code. */
|
||||
export const createGoBinaryFixture = (
|
||||
options: {
|
||||
format?: "elf" | "pe" | "macho";
|
||||
bits?: 32 | 64;
|
||||
byteOrder?: "little" | "big";
|
||||
encoding?: "inline" | "pointer";
|
||||
sectionless?: boolean;
|
||||
goVersion?: string;
|
||||
moduleText?: string;
|
||||
omitBuildInfo?: boolean;
|
||||
} = {},
|
||||
): {
|
||||
bytes: Buffer;
|
||||
headerOffset: number;
|
||||
versionOffset: number;
|
||||
moduleOffset: number;
|
||||
moduleBytes: Buffer;
|
||||
} => {
|
||||
const format = options.format ?? "elf";
|
||||
const bits = options.bits ?? 64;
|
||||
const little = (options.byteOrder ?? "little") === "little";
|
||||
const encoding = options.encoding ?? "inline";
|
||||
const bytes = Buffer.alloc(4096);
|
||||
const headerOffset = 1024;
|
||||
const base = 0x10000;
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const u16 = (offset: number, value: number) =>
|
||||
view.setUint16(offset, value, little);
|
||||
const u32 = (offset: number, value: number) =>
|
||||
view.setUint32(offset, value, little);
|
||||
const word = (offset: number, value: number) => {
|
||||
if (bits === 64) view.setBigUint64(offset, BigInt(value), little);
|
||||
else u32(offset, value);
|
||||
};
|
||||
writeFixtureContainer(format, options.sectionless ?? false, {
|
||||
bytes,
|
||||
bits,
|
||||
little,
|
||||
base,
|
||||
headerOffset,
|
||||
u16,
|
||||
u32,
|
||||
word,
|
||||
});
|
||||
const version = Buffer.from(options.goVersion ?? "go1.26.0");
|
||||
const moduleBytes = Buffer.concat([
|
||||
MODULE_START,
|
||||
Buffer.from(options.moduleText ?? GO_MODULE_TEXT),
|
||||
MODULE_END,
|
||||
]);
|
||||
let versionOffset: number;
|
||||
let moduleOffset: number;
|
||||
if (encoding === "inline") {
|
||||
const versionLength = encodeVarint(version.length);
|
||||
versionOffset = headerOffset + 32 + versionLength.length;
|
||||
const moduleLength = encodeVarint(moduleBytes.length);
|
||||
moduleOffset = versionOffset + version.length + moduleLength.length;
|
||||
versionLength.copy(bytes, headerOffset + 32);
|
||||
version.copy(bytes, versionOffset);
|
||||
moduleLength.copy(bytes, versionOffset + version.length);
|
||||
moduleBytes.copy(bytes, moduleOffset);
|
||||
} else {
|
||||
const width = bits / 8;
|
||||
word(headerOffset + 16, base + 1536);
|
||||
word(headerOffset + 16 + width, base + 1536 + width * 2);
|
||||
versionOffset = 2048;
|
||||
moduleOffset = 2304;
|
||||
word(1536, base + versionOffset);
|
||||
word(1536 + width, version.length);
|
||||
word(1536 + width * 2, base + moduleOffset);
|
||||
word(1536 + width * 3, moduleBytes.length);
|
||||
version.copy(bytes, versionOffset);
|
||||
moduleBytes.copy(bytes, moduleOffset);
|
||||
}
|
||||
if (!options.omitBuildInfo) {
|
||||
Buffer.from("ff20476f206275696c64696e663a", "hex").copy(
|
||||
bytes,
|
||||
headerOffset,
|
||||
);
|
||||
bytes[headerOffset + 14] = bits / 8;
|
||||
bytes[headerOffset + 15] =
|
||||
(little ? 0 : 1) | (encoding === "inline" ? 2 : 0);
|
||||
}
|
||||
return { bytes, headerOffset, versionOffset, moduleOffset, moduleBytes };
|
||||
};
|
||||
|
||||
/** Embedded invalid UTF-8 alongside valid records, with exact independent byte expectations. */
|
||||
export const createGoBinaryByteStringFixture = () => {
|
||||
const version = Buffer.from("xgo1.26.0");
|
||||
const invalidLine = Buffer.from("build\t-tags=x");
|
||||
const fixture = createGoBinaryFixture({
|
||||
goVersion: version.toString("utf8"),
|
||||
moduleText:
|
||||
"path\texample.com/tool/cmd/tool\n" +
|
||||
"mod\texample.com/tool\t(devel)\t\n" +
|
||||
"build\tGOARCH=amd64\n" +
|
||||
`${invalidLine.toString("utf8")}\n`,
|
||||
});
|
||||
version[0] = 0xff;
|
||||
version.copy(fixture.bytes, fixture.versionOffset);
|
||||
const lineOffset = fixture.moduleBytes.indexOf(invalidLine);
|
||||
fixture.moduleBytes[lineOffset + invalidLine.length - 1] = 0xff;
|
||||
invalidLine[invalidLine.length - 1] = 0xff;
|
||||
fixture.moduleBytes.copy(fixture.bytes, fixture.moduleOffset);
|
||||
return {
|
||||
bytes: fixture.bytes,
|
||||
expectedBuildInfo: {
|
||||
header_offset: fixture.headerOffset,
|
||||
encoding: "inline",
|
||||
go_version: null,
|
||||
go_version_bytes_base64: version.toString("base64"),
|
||||
module_text: null,
|
||||
module_bytes_base64: fixture.moduleBytes.toString("base64"),
|
||||
version_location: {
|
||||
offset: fixture.versionOffset,
|
||||
bytes: version.length,
|
||||
},
|
||||
module_location: {
|
||||
offset: fixture.moduleOffset,
|
||||
bytes: fixture.moduleBytes.length,
|
||||
},
|
||||
module: {
|
||||
path: "example.com/tool/cmd/tool",
|
||||
main: {
|
||||
path: "example.com/tool",
|
||||
version: "(devel)",
|
||||
sum: "",
|
||||
replacement: null,
|
||||
},
|
||||
dependencies: [],
|
||||
settings: [{ key: "GOARCH", value: "amd64" }],
|
||||
unparsed_lines: [],
|
||||
unparsed_line_bytes_base64: [invalidLine.toString("base64")],
|
||||
complete: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Unsupported DOS/Windows carriers and damaged PE records for public diagnostics. */
|
||||
export const createGoBinaryDiagnosticFixtures = () => {
|
||||
const unsupported = [
|
||||
{ name: "dos-short", bytes: dosMz(16) },
|
||||
{ name: "dos", bytes: dosMz() },
|
||||
];
|
||||
for (const signature of ["NE", "LE", "LX"]) {
|
||||
const bytes = dosMz();
|
||||
bytes.writeUInt16LE(4, 8);
|
||||
bytes.writeUInt32LE(64, 60);
|
||||
bytes.write(signature, 64, "ascii");
|
||||
unsupported.push({ name: signature.toLowerCase(), bytes });
|
||||
}
|
||||
const damagedPe = createGoBinaryFixture({ format: "pe" }).bytes;
|
||||
damagedPe.write("NO", 128, "ascii");
|
||||
const absentDirectories = createGoBinaryFixture({ format: "pe" }).bytes;
|
||||
absentDirectories.writeUInt32LE(1, 152 + 108);
|
||||
const shortOptionalHeaders = [0, 1].map((size) => {
|
||||
const bytes = createGoBinaryFixture({ format: "pe" }).bytes;
|
||||
bytes.writeUInt16LE(size, 148);
|
||||
// Bytes following the declared header must not supply its magic field.
|
||||
bytes.fill(0xff, 152 + size, 154);
|
||||
return { name: `optional-header-${String(size)}-bytes`, bytes };
|
||||
});
|
||||
return [
|
||||
...unsupported.map((fixture) => ({
|
||||
...fixture,
|
||||
code: "unsupported_target" as const,
|
||||
details: { operation: "inspect_go_binary" },
|
||||
})),
|
||||
...[
|
||||
{ name: "damaged-pe", bytes: damagedPe },
|
||||
{ name: "absent-directories", bytes: absentDirectories },
|
||||
...shortOptionalHeaders,
|
||||
].map((fixture) => ({
|
||||
...fixture,
|
||||
code: "invalid_request" as const,
|
||||
details: {
|
||||
operation: "inspect_go_binary",
|
||||
issues: [{ path: ["path"], reason: "invalid_format" }],
|
||||
},
|
||||
})),
|
||||
];
|
||||
};
|
||||
|
||||
const encodeVarint = (input: number): Buffer => {
|
||||
let value = BigInt(input);
|
||||
const bytes: number[] = [];
|
||||
while (value >= 128n) {
|
||||
bytes.push(Number(value & 127n) | 128);
|
||||
value >>= 7n;
|
||||
}
|
||||
bytes.push(Number(value));
|
||||
return Buffer.from(bytes);
|
||||
};
|
||||
|
||||
const writeFixtureContainer = (
|
||||
format: "elf" | "pe" | "macho",
|
||||
sectionless: boolean,
|
||||
context: {
|
||||
bytes: Buffer;
|
||||
bits: 32 | 64;
|
||||
little: boolean;
|
||||
base: number;
|
||||
headerOffset: number;
|
||||
u16: (offset: number, value: number) => void;
|
||||
u32: (offset: number, value: number) => void;
|
||||
word: (offset: number, value: number) => void;
|
||||
},
|
||||
): void => {
|
||||
const { bytes, bits, little, base, headerOffset, u16, u32, word } = context;
|
||||
if (format === "elf") {
|
||||
bytes.set([0x7f, 0x45, 0x4c, 0x46, bits === 64 ? 2 : 1, little ? 1 : 2, 1]);
|
||||
u16(16, 2);
|
||||
u16(18, bits === 64 ? 62 : 3);
|
||||
u32(20, 1);
|
||||
const wide = bits === 64;
|
||||
word(wide ? 32 : 28, 128);
|
||||
word(wide ? 40 : 32, sectionless ? 0 : 256);
|
||||
u16(wide ? 52 : 40, wide ? 64 : 52);
|
||||
u16(wide ? 54 : 42, wide ? 56 : 32);
|
||||
u16(wide ? 56 : 44, 1);
|
||||
u16(wide ? 58 : 46, wide ? 64 : 40);
|
||||
u16(wide ? 60 : 48, sectionless ? 0 : 3);
|
||||
u16(wide ? 62 : 50, sectionless ? 0 : 1);
|
||||
u32(128, 1);
|
||||
if (wide) {
|
||||
u32(132, 6);
|
||||
word(136, 0);
|
||||
word(144, base);
|
||||
word(160, bytes.length);
|
||||
word(168, bytes.length);
|
||||
} else {
|
||||
word(132, 0);
|
||||
word(136, base);
|
||||
word(144, bytes.length);
|
||||
word(148, bytes.length);
|
||||
u32(152, 6);
|
||||
}
|
||||
if (!sectionless) {
|
||||
const entrySize = wide ? 64 : 40;
|
||||
const strings = Buffer.from("\0.shstrtab\0.go.buildinfo\0");
|
||||
strings.copy(bytes, 768);
|
||||
const names = 256 + entrySize;
|
||||
u32(names, 1);
|
||||
u32(names + 4, 3);
|
||||
word(names + (wide ? 24 : 16), 768);
|
||||
word(names + (wide ? 32 : 20), strings.length);
|
||||
const info = 256 + entrySize * 2;
|
||||
u32(info, 11);
|
||||
u32(info + 4, 1);
|
||||
word(info + (wide ? 16 : 12), base + headerOffset);
|
||||
word(info + (wide ? 24 : 16), headerOffset);
|
||||
word(info + (wide ? 32 : 20), 2048);
|
||||
}
|
||||
} else if (format === "pe") {
|
||||
if (!little) throw new Error("PE fixtures are little endian");
|
||||
bytes.write("MZ", 0, "ascii");
|
||||
u32(60, 128);
|
||||
bytes.write("PE\0\0", 128, "ascii");
|
||||
u16(132, bits === 64 ? 0x8664 : 0x14c);
|
||||
u16(134, 1);
|
||||
const optionalSize = bits === 64 ? 112 : 96;
|
||||
u16(148, optionalSize);
|
||||
u16(152, bits === 64 ? 0x20b : 0x10b);
|
||||
word(152 + (bits === 64 ? 24 : 28), base);
|
||||
const section = 152 + optionalSize;
|
||||
bytes.write(".data", section, "ascii");
|
||||
u32(section + 8, 2048);
|
||||
u32(section + 12, headerOffset);
|
||||
u32(section + 16, 2048);
|
||||
u32(section + 20, headerOffset);
|
||||
u32(section + 36, 0xc0000040);
|
||||
} else {
|
||||
const wide = bits === 64;
|
||||
u32(0, wide ? 0xfeedfacf : 0xfeedface);
|
||||
u32(4, wide ? 0x01000007 : 7);
|
||||
u32(8, 3);
|
||||
u32(12, 2);
|
||||
u32(16, 1);
|
||||
const segmentSize = wide ? 72 : 56;
|
||||
const sectionSize = wide ? 80 : 68;
|
||||
const commandSize = segmentSize + (sectionless ? 0 : sectionSize);
|
||||
u32(20, commandSize);
|
||||
const command = wide ? 32 : 28;
|
||||
u32(command, wide ? 0x19 : 1);
|
||||
u32(command + 4, commandSize);
|
||||
bytes.write("__DATA", command + 8, "ascii");
|
||||
word(command + 24, base);
|
||||
word(command + (wide ? 32 : 28), bytes.length);
|
||||
word(command + (wide ? 40 : 32), 0);
|
||||
word(command + (wide ? 48 : 36), bytes.length);
|
||||
u32(command + (wide ? 56 : 40), 3);
|
||||
u32(command + (wide ? 60 : 44), 3);
|
||||
u32(command + (wide ? 64 : 48), sectionless ? 0 : 1);
|
||||
if (!sectionless) {
|
||||
const section = command + segmentSize;
|
||||
bytes.write("__go_buildinfo", section, "ascii");
|
||||
bytes.write("__DATA", section + 16, "ascii");
|
||||
word(section + 32, base + headerOffset);
|
||||
word(section + (wide ? 40 : 36), 2048);
|
||||
u32(section + (wide ? 48 : 40), headerOffset);
|
||||
}
|
||||
}
|
||||
};
|
||||
+22
-17
@@ -10,6 +10,7 @@ interface InspectorCommand {
|
||||
|
||||
interface FakeV8InspectorOptions {
|
||||
readonly targetUrl: string;
|
||||
readonly attached?: boolean | null;
|
||||
readonly targetType?: "node" | "page";
|
||||
readonly runtimeProduct?: string;
|
||||
readonly scriptUrls?: readonly string[];
|
||||
@@ -60,21 +61,19 @@ export const startFakeV8Inspector = async (
|
||||
if (request.url === "/json/list") {
|
||||
response.end(
|
||||
JSON.stringify([
|
||||
target(
|
||||
targetId,
|
||||
options.targetUrl,
|
||||
options.targetType ?? "node",
|
||||
target(targetId, options.targetUrl, {
|
||||
type: options.targetType ?? "node",
|
||||
port,
|
||||
),
|
||||
attached: options.attached,
|
||||
}),
|
||||
...(options.additionalTargetUrl === undefined
|
||||
? []
|
||||
: [
|
||||
target(
|
||||
otherTargetId,
|
||||
options.additionalTargetUrl,
|
||||
options.targetType ?? "node",
|
||||
target(otherTargetId, options.additionalTargetUrl, {
|
||||
type: options.targetType ?? "node",
|
||||
port,
|
||||
),
|
||||
attached: options.attached,
|
||||
}),
|
||||
]),
|
||||
...Array.from(
|
||||
{ length: options.additionalTargetCount ?? 0 },
|
||||
@@ -82,8 +81,11 @@ export const startFakeV8Inspector = async (
|
||||
target(
|
||||
`00000000-0000-4000-8000-${String(index + 3).padStart(12, "0")}`,
|
||||
options.targetUrl,
|
||||
options.targetType ?? "node",
|
||||
port,
|
||||
{
|
||||
type: options.targetType ?? "node",
|
||||
port,
|
||||
attached: options.attached,
|
||||
},
|
||||
),
|
||||
),
|
||||
]),
|
||||
@@ -220,15 +222,18 @@ const sendScriptEvents = (
|
||||
const target = (
|
||||
id: string,
|
||||
url: string,
|
||||
type: "node" | "page",
|
||||
port: number,
|
||||
options: {
|
||||
readonly type: "node" | "page";
|
||||
readonly port: number;
|
||||
readonly attached: boolean | null | undefined;
|
||||
},
|
||||
) => ({
|
||||
id,
|
||||
type,
|
||||
type: options.type,
|
||||
title: "redacted-by-provider",
|
||||
url,
|
||||
attached: false,
|
||||
webSocketDebuggerUrl: `ws://localhost:${String(port)}/${id}`,
|
||||
...(options.attached === undefined ? {} : { attached: options.attached }),
|
||||
webSocketDebuggerUrl: `ws://localhost:${String(options.port)}/${id}`,
|
||||
});
|
||||
|
||||
const parseCommand = (raw: string): InspectorCommand => {
|
||||
|
||||
Vendored
+4
-1
@@ -72,7 +72,10 @@ export async function connectLocalToolsMcp() {
|
||||
const call = async (name: string, arguments_: Record<string, unknown>) => {
|
||||
const definition = definitions.get(name);
|
||||
if (definition !== undefined) compileValidator(definition.inputSchema);
|
||||
const response = await client.callTool({ name, arguments: arguments_ });
|
||||
const response = await client.callTool(
|
||||
{ name, arguments: arguments_ },
|
||||
definition === undefined ? undefined : { toolDefinition: definition },
|
||||
);
|
||||
if (
|
||||
response.structuredContent !== undefined &&
|
||||
definition?.outputSchema !== undefined
|
||||
|
||||
Vendored
+1
-1
@@ -38,7 +38,7 @@ const outputFor = async (
|
||||
arguments_[0] === "-imports" ? "dyld-imports.txt" : "dyld-exports.txt",
|
||||
);
|
||||
if (tool === "dwarfdump")
|
||||
return "UUID: 01234567-89AB-CDEF-0123-456789ABCDEF (arm64) fixture\n";
|
||||
return `UUID: 01234567-89AB-CDEF-0123-456789ABCDEF (arm64) ${arguments_.at(-1)}\n`;
|
||||
if (tool === "file")
|
||||
return arguments_.at(-1)?.endsWith(".plist") === true
|
||||
? "XML 1.0 document text\n"
|
||||
|
||||
+104
-26
@@ -26,38 +26,42 @@ func fixture(
|
||||
@main
|
||||
struct ProcessRunTokenParserProbe {
|
||||
static func main() throws {
|
||||
let argvDecoy = try token(in: fixture(
|
||||
let argvDecoy = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable", "REA_PROCESS_RUN_ID=argv-decoy", "trailing"],
|
||||
environment: ["DECOY=words REA_PROCESS_RUN_ID=synthetic-decoy"]
|
||||
))
|
||||
let realToken = try token(in: fixture(
|
||||
let realToken = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: ["DECOY=words REA_PROCESS_RUN_ID=synthetic-decoy", "REA_PROCESS_RUN_ID=owned-token"]
|
||||
))
|
||||
let emptyLaterArgument = try token(in: fixture(
|
||||
let readableNoToken = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: ["PATH=/usr/bin"]
|
||||
))
|
||||
let emptyLaterArgument = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable", "", "after-empty"],
|
||||
environment: ["REA_PROCESS_RUN_ID=empty-argument-token"],
|
||||
pointerSize: 8
|
||||
))
|
||||
let alternatePadding = try token(in: fixture(
|
||||
let alternatePadding = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable", "argument"],
|
||||
environment: ["REA_PROCESS_RUN_ID=alternate-padding-token"],
|
||||
pointerSize: 4
|
||||
), pointerSize: 4)
|
||||
let emptyArgv0Read = try token(in: fixture(
|
||||
let emptyArgv0Read = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["", "", "after-empty"],
|
||||
environment: ["REA_PROCESS_RUN_ID=empty-argv0-token"],
|
||||
pointerSize: 8
|
||||
))
|
||||
let finalAssignmentArgumentRead = try token(in: fixture(
|
||||
let finalAssignmentArgumentRead = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable", "FOO=bar"],
|
||||
environment: ["REA_PROCESS_RUN_ID=final-assignment-token"]
|
||||
))
|
||||
let reservedArgumentIgnored = try token(in: fixture(
|
||||
let reservedArgumentIgnored = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable", "REA_PROCESS_RUN_ID=argv-decoy"],
|
||||
environment: ["DECOY=words REA_PROCESS_RUN_ID=synthetic-decoy"]
|
||||
))
|
||||
let nonAsciiPathRead = try token(in: fixture(
|
||||
let nonAsciiPathRead = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/é", "FOO=bar"],
|
||||
environment: ["REA_PROCESS_RUN_ID=utf8-path-token"],
|
||||
pointerSize: 8,
|
||||
@@ -65,7 +69,7 @@ struct ProcessRunTokenParserProbe {
|
||||
))
|
||||
let appleVectorTokenFailsClosed: Bool
|
||||
do {
|
||||
_ = try token(in: fixture(
|
||||
_ = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: ["pfz=user-value", "PATH=/usr/bin"],
|
||||
appleRecords: ["pfz=synthetic", "REA_PROCESS_RUN_ID=apple-decoy"]
|
||||
@@ -76,7 +80,7 @@ struct ProcessRunTokenParserProbe {
|
||||
}
|
||||
let clearedAppleVectorTokenFailsClosed: Bool
|
||||
do {
|
||||
_ = try token(in: fixture(
|
||||
_ = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: ["REA_PROCESS_RUN_ID=cleared-pfz-owned-token"],
|
||||
appleRecords: ["REA_PROCESS_RUN_ID=apple-decoy"],
|
||||
@@ -86,14 +90,14 @@ struct ProcessRunTokenParserProbe {
|
||||
} catch RunTokenReadError.ambiguousEnvironmentBoundary {
|
||||
clearedAppleVectorTokenFailsClosed = true
|
||||
}
|
||||
let callerPfzBeforeTokenRead = try token(in: fixture(
|
||||
let callerPfzBeforeTokenRead = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: ["pfz=caller-value", "REA_PROCESS_RUN_ID=cleared-pfz-owned-token"],
|
||||
zeroedPfz: true
|
||||
))
|
||||
let emptyEnvironmentRecordsBeforeTokenFailClosed: Bool
|
||||
do {
|
||||
_ = try token(in: fixture(
|
||||
_ = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: ["DECOY=value", "", "", "REA_PROCESS_RUN_ID=synthetic-decoy"],
|
||||
appleRecords: [],
|
||||
@@ -103,7 +107,7 @@ struct ProcessRunTokenParserProbe {
|
||||
} catch RunTokenReadError.ambiguousEnvironmentBoundary {
|
||||
emptyEnvironmentRecordsBeforeTokenFailClosed = true
|
||||
}
|
||||
let zeroArgumentsRead = try token(in: fixture(
|
||||
let zeroArgumentsRead = try parseProcessEnvironment(in: fixture(
|
||||
arguments: [],
|
||||
environment: ["REA_PROCESS_RUN_ID=zero-argc-token"],
|
||||
pointerSize: 4
|
||||
@@ -117,14 +121,14 @@ struct ProcessRunTokenParserProbe {
|
||||
truncatedArgv.append(contentsOf: Array("REA_PROCESS_RUN_ID=synthetic-decoy".utf8))
|
||||
let truncatedArgvFailsClosed: Bool
|
||||
do {
|
||||
_ = try token(in: truncatedArgv)
|
||||
_ = try parseProcessEnvironment(in: truncatedArgv)
|
||||
truncatedArgvFailsClosed = false
|
||||
} catch {
|
||||
truncatedArgvFailsClosed = true
|
||||
}
|
||||
let duplicateTokenFailsClosed: Bool
|
||||
do {
|
||||
_ = try token(in: fixture(
|
||||
_ = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: ["REA_PROCESS_RUN_ID=first", "REA_PROCESS_RUN_ID=second"]
|
||||
))
|
||||
@@ -134,7 +138,7 @@ struct ProcessRunTokenParserProbe {
|
||||
}
|
||||
let missingAppleBoundaryFailsClosed: Bool
|
||||
do {
|
||||
_ = try token(in: fixture(
|
||||
_ = try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: ["REA_PROCESS_RUN_ID=synthetic-decoy"],
|
||||
appleRecords: []
|
||||
@@ -144,23 +148,97 @@ struct ProcessRunTokenParserProbe {
|
||||
missingAppleBoundaryFailsClosed = true
|
||||
}
|
||||
|
||||
let restrictedReadableNoToken = processRunTokenObservation(
|
||||
pid: 1,
|
||||
parse: .success(readableNoToken),
|
||||
codeSigningFlags: { 0x0000_0800 }
|
||||
)
|
||||
let restrictedEmptyEnvironment = processRunTokenObservation(
|
||||
pid: 1,
|
||||
parse: .success(try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: []
|
||||
))),
|
||||
codeSigningFlags: { 0x0000_0800 }
|
||||
)
|
||||
let platformEmptyEnvironment = processRunTokenObservation(
|
||||
pid: 1,
|
||||
parse: .success(try parseProcessEnvironment(in: fixture(
|
||||
arguments: ["/fixture/executable"],
|
||||
environment: []
|
||||
))),
|
||||
codeSigningFlags: { 0x0400_0000 }
|
||||
)
|
||||
let restrictedUnavailableEnvironment = processRunTokenObservation(
|
||||
pid: 1,
|
||||
parse: .failure(.environmentUnavailable),
|
||||
codeSigningFlags: { 0x0000_0800 }
|
||||
)
|
||||
let restrictedAmbiguousEnvironment = processRunTokenObservation(
|
||||
pid: 1,
|
||||
parse: .failure(.ambiguousEnvironmentBoundary),
|
||||
codeSigningFlags: { 0x0000_0800 }
|
||||
)
|
||||
let ordinaryAmbiguousEnvironment = processRunTokenObservation(
|
||||
pid: 1,
|
||||
parse: .failure(.ambiguousEnvironmentBoundary),
|
||||
codeSigningFlags: { 0 }
|
||||
)
|
||||
let ordinaryUnavailableEnvironment = processRunTokenObservation(
|
||||
pid: 1,
|
||||
parse: .failure(.environmentUnavailable),
|
||||
codeSigningFlags: { 0 }
|
||||
)
|
||||
|
||||
let result: [String: Any] = [
|
||||
"argvDecoyIgnored": argvDecoy == nil,
|
||||
"realTokenRead": realToken == "owned-token",
|
||||
"emptyLaterArgumentRead": emptyLaterArgument == "empty-argument-token",
|
||||
"alternatePaddingRead": alternatePadding == "alternate-padding-token",
|
||||
"argvDecoyIgnored": argvDecoy.runId == nil && argvDecoy.environmentEntryCount == 1,
|
||||
"realTokenRead": realToken.runId == "owned-token",
|
||||
"readableEnvironmentWithoutToken": [
|
||||
"runId": readableNoToken.runId as Any? ?? NSNull(),
|
||||
"environmentEntryCount": readableNoToken.environmentEntryCount,
|
||||
],
|
||||
"restrictedReadableEnvironmentWithoutToken": [
|
||||
"state": restrictedReadableNoToken.state,
|
||||
"reason": restrictedReadableNoToken.reason as Any? ?? NSNull(),
|
||||
],
|
||||
"restrictedEmptyEnvironment": [
|
||||
"state": restrictedEmptyEnvironment.state,
|
||||
"reason": restrictedEmptyEnvironment.reason as Any? ?? NSNull(),
|
||||
],
|
||||
"platformEmptyEnvironment": [
|
||||
"state": platformEmptyEnvironment.state,
|
||||
"reason": platformEmptyEnvironment.reason as Any? ?? NSNull(),
|
||||
],
|
||||
"restrictedUnavailableEnvironment": [
|
||||
"state": restrictedUnavailableEnvironment.state,
|
||||
"reason": restrictedUnavailableEnvironment.reason as Any? ?? NSNull(),
|
||||
],
|
||||
"restrictedAmbiguousEnvironment": [
|
||||
"state": restrictedAmbiguousEnvironment.state,
|
||||
"reason": restrictedAmbiguousEnvironment.reason as Any? ?? NSNull(),
|
||||
],
|
||||
"ordinaryAmbiguousEnvironment": [
|
||||
"state": ordinaryAmbiguousEnvironment.state,
|
||||
"reason": ordinaryAmbiguousEnvironment.reason as Any? ?? NSNull(),
|
||||
],
|
||||
"ordinaryUnavailableEnvironment": [
|
||||
"state": ordinaryUnavailableEnvironment.state,
|
||||
"reason": ordinaryUnavailableEnvironment.reason as Any? ?? NSNull(),
|
||||
],
|
||||
"emptyLaterArgumentRead": emptyLaterArgument.runId == "empty-argument-token",
|
||||
"alternatePaddingRead": alternatePadding.runId == "alternate-padding-token",
|
||||
"truncatedArgvFailsClosed": truncatedArgvFailsClosed,
|
||||
"duplicateTokenFailsClosed": duplicateTokenFailsClosed,
|
||||
"missingAppleBoundaryFailsClosed": missingAppleBoundaryFailsClosed,
|
||||
"emptyArgv0Read": emptyArgv0Read == "empty-argv0-token",
|
||||
"finalAssignmentArgumentRead": finalAssignmentArgumentRead == "final-assignment-token",
|
||||
"reservedArgumentIgnored": reservedArgumentIgnored == nil,
|
||||
"nonAsciiPathRead": nonAsciiPathRead == "utf8-path-token",
|
||||
"emptyArgv0Read": emptyArgv0Read.runId == "empty-argv0-token",
|
||||
"finalAssignmentArgumentRead": finalAssignmentArgumentRead.runId == "final-assignment-token",
|
||||
"reservedArgumentIgnored": reservedArgumentIgnored.runId == nil && reservedArgumentIgnored.environmentEntryCount == 1,
|
||||
"nonAsciiPathRead": nonAsciiPathRead.runId == "utf8-path-token",
|
||||
"appleVectorTokenFailsClosed": appleVectorTokenFailsClosed,
|
||||
"clearedAppleVectorTokenFailsClosed": clearedAppleVectorTokenFailsClosed,
|
||||
"callerPfzBeforeTokenRead": callerPfzBeforeTokenRead == "cleared-pfz-owned-token",
|
||||
"callerPfzBeforeTokenRead": callerPfzBeforeTokenRead.runId == "cleared-pfz-owned-token",
|
||||
"emptyEnvironmentRecordsBeforeTokenFailClosed": emptyEnvironmentRecordsBeforeTokenFailClosed,
|
||||
"zeroArgumentsRead": zeroArgumentsRead == "zero-argc-token",
|
||||
"zeroArgumentsRead": zeroArgumentsRead.runId == "zero-argc-token",
|
||||
]
|
||||
let output = try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys])
|
||||
FileHandle.standardOutput.write(output)
|
||||
|
||||
Vendored
+2
@@ -12,3 +12,5 @@ WABT and compares exact producer output against the public CLI/MCP surfaces.
|
||||
`custom-names.wat` covers newlines, quotes, Unicode, backslashes, embedded
|
||||
section markers and NUL in custom names; objdump displays those names without
|
||||
escaping and ends each at its first NUL.
|
||||
It also covers leading U+FEFF, including a name distinct from the special `name`
|
||||
section, and distinguishes a U+FEFF-only name from an empty name.
|
||||
|
||||
Vendored
+5
-1
@@ -2,4 +2,8 @@
|
||||
(@custom "test\0aline" "payload")
|
||||
(@custom "fake\22\0aSection Details:\0a Type start=0x0000000a end=0x0000000b (size=0x00000001) count: 0\0a\22end" "payload")
|
||||
(@custom "unicode-\c3\a9\\\t" "payload")
|
||||
(@custom "visible\00hidden" "payload"))
|
||||
(@custom "visible\00hidden" "payload")
|
||||
(@custom "\ef\bb\bfsection" "payload")
|
||||
(@custom "\ef\bb\bfname" "payload")
|
||||
(@custom "\ef\bb\bf" "payload")
|
||||
(@custom "" "payload"))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { resolve } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
import {
|
||||
createTestWorkspace,
|
||||
@@ -58,6 +59,15 @@ export const createTestCli = (
|
||||
cwd: cwd ?? process.cwd(),
|
||||
env: {
|
||||
PATH: process.env.PATH ?? "",
|
||||
// Native Windows APIs need the system root and a writable temporary
|
||||
// directory even when the command's application environment is empty.
|
||||
...(process.platform === "win32"
|
||||
? {
|
||||
SystemRoot: process.env.SystemRoot,
|
||||
TEMP: tmpdir(),
|
||||
TMP: tmpdir(),
|
||||
}
|
||||
: {}),
|
||||
...(compileCache === undefined ||
|
||||
environment?.NODE_V8_COVERAGE !== undefined
|
||||
? {}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { open, type FileHandle } from "node:fs/promises";
|
||||
import { vi } from "vitest";
|
||||
|
||||
/** Pause after one selected file chunk reaches the operating system. */
|
||||
export const holdFirstFileRead = async (path: string) => {
|
||||
const probe = await open(path, "r");
|
||||
const identity = await probe.stat();
|
||||
const fileHandlePrototype = Object.getPrototypeOf(probe) as {
|
||||
read(
|
||||
buffer: Buffer,
|
||||
offset: number,
|
||||
length: number,
|
||||
position: number | null,
|
||||
): Promise<{ readonly bytesRead: number; readonly buffer: Buffer }>;
|
||||
};
|
||||
await probe.close();
|
||||
let totalReadBytes = 0;
|
||||
let readCount = 0;
|
||||
let resolveFirstRead: (() => void) | undefined;
|
||||
const firstRead = new Promise<void>((resolve) => {
|
||||
resolveFirstRead = resolve;
|
||||
});
|
||||
let releaseRead: (() => void) | undefined;
|
||||
const readGate = new Promise<void>((resolve) => {
|
||||
releaseRead = resolve;
|
||||
});
|
||||
const read = fileHandlePrototype.read;
|
||||
vi.spyOn(fileHandlePrototype, "read").mockImplementation(async function (
|
||||
this: FileHandle,
|
||||
...args: [Buffer, number, number, number | null]
|
||||
) {
|
||||
const current = await this.stat();
|
||||
const isTarget =
|
||||
current.dev === identity.dev && current.ino === identity.ino;
|
||||
const result = await read.call(this, ...args);
|
||||
if (!isTarget) return result;
|
||||
totalReadBytes += result.bytesRead;
|
||||
readCount += 1;
|
||||
if (readCount === 1) {
|
||||
resolveFirstRead?.();
|
||||
await readGate;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
return {
|
||||
firstRead,
|
||||
release: () => releaseRead?.(),
|
||||
get readCount() {
|
||||
return readCount;
|
||||
},
|
||||
get totalReadBytes() {
|
||||
return totalReadBytes;
|
||||
},
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user