fix(artifacts): reuse current classification and region reads
This commit is contained in:
@@ -29,6 +29,14 @@ const createModuleLookupFixture = async () => {
|
||||
'import "ancestor-empty";',
|
||||
'import "ancestor-blocked";',
|
||||
'import "ancestor-sub/parser";',
|
||||
'import "./.hidden.js";',
|
||||
'import "./..pkg.js";',
|
||||
'import "./exact.js/.";',
|
||||
'import "./exact.js/child/..";',
|
||||
'import ".hidden.js";',
|
||||
'import "..pkg.js";',
|
||||
'import ".";',
|
||||
'import "..";',
|
||||
"void fallback;",
|
||||
].join("\n"),
|
||||
"esm/extensionless.js": "module.exports = 1;",
|
||||
@@ -36,6 +44,10 @@ const createModuleLookupFixture = async () => {
|
||||
"esm/explicit.js.js": "module.exports = 3;",
|
||||
"esm/exact.js": "module.exports = 4;",
|
||||
"esm/actual.cjs": "module.exports = 5;",
|
||||
"esm/.hidden.js": "module.exports = 'local hidden';",
|
||||
"esm/..pkg.js": "module.exports = 'local dot package';",
|
||||
"node_modules/.hidden.js/index.js": "module.exports = 'hidden package';",
|
||||
"node_modules/..pkg.js/index.js": "module.exports = 'dot package';",
|
||||
"esm/typed.mts": 'import value from "./typed-dep.js"; void value;',
|
||||
"esm/typed-dep.ts": "export default 42;",
|
||||
"cjs/entry.cjs": [
|
||||
@@ -54,8 +66,15 @@ const createModuleLookupFixture = async () => {
|
||||
'require("ancestor-empty");',
|
||||
'require("ancestor-blocked");',
|
||||
'require("ancestor-sub/parser");',
|
||||
'require(".hidden.js");',
|
||||
'require("./.hidden.js");',
|
||||
'require(".");',
|
||||
'require("..");',
|
||||
].join("\n"),
|
||||
"cjs/directory/index.cjs": "module.exports = 6;",
|
||||
"cjs/index.js": "module.exports = 'current directory';",
|
||||
"index.js": "module.exports = 'parent directory';",
|
||||
"cjs/.hidden.js": "module.exports = 'local hidden';",
|
||||
"cjs/extensionless.cjs": "module.exports = 1;",
|
||||
"cjs/feature.cjs": "module.exports = 2;",
|
||||
"cjs/module-only.mjs": "export default 42;",
|
||||
@@ -79,7 +98,7 @@ const createModuleLookupFixture = async () => {
|
||||
"node_modules/ancestor-blocked/index.js": "module.exports = 9;",
|
||||
"node_modules/ancestor-sub/parser.js": "module.exports = 10;",
|
||||
"esm/runtime-control.mjs": [
|
||||
'const specifiers = ["./extensionless", "./directory", "./explicit.js", "./exact.js", "./actual.cjs?cache=1", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
|
||||
'const specifiers = ["./extensionless", "./directory", "./explicit.js", "./exact.js", "./actual.cjs?cache=1", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser", "./.hidden.js", "./..pkg.js", "./exact.js/.", "./exact.js/child/..", ".hidden.js", "..pkg.js", ".", ".."];',
|
||||
"const results = [];",
|
||||
"for (const specifier of specifiers) {",
|
||||
" try { const value = (await import(specifier)).default; results.push({ specifier, ok: true, value }); }",
|
||||
@@ -88,7 +107,7 @@ const createModuleLookupFixture = async () => {
|
||||
"console.log(JSON.stringify(results));",
|
||||
].join("\n"),
|
||||
"cjs/runtime-control.cjs": [
|
||||
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./module-only", "./valid-directory", "./default-js", "./default-json", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
|
||||
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./module-only", "./valid-directory", "./default-js", "./default-json", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser", ".hidden.js", "./.hidden.js", ".", ".."];',
|
||||
"const results = [];",
|
||||
"for (const specifier of specifiers) {",
|
||||
" try { const value = require(specifier); results.push({ specifier, ok: true, value }); }",
|
||||
@@ -109,6 +128,110 @@ const createModuleLookupFixture = async () => {
|
||||
return root;
|
||||
};
|
||||
|
||||
type RuntimeControlResult = {
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
readonly value?: unknown;
|
||||
};
|
||||
|
||||
const expectNodeRuntimeControls = (
|
||||
esmOutput: string,
|
||||
cjsOutput: string,
|
||||
): void => {
|
||||
const esmResults = JSON.parse(esmOutput) as RuntimeControlResult[];
|
||||
const cjsResults = JSON.parse(cjsOutput) as RuntimeControlResult[];
|
||||
expect(esmResults).toEqual([
|
||||
{
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "./explicit.js",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./exact.js", ok: true, value: 4 },
|
||||
{ specifier: "./actual.cjs?cache=1", ok: true, value: 5 },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-empty", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{
|
||||
specifier: "ancestor-blocked",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "ancestor-sub/parser",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./.hidden.js", ok: true, value: "local hidden" },
|
||||
{ specifier: "./..pkg.js", ok: true, value: "local dot package" },
|
||||
{
|
||||
specifier: "./exact.js/.",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "./exact.js/child/..",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: ".hidden.js",
|
||||
ok: false,
|
||||
code: "ERR_INVALID_MODULE_SPECIFIER",
|
||||
},
|
||||
{
|
||||
specifier: "..pkg.js",
|
||||
ok: false,
|
||||
code: "ERR_INVALID_MODULE_SPECIFIER",
|
||||
},
|
||||
{ specifier: ".", ok: false, code: "ERR_UNSUPPORTED_DIR_IMPORT" },
|
||||
{ specifier: "..", ok: false, code: "ERR_UNSUPPORTED_DIR_IMPORT" },
|
||||
]);
|
||||
expect(cjsResults).toEqual([
|
||||
{
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./feature",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./feature.cjs", ok: true, value: 2 },
|
||||
{ specifier: "./module-only", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "./valid-directory", ok: true, value: 42 },
|
||||
{ specifier: "./default-js", ok: true, value: 3 },
|
||||
{ specifier: "./default-json", ok: true, value: { value: 4 } },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: true, value: 7 },
|
||||
{ specifier: "ancestor-empty", ok: true, value: 8 },
|
||||
{ specifier: "ancestor-blocked", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-sub/parser", ok: true, value: 10 },
|
||||
{ specifier: ".hidden.js", ok: true, value: "hidden package" },
|
||||
{ specifier: "./.hidden.js", ok: true, value: "local hidden" },
|
||||
{ specifier: ".", ok: true, value: "current directory" },
|
||||
{ specifier: "..", ok: true, value: "parent directory" },
|
||||
]);
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"matches Node module lookup for ESM and CommonJS through %s",
|
||||
async (surface, { cli }) => {
|
||||
@@ -123,79 +246,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
timeout: 5_000,
|
||||
}),
|
||||
]);
|
||||
const esmResults = JSON.parse(esmControl.stdout) as Array<{
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
readonly value?: unknown;
|
||||
}>;
|
||||
const cjsResults = JSON.parse(cjsControl.stdout) as Array<{
|
||||
readonly specifier: string;
|
||||
readonly ok: boolean;
|
||||
readonly code?: string;
|
||||
readonly value?: unknown;
|
||||
}>;
|
||||
expect(esmResults).toEqual([
|
||||
{
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "ERR_UNSUPPORTED_DIR_IMPORT",
|
||||
},
|
||||
{
|
||||
specifier: "./explicit.js",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./exact.js", ok: true, value: 4 },
|
||||
{ specifier: "./actual.cjs?cache=1", ok: true, value: 5 },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-empty", ok: false, code: "ERR_MODULE_NOT_FOUND" },
|
||||
{
|
||||
specifier: "ancestor-blocked",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "ancestor-sub/parser",
|
||||
ok: false,
|
||||
code: "ERR_MODULE_NOT_FOUND",
|
||||
},
|
||||
]);
|
||||
expect(cjsResults).toEqual([
|
||||
{
|
||||
specifier: "./extensionless",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./directory",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{
|
||||
specifier: "./feature",
|
||||
ok: false,
|
||||
code: "MODULE_NOT_FOUND",
|
||||
},
|
||||
{ specifier: "./feature.cjs", ok: true, value: 2 },
|
||||
{ specifier: "./module-only", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "./valid-directory", ok: true, value: 42 },
|
||||
{ specifier: "./default-js", ok: true, value: 3 },
|
||||
{ specifier: "./default-json", ok: true, value: { value: 4 } },
|
||||
{ specifier: "empty-main", ok: true, value: 42 },
|
||||
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "file-only", ok: true, value: 7 },
|
||||
{ specifier: "ancestor-empty", ok: true, value: 8 },
|
||||
{ specifier: "ancestor-blocked", ok: false, code: "MODULE_NOT_FOUND" },
|
||||
{ specifier: "ancestor-sub/parser", ok: true, value: 10 },
|
||||
]);
|
||||
expectNodeRuntimeControls(esmControl.stdout, cjsControl.stdout);
|
||||
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const expectations = [
|
||||
@@ -211,6 +262,14 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
["import", "ancestor-empty", null, "not-found"],
|
||||
["import", "ancestor-blocked", null, "not-found"],
|
||||
["import", "ancestor-sub/parser", null, "not-found"],
|
||||
["import", "./.hidden.js", "esm/.hidden.js", "resolved"],
|
||||
["import", "./..pkg.js", "esm/..pkg.js", "resolved"],
|
||||
["import", ".hidden.js", null, "rejected"],
|
||||
["import", "..pkg.js", null, "rejected"],
|
||||
["import", ".", null, "not-found"],
|
||||
["import", "..", null, "not-found"],
|
||||
["import", "./exact.js/.", null, "not-found"],
|
||||
["import", "./exact.js/child/..", null, "not-found"],
|
||||
["require", "./extensionless", null, "not-found"],
|
||||
["require", "./directory", null, "not-found"],
|
||||
["require", "./feature", null, "not-found"],
|
||||
@@ -242,19 +301,30 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"node_modules/ancestor-sub/parser.js",
|
||||
"resolved",
|
||||
],
|
||||
["require", ".hidden.js", "node_modules/.hidden.js/index.js", "resolved"],
|
||||
["require", "./.hidden.js", "cjs/.hidden.js", "resolved"],
|
||||
["require", ".", "cjs/index.js", "resolved"],
|
||||
["require", "..", "index.js", "resolved"],
|
||||
] as const;
|
||||
|
||||
for (const [kind, specifier, resolvedPath, status] of expectations)
|
||||
expect(graph.edges).toContainEqual(
|
||||
for (const [kind, specifier, resolvedPath, status] of expectations) {
|
||||
const matchingProperties = graph.edges
|
||||
.filter((edge) => edge.relation === "imports")
|
||||
.map((edge) => edge.properties)
|
||||
.filter(
|
||||
(properties) =>
|
||||
"module_link_kind" in properties &&
|
||||
properties.module_link_kind === kind &&
|
||||
properties.specifier === specifier,
|
||||
);
|
||||
expect(matchingProperties).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: kind,
|
||||
specifier,
|
||||
resolved_path: resolvedPath,
|
||||
resolution_status: status,
|
||||
}),
|
||||
module_link_kind: kind,
|
||||
specifier,
|
||||
resolved_path: resolvedPath,
|
||||
resolution_status: status,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -20,6 +20,50 @@ import { inesFixture } from "../fixtures/ines.js";
|
||||
import { writeOrderedZip } from "../fixtures/artifactEntryOrder.js";
|
||||
import { ZIP_PACKAGE_FORMATS } from "../../src/domain/zipPackageFormat.js";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import { buildBinary } from "plist";
|
||||
|
||||
cliTest(
|
||||
"extracts replacement iNES bytes from an already open plist through MCP",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-plist-refresh-");
|
||||
const path = join(root, "source.bin");
|
||||
await writeFile(path, buildBinary({ value: "old" }));
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const opened = await call("open_binary", { path });
|
||||
expect(opened.isError, JSON.stringify(opened.structuredContent)).not.toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
toolContract("open_binary").outputSchema.parse(opened.structuredContent)
|
||||
.result,
|
||||
).toMatchObject({ format: "plist" });
|
||||
const bytes = inesFixture();
|
||||
await writeFile(path, bytes);
|
||||
const extracted = await call("extract_artifact", {});
|
||||
expect(
|
||||
extracted.isError,
|
||||
JSON.stringify(extracted.structuredContent),
|
||||
).not.toBe(true);
|
||||
const result = artifactExtractionResultSchema.parse(
|
||||
parseEvidence(extracted.structuredContent).normalized_result,
|
||||
);
|
||||
try {
|
||||
expect(result.manifest.root_format).toBe("ines");
|
||||
expect(
|
||||
Buffer.concat(
|
||||
await Promise.all(
|
||||
["header.bin", "prg/000.bin", "prg/001.bin", "chr/000.bin"].map(
|
||||
(part) => readFile(join(result.output_root, part)),
|
||||
),
|
||||
),
|
||||
),
|
||||
).toEqual(bytes);
|
||||
} finally {
|
||||
await rm(result.output_root, { recursive: true, force: true });
|
||||
}
|
||||
await call("close_binary", {});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"refreshes an iNES path through MCP for every ZIP package family",
|
||||
|
||||
@@ -6,6 +6,17 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const cases = [
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "malformed UTF-8",
|
||||
bytes: Buffer.concat([
|
||||
Buffer.from('{"label":"'),
|
||||
Buffer.from([0xff]),
|
||||
Buffer.from('"}'),
|
||||
]),
|
||||
diagnostic: "not valid UTF-8",
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
@@ -92,7 +103,9 @@ for (const scenario of cases)
|
||||
);
|
||||
const config = join(home, scenario.path);
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
await writeFile(config, scenario.text);
|
||||
const original =
|
||||
"bytes" in scenario ? scenario.bytes : Buffer.from(scenario.text);
|
||||
await writeFile(config, original);
|
||||
const environment = {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
@@ -146,7 +159,7 @@ for (const scenario of cases)
|
||||
});
|
||||
if (!("syntax" in scenario))
|
||||
expect(uninstall.stdout).not.toContain("not valid JSON");
|
||||
expect(await readFile(config, "utf8")).toBe(scenario.text);
|
||||
expect(await readFile(config)).toEqual(original);
|
||||
expect(await readdir(dirname(config))).toEqual([
|
||||
scenario.path.split("/").at(-1),
|
||||
]);
|
||||
|
||||
@@ -26,6 +26,26 @@ class FixtureProcess extends EventEmitter implements ProviderProcessHandle {
|
||||
}
|
||||
}
|
||||
|
||||
const fixtureLauncher =
|
||||
(process: FixtureProcess): JadxLauncher =>
|
||||
async ({ runId }) => ({
|
||||
process,
|
||||
ownership: {
|
||||
runId,
|
||||
leaderPid: process.pid,
|
||||
processGroupId: process.pid,
|
||||
expectedParentPid: process.pid,
|
||||
},
|
||||
cleanup: async () => {
|
||||
process.emit("exit", 0, null);
|
||||
process.emit("close", 0, null);
|
||||
process.stdout.end();
|
||||
process.stderr.end();
|
||||
process.stdin.end();
|
||||
return { cleaned: true, signaled: false };
|
||||
},
|
||||
});
|
||||
|
||||
it("joins pending input errors before detaching the owned protocol stream", async () => {
|
||||
let completeWrite: ((cause: Error) => void) | undefined;
|
||||
const failure = new Error("owned pipe closed during cancellation");
|
||||
@@ -70,26 +90,9 @@ it("joins pending input errors before detaching the owned protocol stream", asyn
|
||||
|
||||
it("decodes split UTF-8 and newline bytes, then routes multiple complete frames", async () => {
|
||||
const process = new FixtureProcess();
|
||||
const launcher: JadxLauncher = async ({ runId }) => ({
|
||||
process,
|
||||
ownership: {
|
||||
runId,
|
||||
leaderPid: process.pid,
|
||||
processGroupId: process.pid,
|
||||
expectedParentPid: process.pid,
|
||||
},
|
||||
cleanup: async () => {
|
||||
process.emit("exit", 0, null);
|
||||
process.emit("close", 0, null);
|
||||
process.stdout.end();
|
||||
process.stderr.end();
|
||||
process.stdin.end();
|
||||
return { cleaned: true, signaled: false };
|
||||
},
|
||||
});
|
||||
const transport = new JadxMcpTransport(
|
||||
{ command: "fixture", arguments: [] },
|
||||
launcher,
|
||||
fixtureLauncher(process),
|
||||
);
|
||||
const received: JSONRPCMessage[] = [];
|
||||
transport.onmessage = (message) => received.push(message);
|
||||
@@ -98,7 +101,9 @@ it("decodes split UTF-8 and newline bytes, then routes multiple complete frames"
|
||||
const first = {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: { content: [{ type: "text", text: "snow 雪 🦊" }] },
|
||||
result: {
|
||||
content: [{ type: "text", text: "snow 雪 🦊 and literal �" }],
|
||||
},
|
||||
} satisfies JSONRPCMessage;
|
||||
const second = {
|
||||
jsonrpc: "2.0",
|
||||
@@ -120,28 +125,41 @@ it("decodes split UTF-8 and newline bytes, then routes multiple complete frames"
|
||||
await transport.close();
|
||||
});
|
||||
|
||||
it("accepts a complete JSON-RPC frame at the 8 MiB boundary", async () => {
|
||||
it.each([
|
||||
["invalid UTF-8 byte", Buffer.from([0xff])],
|
||||
["truncated UTF-8 sequence", Buffer.from([0xe2, 0x82])],
|
||||
])("rejects %s in a complete JSON-RPC frame", async (_label, invalid) => {
|
||||
const process = new FixtureProcess();
|
||||
const launcher: JadxLauncher = async ({ runId }) => ({
|
||||
process,
|
||||
ownership: {
|
||||
runId,
|
||||
leaderPid: process.pid,
|
||||
processGroupId: process.pid,
|
||||
expectedParentPid: process.pid,
|
||||
},
|
||||
cleanup: async () => {
|
||||
process.emit("exit", 0, null);
|
||||
process.emit("close", 0, null);
|
||||
process.stdout.end();
|
||||
process.stderr.end();
|
||||
process.stdin.end();
|
||||
return { cleaned: true, signaled: false };
|
||||
},
|
||||
});
|
||||
const transport = new JadxMcpTransport(
|
||||
{ command: "fixture", arguments: [] },
|
||||
launcher,
|
||||
fixtureLauncher(process),
|
||||
);
|
||||
const received: JSONRPCMessage[] = [];
|
||||
const errors: Error[] = [];
|
||||
transport.onmessage = (message) => received.push(message);
|
||||
transport.onerror = (cause) => errors.push(cause);
|
||||
|
||||
await transport.start();
|
||||
process.stdout.write(
|
||||
Buffer.concat([
|
||||
Buffer.from('{"jsonrpc":"2.0","id":1,"result":{"text":"'),
|
||||
invalid,
|
||||
Buffer.from('"}}\n'),
|
||||
]),
|
||||
);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await transport.close();
|
||||
|
||||
expect(received).toEqual([]);
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]?.message).toMatch(/encoded data was not valid/i);
|
||||
});
|
||||
|
||||
it("accepts a complete JSON-RPC frame at the 8 MiB boundary", async () => {
|
||||
const process = new FixtureProcess();
|
||||
const transport = new JadxMcpTransport(
|
||||
{ command: "fixture", arguments: [] },
|
||||
fixtureLauncher(process),
|
||||
);
|
||||
const received: JSONRPCMessage[] = [];
|
||||
transport.onmessage = (message) => received.push(message);
|
||||
|
||||
@@ -3,6 +3,37 @@ import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
describe("screenshot committed document identity", () => {
|
||||
it.each([
|
||||
{ offset: 8, value: 14 },
|
||||
{ offset: 16, value: 0x8000_0000 },
|
||||
{ offset: 20, value: 0x8000_0000 },
|
||||
])("rejects invalid screenshot IHDR metadata", async ({ offset, value }) => {
|
||||
const bytes = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
bytes.writeUInt32BE(value, offset);
|
||||
const browser = await startFakeCdpBrowser({
|
||||
commandResult: ({ method }) =>
|
||||
method === "Page.captureScreenshot"
|
||||
? { data: bytes.toString("base64") }
|
||||
: undefined,
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await browser.close();
|
||||
});
|
||||
const result = await new CdpBrowserProvider().captureScreenshot(
|
||||
captureWebScreenshotInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "protocol_error" },
|
||||
});
|
||||
});
|
||||
it.each(["loader-main", "loader-reloaded"])(
|
||||
"distinguishes %s for the same URL",
|
||||
async (screenshotDocumentLoader) => {
|
||||
|
||||
@@ -7,6 +7,9 @@ import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { webNetworkCaptureSchema } from "../../../src/domain/webNetworkCapture.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
const entrypoint = fileURLToPath(
|
||||
new URL("../../../scripts/rea.mjs", import.meta.url),
|
||||
);
|
||||
@@ -41,6 +44,91 @@ const cli = async (
|
||||
};
|
||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
|
||||
it("excludes declared binary lengths through CLI, MCP and retained capture pages", async () => {
|
||||
const root = await createTestTempDirectory("rea-har-byte-length-");
|
||||
const path = join(root, "capture.har");
|
||||
const fixture = historicalHar();
|
||||
const entry = fixture.log.entries[0];
|
||||
if (entry === undefined) throw new Error("fixture missing");
|
||||
const body = Buffer.alloc(12_345, "A");
|
||||
const content = body.toString("base64");
|
||||
const digest = createHash("sha256").update(body).digest("hex");
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({
|
||||
log: {
|
||||
...fixture.log,
|
||||
entries: [
|
||||
{
|
||||
...entry,
|
||||
response: {
|
||||
...entry.response,
|
||||
content: {
|
||||
size: 99,
|
||||
mimeType: "text/plain",
|
||||
encoding: "base64",
|
||||
text: content,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const args = { capture_path: path, format: "har" };
|
||||
const control = await call("inspect_web_network_capture", args);
|
||||
expect(control.isError).not.toBe(true);
|
||||
const retained = parseEvidence(control.structuredContent);
|
||||
const controlCapture = webNetworkCaptureSchema.parse(
|
||||
retained.normalized_result,
|
||||
);
|
||||
expect(controlCapture.records[0]?.binary_fields[0]).toMatchObject({
|
||||
state: "retained",
|
||||
bytes: body.length,
|
||||
content_base64: content,
|
||||
sha256: digest,
|
||||
});
|
||||
for (const literal of ["12345", "2345"]) {
|
||||
// Only the derived count matches, so this cannot pass via another exclusion.
|
||||
expect(content).not.toContain(literal);
|
||||
expect(digest).not.toContain(literal);
|
||||
const fromCli = await cli(path, "har", ["--sensitive-value", literal]);
|
||||
expect(fromCli.ok, fromCli.stdout).toBe(true);
|
||||
const evidence = parseEvidence(JSON.parse(fromCli.stdout));
|
||||
const response = await call("inspect_web_network_capture", {
|
||||
...args,
|
||||
sensitive_values: [literal],
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const fromMcp = parseEvidence(response.structuredContent);
|
||||
expect(fromMcp.normalized_result).toEqual(evidence.normalized_result);
|
||||
const capture = webNetworkCaptureSchema.parse(evidence.normalized_result);
|
||||
expect(capture.records[0]?.reported).toMatchObject({
|
||||
response: { content: { size: 99, text: null } },
|
||||
});
|
||||
expect(capture.records[0]?.binary_fields[0]).toEqual({
|
||||
pointer: "/response/content/text",
|
||||
representation: "har-base64-content",
|
||||
state: "redacted",
|
||||
bytes: null,
|
||||
content_base64: null,
|
||||
sha256: null,
|
||||
});
|
||||
for (const detail of ["preview", "complete"]) {
|
||||
const page = await call("inspect_analysis_view", {
|
||||
source: { kind: "retained-evidence", evidence_id: fromMcp.evidence_id },
|
||||
view: { kind: "capture", detail },
|
||||
});
|
||||
expect(page.isError).not.toBe(true);
|
||||
const result = parseEvidence(page.structuredContent);
|
||||
expect(result.normalized_result).toMatchObject({
|
||||
items: [{ binary_fields: [{ state: "redacted", bytes: null }] }],
|
||||
});
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("reads actual upstream HAR packages in an owned process and retains selected producer order", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-history-har-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { packetFieldsCatalogSchema } from "../../../src/domain/captures/packetFields.js";
|
||||
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
|
||||
import { it, expect, onTestFinished } from "vitest";
|
||||
import { writeFile, readdir, chmod, symlink } from "node:fs/promises";
|
||||
@@ -20,14 +21,15 @@ const fixture = async (mode = "ok", failCleanup = false) => {
|
||||
await writeFile(
|
||||
script,
|
||||
`import {readFileSync, writeFileSync, chmodSync, truncateSync} from 'node:fs';
|
||||
if (process.argv.includes('--version')) { console.log('TShark (Wireshark) 4.6.9 (fixture)'); console.error('version warning'); }
|
||||
if (process.argv.includes('--version')) { console.log(${JSON.stringify(mode)} === 'bad-version' ? 'TShark (Wireshark) 3.0.0' : 'TShark (Wireshark) 4.6.9 (fixture)'); console.error('version warning'); }
|
||||
else if (${JSON.stringify(mode)} === 'nonzero') { console.error('invalid decoder'); process.exitCode = 1; }
|
||||
else if (${JSON.stringify(mode)} === 'malformed-copy') { chmodSync('capture', 0o600); writeFileSync('capture', 'changed'); }
|
||||
else if (${JSON.stringify(mode)} === 'oversized-copy') { chmodSync('capture', 0o600); truncateSync('capture', 32 * 1024 * 1024 + 1); console.log('[]'); }
|
||||
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat(5 * 1024 * 1024));
|
||||
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat((process.argv.includes('-G') ? 33 : 5) * 1024 * 1024));
|
||||
else if (${JSON.stringify(mode)} === 'wait') { console.log('ready'); setInterval(() => {}, 1000); }
|
||||
else if (${JSON.stringify(mode)} === 'invalid-json') console.log('not json');
|
||||
else if (${JSON.stringify(mode)} === 'many') console.log(JSON.stringify(Array.from({length:90},(_,i)=>({_source:{layers:{"frame.number":[String(i+1)],"ip.addr":["192.0.2.1"]}}}))));
|
||||
else if (process.argv.includes('-G')) { console.log('P\\tUniversal Serial Bus\\tusb\\nF\\tVendor ID\\tusb.idVendor\\tFT_UINT16\\tusb\\tBASE_HEX\\t0x0\\t\\nF\\tOther Vendor\\tusb.idVendor\\tFT_UINT32\\tusb\\tBASE_HEX\\t0x0\\tSecond registration\\nP\\tInternet Protocol\\tip\\nF\\tAddress\\tip.addr\\tFT_IPv4\\tip\\t\\t0x0\\tSource or destination'); console.error('glossary warning'); }
|
||||
else { if(readFileSync('capture', 'utf8') !== 'recording bytes') throw Error('wrong copy'); console.log(JSON.stringify([{_source:{layers:{"frame.number":["1"],"ip.addr":["192.0.2.1","192.0.2.2"]}}}])); console.error('producer warning'); }
|
||||
`,
|
||||
);
|
||||
@@ -301,6 +303,9 @@ it("retains a completed observation when cancellation arrives at the service bou
|
||||
const execution = await f.service.provider.inspect(input);
|
||||
if (!execution.ok) throw execution.error;
|
||||
const service = new PacketCaptureService({
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
f.controller.abort();
|
||||
return execution;
|
||||
@@ -465,3 +470,158 @@ it("rejects oversized selector lists and UTF-8 argv expansion before provider wo
|
||||
}
|
||||
expect(f.calls()).toBe(0);
|
||||
});
|
||||
|
||||
it("discovers installed protocols and field definitions without a capture", async () => {
|
||||
const f = await fixture();
|
||||
for (const [input, expected] of [
|
||||
[
|
||||
{ query: "USB" },
|
||||
{
|
||||
records: [{ abbreviation: "usb", kind: "protocol", field_type: null }],
|
||||
output_window: { examined: 2, matching: 1, returned: 1 },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ kind: "fields", protocol: "usb", limit: 1 },
|
||||
{
|
||||
records: [
|
||||
{
|
||||
abbreviation: "usb.idVendor",
|
||||
field_type: "FT_UINT16",
|
||||
source_line: 2,
|
||||
},
|
||||
],
|
||||
output_window: {
|
||||
examined: 3,
|
||||
matching: 2,
|
||||
returned: 1,
|
||||
has_more: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{ kind: "fields", protocol: "usb", offset: 1, limit: null },
|
||||
{
|
||||
records: [
|
||||
{
|
||||
abbreviation: "usb.idVendor",
|
||||
field_type: "FT_UINT32",
|
||||
source_line: 3,
|
||||
},
|
||||
],
|
||||
output_window: { matching: 2, returned: 1, has_more: false },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ kind: "fields", query: "destination" },
|
||||
{
|
||||
records: [
|
||||
{
|
||||
abbreviation: "ip.addr",
|
||||
description: "Source or destination",
|
||||
display_base: "",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
{ query: "no-such-protocol" },
|
||||
{ records: [], output_window: { matching: 0, returned: 0 } },
|
||||
],
|
||||
] as const) {
|
||||
const result = await f.service.inspectFields(input);
|
||||
if (!result.ok) throw result.error;
|
||||
const report = packetFieldsCatalogSchema.parse(
|
||||
result.value.normalized_result,
|
||||
);
|
||||
expect(report).toMatchObject(expected);
|
||||
expect(report.tool.arguments).toEqual(["-G", "fields"]);
|
||||
expect(report.tool.version_diagnostics).toBe("version warning\n");
|
||||
expect(report.diagnostics).toBe("glossary warning\n");
|
||||
expect(report.limits.output_bytes).toBe(32 * 1024 * 1024);
|
||||
}
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("shares discovery admission with inspection and refuses work after shutdown", async () => {
|
||||
const f = await fixture("gated");
|
||||
const active = f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
await f.acquired;
|
||||
const busy = await f.service.inspectFields({});
|
||||
f.release();
|
||||
if (!(await active).ok) throw new Error("Inspection failed");
|
||||
expect(busy).toMatchObject({
|
||||
ok: false,
|
||||
error: { operation: "inspect_packet_fields", resource: "capacity" },
|
||||
});
|
||||
await f.service.close();
|
||||
expect(await f.service.inspectFields({})).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
operation: "inspect_packet_fields",
|
||||
_tag: "AnalysisCancelledError",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
"bad-version",
|
||||
"nonzero",
|
||||
"overflow",
|
||||
"wait",
|
||||
"oversized-tool",
|
||||
"invalid-json",
|
||||
])("retains field discovery failure facts: %s", async (mode) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspectFields(
|
||||
{},
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected failure");
|
||||
expect(result.error).toMatchObject({ operation: "inspect_packet_fields" });
|
||||
if (mode === "bad-version")
|
||||
expect(result.error.capturedOutput).toMatchObject({
|
||||
stdout: "TShark (Wireshark) 3.0.0\n",
|
||||
stderr: "version warning\n",
|
||||
});
|
||||
if (mode === "invalid-json")
|
||||
expect(result.error.capturedOutput?.stdout).toBe("not json\n");
|
||||
if (mode === "overflow")
|
||||
expect(result.error).toMatchObject({
|
||||
resource: "memory",
|
||||
reportedLimits: { output_bytes: 32 * 1024 * 1024 },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains completed discovery on late cancellation and cleanup failure", async () => {
|
||||
for (const mode of ["post-run-abort", "cleanup"]) {
|
||||
const f = await fixture(mode, mode === "cleanup");
|
||||
const result = await f.service.inspectFields(
|
||||
{ query: "usb" },
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
partialObservation: {
|
||||
operation: "inspect_packet_fields",
|
||||
normalized_result: { records: [{ abbreviation: "usb" }] },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (mode === "cleanup") {
|
||||
await f.service.inspectFields({});
|
||||
await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
|
||||
expect(f.calls()).toBe(2);
|
||||
for (let attempt = 0; attempt < 2; attempt++)
|
||||
await expect(f.service.close()).rejects.toMatchObject({
|
||||
operation: "inspect_packet_fields",
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
}
|
||||
f.allowCleanup();
|
||||
await f.service.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { inspectPacketFieldsInputSchema } from "../../../src/domain/captures/packetFields.js";
|
||||
import { parseFieldDiscovery } from "../../../src/captures/parseFieldDiscovery.js";
|
||||
|
||||
it("keeps duplicate registrations and source ordinals instead of overwriting abbreviations", () => {
|
||||
const text =
|
||||
"P\tUSB\tusb\r\nF\tVendor\tusb.idVendor\tFT_UINT16\tusb\tBASE_HEX\t0x0\t\r\nF\tVendor\tusb.idVendor\tFT_UINT32\tusb\tBASE_HEX\t0x0\t";
|
||||
const result = parseFieldDiscovery(
|
||||
text,
|
||||
inspectPacketFieldsInputSchema.parse({
|
||||
kind: "fields",
|
||||
query: "idVendor",
|
||||
offset: 1,
|
||||
}),
|
||||
);
|
||||
expect(result.records).toMatchObject([
|
||||
{
|
||||
source_line: 3,
|
||||
abbreviation: "usb.idVendor",
|
||||
field_type: "FT_UINT32",
|
||||
description: "",
|
||||
},
|
||||
]);
|
||||
expect(result.output_window).toEqual({
|
||||
examined: 2,
|
||||
matching: 2,
|
||||
returned: 1,
|
||||
has_more: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects damaged records even outside the selected page", () => {
|
||||
for (const text of [
|
||||
"",
|
||||
"P\tmissing",
|
||||
"F\tname\tabbr",
|
||||
"P\tname\t",
|
||||
"P\tUSB\tusb\nBAD",
|
||||
])
|
||||
expect(() =>
|
||||
parseFieldDiscovery(
|
||||
text,
|
||||
inspectPacketFieldsInputSchema.parse({ limit: 1 }),
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("bounds explicit full-result expansion while allowing a page from the same large glossary", () => {
|
||||
const text = "P\t" + "Long name ".repeat(30) + "\tabbr\n";
|
||||
const glossary = text.repeat(6000);
|
||||
expect(() =>
|
||||
parseFieldDiscovery(
|
||||
glossary,
|
||||
inspectPacketFieldsInputSchema.parse({ limit: null }),
|
||||
),
|
||||
).toThrow("representation budget");
|
||||
const result = parseFieldDiscovery(
|
||||
glossary,
|
||||
inspectPacketFieldsInputSchema.parse({ offset: 5999, limit: 1 }),
|
||||
);
|
||||
expect(result.output_window).toEqual({
|
||||
examined: 6000,
|
||||
matching: 6000,
|
||||
returned: 1,
|
||||
has_more: false,
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,9 @@ it.each([false, true])(
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => err(original),
|
||||
close: async () => {
|
||||
await Promise.resolve();
|
||||
@@ -87,6 +90,9 @@ it("rejects an oversized selector budget before the CLI invokes its service", as
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
@@ -125,6 +131,9 @@ it("rejects conflicting output options before the CLI invokes its service", asyn
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
|
||||
@@ -30,6 +30,9 @@ it.each([
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectDecoders: async () => {
|
||||
throw new Error("Unexpected discovery call");
|
||||
},
|
||||
decode: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not decode");
|
||||
@@ -84,6 +87,9 @@ it.each([false, true])(
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectDecoders: async () => {
|
||||
throw new Error("Unexpected discovery call");
|
||||
},
|
||||
decode: async () => err(original),
|
||||
close: async () => {
|
||||
await Promise.resolve();
|
||||
|
||||
@@ -1,13 +1,91 @@
|
||||
import { chmod, readFile, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parse as parseToml } from "smol-toml";
|
||||
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import {
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("accepts a literal UTF-8 replacement character without changing its value", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-config-utf8-");
|
||||
const configPath = join(root, "config.json");
|
||||
const original = Buffer.concat([
|
||||
Buffer.from('{"label":"'),
|
||||
Buffer.from("\uFFFD"),
|
||||
Buffer.from('"}'),
|
||||
]);
|
||||
await writeFile(configPath, original);
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", format: "json", configPath },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
expect(result.status).toBe("configured");
|
||||
expect(await readFile(`${configPath}.rea.backup`)).toEqual(original);
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).label).toBe("\uFFFD");
|
||||
});
|
||||
|
||||
it("previews and creates a current recovery backup while preserving the first backup", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-current-recovery-");
|
||||
const configPath = join(root, "config.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
const client = { name: "cursor", format: "json", configPath } as const;
|
||||
await writeFile(configPath, currentOriginal);
|
||||
await writeFile(`${configPath}.rea.backup`, firstOriginal);
|
||||
|
||||
const recoveryPath = `${configPath}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
expect(await inspectClientConfiguration(client, {}, ["rea", "mcp"])).toEqual({
|
||||
status: "update",
|
||||
backupPath: recoveryPath,
|
||||
});
|
||||
|
||||
expect(
|
||||
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toEqual({ status: "configured", backupPath: recoveryPath });
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(
|
||||
firstOriginal,
|
||||
);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe(currentOriginal);
|
||||
});
|
||||
|
||||
it("blocks configuration when the planned content-addressed backup is occupied", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-recovery-conflict-");
|
||||
const configPath = join(root, "config.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
const client = { name: "cursor", format: "json", configPath } as const;
|
||||
await writeFile(configPath, currentOriginal);
|
||||
await writeFile(`${configPath}.rea.backup`, firstOriginal);
|
||||
const recoveryPath = `${configPath}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
await writeFile(recoveryPath, "occupied by other data");
|
||||
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toMatchObject({
|
||||
status: "invalid",
|
||||
remediation: expect.stringContaining(recoveryPath),
|
||||
});
|
||||
expect(
|
||||
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toEqual({ status: "failed", reason: "backup" });
|
||||
expect(await readFile(configPath, "utf8")).toBe(currentOriginal);
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(
|
||||
firstOriginal,
|
||||
);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe("occupied by other data");
|
||||
});
|
||||
|
||||
describe("client configuration write failures", () => {
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0).each([
|
||||
["json", configureClientConfiguration],
|
||||
|
||||
@@ -191,12 +191,9 @@ describe.skipIf(process.platform === "win32")(
|
||||
it.each([
|
||||
["name=other\nversion=12.1.3\n", "does not match"],
|
||||
["name=ghidra-allegrex\nversion=12.1.4\n", "does not match"],
|
||||
[
|
||||
"name=ghidra-allegrex\nversion=12.1.3\nversion=12.1.3\n",
|
||||
"exactly one version",
|
||||
],
|
||||
["name=ghidra-allegrex\nversion=12.1.\\uZZZZ\n", "Unicode escape"],
|
||||
])(
|
||||
"rejects incompatible or ambiguous extension metadata %s",
|
||||
"rejects mismatched or malformed extension metadata %s",
|
||||
async (properties, reason) => {
|
||||
const { root } = await installation();
|
||||
await writeFile(join(root, "extension.properties"), properties);
|
||||
@@ -504,3 +501,38 @@ describe.skipIf(process.platform === "win32")(
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"PSP extension property syntax",
|
||||
() => {
|
||||
it.each([
|
||||
{
|
||||
form: "escaped key and value with colon separator",
|
||||
properties: "n\\u0061me : ghidra-allegrex\nver\\u0073ion=12.1.3\n",
|
||||
},
|
||||
{
|
||||
form: "continued key and value lines",
|
||||
properties: "name=ghidra-\\\n allegrex\nversion=12.1.\\\n 3\n",
|
||||
},
|
||||
{
|
||||
form: "duplicate keys use the last value",
|
||||
properties:
|
||||
"name=wrong\nname=ghidra-allegrex\nversion=12.1.4\nversion=12.1.3\n",
|
||||
},
|
||||
])(
|
||||
"accepts Java Properties $form and hashes raw bytes",
|
||||
async ({ properties }) => {
|
||||
const { root } = await installation();
|
||||
const canonical = await inspectGhidraPspExtension(root, "12.1.3");
|
||||
const latin1Properties = Buffer.from(
|
||||
`${properties}author=caf\u00e9\n`,
|
||||
"latin1",
|
||||
);
|
||||
await writeFile(join(root, "extension.properties"), latin1Properties);
|
||||
const extension = await inspectGhidraPspExtension(root, "12.1.3");
|
||||
expect(extension.id).toBe("ghidra-allegrex");
|
||||
expect(extension.sha256).not.toBe(canonical.sha256);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -30,6 +30,81 @@ import {
|
||||
const sha256 = (bytes: Buffer) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
it("reuses scanned iNES region bytes for reconstruction without another full read", async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-read-budget-");
|
||||
const path = join(root, "large-tail.nes");
|
||||
const bytes = inesFixture({ trailing: Buffer.alloc(2 * 1024 * 1024, 0x5a) });
|
||||
await writeFile(path, bytes);
|
||||
const sample = await open(path, "r");
|
||||
const prototype = Object.getPrototypeOf(sample) as Pick<
|
||||
typeof sample,
|
||||
"read"
|
||||
>;
|
||||
await sample.close();
|
||||
const originalRead = prototype.read;
|
||||
let bytesRead = 0;
|
||||
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
||||
this: typeof sample,
|
||||
...args
|
||||
) {
|
||||
const result = await originalRead.call(this, ...args);
|
||||
bytesRead += result.bytesRead;
|
||||
return result;
|
||||
});
|
||||
try {
|
||||
const result = await inventoryArtifact(path);
|
||||
expect(result.ines?.reconstruction).toMatchObject({
|
||||
bytes: bytes.length,
|
||||
sha256: sha256(bytes),
|
||||
verified: true,
|
||||
});
|
||||
// Initial root hash, region scan, final freshness hash, plus bounded headers.
|
||||
expect(bytesRead).toBeLessThanOrEqual(3 * bytes.length + 64 * 1024);
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects region bytes that disagree with stable whole-file hashes", async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-region-digest-");
|
||||
const path = join(root, "source.nes");
|
||||
const bytes = inesFixture();
|
||||
await writeFile(path, bytes);
|
||||
const sample = await open(path, "r");
|
||||
const prototype = Object.getPrototypeOf(sample) as Pick<
|
||||
typeof sample,
|
||||
"read"
|
||||
>;
|
||||
await sample.close();
|
||||
const originalRead = prototype.read;
|
||||
let changed = false;
|
||||
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
||||
this: typeof sample,
|
||||
...args
|
||||
) {
|
||||
const result = await originalRead.call(this, ...args);
|
||||
const arguments_: readonly unknown[] = args;
|
||||
if (!changed && arguments_[3] === 16n && result.bytesRead === 16_384) {
|
||||
// Alter only the region observation, leaving both whole-file passes intact.
|
||||
if (!Buffer.isBuffer(result.buffer))
|
||||
throw new Error("Expected byte buffer");
|
||||
result.buffer.writeUInt8(result.buffer.readUInt8(0) ^ 0xff, 0);
|
||||
changed = true;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
try {
|
||||
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
message: "iNES reconstruction differs from the source",
|
||||
});
|
||||
expect(changed).toBe(true);
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["data", "hop", "HOP"])(
|
||||
"routes iNES bytes as an archive with a .%s suffix",
|
||||
async (suffix) => {
|
||||
@@ -124,7 +199,6 @@ it.each([true, false])(
|
||||
try {
|
||||
const extraction = await extractArtifact({
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot,
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
@@ -418,7 +492,6 @@ it.each(["removed", "directory", "malformed"])(
|
||||
materializeArtifactInventory(
|
||||
{
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot,
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
@@ -462,7 +535,6 @@ it.each(["EISDIR", "ENOTFILE", "EACCES", "cancelled"])(
|
||||
materializeArtifactInventory(
|
||||
{
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot: join(root, "output"),
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
@@ -503,7 +575,6 @@ it("retains a failed close after rejecting changed extraction bytes", async () =
|
||||
materializeInScope(
|
||||
{
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot: join(root, "output"),
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { InesArtifactReader } from "../../../src/artifacts/InesArtifactReader.js";
|
||||
import { scanReader } from "../../../src/artifacts/inventory/scanReader.js";
|
||||
import { hashStableRootArtifactHandle } from "../../../src/artifacts/inventory/hashStableRootArtifact.js";
|
||||
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
|
||||
import { inesFixture } from "../../fixtures/ines.js";
|
||||
@@ -207,10 +208,20 @@ it.each(["stream", "reconstruction"])(
|
||||
if (last === undefined) throw new Error("Missing last iNES region");
|
||||
const result =
|
||||
operation === "reconstruction"
|
||||
? reader.verifyReconstruction(
|
||||
createHash("sha256").update(bytes).digest("hex"),
|
||||
controller.signal,
|
||||
)
|
||||
? (async () => {
|
||||
const { inesRegionScan } = await scanReader(
|
||||
reader,
|
||||
[reader],
|
||||
controller.signal,
|
||||
);
|
||||
if (inesRegionScan === undefined)
|
||||
throw new Error("Missing region scan");
|
||||
return reader.verifyReconstruction(
|
||||
createHash("sha256").update(bytes).digest("hex"),
|
||||
inesRegionScan,
|
||||
controller.signal,
|
||||
);
|
||||
})()
|
||||
: (async () => {
|
||||
for await (const chunk of await reader.open(
|
||||
last,
|
||||
|
||||
+54
@@ -15,6 +15,60 @@ import {
|
||||
} from "../../../support/javascriptApplicationFixture.js";
|
||||
|
||||
describe("TypeScript source module loader semantics", () => {
|
||||
it("keeps whole type-only declarations out of runtime module relationships", async () => {
|
||||
const root = await createTestTempDirectory("rea-type-module-links-");
|
||||
await writeFixtureFiles(root, {
|
||||
"main.ts": `
|
||||
import type { Whole } from "./whole";
|
||||
export type { Remote } from "./remote";
|
||||
import { type Inline } from "./inline";
|
||||
export type LocalType = string;
|
||||
export interface LocalInterface { value: string }
|
||||
`,
|
||||
"whole.ts": "export interface Whole { value: string }",
|
||||
"remote.ts": "export interface Remote { value: string }",
|
||||
"inline.ts": "export interface Inline { value: string }",
|
||||
});
|
||||
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const source = findSourceModule(graph, "main.ts");
|
||||
const sourceProperties = source?.observations.find(
|
||||
({ properties }) => properties.semantic_role === "source-module",
|
||||
)?.properties;
|
||||
|
||||
expect(sourceProperties).toMatchObject({
|
||||
import_relationships: 0,
|
||||
type_relationships: 5,
|
||||
export_names: [],
|
||||
type_export_names: ["LocalInterface", "LocalType", "Remote"],
|
||||
});
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
["./whole", "./remote"].includes(String(properties.specifier)),
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ source_node_id, relation, properties }) =>
|
||||
source_node_id === source?.node_id &&
|
||||
relation === "imports" &&
|
||||
properties.kind === "static-import" &&
|
||||
properties.specifier === "./inline",
|
||||
),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
source?.observations
|
||||
.flatMap(({ evidence }) => evidence.limitations)
|
||||
.join(" "),
|
||||
).toContain(
|
||||
"inline type-only imports or re-exports may preserve a module side-effect dependency",
|
||||
);
|
||||
expect(findExportNode(graph, "main.ts", "LocalType")).toBeUndefined();
|
||||
expect(findExportNode(graph, "main.ts", "LocalInterface")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses emitted TypeScript loader semantics without changing dynamic imports", async () => {
|
||||
const root = await createTestTempDirectory("rea-cts-module-loader-");
|
||||
await writeFixtureFiles(root, {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
type ApplicationVersionComparisonResult,
|
||||
} from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
|
||||
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { electronPageInspectionSchema } from "../../../src/domain/javascript/electronObservation.js";
|
||||
import { compareJavaScriptApplicationVersions } from "../../../src/domain/javascript/javascriptApplicationVersionComparison.js";
|
||||
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { traceApplicationFeature } from "../../../src/domain/javascript/javascriptFeatureTrace.js";
|
||||
@@ -444,6 +445,73 @@ describe("JavaScript application workflow error diagnostics", () => {
|
||||
});
|
||||
|
||||
describe("JavaScript runtime reconciliation local paths", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "case-sensitive POSIX input root",
|
||||
root: null,
|
||||
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
|
||||
status: "unknown",
|
||||
},
|
||||
{
|
||||
name: "case-sensitive POSIX mapping root",
|
||||
root: "/runtime/App",
|
||||
path: "/runtime/app/renderer.js",
|
||||
status: "unknown",
|
||||
},
|
||||
{
|
||||
name: "matching POSIX mapping root",
|
||||
root: "/runtime/App",
|
||||
path: "/runtime/App/renderer.js",
|
||||
status: "matched",
|
||||
},
|
||||
{
|
||||
name: "case-insensitive Windows mapping root",
|
||||
root: String.raw`C:\runtime\App`,
|
||||
path: String.raw`c:\runtime\app\renderer.js`,
|
||||
status: "matched",
|
||||
},
|
||||
])("uses $name on every host", ({ root, path, status }) => {
|
||||
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
|
||||
const original = base.runtime_observations[0]!;
|
||||
const inspection = electronPageInspectionSchema.parse(
|
||||
original.normalized_result,
|
||||
);
|
||||
const runtime = createEvidence(undefined, original.provider, {
|
||||
predicateType: original.predicate_type,
|
||||
operation: original.operation,
|
||||
parameters: { ...original.parameters, include_script_sources: false },
|
||||
result: {
|
||||
...inspection,
|
||||
scripts: {
|
||||
...inspection.scripts,
|
||||
items: inspection.scripts.items.map((script) => ({
|
||||
...script,
|
||||
file_path: path,
|
||||
source: { included: false, reason: "not-requested" },
|
||||
})),
|
||||
},
|
||||
},
|
||||
confidence: original.confidence,
|
||||
authority: original.authority,
|
||||
});
|
||||
const reconciled = reconcileJavaScriptRuntimeEvidence({
|
||||
static_layers: base.static_layers.map((layer) => ({
|
||||
...layer,
|
||||
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
|
||||
})),
|
||||
runtime_observations: [runtime],
|
||||
});
|
||||
if (!reconciled.ok) throw reconciled.error;
|
||||
const result = javascriptRuntimeReconciliationResultSchema.parse(
|
||||
reconciled.value.normalized_result,
|
||||
);
|
||||
expect(
|
||||
result.reconciliations.find(
|
||||
({ entity_kind }) => entity_kind === "script",
|
||||
),
|
||||
).toMatchObject({ status });
|
||||
});
|
||||
|
||||
it("resolves relative file mapping roots before deriving result Evidence", () => {
|
||||
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
|
||||
const relativeRoot = relative(process.cwd(), absoluteRoot);
|
||||
|
||||
@@ -378,6 +378,44 @@ describe("reference source path selection", () => {
|
||||
});
|
||||
|
||||
describe("reference source rooted module specifiers", () => {
|
||||
it("keeps dot-prefixed bare specifiers external while resolving explicit relative paths", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-dot-prefix-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "main.js"),
|
||||
'import ".hidden.js"; import "..pkg.js"; import "./.hidden.js"; require(".hidden.js");\n',
|
||||
),
|
||||
writeFile(join(root, ".hidden.js"), "export {};\n"),
|
||||
writeFile(join(root, "..pkg.js"), "export {};\n"),
|
||||
]);
|
||||
const result = await importTree(root);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.relationships).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
to: ".hidden.js",
|
||||
kind: "imports",
|
||||
resolution: "external",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
to: "..pkg.js",
|
||||
kind: "imports",
|
||||
resolution: "external",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
to: ".hidden.js",
|
||||
kind: "imports",
|
||||
resolution: "internal",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
to: ".hidden.js",
|
||||
kind: "requires",
|
||||
resolution: "external",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not rebase an absolute import onto a coincidentally matching source member", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-rooted-");
|
||||
await mkdir(join(root, "src", "outside"), { recursive: true });
|
||||
|
||||
@@ -6,6 +6,31 @@ import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
|
||||
|
||||
it("imports valid CommonJS wrapper syntax without inventing a parse failure", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-commonjs-mode-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "main.cjs"),
|
||||
'void new.target; require("./dep.cjs"); return;\n',
|
||||
),
|
||||
writeFile(join(root, "dep.cjs"), "module.exports = 1;\n"),
|
||||
]);
|
||||
const imported = await importReferenceSource({
|
||||
root,
|
||||
caller: "native-commonjs-source",
|
||||
policy: { secretPatterns: [] },
|
||||
});
|
||||
if (!imported.ok) throw imported.error;
|
||||
expect(imported.value.parse_failures).toEqual([]);
|
||||
expect(imported.value.relationships).toContainEqual({
|
||||
from_path: "main.cjs",
|
||||
to: "dep.cjs",
|
||||
kind: "requires",
|
||||
resolution: "internal",
|
||||
parse_state: "parsed",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["main.ts", "dep.js", "dep.ts"],
|
||||
["main.mts", "dep.mjs", "dep.mts"],
|
||||
|
||||
@@ -10,6 +10,8 @@ const injectedFilesystemFailures = vi.hoisted(() => ({
|
||||
closeNext: false,
|
||||
blockCloseRetries: false,
|
||||
chmodNext: false,
|
||||
syncAbortAfter: undefined as AbortController | undefined,
|
||||
syncCount: 0,
|
||||
rootIdentityPath: undefined as string | undefined,
|
||||
}));
|
||||
|
||||
@@ -44,6 +46,15 @@ vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
await close();
|
||||
};
|
||||
}
|
||||
if (injectedFilesystemFailures.syncAbortAfter !== undefined) {
|
||||
const sync = handle.sync.bind(handle);
|
||||
handle.sync = async () => {
|
||||
await sync();
|
||||
injectedFilesystemFailures.syncCount += 1;
|
||||
if (injectedFilesystemFailures.syncCount === 2)
|
||||
injectedFilesystemFailures.syncAbortAfter?.abort();
|
||||
};
|
||||
}
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
@@ -82,6 +93,34 @@ describe("safe artifact output close failures", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"keeps the tree unpublished when cancellation arrives during commit durability",
|
||||
async () => {
|
||||
const parent = await createTestTempDirectory("rea-safe-output-cancel-");
|
||||
const output = join(parent, "unpublished");
|
||||
const tree = await SafeOutputTree.create(output);
|
||||
const bytes = Buffer.from("pending output");
|
||||
await tree.write("file.txt", Readable.from(bytes), {
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.byteLength,
|
||||
});
|
||||
const controller = new AbortController();
|
||||
injectedFilesystemFailures.syncCount = 0;
|
||||
injectedFilesystemFailures.syncAbortAfter = controller;
|
||||
try {
|
||||
await expect(tree.commit(controller.signal)).rejects.toMatchObject({
|
||||
reason: "cancelled",
|
||||
});
|
||||
expect(tree.published).toBe(false);
|
||||
} finally {
|
||||
injectedFilesystemFailures.syncAbortAfter = undefined;
|
||||
injectedFilesystemFailures.syncCount = 0;
|
||||
}
|
||||
expect(await tree.rollback()).toMatchObject({ status: "complete" });
|
||||
await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves setup failure when closing the staging handle also fails",
|
||||
async () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "../../../src/application/SetupHost.js";
|
||||
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
|
||||
import { configureDetectedClients } from "../../../src/application/SetupClients.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
@@ -31,6 +32,61 @@ beforeEach(async () => {
|
||||
|
||||
afterEach(() => openMock.mockReset());
|
||||
|
||||
const holdReadHandle = (path: string, reason: string) => {
|
||||
const closeAttempts: object[] = [];
|
||||
let released = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== path) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!released) throw new Error(reason);
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
return {
|
||||
closeAttempts,
|
||||
release: () => {
|
||||
released = true;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fails", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-utf8-close-");
|
||||
const path = join(home, "client.json");
|
||||
const original = Buffer.from([0xff]);
|
||||
await writeFile(path, original);
|
||||
const { closeAttempts, release } = holdReadHandle(
|
||||
path,
|
||||
"held uninstall handle",
|
||||
);
|
||||
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
||||
try {
|
||||
expect(
|
||||
await host.removeClient({
|
||||
name: "cursor",
|
||||
format: "json",
|
||||
configPath: path,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "failed",
|
||||
detail: expect.stringContaining("not valid UTF-8"),
|
||||
});
|
||||
expect(await readFile(path)).toEqual(original);
|
||||
expect(closeAttempts).toHaveLength(2);
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
});
|
||||
|
||||
describe("ZCode fallback cleanup ownership", () => {
|
||||
it.each(["preflight", "configure"])(
|
||||
"retains a failed ZCode fallback close during %s until host cleanup",
|
||||
@@ -49,19 +105,10 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
await mkdir(dirname(fallback), { recursive: true });
|
||||
const original = '{"mcpServers":{"other":{"command":"other"}}}\n';
|
||||
await writeFile(fallback, original);
|
||||
const closeAttempts: object[] = [];
|
||||
let allowClose = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== fallback) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!allowClose) throw new Error("held fallback handle");
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
const { closeAttempts, release } = holdReadHandle(
|
||||
fallback,
|
||||
"held fallback handle",
|
||||
);
|
||||
try {
|
||||
const action =
|
||||
operation === "preflight"
|
||||
@@ -79,12 +126,12 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
await expect(readFile(client.configPath)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
allowClose = true;
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
},
|
||||
@@ -92,83 +139,87 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
});
|
||||
|
||||
describe("setup client configuration cleanup ownership", () => {
|
||||
it("stops client configuration and retries the same alignment handle from host close", async () => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-close-");
|
||||
const environment = {
|
||||
HOME: home,
|
||||
XDG_CONFIG_HOME: join(home, "xdg"),
|
||||
};
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
||||
environment,
|
||||
);
|
||||
const client = (await host.supportedClients()).find(
|
||||
({ name }) => name === "vscode",
|
||||
);
|
||||
if (client === undefined) throw new Error("VS Code setup client missing");
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
const original = Buffer.from('{"servers": {"other": {}}}\n');
|
||||
await writeFile(client.configPath, original);
|
||||
it.each([
|
||||
["valid UTF-8", Buffer.from('{"servers": {"other": {}}}\n')],
|
||||
["malformed UTF-8", Buffer.from([0xff])],
|
||||
] as const)(
|
||||
"stops configuration and retains the %s read owner until host close",
|
||||
async (encoding, original) => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-close-");
|
||||
const environment = {
|
||||
HOME: home,
|
||||
XDG_CONFIG_HOME: join(home, "xdg"),
|
||||
};
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
||||
environment,
|
||||
);
|
||||
const client = (await host.supportedClients()).find(
|
||||
({ name }) => name === "vscode",
|
||||
);
|
||||
if (client === undefined) throw new Error("VS Code setup client missing");
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
await writeFile(client.configPath, original);
|
||||
|
||||
const closeAttempts: object[] = [];
|
||||
let allowClose = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== client.configPath) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!allowClose) throw new Error("test holds the config handle open");
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
const configure = vi.spyOn(host, "configureClient");
|
||||
const { closeAttempts, release } = holdReadHandle(
|
||||
client.configPath,
|
||||
"test holds the config handle open",
|
||||
);
|
||||
const configure = vi.spyOn(host, "configureClient");
|
||||
|
||||
try {
|
||||
const failure = await filterClientsNeedingConfigure(host, [client], {}, [
|
||||
"rea",
|
||||
"mcp",
|
||||
])
|
||||
.then((detectedClients) =>
|
||||
configureDetectedClients({
|
||||
host,
|
||||
detectedClients,
|
||||
providerEnvironment: {},
|
||||
command: ["rea", "mcp"],
|
||||
clients: {},
|
||||
appliedActions: [],
|
||||
}),
|
||||
try {
|
||||
const failure = await filterClientsNeedingConfigure(
|
||||
host,
|
||||
[client],
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
)
|
||||
.then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(ConfigurationError);
|
||||
expect(failure).toMatchObject({
|
||||
_tag: "ConfigurationError",
|
||||
cause: expect.any(RegularFileCleanupFailure),
|
||||
cleanup: {
|
||||
resources: [client.configPath],
|
||||
reason: expect.stringContaining("test holds the config handle open"),
|
||||
},
|
||||
});
|
||||
expect(configure).not.toHaveBeenCalled();
|
||||
expect(closeAttempts).toHaveLength(2);
|
||||
expect(closeAttempts[0]).toBe(closeAttempts[1]);
|
||||
expect(await readFile(client.configPath)).toEqual(original);
|
||||
.then((detectedClients) =>
|
||||
configureDetectedClients({
|
||||
host,
|
||||
detectedClients,
|
||||
providerEnvironment: {},
|
||||
command: ["rea", "mcp"],
|
||||
clients: {},
|
||||
appliedActions: [],
|
||||
}),
|
||||
)
|
||||
.then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(ConfigurationError);
|
||||
if (encoding === "malformed UTF-8")
|
||||
expect(failure).toMatchObject({
|
||||
cause: {
|
||||
outcome: { kind: "failed", cause: expect.any(TypeError) },
|
||||
},
|
||||
});
|
||||
expect(failure).toMatchObject({
|
||||
_tag: "ConfigurationError",
|
||||
cause: expect.any(RegularFileCleanupFailure),
|
||||
cleanup: {
|
||||
resources: [client.configPath],
|
||||
reason: expect.stringContaining(
|
||||
"test holds the config handle open",
|
||||
),
|
||||
},
|
||||
});
|
||||
expect(configure).not.toHaveBeenCalled();
|
||||
expect(closeAttempts).toHaveLength(2);
|
||||
expect(closeAttempts[0]).toBe(closeAttempts[1]);
|
||||
expect(await readFile(client.configPath)).toEqual(original);
|
||||
|
||||
allowClose = true;
|
||||
const close = host.close;
|
||||
if (close === undefined) throw new Error("Setup host close is missing");
|
||||
expect(await close()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
await host.close?.();
|
||||
}
|
||||
});
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("waits for an admitted configuration read and rejects later admissions", async () => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-inflight-");
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
createDeferred,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const connectImportSession = async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-import-lifecycle-");
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Evidence import must not start a binary provider");
|
||||
});
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({
|
||||
name: "evidence-import-lifecycle",
|
||||
version: "1",
|
||||
});
|
||||
const readCompleted = createDeferred<void>();
|
||||
const releaseRead = createDeferred<void>();
|
||||
const originalFileClose = OwnedFileHandle.prototype.close;
|
||||
vi.spyOn(OwnedFileHandle.prototype, "close").mockImplementationOnce(
|
||||
async function (this: OwnedFileHandle) {
|
||||
await originalFileClose.call(this);
|
||||
readCompleted.resolve();
|
||||
await releaseRead.promise;
|
||||
},
|
||||
);
|
||||
const closeStarted = createDeferred<void>();
|
||||
const originalSessionClose = session.close.bind(session);
|
||||
const events: string[] = [];
|
||||
vi.spyOn(session, "close").mockImplementation((...args) => {
|
||||
const closing = originalSessionClose(...args);
|
||||
closeStarted.resolve();
|
||||
return closing.then((result) => {
|
||||
events.push("close");
|
||||
return result;
|
||||
});
|
||||
});
|
||||
const originalImport = session.importEvidenceBundle.bind(session);
|
||||
vi.spyOn(session, "importEvidenceBundle").mockImplementation((bundle) => {
|
||||
const imported = originalImport(bundle);
|
||||
events.push("import");
|
||||
return imported;
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
releaseRead.resolve();
|
||||
vi.restoreAllMocks();
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const laterImportDispatched = createDeferred<void>();
|
||||
let importsDispatched = 0;
|
||||
const send = clientTransport.send.bind(clientTransport);
|
||||
vi.spyOn(clientTransport, "send").mockImplementation(
|
||||
async (message, ...args) => {
|
||||
await send(message, ...args);
|
||||
if (
|
||||
"method" in message &&
|
||||
message.method === "tools/call" &&
|
||||
message.params?.name === "import_evidence_bundle"
|
||||
) {
|
||||
importsDispatched += 1;
|
||||
if (importsDispatched === 2) laterImportDispatched.resolve();
|
||||
}
|
||||
},
|
||||
);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const importBundle = async (operation: string) => {
|
||||
const record = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation, parameters: {}, result: { retained: operation } },
|
||||
);
|
||||
const path = join(root, `${operation}.json`);
|
||||
await writeFile(path, JSON.stringify(createEvidenceBundle([record])));
|
||||
return client.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path },
|
||||
});
|
||||
};
|
||||
return {
|
||||
client,
|
||||
session,
|
||||
events,
|
||||
importBundle,
|
||||
readCompleted: readCompleted.promise,
|
||||
closeStarted: closeStarted.promise,
|
||||
laterImportDispatched: laterImportDispatched.promise,
|
||||
releaseRead: () => releaseRead.resolve(),
|
||||
};
|
||||
};
|
||||
|
||||
it("drains a file import before close_binary clears the session", async () => {
|
||||
const fixture = await connectImportSession();
|
||||
const importing = fixture.importBundle("before_close");
|
||||
await fixture.readCompleted;
|
||||
const closing = fixture.client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
await fixture.closeStarted;
|
||||
await fixture.client.ping();
|
||||
fixture.releaseRead();
|
||||
const [imported, closed] = await Promise.all([importing, closing]);
|
||||
|
||||
expect(imported.isError, JSON.stringify(imported)).not.toBe(true);
|
||||
expect(imported.structuredContent).toMatchObject({
|
||||
result: { imported: 1, unknowns_added: 0, total: 1 },
|
||||
});
|
||||
expect(closed.isError, JSON.stringify(closed)).not.toBe(true);
|
||||
expect(fixture.events).toEqual(["import", "close"]);
|
||||
expect(fixture.session.exportEvidenceBundle().records).toEqual([]);
|
||||
await fixture.client.ping();
|
||||
});
|
||||
|
||||
it("admits a later import after close_binary without retaining the earlier bundle", async () => {
|
||||
const fixture = await connectImportSession();
|
||||
const earlier = fixture.importBundle("before_close");
|
||||
await fixture.readCompleted;
|
||||
const closing = fixture.client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
await fixture.closeStarted;
|
||||
const later = fixture.importBundle("after_close");
|
||||
await fixture.laterImportDispatched;
|
||||
await fixture.client.ping();
|
||||
fixture.releaseRead();
|
||||
const results = await Promise.all([earlier, closing, later]);
|
||||
|
||||
for (const result of results)
|
||||
expect(result.isError, JSON.stringify(result)).not.toBe(true);
|
||||
expect(results[2]?.structuredContent).toMatchObject({
|
||||
result: { imported: 1, unknowns_added: 0, total: 1 },
|
||||
});
|
||||
expect(fixture.events).toEqual(["import", "close", "import"]);
|
||||
expect(
|
||||
fixture.session
|
||||
.exportEvidenceBundle()
|
||||
.records.map((record) => record.operation),
|
||||
).toEqual(["after_close"]);
|
||||
await fixture.client.ping();
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { copyFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createBinarySession } from "../../../src/composition/binary.js";
|
||||
import { parseConfig } from "../../../src/config/parseConfig.js";
|
||||
import { inspectMachoSchema } from "../../../src/domain/native/nativeInspection.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { mcpTest } from "../../support/mcp/mcpFixture.js";
|
||||
|
||||
const evidenceOf = <Schema extends z.ZodType>(schema: Schema) =>
|
||||
z.object({
|
||||
evidence_id: z.string(),
|
||||
parameters: z.record(z.string(), z.unknown()),
|
||||
normalized_result: schema,
|
||||
});
|
||||
const countSchema = z.object({
|
||||
returned: z.number(),
|
||||
total: z.number().nullable(),
|
||||
exhaustive: z.boolean(),
|
||||
});
|
||||
const summarySchema = z.object({
|
||||
kind: z.literal("summary"),
|
||||
parent_evidence_id: z.string(),
|
||||
summary: z.object({
|
||||
uuid: z.string().nullable(),
|
||||
collections: z.record(z.string(), countSchema),
|
||||
provenance_count: z.number(),
|
||||
}),
|
||||
});
|
||||
const pageSchema = z.object({
|
||||
kind: z.literal("macho"),
|
||||
item: z.array(z.unknown()),
|
||||
coverage: z.object({ next_offset: z.number().nullable() }),
|
||||
});
|
||||
|
||||
describe.skipIf(process.platform !== "darwin")(
|
||||
"Mach-O summary delivery through MCP",
|
||||
() => {
|
||||
mcpTest(
|
||||
"retains complete inspect_macho Evidence and pages its exact rows",
|
||||
async ({ mcp, onTestFinished }) => {
|
||||
const target = join(
|
||||
await createTestTempDirectory("rea-macho-summary-mcp-"),
|
||||
"ls",
|
||||
);
|
||||
await copyFile("/bin/ls", target);
|
||||
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
|
||||
if (!configured.ok) throw configured.error;
|
||||
const session = createBinarySession(
|
||||
configured.value,
|
||||
silentLogger,
|
||||
process.env,
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
await session.close();
|
||||
});
|
||||
const client = await mcp.connect(
|
||||
createServer({ kind: "session", session }),
|
||||
);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: target },
|
||||
});
|
||||
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
|
||||
|
||||
const complete = await client.callTool({
|
||||
name: "inspect_macho",
|
||||
arguments: {},
|
||||
});
|
||||
expect(complete.isError, JSON.stringify(complete.content)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const full = evidenceOf(inspectMachoSchema).parse(
|
||||
complete.structuredContent,
|
||||
);
|
||||
// Omitted detail keeps the default Evidence parameters unchanged.
|
||||
expect(full.parameters).toEqual({});
|
||||
|
||||
const summarized = await client.callTool({
|
||||
name: "inspect_macho",
|
||||
arguments: { detail: "summary" },
|
||||
});
|
||||
expect(summarized.isError, JSON.stringify(summarized.content)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const summary = evidenceOf(summarySchema).parse(
|
||||
summarized.structuredContent,
|
||||
).normalized_result;
|
||||
// Delivery detail never reaches the tools or the source Evidence ID.
|
||||
expect(summary.parent_evidence_id).toBe(full.evidence_id);
|
||||
const report = full.normalized_result;
|
||||
expect(summary.summary.uuid).toBe(report.uuid);
|
||||
expect(summary.summary.provenance_count).toBe(report.provenance.length);
|
||||
for (const name of ["imports", "exports", "dependencies"] as const)
|
||||
expect(summary.summary.collections[name]).toEqual({
|
||||
returned: report[name].items.length,
|
||||
total: report[name].total,
|
||||
exhaustive: report[name].exhaustive,
|
||||
});
|
||||
expect(JSON.stringify(summarized.structuredContent)).not.toContain(
|
||||
report.imports.items[0]?.name ?? "_",
|
||||
);
|
||||
|
||||
// Every facet must reassemble the unparsed complete rows exactly.
|
||||
const raw = z
|
||||
.object({ normalized_result: z.record(z.string(), z.unknown()) })
|
||||
.parse(complete.structuredContent).normalized_result;
|
||||
const facets = [
|
||||
"entrypoints",
|
||||
"architectures",
|
||||
"build_metadata",
|
||||
"load_commands",
|
||||
"dependencies",
|
||||
"imports",
|
||||
"exports",
|
||||
"segments",
|
||||
"provenance",
|
||||
] as const;
|
||||
for (const facet of facets) {
|
||||
const rows: unknown[] = [];
|
||||
let offset: number | null = 0;
|
||||
while (offset !== null) {
|
||||
const paged = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: summary.parent_evidence_id,
|
||||
},
|
||||
view: { kind: "macho", facet, offset, limit: 16 },
|
||||
},
|
||||
});
|
||||
expect(paged.isError, JSON.stringify(paged.content)).not.toBe(true);
|
||||
const page = evidenceOf(pageSchema).parse(
|
||||
paged.structuredContent,
|
||||
).normalized_result;
|
||||
rows.push(...page.item);
|
||||
offset = page.coverage.next_offset;
|
||||
}
|
||||
expect(rows, facet).toEqual(
|
||||
facet === "provenance"
|
||||
? raw.provenance
|
||||
: z.object({ items: z.array(z.unknown()) }).parse(raw[facet])
|
||||
.items,
|
||||
);
|
||||
}
|
||||
|
||||
const wrongKind = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: summary.parent_evidence_id,
|
||||
},
|
||||
view: { kind: "wasm", facet: "exports" },
|
||||
},
|
||||
});
|
||||
expect(wrongKind.isError).toBe(true);
|
||||
expect(JSON.stringify(wrongKind.content)).toContain(
|
||||
"Mach-O inspection supports summary and macho views.",
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
mcpTest(
|
||||
"refuses summary delivery before analysis when the server retains no Evidence",
|
||||
async ({ mcp, onTestFinished }) => {
|
||||
const target = join(
|
||||
await createTestTempDirectory("rea-summary-preflight-"),
|
||||
"tool",
|
||||
);
|
||||
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
|
||||
const executed: string[] = [];
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: (operation) => {
|
||||
executed.push(operation);
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
close: () => Promise.resolve(ok(null)),
|
||||
}));
|
||||
onTestFinished(async () => {
|
||||
await session.close();
|
||||
});
|
||||
const opened = await session.open(target);
|
||||
if (!opened.ok) throw opened.error;
|
||||
const client = await mcp.connect(
|
||||
createServer({ kind: "fixed", analysis: session }),
|
||||
);
|
||||
const refused = [];
|
||||
for (const name of ["inspect_macho", "inspect_artifact"])
|
||||
refused.push(
|
||||
await client.callTool({ name, arguments: { detail: "summary" } }),
|
||||
);
|
||||
// Neither analysis ran only to be discarded by the delivery refusal.
|
||||
expect(executed.filter((operation) => operation !== "health")).toEqual([]);
|
||||
for (const result of refused)
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("does not retain Evidence"),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -8,42 +8,53 @@ import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
|
||||
it("advertises valid target-free packet capture schemas and actionable missing-tool diagnostics", async () => {
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { environment: {} },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const tool = (await harness.client.listTools()).tools.find(
|
||||
({ name }) => name === "inspect_packet_capture",
|
||||
);
|
||||
if (tool?.outputSchema === undefined) throw new Error("Capture tool missing");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = tool.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = tool.outputSchema;
|
||||
expect(ajv.validateSchema(inputSchema)).toBe(true);
|
||||
expect(ajv.validateSchema(outputSchema)).toBe(true);
|
||||
const input = {
|
||||
path:
|
||||
process.platform === "win32" ? "C:\\recording.pcap" : "/recording.pcap",
|
||||
fields: ["ip.addr"],
|
||||
};
|
||||
expect(ajv.validate(inputSchema, input)).toBe(true);
|
||||
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(false);
|
||||
const result = await harness.client.callTool({
|
||||
name: tool.name,
|
||||
arguments: input,
|
||||
});
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
operation: tool.name,
|
||||
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
|
||||
it.each(["inspect_packet_capture", "inspect_packet_fields"])(
|
||||
"advertises valid target-free schemas and missing-tool diagnostics: %s",
|
||||
async (name) => {
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { environment: {} },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const tool = (await harness.client.listTools()).tools.find(
|
||||
(tool) => tool.name === name,
|
||||
);
|
||||
if (tool?.outputSchema === undefined)
|
||||
throw new Error("Capture tool missing");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = tool.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = tool.outputSchema;
|
||||
expect(ajv.validateSchema(inputSchema)).toBe(true);
|
||||
expect(ajv.validateSchema(outputSchema)).toBe(true);
|
||||
const input =
|
||||
name === "inspect_packet_fields"
|
||||
? { query: "usb" }
|
||||
: {
|
||||
path:
|
||||
process.platform === "win32"
|
||||
? "C:\\recording.pcap"
|
||||
: "/recording.pcap",
|
||||
fields: ["ip.addr"],
|
||||
};
|
||||
expect(ajv.validate(inputSchema, input)).toBe(true);
|
||||
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(
|
||||
false,
|
||||
);
|
||||
const result = await harness.client.callTool({
|
||||
name: tool.name,
|
||||
arguments: input,
|
||||
});
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
operation: tool.name,
|
||||
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await harness.client.ping();
|
||||
});
|
||||
});
|
||||
await harness.client.ping();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["cancelled", "cleanup"])(
|
||||
"retains completed Evidence after %s failure",
|
||||
@@ -78,6 +89,9 @@ it.each(["cancelled", "cleanup"])(
|
||||
},
|
||||
);
|
||||
const packetCapture = new PacketCaptureService({
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => err(failure),
|
||||
close: async () => {},
|
||||
});
|
||||
@@ -120,6 +134,9 @@ it.each(["cancelled", "cleanup"])(
|
||||
it("rejects oversized selector expansion through the MCP boundary before invoking the provider", async () => {
|
||||
let calls = 0;
|
||||
const packetCapture = new PacketCaptureService({
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
calls++;
|
||||
return err(new AnalysisCancelledError("inspect_packet_capture"));
|
||||
|
||||
@@ -309,7 +309,9 @@ it("separately rejects a tampered digest before admission to any consumer or ses
|
||||
};
|
||||
const digestMismatch = /semantic identifier does not match/u;
|
||||
expect(() => parseEvidence(tampered)).toThrow(digestMismatch);
|
||||
expect(() => findChangedBehavior([tampered])).toThrow(digestMismatch);
|
||||
expect(() => findChangedBehavior({ comparisons: [tampered] })).toThrow(
|
||||
digestMismatch,
|
||||
);
|
||||
expect(() => correlateStaticAndRuntime(correlationInput(tampered))).toThrow(
|
||||
digestMismatch,
|
||||
);
|
||||
@@ -336,6 +338,19 @@ it("separately rejects a tampered digest before admission to any consumer or ses
|
||||
}
|
||||
});
|
||||
|
||||
it("maps malformed changed-behavior Evidence to an invalid request before closure lookup", async () => {
|
||||
const { client, comparison } = await connectedComparison();
|
||||
const malformed = { ...comparison, evidence_links: undefined } as unknown;
|
||||
const response = await client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: { comparisons: [malformed] },
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response)).toMatchObject({
|
||||
error: { code: "invalid_request" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps withheld ownership unknown through CLI and MCP comparison", async () => {
|
||||
const { client, right } = await connectedComparison();
|
||||
const left = captureEvidence("left", {
|
||||
|
||||
@@ -8,41 +8,51 @@ import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
|
||||
it("advertises valid target-free signal decoding schemas and actionable missing-tool diagnostics", async () => {
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { environment: {} },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const tool = (await harness.client.listTools()).tools.find(
|
||||
({ name }) => name === "decode_signal_recording",
|
||||
);
|
||||
if (tool?.outputSchema === undefined) throw new Error("Signal tool missing");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = tool.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = tool.outputSchema;
|
||||
expect(ajv.validateSchema(inputSchema)).toBe(true);
|
||||
expect(ajv.validateSchema(outputSchema)).toBe(true);
|
||||
const input = {
|
||||
path: process.platform === "win32" ? "C:\\recording.vcd" : "/recording.vcd",
|
||||
decoders: "uart",
|
||||
};
|
||||
expect(ajv.validate(inputSchema, input)).toBe(true);
|
||||
expect(ajv.validate(inputSchema, { ...input, driver: "demo" })).toBe(false);
|
||||
const result = await harness.client.callTool({
|
||||
name: tool.name,
|
||||
arguments: input,
|
||||
});
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
operation: tool.name,
|
||||
reason: expect.stringContaining("REA_SIGROK_COMMAND"),
|
||||
it.each(["decode_signal_recording", "inspect_signal_decoders"])(
|
||||
"advertises valid target-free schemas and missing-tool diagnostics: %s",
|
||||
async (name) => {
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { environment: {} },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const tool = (await harness.client.listTools()).tools.find(
|
||||
(tool) => tool.name === name,
|
||||
);
|
||||
if (tool?.outputSchema === undefined)
|
||||
throw new Error("Signal tool missing");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = tool.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = tool.outputSchema;
|
||||
expect(ajv.validateSchema(inputSchema)).toBe(true);
|
||||
expect(ajv.validateSchema(outputSchema)).toBe(true);
|
||||
const input =
|
||||
name === "inspect_signal_decoders"
|
||||
? { query: "uart" }
|
||||
: {
|
||||
path:
|
||||
process.platform === "win32"
|
||||
? "C:\\recording.vcd"
|
||||
: "/recording.vcd",
|
||||
decoders: "uart",
|
||||
};
|
||||
expect(ajv.validate(inputSchema, input)).toBe(true);
|
||||
expect(ajv.validate(inputSchema, { ...input, driver: "demo" })).toBe(false);
|
||||
const result = await harness.client.callTool({
|
||||
name: tool.name,
|
||||
arguments: input,
|
||||
});
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
operation: tool.name,
|
||||
reason: expect.stringContaining("REA_SIGROK_COMMAND"),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await harness.client.ping();
|
||||
});
|
||||
});
|
||||
await harness.client.ping();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["cancelled", "cleanup"])(
|
||||
"retains completed Evidence after %s failure",
|
||||
@@ -77,6 +87,9 @@ it.each(["cancelled", "cleanup"])(
|
||||
},
|
||||
);
|
||||
const signalRecording = new SignalRecordingService({
|
||||
inspectDecoders: async () => {
|
||||
throw new Error("Unexpected discovery call");
|
||||
},
|
||||
decode: async () => err(failure),
|
||||
close: async () => {},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseJavaScriptSource } from "../../../src/domain/javascript/javascriptSourceParser.js";
|
||||
import { processTest } from "../../support/process/processFixture.js";
|
||||
|
||||
for (const source of [
|
||||
"return;",
|
||||
"void new.target;",
|
||||
"var await = 1; return;",
|
||||
"with ({ value: 1 }) { void value; } void new.target;",
|
||||
]) {
|
||||
processTest(
|
||||
`accepts Node CommonJS syntax while retaining module errors: ${source}`,
|
||||
async ({ processes }) => {
|
||||
const commonjs = await processes.run(
|
||||
process.execPath,
|
||||
["--check", "--input-type=commonjs"],
|
||||
{ input: source, timeoutMs: 5_000 },
|
||||
);
|
||||
expect(commonjs.exitCode).toBe(0);
|
||||
const module = await processes.run(
|
||||
process.execPath,
|
||||
["--check", "--input-type=module"],
|
||||
{ input: source, timeoutMs: 5_000 },
|
||||
);
|
||||
expect(module.exitCode).not.toBe(0);
|
||||
|
||||
const parsed = parseJavaScriptSource(source, "main.cjs");
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed?.errors).toEqual([]);
|
||||
expect(
|
||||
parseJavaScriptSource(source, "main.mjs")?.errors.length,
|
||||
).toBeGreaterThan(0);
|
||||
expect(
|
||||
parseJavaScriptSource(source, "main.mts")?.errors.length,
|
||||
).toBeGreaterThan(0);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { access, readFile, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect } from "vitest";
|
||||
import { expect, vi } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { itWithCaptureCapability } from "./processCaptureCapability.js";
|
||||
|
||||
@@ -123,6 +123,93 @@ const terminateFixtureProcess = async (pid: number): Promise<void> => {
|
||||
await waitForProcessExit(pid);
|
||||
};
|
||||
|
||||
itWithCaptureCapability(
|
||||
"keeps the process deadline bounded when the wall clock moves backward",
|
||||
async () => {
|
||||
const wallStart = Date.now();
|
||||
let wallReads = 0;
|
||||
const now = vi.spyOn(Date, "now").mockImplementation(() => {
|
||||
wallReads += 1;
|
||||
return wallReads === 1 ? wallStart : wallStart - 60_000 + wallReads;
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const fallback = setTimeout(() => controller.abort(), 1_500);
|
||||
try {
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "hang"],
|
||||
working_directory: dirname(processFixture),
|
||||
timeout_ms: 100,
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
controller.signal,
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.exit.reason).toBe("timeout");
|
||||
} finally {
|
||||
clearTimeout(fallback);
|
||||
now.mockRestore();
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"preserves reversed wall-clock observations and monotonic frames across capture",
|
||||
async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(new Date("2026-01-02T00:00:00.000Z"));
|
||||
try {
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "partial"],
|
||||
working_directory: dirname(processFixture),
|
||||
settle_ms: 0,
|
||||
timeout_ms: 5_000,
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
undefined,
|
||||
process.platform,
|
||||
process.env,
|
||||
undefined,
|
||||
undefined,
|
||||
{
|
||||
async report(update) {
|
||||
if (update.phase === "running")
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.frames.length).toBeGreaterThan(0);
|
||||
expect(Date.parse(result.value.manifest.completed_at)).toBeLessThan(
|
||||
Date.parse(result.value.manifest.started_at),
|
||||
);
|
||||
expect(result.value.limitations).toContain(
|
||||
"Wall-clock completion time precedes start time; elapsed capture timing is recorded separately and remains monotonic.",
|
||||
);
|
||||
expect(
|
||||
result.value.frames.map(({ at_ms }) => at_ms),
|
||||
"capture-relative frame times stay ordered and nonnegative",
|
||||
).toEqual(
|
||||
result.value.frames.map(({ at_ms }) => at_ms).sort(
|
||||
(left, right) => left - right,
|
||||
),
|
||||
);
|
||||
expect(result.value.frames.every(({ at_ms }) => at_ms >= 0)).toBe(true);
|
||||
expect(result.value.exit.reason).toBe("exited");
|
||||
expect(result.value.settlement.elapsed_ms).toBeGreaterThan(0);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"cleans detached run-token children omitted by sampling and preserves an unowned neighbor",
|
||||
async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { mkdir, readFile, symlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, it } from "vitest";
|
||||
@@ -202,3 +202,61 @@ itWithLinuxCaptureCapability.each([false, true])(
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"preserves selected nested path identities in actual PTY Evidence",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-process-nested-paths-");
|
||||
const executable = join(root, "selected-node");
|
||||
const observed = join(root, "data");
|
||||
await symlink(process.execPath, executable);
|
||||
await mkdir(observed);
|
||||
const original = `${executable}\n${observed}/result\n${root}/log`;
|
||||
const scenario = parseProcessScenario({
|
||||
executable,
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [observed],
|
||||
arguments: ["-e", `process.stdout.write(${JSON.stringify(original)})`],
|
||||
normalization: { paths: true, pids: false, ports: false, patterns: [] },
|
||||
settle_ms: 100,
|
||||
});
|
||||
const result = await captureProcessScenario(scenario);
|
||||
if (!result.ok) throw result.error;
|
||||
const capture = parseProcessCapture(
|
||||
createProcessCaptureEvidence(scenario, result.value).normalized_result,
|
||||
);
|
||||
expect(capture.frames.map(({ data }) => data).join("")).toBe(
|
||||
"<executable>\r\n<filesystem-root-0>/result\r\n<working-directory>/log",
|
||||
);
|
||||
expect(
|
||||
capture.frames.map(({ raw_data, data }) => raw_data ?? data).join(""),
|
||||
).toBe(original.replaceAll("\n", "\r\n"));
|
||||
expect(capture.manifest.comparison_contract).toHaveProperty(
|
||||
"path_normalization_version",
|
||||
"longest-original-paths-v1",
|
||||
);
|
||||
const legacyContract = { ...capture.manifest.comparison_contract };
|
||||
delete legacyContract.path_normalization_version;
|
||||
const legacy = parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
comparison_contract: legacyContract,
|
||||
comparison_contract_sha256: digestProcessCommitment(legacyContract),
|
||||
},
|
||||
});
|
||||
expect(() => compareProcessCaptures(legacy, capture)).toThrow(
|
||||
expect.objectContaining({
|
||||
issues: [
|
||||
expect.objectContaining({ expected: ["path_normalization_version"] }),
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(capture.exit).toMatchObject({ code: 0, reason: "exited" });
|
||||
expect(capture.cleanup).toMatchObject({
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
});
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
@@ -167,46 +167,50 @@ it("retains a failed rollback owner and preserves the materialization failure",
|
||||
await expect(access(output)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("retains a tree whose setup failed after root identity was captured", async () => {
|
||||
const { root, archive } = await createArchive();
|
||||
const output = join(root, "output");
|
||||
const blocker = join(output, "unowned.txt");
|
||||
const client = createClient(archive);
|
||||
const prototypeHandle = await open(join(root, "prototype-handle"), "w");
|
||||
const handlePrototype = Object.getPrototypeOf(prototypeHandle) as Pick<
|
||||
typeof prototypeHandle,
|
||||
"chmod"
|
||||
>;
|
||||
await prototypeHandle.close();
|
||||
await rm(join(root, "prototype-handle"));
|
||||
onTestFinished(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await rm(blocker, { force: true });
|
||||
await client.close();
|
||||
});
|
||||
vi.spyOn(handlePrototype, "chmod").mockImplementationOnce(async function (
|
||||
this: typeof prototypeHandle,
|
||||
) {
|
||||
await writeFile(blocker, "keep until owner retry");
|
||||
throw new Error("injected output setup failure");
|
||||
});
|
||||
// Windows intentionally skips directory fchmod; this fault requires POSIX setup.
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains a tree whose POSIX setup failed after root identity was captured",
|
||||
async () => {
|
||||
const { root, archive } = await createArchive();
|
||||
const output = join(root, "output");
|
||||
const blocker = join(output, "unowned.txt");
|
||||
const client = createClient(archive);
|
||||
const prototypeHandle = await open(join(root, "prototype-handle"), "w");
|
||||
const handlePrototype = Object.getPrototypeOf(prototypeHandle) as Pick<
|
||||
typeof prototypeHandle,
|
||||
"chmod"
|
||||
>;
|
||||
await prototypeHandle.close();
|
||||
await rm(join(root, "prototype-handle"));
|
||||
onTestFinished(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await rm(blocker, { force: true });
|
||||
await client.close();
|
||||
});
|
||||
vi.spyOn(handlePrototype, "chmod").mockImplementationOnce(async function (
|
||||
this: typeof prototypeHandle,
|
||||
) {
|
||||
await writeFile(blocker, "keep until owner retry");
|
||||
throw new Error("injected output setup failure");
|
||||
});
|
||||
|
||||
const extraction = await client.execute("extract_artifact", {
|
||||
output_root: output,
|
||||
});
|
||||
expect(extraction).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "ArtifactOperationError",
|
||||
detail: expect.stringContaining("injected output setup failure"),
|
||||
cleanup: { resources: [output] },
|
||||
},
|
||||
});
|
||||
expect(await readFile(blocker, "utf8")).toBe("keep until owner retry");
|
||||
await rm(blocker);
|
||||
expect(await client.close()).toMatchObject({ ok: true });
|
||||
await expect(access(output)).rejects.toThrow();
|
||||
});
|
||||
const extraction = await client.execute("extract_artifact", {
|
||||
output_root: output,
|
||||
});
|
||||
expect(extraction).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "ArtifactOperationError",
|
||||
detail: expect.stringContaining("injected output setup failure"),
|
||||
cleanup: { resources: [output] },
|
||||
},
|
||||
});
|
||||
expect(await readFile(blocker, "utf8")).toBe("keep until owner retry");
|
||||
await rm(blocker);
|
||||
expect(await client.close()).toMatchObject({ ok: true });
|
||||
await expect(access(output)).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it("waits for admitted extraction before close and rejects later work", async () => {
|
||||
const { root, archive } = await createArchive();
|
||||
|
||||
@@ -3,7 +3,7 @@ import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createPackage, createPackageWithOptions } from "@electron/asar";
|
||||
import { expect, it } from "vitest";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
import {
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { DirectoryArtifactReader } from "../../../../src/artifacts/DirectoryArtifactReader.js";
|
||||
|
||||
it.each(["file", "directory"] as const)(
|
||||
"rolls back when an inventoried %s disappears before extraction",
|
||||
@@ -61,6 +62,41 @@ it("still refuses a regular file added after inventory and rolls back", async ()
|
||||
await expect(access(output)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("rolls back when cancellation arrives while closing the materialization reader", async () => {
|
||||
const root = await createTestTempDirectory("rea-extract-cancel-close-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "payload.txt"), "complete payload\n");
|
||||
const snapshot = await scanArtifactInventory(source);
|
||||
const output = join(root, "output");
|
||||
const controller = new AbortController();
|
||||
const close = DirectoryArtifactReader.prototype.close;
|
||||
const closeSpy = vi
|
||||
.spyOn(DirectoryArtifactReader.prototype, "close")
|
||||
.mockImplementation(async function (this: DirectoryArtifactReader) {
|
||||
controller.abort();
|
||||
await close.call(this);
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
materializeArtifactInventory(
|
||||
{
|
||||
inputPath: source,
|
||||
outputRoot: output,
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
},
|
||||
source,
|
||||
snapshot,
|
||||
controller.signal,
|
||||
),
|
||||
).rejects.toMatchObject({ reason: "cancelled" });
|
||||
await expect(access(output)).rejects.toThrow();
|
||||
} finally {
|
||||
closeSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves every equal-content occurrence and copies a nested ASAR as its containing file", async () => {
|
||||
const root = await createTestTempDirectory("rea-extract-nested-");
|
||||
const source = join(root, "source");
|
||||
@@ -135,7 +171,6 @@ const inventoriedExtraction = async (source: string, output: string) => {
|
||||
materializeArtifactInventory(
|
||||
{
|
||||
inputPath: source,
|
||||
inputFormat: "asar",
|
||||
outputRoot: output,
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
|
||||
@@ -3,17 +3,63 @@ import { access, mkdir, readFile, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildBinary } from "plist";
|
||||
|
||||
import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
|
||||
import { inesFixture } from "../../../fixtures/ines.js";
|
||||
import { nativeAotPeFixture } from "../../../fixtures/nativeaotPe.js";
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
|
||||
|
||||
it.each(["plist", "pe"] as const)(
|
||||
"extracts current iNES bytes after a non-extractable %s target is replaced",
|
||||
async (format) => {
|
||||
const root = await createTestTempDirectory("rea-extract-current-");
|
||||
const path = join(root, "source.bin");
|
||||
await writeFile(
|
||||
path,
|
||||
format === "plist" ? buildBinary({ value: "old" }) : nativeAotPeFixture(),
|
||||
);
|
||||
const target = await parseBinaryTarget(path);
|
||||
if (!target.ok) throw target.error;
|
||||
expect(target.value.format).toBe(format);
|
||||
const client = new ArtifactProvider(process.env).createClient(target.value);
|
||||
const bytes = inesFixture({
|
||||
trainer: true,
|
||||
trailing: Buffer.from("tail"),
|
||||
});
|
||||
await writeFile(path, bytes);
|
||||
const output = join(root, "output");
|
||||
const result = await client.execute(
|
||||
"extract_artifact",
|
||||
artifactExtractionExecutionSchema.parse({ output_root: output }),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
const extracted = artifactExtractionResultSchema.parse(result.value.result);
|
||||
expect(extracted.manifest.root_format).toBe("ines");
|
||||
const paths = [
|
||||
"header.bin",
|
||||
"trainer.bin",
|
||||
"prg/000.bin",
|
||||
"prg/001.bin",
|
||||
"chr/000.bin",
|
||||
"trailing.bin",
|
||||
];
|
||||
expect(extracted.artifacts).toHaveLength(paths.length);
|
||||
expect(
|
||||
Buffer.concat(
|
||||
await Promise.all(paths.map((part) => readFile(join(output, part)))),
|
||||
),
|
||||
).toEqual(bytes);
|
||||
await client.close();
|
||||
},
|
||||
);
|
||||
|
||||
describe("artifact extraction format support", () => {
|
||||
it.each(["zip", "asar", "hap", "hsp", "app"] as const)(
|
||||
"extracts the scanned %s after an active iNES path is replaced",
|
||||
@@ -82,10 +128,12 @@ describe("artifact extraction format support", () => {
|
||||
await expect(access(output)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("refuses unsupported formats before inventory or output", async () => {
|
||||
it("refuses a currently unsupported format before child inventory or output", async () => {
|
||||
const root = await createTestTempDirectory("rea-extract-format-");
|
||||
const image = join(root, "Image.dmg");
|
||||
await writeFile(image, "not mounted");
|
||||
const bytes = Buffer.alloc(512);
|
||||
bytes.write("koly", 0, "ascii");
|
||||
await writeFile(image, bytes);
|
||||
const alias = join(root, "Alias.dmg");
|
||||
await symlink(image, alias);
|
||||
const output = join(root, "output");
|
||||
|
||||
@@ -3,6 +3,8 @@ import { readFile } from "node:fs/promises";
|
||||
import { describe, expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
|
||||
import { XcrunCommandRunner } from "../../../../src/native/CommandRunner.js";
|
||||
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
|
||||
|
||||
/**
|
||||
* Read a 32-bit FAT table directly. The host's /bin/ls changes between macOS
|
||||
@@ -20,6 +22,26 @@ const fatSlices = async (
|
||||
};
|
||||
|
||||
describe("Mach-O slice reader with system lipo", () => {
|
||||
it("names the process ownership helper prerequisite when lipo cannot be supervised", async () => {
|
||||
const prerequisite =
|
||||
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.";
|
||||
const reader = new MachOSliceArtifactReader(
|
||||
process.execPath,
|
||||
{},
|
||||
new XcrunCommandRunner({}, undefined, () =>
|
||||
Promise.reject(new DarwinProcessOwnershipInspectionError(prerequisite)),
|
||||
),
|
||||
);
|
||||
onTestFinished(() => reader.close());
|
||||
const enumerate = async () => {
|
||||
for await (const _entry of reader.entries()) continue;
|
||||
};
|
||||
await expect(enumerate()).rejects.toMatchObject({
|
||||
reason: "unavailable",
|
||||
message: `lipo could not enumerate universal Mach-O slices: ${prerequisite}`,
|
||||
});
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "darwin")(
|
||||
"checks real /bin/ls slice ranges against its FAT table",
|
||||
async () => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type NativeCommandLauncher,
|
||||
} from "../../../../src/native/CommandRunner.js";
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
@@ -210,3 +211,23 @@ it.skipIf(process.platform === "win32")(
|
||||
if (!killed.ok) expect(killed.error.reason).toBe("nonzero-exit");
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the ownership helper prerequisite when xcrun cannot be supervised", async () => {
|
||||
const inspection = new DarwinProcessOwnershipInspectionError(
|
||||
"macOS process ownership inspection requires the Apple Swift compiler via xcrun",
|
||||
);
|
||||
const runner = new XcrunCommandRunner({}, undefined, () =>
|
||||
Promise.reject(inspection),
|
||||
);
|
||||
|
||||
const result = await runner.run("file", [], {});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toMatchObject({
|
||||
tool: "file",
|
||||
reason: "io",
|
||||
detail: inspection.message,
|
||||
cause: { tool: "xcrun", detail: inspection.message, cause: inspection },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
@@ -280,6 +281,30 @@ describe("native command failure capture and limits", () => {
|
||||
stderr_bytes: expect.any(Number),
|
||||
},
|
||||
});
|
||||
expect(projectAnalysisError(result.error).details).not.toHaveProperty(
|
||||
"diagnostics.detail",
|
||||
);
|
||||
});
|
||||
|
||||
it("projects the ownership helper prerequisite when a command cannot be supervised", async () => {
|
||||
const inspection = new DarwinProcessOwnershipInspectionError(
|
||||
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.",
|
||||
);
|
||||
const runner = new XcrunCommandRunner(
|
||||
{},
|
||||
() =>
|
||||
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
|
||||
() => Promise.reject(inspection),
|
||||
);
|
||||
const result = await new NativeMacOSProvider({}, runner, "darwin")
|
||||
.createClient(machoTarget("/private/fixture"))
|
||||
.execute("demangle_swift", { symbols: ["fixture-symbol"] });
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(projectAnalysisError(result.error).details).toMatchObject({
|
||||
diagnostics: { reason: "io", detail: inspection.message },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains output written before cancellation and reaps the stalled command", async () => {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { inspectSignalDecodersInputSchema } from "../../../src/domain/signals/signalDecoders.js";
|
||||
import { parseDecoderDiscovery } from "../../../src/signals/parseDecoderDiscovery.js";
|
||||
|
||||
it("rejects malformed catalogs and the wrong decoder identity", () => {
|
||||
for (const text of [
|
||||
"",
|
||||
"Supported protocol decoders:\n",
|
||||
"Supported protocol decoders:\n uart UART\n uart Duplicate",
|
||||
"Supported protocol decoders:\n malformed",
|
||||
]) {
|
||||
expect(() =>
|
||||
parseDecoderDiscovery(text, inspectSignalDecodersInputSchema.parse({})),
|
||||
).toThrow();
|
||||
}
|
||||
expect(() =>
|
||||
parseDecoderDiscovery(
|
||||
"ID: spi\nOptions:",
|
||||
inspectSignalDecodersInputSchema.parse({ decoder: "uart" }),
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("keeps help line ordinals, blank lines and literal special characters through selection", () => {
|
||||
const text = "ID: uart\r\nOptions:\r\n\r\n- mode: A[0] (default 'x')\r\n";
|
||||
const result = parseDecoderDiscovery(
|
||||
text,
|
||||
inspectSignalDecodersInputSchema.parse({
|
||||
decoder: "uart",
|
||||
query: "[0]",
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
);
|
||||
expect(result.help_lines).toEqual([
|
||||
{ line_number: 4, text: "- mode: A[0] (default 'x')" },
|
||||
]);
|
||||
expect(result.output_window.examined).toBe(4);
|
||||
});
|
||||
|
||||
it("bounds line expansion before constructing help records", () => {
|
||||
expect(() =>
|
||||
parseDecoderDiscovery(
|
||||
"ID: uart\n" + "\n".repeat(65536),
|
||||
inspectSignalDecodersInputSchema.parse({ decoder: "uart" }),
|
||||
),
|
||||
).toThrow("representation budget");
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { signalDecodersSchema } from "../../../src/domain/signals/signalDecoders.js";
|
||||
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
|
||||
import { it, expect, onTestFinished } from "vitest";
|
||||
import { writeFile, readdir, chmod, symlink } from "node:fs/promises";
|
||||
@@ -23,13 +24,17 @@ const fixture = async (mode = "ok", failCleanup = false) => {
|
||||
await writeFile(
|
||||
script,
|
||||
`import {readFileSync, writeFileSync, chmodSync, truncateSync} from 'node:fs';
|
||||
if (process.argv.includes('--version')) { console.log('sigrok-cli 0.7.2\\nlibsigrokdecode 0.5.3'); console.error('version warning'); }
|
||||
if (process.argv.includes('--version')) { console.log(${JSON.stringify(mode)} === 'bad-version' ? 'sigrok-cli 0.7.1' : 'sigrok-cli 0.7.2\\nlibsigrokdecode 0.5.3'); console.error('version warning'); }
|
||||
else if (${JSON.stringify(mode)} === 'bad-version') console.log('unexpected version fallback');
|
||||
else if (${JSON.stringify(mode)} === 'nonzero') { console.error('invalid decoder'); process.exitCode = 1; }
|
||||
else if (${JSON.stringify(mode)} === 'malformed-copy') { chmodSync('recording', 0o600); writeFileSync('recording', 'changed'); }
|
||||
else if (${JSON.stringify(mode)} === 'oversized-copy') { chmodSync('recording', 0o600); truncateSync('recording', 32 * 1024 * 1024 + 1); }
|
||||
else if (${JSON.stringify(mode)} === 'line-budget') process.stdout.write('ID: uart' + '\\n'.repeat(65536));
|
||||
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat(5 * 1024 * 1024));
|
||||
else if (${JSON.stringify(mode)} === 'wait') { console.log('ready'); setInterval(() => {}, 1000); }
|
||||
else if (${JSON.stringify(mode)} === 'many') process.stdout.write(Array.from({length:90},(_,i)=>'line '+(i+1)+'\\r\\n').join(''));
|
||||
else if (process.argv.includes('--list-supported')) { console.log('Supported hardware drivers:\\n ignored Device\\nSupported protocol decoders:\\n uart Universal Asynchronous Receiver/Transmitter\\n i2c Inter-Integrated Circuit\\n'); console.error('catalog warning'); }
|
||||
else if (process.argv.includes('--show')) console.log('ID: uart\\nOptions:\\n- baudrate: Baud rate (default 115200)\\n- parity: Parity');
|
||||
else { if(readFileSync('recording', 'utf8') !== 'recording bytes') throw Error('wrong copy'); console.log('10-20 uart-1: 42'); console.error('producer warning'); }
|
||||
`,
|
||||
);
|
||||
@@ -285,6 +290,9 @@ it("retains a completed observation when cancellation arrives at the service bou
|
||||
const execution = await f.service.provider.decode(input);
|
||||
if (!execution.ok) throw execution.error;
|
||||
const service = new SignalRecordingService({
|
||||
inspectDecoders: async () => {
|
||||
throw new Error("Unexpected discovery call");
|
||||
},
|
||||
decode: async () => {
|
||||
f.controller.abort();
|
||||
return execution;
|
||||
@@ -419,3 +427,182 @@ it("preserves termination signal and effective file ceiling as a resource failur
|
||||
capturedOutput: { signal: "SIGXFSZ", stderr: "before file limit\n" },
|
||||
});
|
||||
});
|
||||
|
||||
it("discovers decoders without reading a recording and retains installation provenance", async () => {
|
||||
const f = await fixture();
|
||||
for (const [input, expected] of [
|
||||
[
|
||||
{ query: "UART" },
|
||||
{
|
||||
decoders: [
|
||||
{ id: "uart", name: "Universal Asynchronous Receiver/Transmitter" },
|
||||
],
|
||||
output_window: {
|
||||
examined: 2,
|
||||
matching: 1,
|
||||
returned: 1,
|
||||
has_more: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{ limit: 1 },
|
||||
{
|
||||
decoders: [
|
||||
{ id: "uart", name: "Universal Asynchronous Receiver/Transmitter" },
|
||||
],
|
||||
output_window: { matching: 2, returned: 1, has_more: true },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ offset: 1, limit: null },
|
||||
{
|
||||
decoders: [{ id: "i2c", name: "Inter-Integrated Circuit" }],
|
||||
output_window: { returned: 1, has_more: false },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ decoder: "uart", query: "baud" },
|
||||
{
|
||||
help_lines: [
|
||||
{ line_number: 3, text: "- baudrate: Baud rate (default 115200)" },
|
||||
],
|
||||
output_window: { unit: "help-lines", examined: 4, matching: 1 },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ query: "no-such-decoder" },
|
||||
{
|
||||
decoders: [],
|
||||
output_window: { examined: 2, matching: 0, returned: 0 },
|
||||
},
|
||||
],
|
||||
] as const) {
|
||||
const result = await f.service.inspectDecoders(input);
|
||||
if (!result.ok) throw result.error;
|
||||
const report = signalDecodersSchema.parse(result.value.normalized_result);
|
||||
expect(report).toMatchObject(expected);
|
||||
expect(result.value.operation).toBe("inspect_signal_decoders");
|
||||
expect(report.tool.version_diagnostics).toBe("version warning\n");
|
||||
expect(report.tool.arguments).toContain("--dont-scan");
|
||||
expect(
|
||||
report.tool.arguments.some((arg) => arg.startsWith("--input-file")),
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("attributes discovery admission failures to discovery while sharing the decoding slot", async () => {
|
||||
const f = await fixture("gated");
|
||||
const active = f.service.decode({ path: f.path, decoders: "uart" });
|
||||
await f.acquired;
|
||||
const busy = await f.service.inspectDecoders({});
|
||||
f.release();
|
||||
if (!(await active).ok) throw new Error("Decode failed");
|
||||
expect(busy).toMatchObject({
|
||||
ok: false,
|
||||
error: { operation: "inspect_signal_decoders", resource: "capacity" },
|
||||
});
|
||||
await f.service.close();
|
||||
expect(await f.service.inspectDecoders({})).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
operation: "inspect_signal_decoders",
|
||||
_tag: "AnalysisCancelledError",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
"bad-version",
|
||||
"nonzero",
|
||||
"overflow",
|
||||
"line-budget",
|
||||
"wait",
|
||||
"oversized-tool",
|
||||
])("preserves discovery failure diagnostics: %s", async (mode) => {
|
||||
const f = await fixture(mode);
|
||||
const result = await f.service.inspectDecoders(
|
||||
{},
|
||||
{ signal: f.controller.signal },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Expected failure");
|
||||
expect(result.error).toMatchObject({
|
||||
operation: "inspect_signal_decoders",
|
||||
});
|
||||
if (mode === "line-budget") {
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
});
|
||||
expect(result.error.capturedOutput?.stdout).toBe(
|
||||
"ID: uart" + "\n".repeat(65536),
|
||||
);
|
||||
}
|
||||
if (mode === "bad-version")
|
||||
expect(result.error.capturedOutput).toMatchObject({
|
||||
stdout: "sigrok-cli 0.7.1\n",
|
||||
stderr: "version warning\n",
|
||||
});
|
||||
});
|
||||
|
||||
it("retains completed discovery when cleanup fails, then retries before accepting work", async () => {
|
||||
const f = await fixture("ok", true);
|
||||
const first = await f.service.inspectDecoders({ query: "uart" });
|
||||
expect(first).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
operation: "inspect_signal_decoders",
|
||||
partialObservation: { operation: "inspect_signal_decoders" },
|
||||
},
|
||||
});
|
||||
await f.service.inspectDecoders({});
|
||||
await f.service.decode({ path: f.path, decoders: "uart" });
|
||||
expect(f.calls()).toBe(2);
|
||||
for (let attempt = 0; attempt < 2; attempt++)
|
||||
await expect(f.service.close()).rejects.toMatchObject({
|
||||
operation: "inspect_signal_decoders",
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
f.allowCleanup();
|
||||
await f.service.close();
|
||||
});
|
||||
|
||||
it("rejects ambiguous decoder selectors before launch and retains malformed help output", async () => {
|
||||
const f = await fixture();
|
||||
for (const decoder of ["uart:baudrate=1", "uart,spi", "uart\0"]) {
|
||||
expect(await f.service.inspectDecoders({ decoder })).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
}
|
||||
expect(f.calls()).toBe(0);
|
||||
expect(await f.service.inspectDecoders({ decoder: "spi" })).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisOutputError",
|
||||
capturedOutput: { stdout: expect.stringContaining("ID: uart") },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("retains completed discovery on cancellation during identity verification", async () => {
|
||||
const f = await fixture("post-run-abort");
|
||||
expect(
|
||||
await f.service.inspectDecoders(
|
||||
{ query: "uart" },
|
||||
{ signal: f.controller.signal },
|
||||
),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
partialObservation: {
|
||||
operation: "inspect_signal_decoders",
|
||||
normalized_result: { decoders: [{ id: "uart" }] },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
+36
@@ -4,6 +4,7 @@
|
||||
#include <winioctl.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -33,6 +34,41 @@ int wmain(int count, wchar_t** args) {
|
||||
value(L"REA_\u00df") == expectedSharp && value(L"REA_SS") == L"double" ? "true" : "false");
|
||||
return 0;
|
||||
}
|
||||
if ((count == 2 || count == 3) && std::wstring(args[1]) == L"affinity") {
|
||||
// Without a process id this observes itself, which is what an owned child
|
||||
// reports. With one it observes that process, so a caller's own affinity is
|
||||
// read from the process that spawns the child rather than from a separate
|
||||
// probe Windows may place in another processor group.
|
||||
HANDLE opened = nullptr;
|
||||
if (count == 3) {
|
||||
opened = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
|
||||
static_cast<DWORD>(std::wcstoul(args[2], nullptr, 10)));
|
||||
if (!opened) return 9;
|
||||
}
|
||||
const HANDLE target = opened ? opened : GetCurrentProcess();
|
||||
DWORD_PTR affinity = 0, systemAffinity = 0;
|
||||
USHORT groupCount = 1;
|
||||
USHORT groups[1]{};
|
||||
const bool read = GetProcessAffinityMask(target, &affinity, &systemAffinity) != 0;
|
||||
const bool single = read && GetProcessGroupAffinity(target, &groupCount, groups) && groupCount == 1;
|
||||
if (opened) CloseHandle(opened);
|
||||
if (!read) return 8;
|
||||
// A mask can set bits above JavaScript's safe-integer range, so masks cross
|
||||
// as fixed-width hexadecimal strings and are compared without rounding. The
|
||||
// group's own active set distinguishes an unconstrained process from one
|
||||
// deliberately pinned to fewer processors.
|
||||
auto mask = [](DWORD_PTR value, char* text) {
|
||||
std::snprintf(text, 19, "0x%08lX%08lX", static_cast<unsigned long>(value >> 32),
|
||||
static_cast<unsigned long>(value & 0xFFFFFFFFu));
|
||||
return text;
|
||||
};
|
||||
char affinityText[19]{}, systemText[19]{};
|
||||
std::printf("{\"affinityMask\":\"%s\",\"systemMask\":\"%s\","
|
||||
"\"singleProcessorGroup\":%s,\"processorGroup\":%u}\n",
|
||||
mask(affinity, affinityText), mask(systemAffinity, systemText),
|
||||
single ? "true" : "false", single ? static_cast<unsigned>(groups[0]) : 0u);
|
||||
return 0;
|
||||
}
|
||||
if (count == 4 && std::wstring(args[1]) == L"reparse-directory") {
|
||||
// Only the conformance lane's disposable, nonempty source directory is used.
|
||||
const auto substitute = L"\\??\\" + std::wstring(args[3]);
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import { open, readFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
readbackFailed: false,
|
||||
rejectRestore: false,
|
||||
rejectRemove: false,
|
||||
removeCopiedRecovery: false,
|
||||
initialCleanupFailure: undefined as unknown,
|
||||
readbackCleanupFailure: undefined as unknown,
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.removeCopiedRecovery = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
});
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...original,
|
||||
rm: (
|
||||
...arguments_: Parameters<typeof original.rm>
|
||||
): ReturnType<typeof original.rm> => {
|
||||
if (state.rejectRemove && state.readbackFailed)
|
||||
return Promise.reject(new Error("injected restore remove failure"));
|
||||
return original.rm(...arguments_);
|
||||
},
|
||||
writeFile: (
|
||||
...arguments_: Parameters<typeof original.writeFile>
|
||||
): ReturnType<typeof original.writeFile> => {
|
||||
if (state.rejectRestore && state.readbackFailed)
|
||||
return Promise.reject(new Error("injected restore write failure"));
|
||||
return original.writeFile(...arguments_);
|
||||
},
|
||||
copyFile: async (
|
||||
...arguments_: Parameters<typeof original.copyFile>
|
||||
): Promise<void> => {
|
||||
await original.copyFile(...arguments_);
|
||||
const destination = arguments_[1];
|
||||
if (
|
||||
state.removeCopiedRecovery &&
|
||||
typeof destination === "string" &&
|
||||
destination.endsWith(".recovery")
|
||||
)
|
||||
await original.rm(destination);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("write-file-atomic", async (importOriginal) => {
|
||||
const original = await importOriginal<{
|
||||
default: typeof import("write-file-atomic");
|
||||
}>();
|
||||
return {
|
||||
...original,
|
||||
default: async (...arguments_: Parameters<typeof original.default>) => {
|
||||
if (state.initialCleanupFailure !== undefined)
|
||||
throw new Error("unexpected config write before initial read");
|
||||
const result = await original.default(...arguments_);
|
||||
state.readbackFailed = true;
|
||||
return result;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../src/application/RegularFileRead.js", async (importOriginal) => {
|
||||
const original =
|
||||
await importOriginal<
|
||||
typeof import("../../src/application/RegularFileRead.js")
|
||||
>();
|
||||
return {
|
||||
...original,
|
||||
readRegularFileText: (
|
||||
...arguments_: Parameters<typeof original.readRegularFileText>
|
||||
) =>
|
||||
state.initialCleanupFailure !== undefined
|
||||
? Promise.reject(state.initialCleanupFailure)
|
||||
: state.readbackFailed && state.readbackCleanupFailure !== undefined
|
||||
? Promise.reject(state.readbackCleanupFailure)
|
||||
: state.readbackFailed
|
||||
? Promise.reject(new Error("injected readback failure"))
|
||||
: original.readRegularFileText(...arguments_),
|
||||
};
|
||||
});
|
||||
|
||||
import { configureClientConfiguration } from "../../src/application/SetupClientConfiguration.js";
|
||||
import { RegularFileCleanupFailure } from "../../src/application/RegularFileRead.js";
|
||||
import { OwnedFileHandle } from "../../src/filesystem/OwnedFileHandle.js";
|
||||
import type { DoctorHost } from "../../src/application/Doctor.js";
|
||||
import { systemSetupHost } from "../../src/application/SetupHost.js";
|
||||
import { ConfigurationError } from "../../src/domain/configurationErrors.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
const ownReadHandle = async (path: string) => {
|
||||
const owner = new OwnedFileHandle(await open(path, "r"));
|
||||
onTestFinished(() => owner.close());
|
||||
return owner;
|
||||
};
|
||||
|
||||
it("reports a failed config rollback and retains its backup path", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-rollback-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
state.rejectRestore = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: `${path}.rea.backup`,
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore write failure",
|
||||
},
|
||||
});
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original);
|
||||
expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({
|
||||
mcpServers: { rea: { command: "rea", args: ["mcp"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the first backup and reports a verified backup of the current original", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-stale-backup-");
|
||||
const path = join(root, "client.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
await import("node:fs/promises").then(async ({ writeFile }) => {
|
||||
await writeFile(path, currentOriginal);
|
||||
await writeFile(`${path}.rea.backup`, firstOriginal);
|
||||
});
|
||||
state.rejectRestore = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.rejectRestore = false;
|
||||
|
||||
const recoveryPath = `${path}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: recoveryPath,
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore write failure",
|
||||
},
|
||||
});
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(firstOriginal);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe(currentOriginal);
|
||||
});
|
||||
|
||||
it("does not write config when a recovery copy disappears before verification", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.removeCopiedRecovery = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-vanished-recovery-");
|
||||
const path = join(root, "client.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
await import("node:fs/promises").then(async ({ writeFile }) => {
|
||||
await writeFile(path, currentOriginal);
|
||||
await writeFile(`${path}.rea.backup`, firstOriginal);
|
||||
});
|
||||
state.removeCopiedRecovery = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.removeCopiedRecovery = false;
|
||||
|
||||
expect(result).toEqual({ status: "failed", reason: "backup" });
|
||||
expect(await readFile(path, "utf8")).toBe(currentOriginal);
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(firstOriginal);
|
||||
});
|
||||
|
||||
it("does not roll back or remove config when its initial read cleanup fails", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-initial-cleanup-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
const failure = new RegularFileCleanupFailure(
|
||||
path,
|
||||
await ownReadHandle(path),
|
||||
{ kind: "completed", value: original },
|
||||
new Error("injected initial close failure"),
|
||||
);
|
||||
state.initialCleanupFailure = failure;
|
||||
|
||||
await expect(
|
||||
configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
),
|
||||
).rejects.toBe(failure);
|
||||
expect(await readFile(path, "utf8")).toBe(original);
|
||||
});
|
||||
|
||||
it("reports first-run rollback removal failure without a backup", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-first-run-rollback-");
|
||||
const path = join(root, "client.json");
|
||||
state.rejectRemove = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.rejectRemove = false;
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore remove failure",
|
||||
},
|
||||
});
|
||||
expect(result).not.toHaveProperty("backupPath");
|
||||
expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({
|
||||
mcpServers: { rea: { command: "rea", args: ["mcp"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains readback cleanup ownership when rollback also fails", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-readback-cleanup-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
const owner = await ownReadHandle(path);
|
||||
const cleanupFailure = new RegularFileCleanupFailure(
|
||||
path,
|
||||
owner,
|
||||
{ kind: "completed", value: "" },
|
||||
new Error("injected readback close failure"),
|
||||
);
|
||||
state.readbackCleanupFailure = cleanupFailure;
|
||||
state.rejectRestore = true;
|
||||
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: root } as DoctorHost,
|
||||
{ HOME: root },
|
||||
);
|
||||
let caught: unknown;
|
||||
try {
|
||||
await host.configureClient(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
caught = cause;
|
||||
} finally {
|
||||
await host.close?.();
|
||||
}
|
||||
|
||||
if (!(caught instanceof ConfigurationError)) throw caught;
|
||||
expect(caught.message).toContain("injected restore write failure");
|
||||
expect(caught.message).toContain(`${path}.rea.backup`);
|
||||
const cleanupOwnerError = caught.cause;
|
||||
if (!(cleanupOwnerError instanceof RegularFileCleanupFailure))
|
||||
throw new Error("Configuration failure lost its read owner");
|
||||
expect(cleanupOwnerError).toMatchObject({
|
||||
path,
|
||||
outcome: { kind: "completed", value: "" },
|
||||
cleanupCause: expect.any(AggregateError),
|
||||
});
|
||||
expect(cleanupOwnerError.owner).toBe(owner);
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original);
|
||||
});
|
||||
Reference in New Issue
Block a user