test: overhaul deterministic suite architecture
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
BrowserStartupError,
|
||||
waitForBrowserDevtoolsPort,
|
||||
} from "../../../src/browser/BrowserProcessStartup.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser process startup", () => {
|
||||
it("returns a delayed valid DevToolsActivePort", async () => {
|
||||
const root = await temporaryRoot();
|
||||
const portPath = join(root, "DevToolsActivePort");
|
||||
const child = spawn(process.execPath, [
|
||||
"-e",
|
||||
`setTimeout(() => require("node:fs").writeFileSync(${JSON.stringify(portPath)}, "43117\\n/browser"), 20); setTimeout(() => {}, 1000)`,
|
||||
]);
|
||||
try {
|
||||
await expect(
|
||||
waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
executable: process.execPath,
|
||||
activePortPath: portPath,
|
||||
stderr: () => "",
|
||||
timeoutMs: 1_000,
|
||||
pollIntervalMs: 5,
|
||||
}),
|
||||
).resolves.toBe(43_117);
|
||||
} finally {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
});
|
||||
|
||||
it("classifies signal termination instead of timing out", async () => {
|
||||
const root = await temporaryRoot();
|
||||
const child = spawn(process.execPath, [
|
||||
"-e",
|
||||
"process.kill(process.pid, 'SIGTERM')",
|
||||
]);
|
||||
|
||||
const failure = await waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
executable: process.execPath,
|
||||
activePortPath: join(root, "DevToolsActivePort"),
|
||||
stderr: () => "signal fixture",
|
||||
timeoutMs: 1_000,
|
||||
pollIntervalMs: 5,
|
||||
}).catch((cause: unknown) => cause);
|
||||
|
||||
expect(failure).toBeInstanceOf(BrowserStartupError);
|
||||
expect(failure).toMatchObject({
|
||||
failure: "signalled",
|
||||
exitCode: null,
|
||||
signalCode: "SIGTERM",
|
||||
stderr: "signal fixture",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports bounded timeout diagnostics", async () => {
|
||||
const root = await temporaryRoot();
|
||||
const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 1000)"]);
|
||||
try {
|
||||
const failure = await waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
executable: process.execPath,
|
||||
activePortPath: join(root, "DevToolsActivePort"),
|
||||
stderr: () => "",
|
||||
timeoutMs: 20,
|
||||
pollIntervalMs: 5,
|
||||
}).catch((cause: unknown) => cause);
|
||||
|
||||
expect(failure).toBeInstanceOf(BrowserStartupError);
|
||||
expect(failure).toMatchObject({
|
||||
failure: "timeout",
|
||||
exitCode: null,
|
||||
signalCode: null,
|
||||
});
|
||||
expect(String(failure)).toContain("stderr=<empty>");
|
||||
} finally {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const temporaryRoot = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-browser-startup-");
|
||||
roots.push(root);
|
||||
return root;
|
||||
};
|
||||
@@ -0,0 +1,216 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
it("lists only exact-origin pages and sanitizes URLs", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const result = await provider.listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.targets.items).toEqual([
|
||||
expect.objectContaining({
|
||||
target_id: "allowed-page",
|
||||
origin: browser.allowedOrigin,
|
||||
url: `${browser.allowedOrigin}/app?token=%5BREDACTED%5D`,
|
||||
}),
|
||||
]);
|
||||
expect(result.value.excluded).toEqual({
|
||||
disallowed_origin: 1,
|
||||
unsupported_url: 1,
|
||||
non_page: 1,
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("forbidden");
|
||||
expect(JSON.stringify(result.value)).not.toContain("page-secret");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["absolute", true, ""],
|
||||
["host/path", "host-path", ""],
|
||||
["root-relative", "root-relative", ""],
|
||||
["prefixed host/path", "prefixed", "Loading "],
|
||||
] as const)(
|
||||
"sanitizes %s transitional target titles",
|
||||
async (_label, urlShapedAllowedTitle, prefix) => {
|
||||
const browser = await startFakeCdpBrowser({ urlShapedAllowedTitle });
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const input = {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
approved: true as const,
|
||||
target_id: "allowed-page",
|
||||
};
|
||||
const expected = `${prefix}${browser.allowedOrigin}/app?startup=%5BREDACTED%5D`;
|
||||
const listed = await provider.listTargets(
|
||||
listBrowserTargetsInputSchema.parse(input),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets.items[0]?.title).toBe(expected);
|
||||
|
||||
const inspected = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({ ...input, observation_ms: 0 }),
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.title).toBe(expected);
|
||||
expect(JSON.stringify({ listed, inspected })).not.toContain(
|
||||
"title-secret",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("uses page-scoped discovery sockets as direct target transports", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
additionalPageWithWebSocket: true,
|
||||
additionalPageWithoutWebSocket: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const listed = await provider.listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(
|
||||
listed.value.targets.items.map(({ target_id }) => target_id),
|
||||
).toEqual(["allowed-page", "allowed-page-with-socket"]);
|
||||
expect(listed.value.limitations).toContain(
|
||||
"1 otherwise allowed page target(s) lacked a validated direct CDP WebSocket and were excluded.",
|
||||
);
|
||||
|
||||
const inspected = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.target_id).toBe("allowed-page");
|
||||
expect(inspected.value.network.requests).toHaveLength(1);
|
||||
|
||||
const second = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page-with-socket",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!second.ok) throw second.error;
|
||||
expect(second.value.target.target_id).toBe("allowed-page-with-socket");
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Target.attachToTarget");
|
||||
expect(methods).not.toContain("Target.detachFromTarget");
|
||||
expect(
|
||||
browser.commands.every(({ sessionId }) => sessionId === undefined),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: discovery authorization 2", () => {
|
||||
it("rejects empty browser attachment session identifiers", async () => {
|
||||
const browser = await startFakeCdpBrowser({ invalidAttachedSession: true });
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).toEqual([
|
||||
"Target.attachToTarget",
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects missing and disallowed page targets before attaching", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
for (const targetId of ["missing", "disallowed-page"]) {
|
||||
const result = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: targetId,
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "BrowserObservationError",
|
||||
reason:
|
||||
targetId === "missing" ? "target_not_found" : "target_not_allowed",
|
||||
});
|
||||
}
|
||||
expect(browser.commands).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns typed errors for malformed discovery and disconnects", async () => {
|
||||
const malformed = await startFakeCdpBrowser({ malformedDiscovery: true });
|
||||
trackBrowser(malformed);
|
||||
const malformedResult = await new CdpBrowserProvider().listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: malformed.endpoint,
|
||||
allowed_origins: [malformed.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
expect(malformedResult).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BrowserObservationError",
|
||||
reason: "invalid_endpoint_response",
|
||||
},
|
||||
});
|
||||
|
||||
const disconnecting = await startFakeCdpBrowser({
|
||||
closeOnMethod: "Page.getFrameTree",
|
||||
});
|
||||
trackBrowser(disconnecting);
|
||||
const disconnectedResult = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: disconnecting.endpoint,
|
||||
allowed_origins: [disconnecting.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(disconnectedResult).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "disconnected" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,441 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
|
||||
import { discoverWebMcpToolsInputSchema } from "../../../src/domain/webMcpDiscovery.js";
|
||||
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 1", () => {
|
||||
it("captures bounded accessibility text only after independent approval", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_accessibility_text: true,
|
||||
limits: {
|
||||
max_ax_text_field_bytes: 6,
|
||||
max_total_ax_text_bytes: 6,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.accessibility).toMatchObject({
|
||||
text_capture: {
|
||||
status: "truncated",
|
||||
retained_bytes: 6,
|
||||
truncated_fields: 2,
|
||||
},
|
||||
nodes: [expect.objectContaining({ name: "Submit" })],
|
||||
});
|
||||
expect(result.value.completeness.truncated_sections).toContain(
|
||||
"accessibility",
|
||||
);
|
||||
});
|
||||
|
||||
it("includes allowed script source only after explicit approval", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const result = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_script_sources: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.scripts.items[0]?.source).toEqual(
|
||||
expect.objectContaining({
|
||||
included: true,
|
||||
artifact: expect.objectContaining({
|
||||
text: "export const observed = 'source-secret';",
|
||||
bytes: 40,
|
||||
uri: expect.stringMatching(/^rea:\/\/web-content\/sha256\//u),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(browser.commands.map((command) => command.method)).toContain(
|
||||
"Debugger.getScriptSource",
|
||||
);
|
||||
});
|
||||
|
||||
it("fetches and validates source maps only after separate approval", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sourceMapBody: JSON.stringify({
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["src/main.ts"],
|
||||
sourcesContent: ["export const original = true;"],
|
||||
mappings: "AAAA",
|
||||
}),
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().analyzeBundle(
|
||||
analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
source_capture_approved: true,
|
||||
observation_ms: 0,
|
||||
fetch_source_maps: true,
|
||||
source_map_fetch_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.observations.source_maps).toMatchObject({
|
||||
status: "included",
|
||||
items: [
|
||||
{
|
||||
status: "included",
|
||||
original_sources: [
|
||||
expect.objectContaining({
|
||||
source: `${browser.allowedOrigin}/src/main.ts`,
|
||||
}),
|
||||
],
|
||||
mappings: [expect.any(Object)],
|
||||
},
|
||||
],
|
||||
});
|
||||
const sourceMapRequest = browser.httpRequests.find(({ url }) =>
|
||||
url.startsWith("/app.js.map"),
|
||||
);
|
||||
expect(sourceMapRequest).toEqual({
|
||||
url: "/app.js.map?token=map-secret",
|
||||
authorization: undefined,
|
||||
cookie: undefined,
|
||||
referer: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 2", () => {
|
||||
it("discovers untrusted WebMCP declarations without registering or invoking them", async () => {
|
||||
const browser = await startFakeCdpBrowser({ webMcpTools: true });
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value).toMatchObject({
|
||||
status: "available",
|
||||
tools: {
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
name: "search_orders",
|
||||
description: "Search orders; authorization=[REDACTED]",
|
||||
declaration_kind: "declarative",
|
||||
owner_origin: browser.allowedOrigin,
|
||||
annotations: {
|
||||
read_only: true,
|
||||
untrusted_content: true,
|
||||
autosubmit: false,
|
||||
},
|
||||
trust: "page-declared-untrusted",
|
||||
registration_source: {
|
||||
url: `${browser.allowedOrigin}/app.js?token=%5BREDACTED%5D`,
|
||||
line: 12,
|
||||
column: 4,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const serialized = JSON.stringify(result.value);
|
||||
for (const secret of [
|
||||
"tool-secret",
|
||||
"schema-secret",
|
||||
"tool-source-secret",
|
||||
"private-tool-secret",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).toContain("WebMCP.enable");
|
||||
expect(methods).not.toContain("WebMCP.invokeTool");
|
||||
expect(methods).not.toContain("Runtime.evaluate");
|
||||
});
|
||||
|
||||
it("reports WebMCP unavailable when the experimental domain is absent", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
unsupportedMethods: ["WebMCP.enable"],
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.status).toBe("unavailable");
|
||||
expect(result.value.tools.items).toEqual([]);
|
||||
expect(result.value.completeness.unavailable_sections).toContain(
|
||||
"webmcp_tools",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects WebMCP evidence when the page leaves its approved origin", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
frameUrlAfterFirstRead: "https://private.example.test/tools",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BrowserObservationError",
|
||||
operation: "discover_webmcp_tools",
|
||||
reason: "target_not_allowed",
|
||||
},
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).not.toContain(
|
||||
"WebMCP.invokeTool",
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds WebMCP registration replay and reports dropped declarations", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
extraCollections: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
max_tools: 1,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.tools).toMatchObject({
|
||||
total: 2,
|
||||
items: [expect.any(Object)],
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
dropped_events: { webmcp_tools: 1 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 3", () => {
|
||||
it("removes WebMCP declarations after their child frame leaves scope", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
extraCollections: true,
|
||||
webMcpChildLeavesScope: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
const names = result.value.tools.items.map(({ name }) => name);
|
||||
expect(names).toEqual(
|
||||
expect.arrayContaining(["search_orders", "update_order"]),
|
||||
);
|
||||
expect(names).not.toEqual(
|
||||
expect.arrayContaining(["child_tool", "escaped_child_tool"]),
|
||||
);
|
||||
expect(result.value.completeness.policy_filtered_sections).toContain(
|
||||
"webmcp_tools",
|
||||
);
|
||||
expect(JSON.stringify(result.value)).not.toContain(
|
||||
"cross-origin-child-secret",
|
||||
);
|
||||
});
|
||||
|
||||
it("captures an explicitly approved content-addressed viewport screenshot", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().captureScreenshot(
|
||||
captureWebScreenshotInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
screenshot_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value).toMatchObject({
|
||||
viewport: { width: 1, height: 1 },
|
||||
artifact: {
|
||||
uri: expect.stringMatching(/^rea:\/\/web-screenshot\/sha256\//u),
|
||||
bytes: 70,
|
||||
media_type: "image/png",
|
||||
},
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).toContain(
|
||||
"Page.captureScreenshot",
|
||||
);
|
||||
});
|
||||
|
||||
it("discards screenshot pixels when the main frame navigates during capture", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
navigateDuringScreenshotUrl: "https://private.example.test/screenshot",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().captureScreenshot(
|
||||
captureWebScreenshotInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
screenshot_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BrowserObservationError",
|
||||
operation: "capture_web_screenshot",
|
||||
reason: "target_not_allowed",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reports configured truncation without over-reading DOM or script source", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_script_sources: true,
|
||||
limits: {
|
||||
max_frames: 1,
|
||||
max_dom_nodes: 1,
|
||||
max_ax_nodes: 1,
|
||||
max_scripts: 1,
|
||||
max_resources: 1,
|
||||
max_workers: 1,
|
||||
max_storage_keys: 1,
|
||||
max_script_source_bytes: 10,
|
||||
max_total_script_source_bytes: 10,
|
||||
max_network_events: 1,
|
||||
max_console_events: 1,
|
||||
max_websocket_events: 1,
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
truncated_sections: ["dom", "script_sources"],
|
||||
});
|
||||
expect(result.value.dom).toMatchObject({ total_nodes: 2 });
|
||||
expect(result.value.dom.nodes).toHaveLength(1);
|
||||
expect(result.value.scripts.items[0]?.source).toMatchObject({
|
||||
included: false,
|
||||
reason: "declared script length exceeds per-script limit",
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).not.toContain(
|
||||
"Debugger.getScriptSource",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 4", () => {
|
||||
it("bounds frames, resources, workers, accessibility, and storage inventories", async () => {
|
||||
const browser = await startFakeCdpBrowser({ extraCollections: true });
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_storage_keys: true,
|
||||
limits: {
|
||||
max_frames: 1,
|
||||
max_dom_nodes: 2,
|
||||
max_ax_nodes: 1,
|
||||
max_scripts: 1,
|
||||
max_resources: 1,
|
||||
max_workers: 1,
|
||||
max_storage_keys: 1,
|
||||
max_script_source_bytes: 10,
|
||||
max_total_script_source_bytes: 10,
|
||||
max_network_events: 1,
|
||||
max_console_events: 1,
|
||||
max_websocket_events: 1,
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
truncated_sections: [
|
||||
"accessibility",
|
||||
"frames",
|
||||
"resources",
|
||||
"storage_keys",
|
||||
"workers",
|
||||
],
|
||||
});
|
||||
expect(result.value.frames).toHaveLength(1);
|
||||
expect(result.value.resources).toHaveLength(1);
|
||||
expect(result.value.workers).toHaveLength(1);
|
||||
expect(result.value.accessibility).toMatchObject({ total_nodes: 2 });
|
||||
expect(result.value.accessibility.nodes).toHaveLength(1);
|
||||
expect(result.value.storage.local_storage_keys).toHaveLength(1);
|
||||
expect(result.value.storage.session_storage_keys).toHaveLength(1);
|
||||
expect(result.value.storage.indexed_db_names).toHaveLength(1);
|
||||
expect(result.value.storage.cache_names).toHaveLength(1);
|
||||
expect(result.value.storage.content_fingerprints).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,484 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
|
||||
import { observeWebSessionInputSchema } from "../../../src/domain/browserSession.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 1", () => {
|
||||
it("projects direct-session cancellation onto the requested operation", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
report(update) {
|
||||
if (update.completed === 1) controller.abort();
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "observe_web_session",
|
||||
},
|
||||
});
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Target.attachToTarget");
|
||||
expect(methods).not.toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
});
|
||||
|
||||
it("projects capture-window cancellation onto bundle analysis", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const result = await new CdpBrowserProvider().analyzeBundle(
|
||||
analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
source_capture_approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
report(update) {
|
||||
if (update.completed === 2) controller.abort();
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "analyze_web_bundle",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("observes user-driven reload, SPA, redirect, failure, and lifecycle events", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "same_origin",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 20,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
expect(result.value.timeline.map(({ type }) => type)).toEqual([
|
||||
"navigation_requested",
|
||||
"same_origin_reload",
|
||||
"same_document_navigation",
|
||||
"redirect",
|
||||
"load_failed",
|
||||
"lifecycle",
|
||||
]);
|
||||
expect(result.value.timeline).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "same_document_navigation",
|
||||
url: `${browser.allowedOrigin}/reloaded?token=%5BREDACTED%5D`,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: "load_failed",
|
||||
detail: "net::ERR_CONNECTION_REFUSED",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(result.value.completeness.status).toBe("attach_limited");
|
||||
expect(JSON.stringify(result.value)).not.toContain("session-secret");
|
||||
expect(JSON.stringify(result.value)).not.toContain("redirect-secret");
|
||||
expect(browser.commands.map(({ method }) => method)).toContain(
|
||||
"Target.detachFromTarget",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 2", () => {
|
||||
it("ends a browser session when its flat target session detaches", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "target_detached",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_terminated");
|
||||
expect(result.value.timeline.at(-1)).toMatchObject({
|
||||
type: "target_terminated",
|
||||
detail: "target_terminated",
|
||||
});
|
||||
});
|
||||
|
||||
it("ends a direct page session when its transport disconnects", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
closeAfterMethod: "Page.setLifecycleEventsEnabled",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_terminated");
|
||||
expect(result.value.timeline.at(-1)).toMatchObject({
|
||||
type: "target_terminated",
|
||||
detail: "target_terminated",
|
||||
});
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Target.attachToTarget");
|
||||
expect(methods).not.toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
});
|
||||
|
||||
it("ends immediately when a redirect leaves policy without exposing its URL", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "outside_policy",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_left_scope");
|
||||
expect(result.value.timeline.at(-1)).toMatchObject({
|
||||
type: "redirect",
|
||||
url: null,
|
||||
destination_scope: "outside_policy",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "policy_filtered",
|
||||
policy_filtered_sections: ["timeline"],
|
||||
excluded: [
|
||||
{
|
||||
section: "timeline",
|
||||
reason: "out_of_target_scope",
|
||||
count: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("private.example.test");
|
||||
});
|
||||
|
||||
it("fails closed when the final session frame leaves policy without an event", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
frameUrlAfterFirstRead: "https://private.example.test/final",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_left_scope");
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "policy_filtered",
|
||||
policy_filtered_sections: ["timeline"],
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("private.example.test");
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 3", () => {
|
||||
it("degrades optional domains but propagates protocol and payload failures", async () => {
|
||||
const optional = await startFakeCdpBrowser({
|
||||
unsupportedMethods: ["Accessibility.getFullAXTree"],
|
||||
});
|
||||
trackBrowser(optional);
|
||||
const degraded = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: optional.endpoint,
|
||||
allowed_origins: [optional.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!degraded.ok) throw degraded.error;
|
||||
expect(degraded.value.accessibility.nodes).toEqual([]);
|
||||
expect(degraded.value.accessibility.text_capture.status).toBe(
|
||||
"unavailable",
|
||||
);
|
||||
expect(degraded.value.completeness.unavailable_sections).toContain(
|
||||
"accessibility",
|
||||
);
|
||||
expect(degraded.value.limitations).toContain(
|
||||
"Accessibility.getFullAXTree was unavailable from this browser target.",
|
||||
);
|
||||
|
||||
for (const [options, reason] of [
|
||||
[{ oversizedDiscovery: true }, "payload_limit"],
|
||||
[{ invalidBrowserWebSocket: true }, "invalid_endpoint_response"],
|
||||
] as const) {
|
||||
const failed = await startFakeCdpBrowser(options);
|
||||
trackBrowser(failed);
|
||||
const result = await new CdpBrowserProvider().listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: failed.endpoint,
|
||||
allowed_origins: [failed.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "BrowserObservationError",
|
||||
reason,
|
||||
});
|
||||
}
|
||||
|
||||
const malformed = await startFakeCdpBrowser({
|
||||
malformedMessageOnMethod: "Page.getFrameTree",
|
||||
});
|
||||
trackBrowser(malformed);
|
||||
const protocol = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: malformed.endpoint,
|
||||
allowed_origins: [malformed.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(protocol).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
|
||||
});
|
||||
|
||||
const malformedEvent = await startFakeCdpBrowser({
|
||||
malformedEventOnMethod: "Debugger.enable",
|
||||
});
|
||||
trackBrowser(malformedEvent);
|
||||
const eventProtocol = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: malformedEvent.endpoint,
|
||||
allowed_origins: [malformedEvent.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(eventProtocol).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
|
||||
});
|
||||
|
||||
const malformedEventShape = await startFakeCdpBrowser({
|
||||
malformedEventShapeOnMethod: "Debugger.enable",
|
||||
});
|
||||
trackBrowser(malformedEventShape);
|
||||
const eventShapeProtocol = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: malformedEventShape.endpoint,
|
||||
allowed_origins: [malformedEventShape.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(eventShapeProtocol).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels observation and still detaches without closing the page", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const pending = new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
// Wait until the attach response has been consumed and capture has begun.
|
||||
// Seeing the attach request alone races its response under worker load.
|
||||
await waitForCommand(browser, "Page.getFrameTree");
|
||||
controller.abort();
|
||||
const result = await pending;
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "inspect_web_page",
|
||||
},
|
||||
});
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 4", () => {
|
||||
it("waits for navigation commit and rechecks the attached main-frame origin", async () => {
|
||||
const transitioning = await startFakeCdpBrowser({
|
||||
transitionalFrameReads: 2,
|
||||
});
|
||||
trackBrowser(transitioning);
|
||||
const input = (browser: FakeCdpBrowser) =>
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
});
|
||||
const committed = await new CdpBrowserProvider().inspectPage(
|
||||
input(transitioning),
|
||||
);
|
||||
if (!committed.ok) throw committed.error;
|
||||
expect(committed.value.target.origin).toBe(transitioning.allowedOrigin);
|
||||
expect(
|
||||
transitioning.commands.filter(
|
||||
({ method }) => method === "Page.getFrameTree",
|
||||
),
|
||||
).toHaveLength(5);
|
||||
|
||||
const navigated = await startFakeCdpBrowser({
|
||||
attachedFrameUrl: "https://unapproved.example.test/after-attach",
|
||||
});
|
||||
trackBrowser(navigated);
|
||||
const denied = await new CdpBrowserProvider().inspectPage(input(navigated));
|
||||
expect(denied).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "target_not_allowed" },
|
||||
});
|
||||
const methods = navigated.commands.map(({ method }) => method);
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("DOMSnapshot.captureSnapshot");
|
||||
expect(methods).not.toContain("Storage.getUsageAndQuota");
|
||||
|
||||
const duringObservation = await startFakeCdpBrowser({
|
||||
navigateDuringObservationUrl:
|
||||
"https://unapproved.example.test/during-observation",
|
||||
});
|
||||
trackBrowser(duringObservation);
|
||||
const interrupted = await new CdpBrowserProvider().inspectPage(
|
||||
input(duringObservation),
|
||||
);
|
||||
expect(interrupted).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "target_not_allowed" },
|
||||
});
|
||||
expect(
|
||||
duringObservation.commands.map(({ method }) => method),
|
||||
).not.toContain("Accessibility.getFullAXTree");
|
||||
|
||||
const captureOptions: { navigateDuringCaptureUrl?: string } = {};
|
||||
const duringCapture = await startFakeCdpBrowser(captureOptions);
|
||||
captureOptions.navigateDuringCaptureUrl = `${duringCapture.allowedOrigin}/changed`;
|
||||
trackBrowser(duringCapture);
|
||||
const discarded = await new CdpBrowserProvider().inspectPage(
|
||||
input(duringCapture),
|
||||
);
|
||||
expect(discarded).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "target_changed" },
|
||||
});
|
||||
expect(duringCapture.commands.map(({ method }) => method)).toContain(
|
||||
"Target.detachFromTarget",
|
||||
);
|
||||
|
||||
const crossOriginCapture = await startFakeCdpBrowser({
|
||||
navigateDuringCaptureUrl:
|
||||
"https://unapproved.example.test/during-capture",
|
||||
});
|
||||
trackBrowser(crossOriginCapture);
|
||||
const rejectedCapture = await new CdpBrowserProvider().inspectPage(
|
||||
input(crossOriginCapture),
|
||||
);
|
||||
expect(rejectedCapture).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "target_not_allowed" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const waitForCommand = async (
|
||||
browser: FakeCdpBrowser,
|
||||
method: string,
|
||||
): Promise<void> => {
|
||||
for (let attempt = 0; attempt < 200; attempt += 1) {
|
||||
if (browser.commands.some((command) => command.method === method)) return;
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 5));
|
||||
}
|
||||
throw new Error(`Timed out waiting for fake CDP command ${method}`);
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: network 1", () => {
|
||||
it("drops network evidence when a request redirects outside the approved origin", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
redirectToDisallowedOrigin: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,387 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
webPageInspectionSchema,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: sensitive data 1", () => {
|
||||
it("captures bounded passive evidence without retaining sensitive values", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
binaryWebSocketEvent: true,
|
||||
foreignSessionEvents: true,
|
||||
unrelatedWorker: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const result = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_storage_keys: true,
|
||||
include_storage_fingerprints: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(() => webPageInspectionSchema.parse(result.value)).not.toThrow();
|
||||
expect(result.value.frames).toHaveLength(1);
|
||||
expect(result.value.dom.nodes).toHaveLength(2);
|
||||
expect(result.value.dom.nodes[1]?.attribute_names).toEqual([
|
||||
"token",
|
||||
"href",
|
||||
"rel",
|
||||
]);
|
||||
expect(result.value.accessibility).toMatchObject({
|
||||
text_capture: {
|
||||
status: "not_approved",
|
||||
retained_bytes: 0,
|
||||
},
|
||||
nodes: [expect.objectContaining({ name: null, description: null })],
|
||||
});
|
||||
expect(result.value.scripts.items).toHaveLength(1);
|
||||
expect(result.value.scripts.items[0]?.script_key).toMatch(
|
||||
/^scr_[a-f0-9]{64}$/u,
|
||||
);
|
||||
expect(result.value.scripts.items[0]?.frame_id).toBe("frame-main");
|
||||
expect(result.value.scripts.items[0]?.source_map_url).toBe(
|
||||
`${browser.allowedOrigin}/app.js.map?token=%5BREDACTED%5D`,
|
||||
);
|
||||
expect(result.value.scripts.items[0]?.resource_reconciliation).toEqual({
|
||||
status: "exact",
|
||||
resource_key: result.value.resources[0]?.resource_key,
|
||||
});
|
||||
expect(result.value.scripts.items[0]?.source).toEqual({
|
||||
included: false,
|
||||
reason: "source capture was not approved",
|
||||
});
|
||||
expect(result.value.resources).toHaveLength(1);
|
||||
expect(result.value.network.requests).toHaveLength(1);
|
||||
expect(result.value.network.requests[0]?.initiator).toEqual({
|
||||
type: "script",
|
||||
url: `${browser.allowedOrigin}/app.js?caller=%5BREDACTED%5D`,
|
||||
line: 3,
|
||||
column: 5,
|
||||
});
|
||||
expect(result.value.network.websocket_events).toEqual([
|
||||
{
|
||||
request_id: "websocket-1",
|
||||
direction: "sent",
|
||||
opcode: 1,
|
||||
payload_bytes: Buffer.byteLength("websocket-secret"),
|
||||
payload_shape: null,
|
||||
},
|
||||
{
|
||||
request_id: "websocket-1",
|
||||
direction: "received",
|
||||
opcode: 2,
|
||||
payload_bytes: 3,
|
||||
payload_shape: null,
|
||||
},
|
||||
]);
|
||||
expect(result.value.console.events[0]?.argument_types).toEqual(["string"]);
|
||||
expect(result.value.workers).toHaveLength(1);
|
||||
expect(result.value.workers[0]).toMatchObject({
|
||||
opener_target_id: "allowed-page",
|
||||
parent_frame_id: null,
|
||||
});
|
||||
expect(result.value.metadata).toMatchObject({
|
||||
headers_allowlisted: true,
|
||||
responses: [
|
||||
{
|
||||
content_length: 321,
|
||||
content_encoding: "br",
|
||||
csp: { nonce_count: 1, hash_count: 1 },
|
||||
policies: {
|
||||
coop: "same-origin",
|
||||
coep: "require-corp",
|
||||
permissions_policy_features: ["camera", "geolocation"],
|
||||
},
|
||||
},
|
||||
],
|
||||
dom_urls: [
|
||||
{
|
||||
attribute: "href",
|
||||
url: `${browser.allowedOrigin}/agent?token=%5BREDACTED%5D`,
|
||||
destination_scope: "approved",
|
||||
},
|
||||
],
|
||||
agent_hints: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
mechanism: "link_rel",
|
||||
declaration: "mcp service-desc",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
mechanism: "dom_link_rel",
|
||||
declaration: "mcp",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
mechanism: "response_header",
|
||||
declaration: "x-model-context",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(result.value.storage).toEqual(
|
||||
expect.objectContaining({
|
||||
local_storage_keys: ["public-key"],
|
||||
session_storage_keys: ["public-key"],
|
||||
indexed_db_names: ["app-db"],
|
||||
cache_names: ["assets-v1"],
|
||||
content_fingerprints: expect.arrayContaining([
|
||||
expect.objectContaining({ scope: "cookie", complete: true }),
|
||||
expect.objectContaining({ scope: "local_storage", complete: true }),
|
||||
expect.objectContaining({ scope: "session_storage", complete: true }),
|
||||
expect.objectContaining({
|
||||
scope: "indexed_db_schema",
|
||||
complete: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
scope: "indexed_db_record",
|
||||
complete: true,
|
||||
}),
|
||||
expect.objectContaining({ scope: "cache_entry", complete: true }),
|
||||
]),
|
||||
fingerprint_algorithm: "sha256",
|
||||
fingerprints_complete: true,
|
||||
values_redacted: true,
|
||||
}),
|
||||
);
|
||||
expectSensitiveValuesAbsent(result.value, browser);
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: sensitive data 2", () => {
|
||||
it("captures only approved redacted console text and value-free payload shapes", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sensitiveShapes: true,
|
||||
binaryWebSocketEvent: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_console_text: true,
|
||||
console_text_approved: true,
|
||||
include_json_body_shapes: true,
|
||||
json_body_schema_approved: true,
|
||||
include_websocket_shapes: true,
|
||||
websocket_shape_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.console.events[0]?.text_capture).toEqual({
|
||||
status: "included",
|
||||
values: [
|
||||
{ argument_index: 0, type: "string", text: "authorization=[REDACTED]" },
|
||||
{ argument_index: 1, type: "number", text: "42" },
|
||||
],
|
||||
retained_bytes: 26,
|
||||
truncated_values: 0,
|
||||
});
|
||||
expect(result.value.network.requests[0]?.body_shapes).toMatchObject({
|
||||
status: "included",
|
||||
request: {
|
||||
root_type: "object",
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "/token", types: ["string"] }),
|
||||
expect.objectContaining({
|
||||
path: "/filters/active",
|
||||
types: ["boolean"],
|
||||
}),
|
||||
]),
|
||||
},
|
||||
response: {
|
||||
root_type: "object",
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: "/result/token",
|
||||
types: ["string"],
|
||||
}),
|
||||
expect.objectContaining({ path: "/items/*/id", types: ["number"] }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(result.value.network.websocket_events).toEqual([
|
||||
expect.objectContaining({
|
||||
opcode: 1,
|
||||
payload_shape: expect.objectContaining({
|
||||
format: "json",
|
||||
json_shape: expect.objectContaining({
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "/token", types: ["string"] }),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
opcode: 2,
|
||||
payload_shape: {
|
||||
format: "binary",
|
||||
json_shape: null,
|
||||
truncated: false,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const serialized = JSON.stringify(result.value);
|
||||
for (const secret of [
|
||||
"request-body-secret",
|
||||
"response-body-secret",
|
||||
"websocket-secret",
|
||||
"console-secret",
|
||||
"object-secret",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).toContain("Network.getResponseBody");
|
||||
expect(methods).not.toContain("Runtime.getProperties");
|
||||
expect(methods).not.toContain("Runtime.callFunctionOn");
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: sensitive data 3", () => {
|
||||
it("reports independent sensitive-capture truncation at aggregate byte limits", async () => {
|
||||
const browser = await startFakeCdpBrowser({ sensitiveShapes: true });
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_console_text: true,
|
||||
console_text_approved: true,
|
||||
include_json_body_shapes: true,
|
||||
json_body_schema_approved: true,
|
||||
include_websocket_shapes: true,
|
||||
websocket_shape_approved: true,
|
||||
limits: {
|
||||
max_console_text_field_bytes: 5,
|
||||
max_total_console_text_bytes: 5,
|
||||
max_json_body_bytes: 10,
|
||||
max_total_json_body_bytes: 10,
|
||||
max_websocket_shape_bytes: 5,
|
||||
max_total_websocket_shape_bytes: 5,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.console.events[0]?.text_capture).toEqual({
|
||||
status: "truncated",
|
||||
values: [{ argument_index: 0, type: "string", text: "autho" }],
|
||||
retained_bytes: 5,
|
||||
truncated_values: 2,
|
||||
});
|
||||
expect(result.value.network.requests[0]?.body_shapes.status).toBe(
|
||||
"truncated",
|
||||
);
|
||||
expect(result.value.network.websocket_events[0]?.payload_shape).toEqual({
|
||||
format: "text",
|
||||
json_shape: null,
|
||||
truncated: true,
|
||||
});
|
||||
expect(result.value.completeness.truncated_sections).toEqual(
|
||||
expect.arrayContaining([
|
||||
"console_text",
|
||||
"json_body_shapes",
|
||||
"websocket_shapes",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed on malformed approved response and binary payload encodings", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
invalidResponseBodyBase64: true,
|
||||
binaryWebSocketEvent: true,
|
||||
invalidBinaryWebSocketEvent: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_json_body_shapes: true,
|
||||
json_body_schema_approved: true,
|
||||
include_websocket_shapes: true,
|
||||
websocket_shape_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests[0]?.body_shapes).toMatchObject({
|
||||
status: "partial",
|
||||
request: expect.any(Object),
|
||||
response: null,
|
||||
});
|
||||
expect(result.value.network.websocket_events[1]).toMatchObject({
|
||||
opcode: 2,
|
||||
payload_bytes: 0,
|
||||
payload_shape: { format: "binary", json_shape: null },
|
||||
});
|
||||
expect(result.value.completeness.unavailable_sections).toEqual(
|
||||
expect.arrayContaining(["json_body_shapes", "websocket_frames"]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const expectSensitiveValuesAbsent = (
|
||||
inspection: ReturnType<typeof webPageInspectionSchema.parse>,
|
||||
browser: FakeCdpBrowser,
|
||||
): void => {
|
||||
const serialized = JSON.stringify(inspection);
|
||||
for (const secret of [
|
||||
"page-secret",
|
||||
"frame-secret",
|
||||
"dom-secret",
|
||||
"forbidden",
|
||||
"resource-secret",
|
||||
"script-secret",
|
||||
"inline-secret",
|
||||
"map-secret",
|
||||
"network-secret",
|
||||
"request-secret",
|
||||
"request-body-secret",
|
||||
"response-secret",
|
||||
"response-body-secret",
|
||||
"websocket-secret",
|
||||
"websocket-url-secret",
|
||||
"console-secret",
|
||||
"unknown-origin-console-secret",
|
||||
"unknown-console-value-secret",
|
||||
"storage-secret",
|
||||
"cookie-secret",
|
||||
"indexed-db-secret",
|
||||
"cache-body-secret",
|
||||
"secret-id",
|
||||
"dom-url-secret",
|
||||
"link-secret",
|
||||
"csp-secret",
|
||||
"hash-secret",
|
||||
"header-secret",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
const methods = browser.commands.map((command) => command.method);
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Runtime.evaluate");
|
||||
expect(methods).not.toContain("Network.getResponseBody");
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import { afterEach, describe } from "vitest";
|
||||
|
||||
import type { FakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
});
|
||||
|
||||
export const trackBrowser = (browser: FakeCdpBrowser): void => {
|
||||
browsers.push(browser);
|
||||
};
|
||||
|
||||
export const describeBrowser = describe;
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpCaptureCompleteness } from "../../../src/browser/CdpCaptureCompleteness.js";
|
||||
|
||||
describe("CdpCaptureCompleteness", () => {
|
||||
it("reports attach-window limitations without claiming a complete history", () => {
|
||||
const capture = new CdpCaptureCompleteness([
|
||||
"network_requests",
|
||||
"console_events",
|
||||
]);
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "attach_limited",
|
||||
conditions: ["attach_limited"],
|
||||
attach_limited_sections: ["console_events", "network_requests"],
|
||||
excluded: [],
|
||||
dropped_events: { total: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("aggregates sparse exclusions and applies explicit status precedence", () => {
|
||||
const capture = new CdpCaptureCompleteness(["network_requests"]);
|
||||
capture.exclude("scripts", "disallowed_origin");
|
||||
capture.exclude("scripts", "disallowed_origin", 2);
|
||||
capture.exclude("storage_keys", "not_approved", null);
|
||||
capture.drop("console_events", 4);
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "truncated",
|
||||
conditions: ["attach_limited", "policy_filtered", "truncated"],
|
||||
policy_filtered_sections: ["scripts", "storage_keys"],
|
||||
truncated_sections: ["console_events"],
|
||||
excluded: [
|
||||
{ section: "scripts", reason: "disallowed_origin", count: 3 },
|
||||
{ section: "storage_keys", reason: "not_approved", count: null },
|
||||
],
|
||||
dropped_events: { console_events: 4, total: 4 },
|
||||
});
|
||||
});
|
||||
|
||||
it("restores initial attach limitations when reused for a new capture", () => {
|
||||
const capture = new CdpCaptureCompleteness(["websocket_frames"]);
|
||||
capture.drop("scripts");
|
||||
capture.exclude("resources", "provider_unavailable", null);
|
||||
|
||||
capture.reset();
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "attach_limited",
|
||||
attach_limited_sections: ["websocket_frames"],
|
||||
unavailable_sections: [],
|
||||
excluded: [],
|
||||
dropped_events: { total: 0 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
captureAccessibility,
|
||||
captureDom,
|
||||
captureFrames,
|
||||
captureResources,
|
||||
} from "../../../src/browser/CdpCaptureDocuments.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
describe("CDP document capture", () => {
|
||||
it("walks deeply nested frame trees iteratively and retains a bounded prefix", () => {
|
||||
let frameTree: Record<string, unknown> = {
|
||||
frame: { id: "frame-0", url: `${origin}/0` },
|
||||
resources: [{ url: `${origin}/0.js`, type: "Script" }],
|
||||
};
|
||||
for (let index = 1; index < 2_000; index += 1) {
|
||||
frameTree = {
|
||||
frame: {
|
||||
id: `frame-${String(index)}`,
|
||||
url: `${origin}/${String(index)}`,
|
||||
},
|
||||
resources: [{ url: `${origin}/${String(index)}.js`, type: "Script" }],
|
||||
childFrames: [frameTree],
|
||||
};
|
||||
}
|
||||
const result = { frameTree };
|
||||
const frames = captureFrames(result, new Set([origin]), 3);
|
||||
const resources = captureResources(result, new Set([origin]), 2);
|
||||
expect(frames).toMatchObject({ total: 2_000 });
|
||||
expect(frames.items).toHaveLength(3);
|
||||
expect(resources).toMatchObject({ total: 2_000 });
|
||||
expect(resources.items).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rebases parent indexes when allowed DOM documents are combined", () => {
|
||||
const input = inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: [origin],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
});
|
||||
const snapshot = {
|
||||
strings: [`${origin}/main`, `${origin}/frame`, "#document", "DIV", ""],
|
||||
documents: [
|
||||
{
|
||||
documentURL: 0,
|
||||
nodes: {
|
||||
nodeType: [9, 1],
|
||||
nodeName: [2, 3],
|
||||
nodeValue: [4, 4],
|
||||
parentIndex: [-1, 0],
|
||||
attributes: [[], []],
|
||||
},
|
||||
},
|
||||
{
|
||||
documentURL: 1,
|
||||
nodes: {
|
||||
nodeType: [9, 1],
|
||||
nodeName: [2, 3],
|
||||
nodeValue: [4, 4],
|
||||
parentIndex: [-1, 0],
|
||||
attributes: [[], []],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const capture = captureDom(snapshot, new Set([origin]), input);
|
||||
expect(capture.nodes.map((node) => node.parent_index)).toEqual([
|
||||
-1, 0, -1, 2,
|
||||
]);
|
||||
});
|
||||
|
||||
it("bounds approved accessibility text by UTF-8 bytes without splitting characters", () => {
|
||||
const capture = captureAccessibility(
|
||||
[
|
||||
{
|
||||
nodes: [
|
||||
{
|
||||
nodeId: "node-1",
|
||||
role: { value: "button" },
|
||||
name: { value: "😀a" },
|
||||
description: { value: "éé" },
|
||||
childIds: ["missing-child"],
|
||||
properties: [
|
||||
{ name: "disabled", value: { value: true } },
|
||||
{ name: "valuetext", value: { value: "private value" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
10,
|
||||
{
|
||||
includeText: true,
|
||||
maximumFieldBytes: 4,
|
||||
maximumTotalBytes: 7,
|
||||
},
|
||||
);
|
||||
|
||||
expect(capture.nodes[0]).toMatchObject({
|
||||
name: "😀",
|
||||
description: "é",
|
||||
states: [{ name: "disabled", value: true }],
|
||||
});
|
||||
expect(capture.treeIncomplete).toBe(true);
|
||||
expect(capture.textCapture).toEqual({
|
||||
status: "truncated",
|
||||
retained_bytes: 6,
|
||||
excluded_fields: 0,
|
||||
truncated_fields: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it("counts accessibility fields omitted without text approval", () => {
|
||||
const capture = captureAccessibility(
|
||||
[
|
||||
{
|
||||
nodes: [
|
||||
{
|
||||
nodeId: "node-1",
|
||||
name: { value: "private name" },
|
||||
description: { value: "private description" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
10,
|
||||
{
|
||||
includeText: false,
|
||||
maximumFieldBytes: 1_024,
|
||||
maximumTotalBytes: 64 * 1_024,
|
||||
},
|
||||
);
|
||||
|
||||
expect(capture.nodes[0]).toMatchObject({ name: null, description: null });
|
||||
expect(capture.textCapture).toEqual({
|
||||
status: "not_approved",
|
||||
retained_bytes: 0,
|
||||
excluded_fields: 2,
|
||||
truncated_fields: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CdpConnection } from "../../../src/browser/CdpConnection.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
describe("CDP connection", () => {
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await Promise.all(
|
||||
browsers.splice(0).map(async (browser) => browser.close()),
|
||||
);
|
||||
});
|
||||
|
||||
it("correlates concurrent command responses over a real WebSocket", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
const connection = await CdpConnection.connect(
|
||||
browser.browserWebSocketUrl,
|
||||
"inspect_web_page",
|
||||
);
|
||||
try {
|
||||
const [attached, frames] = await Promise.all([
|
||||
connection.send("Target.attachToTarget"),
|
||||
connection.send("Page.getFrameTree"),
|
||||
]);
|
||||
expect(attached).toMatchObject({ sessionId: "session-1" });
|
||||
expect(frames).toMatchObject({
|
||||
frameTree: { frame: { id: "frame-main" } },
|
||||
});
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a typed timeout for an unresponsive CDP command", async () => {
|
||||
const browser = await startFakeCdpBrowser({ hangOnMethod: "Page.enable" });
|
||||
browsers.push(browser);
|
||||
const connection = await CdpConnection.connect(
|
||||
browser.browserWebSocketUrl,
|
||||
"observe_web_session",
|
||||
);
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const pending = connection.send("Page.enable");
|
||||
const assertion = expect(pending).rejects.toMatchObject({
|
||||
_tag: "AnalysisTimeoutError",
|
||||
operation: "observe_web_session",
|
||||
timeoutMs: 5_000,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await assertion;
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,262 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
|
||||
import {
|
||||
inspectElectronPageInputSchema,
|
||||
listElectronTargetsInputSchema,
|
||||
} from "../../../src/domain/electronObservation.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider target access", () => {
|
||||
it("lists and inspects only canonical file targets beneath approved roots", async () => {
|
||||
const root = await electronFixture();
|
||||
const index = join(root, "index.html");
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(index).href,
|
||||
duplicateElectronInventory: true,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const provider = new CdpElectronProvider();
|
||||
const listed = await provider.listTargets(
|
||||
listElectronTargetsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets.items).toEqual([
|
||||
expect.objectContaining({
|
||||
target_id: "electron-page",
|
||||
file_path: index,
|
||||
}),
|
||||
]);
|
||||
expect(listed.value.excluded).toEqual({
|
||||
outside_root: 0,
|
||||
unsupported_url: 3,
|
||||
non_page: 2,
|
||||
});
|
||||
|
||||
const inspected = await provider.inspectPage(
|
||||
inspectElectronPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
target_id: "electron-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.file_path).toBe(index);
|
||||
expect(inspected.value.frames).toEqual([
|
||||
expect.objectContaining({ file_path: index }),
|
||||
]);
|
||||
expect(inspected.value.dom).toMatchObject({ total_nodes: 2 });
|
||||
expect(inspected.value.scripts).toMatchObject({
|
||||
total: 1,
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
file_path: join(root, "app.js"),
|
||||
source: {
|
||||
included: false,
|
||||
reason: "source capture was not approved",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(inspected.value.resources).toEqual([
|
||||
expect.objectContaining({ file_path: join(root, "app.js") }),
|
||||
]);
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Runtime.evaluate");
|
||||
expect(methods).not.toContain("Network.enable");
|
||||
expect(methods).not.toContain("Debugger.getScriptSource");
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
|
||||
const missing = await provider.inspectPage(
|
||||
inspectElectronPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
target_id: "missing",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(missing).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BrowserObservationError",
|
||||
operation: "inspect_electron_page",
|
||||
reason: "target_not_found",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("inspects a page-scoped Electron endpoint without browser attachment", async () => {
|
||||
const root = await electronFixture();
|
||||
const index = join(root, "index.html");
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(index).href,
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const result = await new CdpElectronProvider().inspectPage(
|
||||
inspectElectronPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
target_id: "electron-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.target.file_path).toBe(index);
|
||||
expect(browser.commands.map(({ method }) => method)).not.toContain(
|
||||
"Target.attachToTarget",
|
||||
);
|
||||
expect(
|
||||
browser.commands.every(({ sessionId }) => sessionId === undefined),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("maps cancelled Electron discovery to the Electron operation", async () => {
|
||||
const root = await electronFixture();
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const result = await new CdpElectronProvider().listTargets(
|
||||
listElectronTargetsInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_file_roots: [root],
|
||||
approved: true,
|
||||
}),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "list_electron_targets",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider capture", () => {
|
||||
it("captures Electron script source only after separate approval", async () => {
|
||||
const root = await electronFixture();
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const result = await new CdpElectronProvider().inspectPage(
|
||||
inspectElectronPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
target_id: "electron-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_script_sources: true,
|
||||
source_capture_approved: true,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.scripts.items[0]?.source).toMatchObject({
|
||||
included: true,
|
||||
artifact: { text: "export const observed = 'source-secret';" },
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).toContain(
|
||||
"Debugger.getScriptSource",
|
||||
);
|
||||
});
|
||||
|
||||
it("rebases DOM parent indexes across allowed file documents", async () => {
|
||||
const root = await electronFixture();
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
|
||||
extraCollections: true,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const result = await new CdpElectronProvider().inspectPage(
|
||||
inspectElectronPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
target_id: "electron-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.dom).toMatchObject({
|
||||
total_nodes: 4,
|
||||
nodes: [
|
||||
{ index: 0, parent_index: -1 },
|
||||
{ index: 1, parent_index: 0 },
|
||||
{ index: 2, parent_index: -1 },
|
||||
{ index: 3, parent_index: 2 },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects mixed Electron evidence when the main frame navigates", async () => {
|
||||
const root = await electronFixture();
|
||||
const page = join(root, "index.html");
|
||||
const next = join(root, "next.html");
|
||||
await writeFile(next, "<html>next</html>");
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(page).href,
|
||||
navigateDuringCaptureUrl: pathToFileURL(next).href,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const result = await new CdpElectronProvider().inspectPage(
|
||||
inspectElectronPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
target_id: "electron-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BrowserObservationError",
|
||||
operation: "inspect_electron_page",
|
||||
reason: "target_changed",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const electronFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-electron-provider-");
|
||||
temporary.push(root);
|
||||
await writeFile(join(root, "index.html"), "<script src='app.js'></script>");
|
||||
await writeFile(join(root, "app.js"), "export const app = true;");
|
||||
await writeFile(join(root, "child.html"), "<div>child</div>");
|
||||
return root;
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { safeResponseMetadata } from "../../../src/browser/CdpSafeMetadata.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
describe("safe CDP response metadata", () => {
|
||||
it("retains only allowlisted header structure and redacted approved links", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-1",
|
||||
`${origin}/api`,
|
||||
{
|
||||
mimeType: "application/json",
|
||||
headers: {
|
||||
Authorization: "Bearer credential-secret",
|
||||
Cookie: "session=cookie-secret",
|
||||
"Set-Cookie": "session=response-secret",
|
||||
Link: `</agent?token=link-secret>; rel="mcp service-desc"; title="a,b", <https://private.example.test/x>; rel="mcp"`,
|
||||
"Content-Security-Policy":
|
||||
"default-src 'self'; script-src 'nonce-nonce-secret' 'sha256-hash-secret' https://private.example.test",
|
||||
"Permissions-Policy":
|
||||
"camera=(), geolocation=(self), invalid secret=()",
|
||||
"X-Model-Context": "agent-header-secret",
|
||||
},
|
||||
},
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.response).toMatchObject({
|
||||
url: `${origin}/api`,
|
||||
csp: {
|
||||
nonce_count: 1,
|
||||
hash_count: 1,
|
||||
directives: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "script-src",
|
||||
sources: expect.arrayContaining([
|
||||
{ kind: "external_origin", value: null },
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
},
|
||||
links: [
|
||||
{
|
||||
href: `${origin}/agent?token=%5BREDACTED%5D`,
|
||||
destination_scope: "approved",
|
||||
rel: ["mcp", "service-desc"],
|
||||
as: null,
|
||||
type: null,
|
||||
crossorigin: null,
|
||||
},
|
||||
expect.objectContaining({
|
||||
href: null,
|
||||
destination_scope: "outside_policy",
|
||||
}),
|
||||
],
|
||||
policies: { permissions_policy_features: ["camera", "geolocation"] },
|
||||
});
|
||||
expect(captured.agentHints).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ mechanism: "link_rel" }),
|
||||
expect.objectContaining({
|
||||
mechanism: "response_header",
|
||||
declaration: "x-model-context",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const serialized = JSON.stringify(captured);
|
||||
for (const secret of [
|
||||
"credential-secret",
|
||||
"cookie-secret",
|
||||
"response-secret",
|
||||
"link-secret",
|
||||
"nonce-secret",
|
||||
"hash-secret",
|
||||
"agent-header-secret",
|
||||
"private.example.test",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
});
|
||||
|
||||
it("reports well-known agent resources as untrusted observations", () => {
|
||||
const captured = safeResponseMetadata(
|
||||
"request-2",
|
||||
`${origin}/.well-known/mcp?token=secret`,
|
||||
{ headers: {} },
|
||||
new Set([origin]),
|
||||
);
|
||||
|
||||
expect(captured.agentHints).toEqual([
|
||||
{
|
||||
mechanism: "well_known_resource",
|
||||
declaration: "/.well-known/mcp",
|
||||
url: `${origin}/.well-known/mcp?token=%5BREDACTED%5D`,
|
||||
trust: "page-declared-untrusted",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
authEventsByProtocol,
|
||||
authFlowDuration,
|
||||
customProtocolCaptureSchema,
|
||||
correlateProcessIdentity,
|
||||
failedAuthEvents,
|
||||
framesByTransport,
|
||||
looksLikeCredentialFrame,
|
||||
successfulAuthEvents,
|
||||
type AuthFlowEvent,
|
||||
type FrameDirection,
|
||||
type AuthStage,
|
||||
type TokenLifecycleEvent,
|
||||
type CustomProtocolCapture,
|
||||
type ProtocolFrame,
|
||||
} from "../../../src/domain/customProtocolCapture.js";
|
||||
|
||||
const sampleFrames: ProtocolFrame[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 100,
|
||||
transport: "tcp",
|
||||
direction: "sent",
|
||||
source_pid: 100,
|
||||
dest_pid: 200,
|
||||
source_endpoint: "127.0.0.1:8080",
|
||||
dest_endpoint: "127.0.0.1:9090",
|
||||
raw_data: "hello",
|
||||
decoded_content: "hello",
|
||||
size: 5,
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 200,
|
||||
transport: "udp",
|
||||
direction: "received",
|
||||
source_pid: 200,
|
||||
dest_pid: 100,
|
||||
source_endpoint: "127.0.0.1:9090",
|
||||
dest_endpoint: "127.0.0.1:8080",
|
||||
raw_data: "world",
|
||||
decoded_content: "world",
|
||||
size: 5,
|
||||
truncated: false,
|
||||
},
|
||||
];
|
||||
|
||||
const sampleAuthEvents: AuthFlowEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 100,
|
||||
stage: "init",
|
||||
protocol: "OAuth2",
|
||||
token_type: "Bearer",
|
||||
token_lifecycle: "issued",
|
||||
correlation_id: "abc-123",
|
||||
credentials_redacted: true,
|
||||
succeeded: false,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 500,
|
||||
stage: "success",
|
||||
protocol: "OAuth2",
|
||||
token_type: "Bearer",
|
||||
token_lifecycle: "issued",
|
||||
correlation_id: "abc-123",
|
||||
credentials_redacted: true,
|
||||
succeeded: true,
|
||||
error: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("custom protocol capture", () => {
|
||||
it("validates a well-formed capture", () => {
|
||||
const capture = {
|
||||
transport: "tcp" as const,
|
||||
frames: sampleFrames,
|
||||
auth_events: sampleAuthEvents,
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
const result = customProtocolCaptureSchema.safeParse(capture);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("correlates process identity", () => {
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 100)).toBe(true);
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 200)).toBe(true);
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 999)).toBe(false);
|
||||
});
|
||||
|
||||
it("filters frames by transport", () => {
|
||||
const tcpFrames = framesByTransport(sampleFrames, "tcp");
|
||||
expect(tcpFrames).toHaveLength(1);
|
||||
const udpFrames = framesByTransport(sampleFrames, "udp");
|
||||
expect(udpFrames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("detects credential-like frames", () => {
|
||||
const credFrame: ProtocolFrame = {
|
||||
...sampleFrames[0]!,
|
||||
decoded_content: { password: "secret" },
|
||||
};
|
||||
expect(looksLikeCredentialFrame(credFrame)).toBe(true);
|
||||
expect(looksLikeCredentialFrame(sampleFrames[0]!)).toBe(false);
|
||||
});
|
||||
|
||||
it("filters auth events by protocol", () => {
|
||||
const oauthEvents = authEventsByProtocol(sampleAuthEvents, "OAuth2");
|
||||
expect(oauthEvents).toHaveLength(2);
|
||||
const otherEvents = authEventsByProtocol(sampleAuthEvents, "SAML");
|
||||
expect(otherEvents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("gets successful auth events", () => {
|
||||
const success = successfulAuthEvents(sampleAuthEvents);
|
||||
expect(success).toHaveLength(1);
|
||||
expect(success[0]!.succeeded).toBe(true);
|
||||
});
|
||||
|
||||
it("gets failed auth events", () => {
|
||||
const failed = failedAuthEvents(sampleAuthEvents);
|
||||
expect(failed).toHaveLength(1);
|
||||
expect(failed[0]!.succeeded).toBe(false);
|
||||
});
|
||||
|
||||
it("computes auth flow duration", () => {
|
||||
const duration = authFlowDuration(sampleAuthEvents);
|
||||
expect(duration).toBe(400);
|
||||
});
|
||||
|
||||
it("returns null for empty auth events", () => {
|
||||
expect(authFlowDuration([])).toBeNull();
|
||||
});
|
||||
|
||||
it("uses all exported types", () => {
|
||||
const dir: FrameDirection = "sent";
|
||||
expect(dir).toBe("sent");
|
||||
const stage: AuthStage = "init";
|
||||
expect(stage).toBe("init");
|
||||
const event: TokenLifecycleEvent = "issued";
|
||||
expect(event).toBe("issued");
|
||||
const capture: CustomProtocolCapture = {
|
||||
transport: "tcp",
|
||||
frames: sampleFrames,
|
||||
auth_events: sampleAuthEvents,
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
expect(capture.transport).toBe("tcp");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,354 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { createJavaScriptRuntimeObservationEvidence } from "../../../src/application/JavaScriptRuntimeObservationEvidence.js";
|
||||
import {
|
||||
listJavaScriptRuntimeTargets,
|
||||
observeJavaScriptRuntime,
|
||||
} from "../../../src/application/JavaScriptRuntimeObservationService.js";
|
||||
import { createPermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { reconcileJavaScriptRuntimeEvidence } from "../../../src/application/JavaScriptRuntimeReconciliationService.js";
|
||||
import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/browser/V8InspectorProvider.js";
|
||||
import { V8InspectorProvider } from "../../../src/browser/V8InspectorProvider.js";
|
||||
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascriptRuntimeReconciliationExample.js";
|
||||
import type {
|
||||
JavaScriptRuntimeObservation,
|
||||
ObserveJavaScriptRuntimeInput,
|
||||
} from "../../../src/domain/javascriptRuntimeObservation.js";
|
||||
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascriptRuntimeReconciliationSchemas.js";
|
||||
import type {
|
||||
PermissionCeiling,
|
||||
PermissionGrant,
|
||||
} from "../../../src/domain/permissionPolicy.js";
|
||||
import { startFakeV8Inspector } from "../../fixtures/fakeV8Inspector.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("passive V8 Inspector provider", () => {
|
||||
test("filters target locations and never retains the excluded path", async () => {
|
||||
const fixture = await runtimeFixture();
|
||||
const outside = await temporaryFile("outside.js");
|
||||
const fake = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(fixture.entry).href,
|
||||
additionalTargetUrl: pathToFileURL(outside).href,
|
||||
});
|
||||
try {
|
||||
const result = await new V8InspectorProvider().listTargets({
|
||||
inspector_endpoint: fake.endpoint,
|
||||
allowed_file_roots: [fixture.root],
|
||||
allowed_origins: [],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.targets.total).toBe(1);
|
||||
expect(result.value.excluded.outside_file_roots).toBe(1);
|
||||
expect(JSON.stringify(result.value)).not.toContain(outside);
|
||||
} finally {
|
||||
await fake.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("captures only bounded metadata with two enable commands", async () => {
|
||||
const fixture = await runtimeFixture();
|
||||
const outside = await temporaryFile("secret.js");
|
||||
const fake = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(fixture.entry).href,
|
||||
scriptUrls: [
|
||||
pathToFileURL(fixture.entry).href,
|
||||
"node:fs",
|
||||
pathToFileURL(outside).href,
|
||||
],
|
||||
});
|
||||
try {
|
||||
const result = await new V8InspectorProvider().observe(
|
||||
observeInput(fake.endpoint, fake.targetId, fixture.root, "node"),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.scripts.items).toHaveLength(2);
|
||||
expect(result.value.scripts.excluded.outside_file_roots).toBe(1);
|
||||
expect(result.value.execution_contexts).toEqual([
|
||||
{
|
||||
context_key: "1",
|
||||
state: "created",
|
||||
name: null,
|
||||
origin: null,
|
||||
},
|
||||
]);
|
||||
expect(fake.commands.map(({ method }) => method)).toEqual([
|
||||
"Runtime.enable",
|
||||
"Debugger.enable",
|
||||
]);
|
||||
expect(JSON.stringify(result.value)).not.toContain(outside);
|
||||
expect(result.value.unavailable_without_instrumentation).toContain(
|
||||
"Electron IPC messages and handlers",
|
||||
);
|
||||
} finally {
|
||||
await fake.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["node", "node"],
|
||||
["electron-main", "node"],
|
||||
["electron-preload", "page"],
|
||||
["electron-renderer", "page"],
|
||||
] as const)(
|
||||
"admits declared %s only on its protocol target family",
|
||||
async (runtimeKind, targetType) => {
|
||||
const fixture = await runtimeFixture();
|
||||
const fake = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(fixture.entry).href,
|
||||
targetType,
|
||||
});
|
||||
try {
|
||||
const result = await new V8InspectorProvider().observe(
|
||||
observeInput(fake.endpoint, fake.targetId, fixture.root, runtimeKind),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
} finally {
|
||||
await fake.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("passive V8 Inspector evidence", () => {
|
||||
test("marks capture truncation instead of claiming complete coverage", async () => {
|
||||
const fixture = await runtimeFixture();
|
||||
const second = join(fixture.root, "second.js");
|
||||
await writeFile(second, "export {};\n");
|
||||
const fake = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(fixture.entry).href,
|
||||
scriptUrls: [
|
||||
pathToFileURL(fixture.entry).href,
|
||||
pathToFileURL(second).href,
|
||||
],
|
||||
});
|
||||
try {
|
||||
const input = observeInput(
|
||||
fake.endpoint,
|
||||
fake.targetId,
|
||||
fixture.root,
|
||||
"node",
|
||||
);
|
||||
const result = await new V8InspectorProvider().observe({
|
||||
...input,
|
||||
limits: { ...input.limits, max_scripts: 1 },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.capture.truncated).toBe(true);
|
||||
expect(result.value.capture.truncation_reasons).toEqual(["max_scripts"]);
|
||||
expect(result.value.capture.events_dropped).toBe(1);
|
||||
} finally {
|
||||
await fake.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("produces deterministic Evidence through the authorized service", async () => {
|
||||
const fixture = await runtimeFixture();
|
||||
const fake = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(fixture.entry).href,
|
||||
});
|
||||
try {
|
||||
const input = observeInput(
|
||||
fake.endpoint,
|
||||
fake.targetId,
|
||||
fixture.root,
|
||||
"node",
|
||||
);
|
||||
const authority = await authorityFor(fake.endpoint, fixture.root);
|
||||
const first = await observeJavaScriptRuntime(
|
||||
new V8InspectorProvider(),
|
||||
authority,
|
||||
input,
|
||||
);
|
||||
const second = await observeJavaScriptRuntime(
|
||||
new V8InspectorProvider(),
|
||||
authority,
|
||||
input,
|
||||
);
|
||||
expect(first.ok).toBe(true);
|
||||
expect(second.ok).toBe(true);
|
||||
if (!first.ok || !second.ok) return;
|
||||
expect(second.value.evidence_id).toBe(first.value.evidence_id);
|
||||
|
||||
const listed = await listJavaScriptRuntimeTargets(
|
||||
new V8InspectorProvider(),
|
||||
authority,
|
||||
{
|
||||
inspector_endpoint: fake.endpoint,
|
||||
allowed_file_roots: [fixture.root],
|
||||
allowed_origins: [],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
},
|
||||
);
|
||||
expect(listed.ok).toBe(true);
|
||||
} finally {
|
||||
await fake.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("reconciles V8 script presence with static Application Graph Evidence", () => {
|
||||
const root = "/Applications/Example.app/Contents/Resources/app";
|
||||
const observation = runtimeObservation(
|
||||
`${root}/index.html`,
|
||||
`${root}/renderer.js`,
|
||||
);
|
||||
const runtimeEvidence = createJavaScriptRuntimeObservationEvidence(
|
||||
"observe_javascript_runtime",
|
||||
{
|
||||
inspector_endpoint: "http://127.0.0.1:9229",
|
||||
allowed_file_roots: [root],
|
||||
allowed_origins: [],
|
||||
target_id: "example-v8-target",
|
||||
runtime_kind: "electron-main",
|
||||
approved: true,
|
||||
observation_ms: 100,
|
||||
limits: {
|
||||
max_events: 10_000,
|
||||
max_scripts: 2_000,
|
||||
max_execution_contexts: 1_000,
|
||||
max_location_bytes: 16_384,
|
||||
max_total_metadata_bytes: 4_194_304,
|
||||
},
|
||||
},
|
||||
observation,
|
||||
V8_INSPECTOR_PROVIDER_IDENTITY,
|
||||
);
|
||||
const reconciled = reconcileJavaScriptRuntimeEvidence({
|
||||
static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers,
|
||||
runtime_observations: [runtimeEvidence],
|
||||
});
|
||||
expect(reconciled.ok).toBe(true);
|
||||
if (!reconciled.ok) return;
|
||||
const result = javascriptRuntimeReconciliationResultSchema.parse(
|
||||
reconciled.value.normalized_result,
|
||||
);
|
||||
expect(result.runtime_captures[0]?.kind).toBe("v8-inspector");
|
||||
expect(result.summary.runtime_scripts).toBe(1);
|
||||
expect(result.summary.matched).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
const runtimeFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-v8-runtime-");
|
||||
const entry = join(root, "entry.js");
|
||||
await writeFile(entry, "export const value = 1;\n");
|
||||
return { root, entry };
|
||||
};
|
||||
|
||||
const temporaryFile = async (name: string): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-v8-outside-");
|
||||
const path = join(root, name);
|
||||
await writeFile(path, "export {};\n");
|
||||
return path;
|
||||
};
|
||||
|
||||
const observeInput = (
|
||||
endpoint: string,
|
||||
targetId: string,
|
||||
root: string,
|
||||
runtimeKind: ObserveJavaScriptRuntimeInput["runtime_kind"],
|
||||
): ObserveJavaScriptRuntimeInput => ({
|
||||
inspector_endpoint: endpoint,
|
||||
allowed_file_roots: [root],
|
||||
allowed_origins: [],
|
||||
target_id: targetId,
|
||||
runtime_kind: runtimeKind,
|
||||
approved: true,
|
||||
observation_ms: 10,
|
||||
limits: {
|
||||
max_events: 10_000,
|
||||
max_scripts: 2_000,
|
||||
max_execution_contexts: 1_000,
|
||||
max_location_bytes: 16_384,
|
||||
max_total_metadata_bytes: 4_194_304,
|
||||
},
|
||||
});
|
||||
|
||||
const authorityFor = async (endpoint: string, root: string) => {
|
||||
const scope: PermissionCeiling = {
|
||||
capability: "v8_inspector_observe",
|
||||
roots: [root],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: [endpoint],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
};
|
||||
const grant: PermissionGrant = {
|
||||
...scope,
|
||||
grant_id: "test:v8-inspector",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
};
|
||||
const authority = await createPermissionAuthority([scope], [grant]);
|
||||
if (!authority.ok) throw authority.error;
|
||||
return authority.value;
|
||||
};
|
||||
|
||||
const runtimeObservation = (
|
||||
targetPath: string,
|
||||
scriptPath: string,
|
||||
): JavaScriptRuntimeObservation => ({
|
||||
schema_version: 1,
|
||||
runtime: {
|
||||
product: "node.js/v24.4.1",
|
||||
protocol_version: "1.3",
|
||||
v8_version: "13.6",
|
||||
},
|
||||
target: {
|
||||
target_id: "example-v8-target",
|
||||
protocol_type: "node",
|
||||
attached: false,
|
||||
location: { kind: "file", file_path: targetPath },
|
||||
runtime_kind: "electron-main",
|
||||
runtime_kind_authority: "caller-declared-unverified",
|
||||
},
|
||||
capture: {
|
||||
observation_ms: 100,
|
||||
events_observed: 1,
|
||||
events_retained: 1,
|
||||
events_dropped: 0,
|
||||
metadata_bytes_retained: 100,
|
||||
truncated: false,
|
||||
truncation_reasons: [],
|
||||
},
|
||||
scripts: {
|
||||
items: [
|
||||
{
|
||||
script_key: `v8_script_${"4".repeat(64)}`,
|
||||
location: { kind: "file", file_path: scriptPath },
|
||||
execution_context_key: "1",
|
||||
cdp_hash: "v8-hash",
|
||||
length: 29,
|
||||
is_module: true,
|
||||
status: "observed-loaded",
|
||||
},
|
||||
],
|
||||
observed_total: 1,
|
||||
excluded: {
|
||||
outside_file_roots: 0,
|
||||
outside_origins: 0,
|
||||
unsupported_location: 0,
|
||||
invalid_protocol_value: 0,
|
||||
},
|
||||
},
|
||||
execution_contexts: [],
|
||||
directly_observed: ["Debugger.scriptParsed established script presence."],
|
||||
unavailable_without_instrumentation: [
|
||||
"require/import caller-to-callee edges",
|
||||
],
|
||||
unknowns: ["Capture is bounded."],
|
||||
limitations: ["Passive Inspector metadata only."],
|
||||
});
|
||||
@@ -0,0 +1,388 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BrowserScenarioSessionPort } from "../../../src/browser/BrowserScenarioSessionPort.js";
|
||||
import { PlaywrightBrowserScenarioProvider } from "../../../src/browser/PlaywrightBrowserScenarioProvider.js";
|
||||
import { BrowserScenarioCaptureBudget } from "../../../src/browser/PlaywrightScenarioArtifacts.js";
|
||||
import { sanitizeBrowserUrl } from "../../../src/domain/browserObservation.js";
|
||||
import {
|
||||
browserScenarioSchema,
|
||||
type BrowserScenario,
|
||||
type BrowserScenarioAction,
|
||||
} from "../../../src/domain/browserScenario.js";
|
||||
import {
|
||||
browserStepArtifactsSchema,
|
||||
type BrowserScenarioEvent,
|
||||
type BrowserStepArtifacts,
|
||||
} from "../../../src/domain/browserScenarioCapture.js";
|
||||
|
||||
const scenario = (
|
||||
options: {
|
||||
readonly mode?: "launch" | "connect";
|
||||
readonly captures?: readonly (
|
||||
| "screenshot"
|
||||
| "dom"
|
||||
| "accessibility"
|
||||
| "url"
|
||||
| "history"
|
||||
| "storage"
|
||||
)[];
|
||||
readonly events?: readonly (
|
||||
| "console"
|
||||
| "page-errors"
|
||||
| "network"
|
||||
| "websockets"
|
||||
| "frames"
|
||||
| "workers"
|
||||
| "popups"
|
||||
| "downloads"
|
||||
)[];
|
||||
readonly actions?: number;
|
||||
} = {},
|
||||
): BrowserScenario =>
|
||||
browserScenarioSchema.parse({
|
||||
schema_version: 1,
|
||||
browser:
|
||||
options.mode === "connect"
|
||||
? {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
ownership: "external",
|
||||
cleanup: "disconnect-only",
|
||||
}
|
||||
: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: Array.from({ length: options.actions ?? 1 }, (_, index) => ({
|
||||
step_id: `wait_${index}`,
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 1,
|
||||
})),
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: options.captures ?? ["url"],
|
||||
at_end: [],
|
||||
events: options.events ?? [],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 100,
|
||||
max_frames: 10,
|
||||
max_workers: 10,
|
||||
max_popups: 10,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 100,
|
||||
max_accessibility_nodes: 100,
|
||||
max_screenshots: 2,
|
||||
max_screenshot_bytes: 1_024,
|
||||
max_storage_entries: 10,
|
||||
max_total_metadata_bytes: 16_384,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
|
||||
|
||||
const artifactState = (
|
||||
kind: SnapshotKind,
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
incomplete: boolean,
|
||||
) => {
|
||||
if (!requested.has(kind)) return { state: "not_requested" as const };
|
||||
if (kind === "url")
|
||||
return {
|
||||
state: "captured" as const,
|
||||
value: sanitizeBrowserUrl("https://app.example.test/current"),
|
||||
};
|
||||
if (incomplete && kind === "screenshot")
|
||||
return {
|
||||
state: "truncated" as const,
|
||||
observed: 2_048,
|
||||
retained: 0,
|
||||
reason: "fixture limit",
|
||||
};
|
||||
return { state: "missing" as const, reason: "fixture unavailable" };
|
||||
};
|
||||
|
||||
class FakeSession implements BrowserScenarioSessionPort {
|
||||
readonly product = "Fake Chromium";
|
||||
readonly version = "1";
|
||||
readonly initialUrl = "about:blank";
|
||||
readonly processOwnership: "provider-owned" | "external";
|
||||
closeCalls = 0;
|
||||
performCalls = 0;
|
||||
captureCalls = 0;
|
||||
eventTruncations: (
|
||||
| "events"
|
||||
| "frames"
|
||||
| "workers"
|
||||
| "popups"
|
||||
| "websockets"
|
||||
)[] = [];
|
||||
onPerform: (() => void) | undefined;
|
||||
private step = 0;
|
||||
|
||||
constructor(
|
||||
readonly mode: "launch" | "connect",
|
||||
private readonly incomplete = false,
|
||||
private readonly failAction = false,
|
||||
private readonly failCapture = false,
|
||||
) {
|
||||
this.processOwnership = mode === "launch" ? "provider-owned" : "external";
|
||||
}
|
||||
|
||||
currentUrl() {
|
||||
return "https://app.example.test/current";
|
||||
}
|
||||
|
||||
setStep(index: number) {
|
||||
this.step = index;
|
||||
}
|
||||
|
||||
nextEventSequence() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
lastEventSequence() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
events(): {
|
||||
readonly retained: number;
|
||||
readonly dropped: number;
|
||||
readonly items: readonly BrowserScenarioEvent[];
|
||||
} {
|
||||
return { retained: 0, dropped: 0, items: [] };
|
||||
}
|
||||
|
||||
eventTruncationSections() {
|
||||
return this.eventTruncations;
|
||||
}
|
||||
|
||||
async perform(
|
||||
_action: BrowserScenarioAction,
|
||||
_timeout: number,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
this.performCalls += 1;
|
||||
this.onPerform?.();
|
||||
if (signal?.aborted === true) throw new Error("request cancelled");
|
||||
if (this.failAction) throw new Error("fixture secret action failure");
|
||||
}
|
||||
|
||||
capture(
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
_budget: BrowserScenarioCaptureBudget,
|
||||
): Promise<BrowserStepArtifacts> {
|
||||
this.captureCalls += 1;
|
||||
if (this.failCapture) return Promise.reject(new Error("capture failed"));
|
||||
return Promise.resolve(
|
||||
browserStepArtifactsSchema.parse({
|
||||
screenshot: artifactState("screenshot", requested, this.incomplete),
|
||||
dom: artifactState("dom", requested, this.incomplete),
|
||||
accessibility: artifactState(
|
||||
"accessibility",
|
||||
requested,
|
||||
this.incomplete,
|
||||
),
|
||||
url: artifactState("url", requested, this.incomplete),
|
||||
history: artifactState("history", requested, this.incomplete),
|
||||
storage: artifactState("storage", requested, this.incomplete),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closeCalls += 1;
|
||||
return Promise.resolve(
|
||||
this.mode === "launch"
|
||||
? ("terminated-owned-process" as const)
|
||||
: ("disconnected-external" as const),
|
||||
);
|
||||
}
|
||||
|
||||
redactError(error: unknown) {
|
||||
return error instanceof Error
|
||||
? error.message.replaceAll("secret", "[REDACTED]")
|
||||
: "fixture failure";
|
||||
}
|
||||
}
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
it("captures initial and action steps and closes its launched session", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario());
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps.map(({ step_index }) => step_index)).toEqual([
|
||||
0, 1,
|
||||
]);
|
||||
expect(result.value.browser).toMatchObject({
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
});
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("makes missing and truncated captures ineligible for equality", async () => {
|
||||
const session = new FakeSession("launch", true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ captures: ["screenshot", "dom"] }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["dom"],
|
||||
truncated_sections: ["screenshot"],
|
||||
});
|
||||
});
|
||||
|
||||
it("makes event limit truncation ineligible for equality", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
session.eventTruncations = ["events", "websockets"];
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ events: ["websockets"] }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
truncated_sections: ["events", "websockets"],
|
||||
});
|
||||
});
|
||||
|
||||
it("records one failed step, cancels later actions, and still cleans up", async () => {
|
||||
const session = new FakeSession("launch", false, true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario({ actions: 2 }));
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps.map(({ status }) => status)).toEqual([
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
]);
|
||||
expect(result.value.steps[1]?.error).toBe(
|
||||
"fixture [REDACTED] action failure",
|
||||
);
|
||||
expect(session.performCalls).toBe(1);
|
||||
expect(session.closeCalls).toBe(1);
|
||||
expect(result.value.completeness.equality_eligible).toBe(false);
|
||||
});
|
||||
|
||||
it("disconnects external CDP sessions and marks pre-attach events missing", async () => {
|
||||
const session = new FakeSession("connect");
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ mode: "connect" }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.browser).toMatchObject({
|
||||
process_ownership: "external",
|
||||
cleanup: "disconnected-external",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "incomplete",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["events"],
|
||||
});
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("closes the session when initial capture fails", async () => {
|
||||
const session = new FakeSession("launch", false, false, true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario());
|
||||
expect(result.ok).toBe(false);
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("does not open a session for an already-cancelled request", async () => {
|
||||
let opens = 0;
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => {
|
||||
opens += 1;
|
||||
return Promise.resolve(new FakeSession("launch"));
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const result = await provider.captureScenario(scenario(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(opens).toBe(0);
|
||||
});
|
||||
|
||||
it("cancels an active action and still closes the session", async () => {
|
||||
const controller = new AbortController();
|
||||
const session = new FakeSession("launch");
|
||||
session.onPerform = () => controller.abort();
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps[1]?.status).toBe("cancelled");
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BrowserScenarioCaptureBudget", () => {
|
||||
it("enforces cumulative screenshot and metadata limits", () => {
|
||||
const budget = new BrowserScenarioCaptureBudget(1, 10);
|
||||
expect(budget.claimScreenshot()).toBe(true);
|
||||
expect(budget.claimScreenshot()).toBe(false);
|
||||
expect(budget.claimMetadata(6)).toBe(true);
|
||||
expect(budget.claimMetadata(5)).toBe(false);
|
||||
expect(budget.claimMetadata(4)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { withPlaywrightExecutionBoundary } from "../../../src/browser/PlaywrightExecutionBoundary.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../../../src/domain/errors.js";
|
||||
|
||||
describe("withPlaywrightExecutionBoundary", () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("rejects work that exceeds its absolute remaining duration", async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = withPlaywrightExecutionBoundary(
|
||||
() => new Promise<never>(() => undefined),
|
||||
25,
|
||||
);
|
||||
const rejection =
|
||||
expect(result).rejects.toBeInstanceOf(AnalysisTimeoutError);
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
await rejection;
|
||||
});
|
||||
|
||||
it("rejects when the caller cancels active work", async () => {
|
||||
const controller = new AbortController();
|
||||
const result = withPlaywrightExecutionBoundary(
|
||||
() => new Promise<never>(() => undefined),
|
||||
1_000,
|
||||
controller.signal,
|
||||
);
|
||||
controller.abort();
|
||||
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Page } from "playwright-core";
|
||||
|
||||
import { BrowserScenarioSecrets } from "../../../src/browser/BrowserScenarioSecrets.js";
|
||||
import { BrowserScenarioCaptureBudget } from "../../../src/browser/PlaywrightScenarioArtifacts.js";
|
||||
import { PlaywrightScenarioEvents } from "../../../src/browser/PlaywrightScenarioEvents.js";
|
||||
import { browserScenarioSchema } from "../../../src/domain/browserScenario.js";
|
||||
|
||||
describe("PlaywrightScenarioEvents", () => {
|
||||
it("bounds oversized page errors before validating captured events", () => {
|
||||
const listeners = new Map<string, (value: Error) => void>();
|
||||
const page = {
|
||||
url: () => "https://app.example.test/",
|
||||
on: (name: string, listener: (value: Error) => void) => {
|
||||
listeners.set(name, listener);
|
||||
},
|
||||
} as unknown as Page;
|
||||
const scenario = browserScenarioSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "wait",
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 1,
|
||||
},
|
||||
],
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: [],
|
||||
at_end: [],
|
||||
events: ["page-errors"],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 10,
|
||||
max_frames: 10,
|
||||
max_workers: 10,
|
||||
max_popups: 10,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 100,
|
||||
max_accessibility_nodes: 100,
|
||||
max_screenshots: 1,
|
||||
max_screenshot_bytes: 1_024,
|
||||
max_storage_entries: 10,
|
||||
max_total_metadata_bytes: 1_000_000,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
|
||||
if (secrets === undefined) throw new Error("Expected resolved secrets");
|
||||
const events = new PlaywrightScenarioEvents({
|
||||
page,
|
||||
enabled: new Set(["page-errors"]),
|
||||
limits: scenario.limits,
|
||||
secrets,
|
||||
budget: new BrowserScenarioCaptureBudget(1, 1_000_000),
|
||||
allowedOrigins: scenario.allowed_origins,
|
||||
});
|
||||
const error = new Error("m".repeat(70_000));
|
||||
error.stack = "s".repeat(300_000);
|
||||
|
||||
expect(() => listeners.get("pageerror")?.(error)).not.toThrow();
|
||||
expect(events.result().items[0]).toMatchObject({
|
||||
kind: "page-error",
|
||||
message: "m".repeat(65_536),
|
||||
stack: "s".repeat(262_144),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyProtocolFamily,
|
||||
decodeGrpcFrame,
|
||||
decodeJsonRpc,
|
||||
decodeMessagePack,
|
||||
inferMessageSchema,
|
||||
looksLikeCredential,
|
||||
protocolCaptureSchema,
|
||||
type ProtocolMessage,
|
||||
type ProtocolCapture,
|
||||
} from "../../../src/domain/protocolCapture.js";
|
||||
|
||||
describe("protocol capture", () => {
|
||||
it("classifies gRPC from content type", () => {
|
||||
expect(classifyProtocolFamily("application/grpc+proto", null)).toBe("grpc");
|
||||
});
|
||||
|
||||
it("classifies protobuf from content type", () => {
|
||||
expect(classifyProtocolFamily("application/x-protobuf", null)).toBe(
|
||||
"protobuf",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies json-rpc from content type", () => {
|
||||
expect(classifyProtocolFamily("application/json-rpc", null)).toBe(
|
||||
"json-rpc",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies msgpack from content type", () => {
|
||||
expect(classifyProtocolFamily("application/msgpack", null)).toBe(
|
||||
"messagepack",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies from path when content type is null", () => {
|
||||
expect(classifyProtocolFamily(null, "/some/grpc/method")).toBe("grpc");
|
||||
expect(classifyProtocolFamily(null, "/api/json-rpc/2.0")).toBe("json-rpc");
|
||||
});
|
||||
|
||||
it("returns null for unknown protocols", () => {
|
||||
expect(classifyProtocolFamily("text/plain", null)).toBeNull();
|
||||
expect(classifyProtocolFamily(null, null)).toBeNull();
|
||||
});
|
||||
|
||||
it("detects credential-like field names", () => {
|
||||
expect(looksLikeCredential("password")).toBe(true);
|
||||
expect(looksLikeCredential("api_key")).toBe(true);
|
||||
expect(looksLikeCredential("authorization")).toBe(true);
|
||||
expect(looksLikeCredential("username")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JSON-RPC decoding", () => {
|
||||
it("decodes a simple JSON-RPC request", () => {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
method: "add",
|
||||
params: [1, 2],
|
||||
id: 1,
|
||||
}),
|
||||
);
|
||||
const result = decodeJsonRpc(payload);
|
||||
expect(result.decoded_fields.length).toBe(4);
|
||||
expect(result.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it("redacts credential-like fields", () => {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
password: "secret123",
|
||||
username: "admin",
|
||||
}),
|
||||
);
|
||||
const result = decodeJsonRpc(payload);
|
||||
const passwordField = result.decoded_fields.find(
|
||||
(f) => f.path === "password",
|
||||
);
|
||||
expect(passwordField?.value).toBe("[REDACTED]");
|
||||
const usernameField = result.decoded_fields.find(
|
||||
(f) => f.path === "username",
|
||||
);
|
||||
expect(usernameField?.value).toBe("admin");
|
||||
});
|
||||
});
|
||||
|
||||
describe("MessagePack decoding", () => {
|
||||
it("detects map type", () => {
|
||||
const payload = new Uint8Array([0x82]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("map");
|
||||
});
|
||||
|
||||
it("detects array type", () => {
|
||||
const payload = new Uint8Array([0x92]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("array");
|
||||
});
|
||||
|
||||
it("reports unknown type for other tags", () => {
|
||||
const payload = new Uint8Array([0xff]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("unknown");
|
||||
expect(result.decoded_fields[0]?.inferred).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("gRPC frame decoding", () => {
|
||||
it("decodes a valid gRPC frame header", () => {
|
||||
const payload = new Uint8Array([
|
||||
0x00, 0x00, 0x00, 0x00, 0x05, 1, 2, 3, 4, 5,
|
||||
]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields).toHaveLength(2);
|
||||
expect(result.decoded_fields[0]?.path).toBe("compressed");
|
||||
expect(result.decoded_fields[0]?.value).toBe(false);
|
||||
expect(result.decoded_fields[1]?.path).toBe("message_length");
|
||||
expect(result.decoded_fields[1]?.value).toBe(5);
|
||||
});
|
||||
|
||||
it("detects compressed flag", () => {
|
||||
const payload = new Uint8Array([0x01, 0x00, 0x00, 0x00, 0x0a]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe(true);
|
||||
});
|
||||
|
||||
it("handles too-short frames", () => {
|
||||
const payload = new Uint8Array([0x00, 0x01]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields[0]?.path).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("schema inference", () => {
|
||||
it("infers schema from repeated messages", () => {
|
||||
const messages: ProtocolMessage[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
family: "json-rpc",
|
||||
direction: "request",
|
||||
endpoint: "/api",
|
||||
content_type: "application/json",
|
||||
raw_payload: null,
|
||||
decoded_fields: [
|
||||
{ path: "method", wire_type: "json", value: "add", inferred: false },
|
||||
{ path: "id", wire_type: "json", value: 1, inferred: false },
|
||||
],
|
||||
schema_hypotheses: [],
|
||||
truncated: false,
|
||||
credentials_redacted: false,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
family: "json-rpc",
|
||||
direction: "response",
|
||||
endpoint: "/api",
|
||||
content_type: "application/json",
|
||||
raw_payload: null,
|
||||
decoded_fields: [
|
||||
{ path: "result", wire_type: "json", value: 3, inferred: false },
|
||||
{ path: "id", wire_type: "json", value: 1, inferred: false },
|
||||
],
|
||||
schema_hypotheses: [],
|
||||
truncated: false,
|
||||
credentials_redacted: false,
|
||||
},
|
||||
];
|
||||
const hypotheses = inferMessageSchema(messages);
|
||||
expect(hypotheses).toHaveLength(3);
|
||||
const idHypothesis = hypotheses.find((h) => h.field_name === "id");
|
||||
expect(idHypothesis).toBeDefined();
|
||||
expect(idHypothesis!.evidence_count).toBe(2);
|
||||
expect(idHypothesis!.confidence).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("uses ProtocolCapture type", () => {
|
||||
it("validates a well-formed capture typed value", () => {
|
||||
const capture: ProtocolCapture = {
|
||||
family: "grpc",
|
||||
messages: [],
|
||||
inferred_schema: [],
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
expect(capture.family).toBe("grpc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("protocol capture schema validation", () => {
|
||||
it("validates a well-formed capture", () => {
|
||||
const capture = {
|
||||
family: "grpc" as const,
|
||||
messages: [],
|
||||
inferred_schema: [],
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
const result = protocolCaptureSchema.safeParse(capture);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,266 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { fetchWebSourceMaps } from "../../../src/browser/WebSourceMapFetcher.js";
|
||||
import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
const request = {
|
||||
scriptKey: `scr_${"1".repeat(64)}`,
|
||||
declaredUrl: `${origin}/assets/app.js.map?token=%5BREDACTED%5D`,
|
||||
fetchUrl: `${origin}/assets/app.js.map?token=secret`,
|
||||
};
|
||||
|
||||
describe("web source-map fetching and validation", () => {
|
||||
it("fetches without credentials and derives mappings and original modules", async () => {
|
||||
const calls: Array<{ url: string; init: RequestInit | undefined }> = [];
|
||||
const map = JSON.stringify({
|
||||
version: 3,
|
||||
file: "app.js",
|
||||
names: ["entry"],
|
||||
sources: ["../src/main.ts"],
|
||||
sourcesContent: ["import './dependency.ts';\nexport const entry = 1;"],
|
||||
mappings: "AAAAA",
|
||||
});
|
||||
const result = await fetchWebSourceMaps([request], input(), undefined, {
|
||||
fetch: (url, init) => {
|
||||
calls.push({ url: String(url), init });
|
||||
return Promise.resolve(
|
||||
new Response(map, {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]).toMatchObject({
|
||||
url: request.fetchUrl,
|
||||
init: {
|
||||
credentials: "omit",
|
||||
redirect: "manual",
|
||||
referrerPolicy: "no-referrer",
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(calls[0]?.init)).not.toContain("secret");
|
||||
expect(result).toMatchObject({
|
||||
status: "included",
|
||||
requested: 1,
|
||||
processed: 1,
|
||||
dropped: 0,
|
||||
dropped_script_keys: [],
|
||||
items: [
|
||||
{
|
||||
status: "included",
|
||||
artifact: { media_type: "application/source-map+json" },
|
||||
original_sources: [
|
||||
{
|
||||
source: `${origin}/src/main.ts`,
|
||||
artifact: { media_type: "text/typescript" },
|
||||
},
|
||||
],
|
||||
original_module_edges: [
|
||||
{
|
||||
kind: "static_import",
|
||||
specifier: "./dependency.ts",
|
||||
resolved_source: `${origin}/src/dependency.ts`,
|
||||
},
|
||||
],
|
||||
mappings: [
|
||||
{
|
||||
generated_line: 1,
|
||||
generated_column: 0,
|
||||
original_line: 1,
|
||||
original_column: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("validates sectioned maps and reports bounded mapping truncation", async () => {
|
||||
const regular = {
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["a.js"],
|
||||
sourcesContent: ["export const a = 1"],
|
||||
mappings: "AAAA;AACA",
|
||||
};
|
||||
const result = await fetchWebSourceMaps(
|
||||
[request],
|
||||
input({ analysis_limits: { max_source_map_mappings: 1 } }),
|
||||
undefined,
|
||||
{
|
||||
fetch: () =>
|
||||
Promise.resolve(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
sections: [{ offset: { line: 0, column: 0 }, map: regular }],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "truncated",
|
||||
items: [
|
||||
{
|
||||
status: "truncated",
|
||||
mappings: [expect.any(Object)],
|
||||
limitation: expect.stringContaining("truncated from 2 to 1"),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reauthorizes every redirect and never contacts a disallowed origin", async () => {
|
||||
const calls: string[] = [];
|
||||
const result = await fetchWebSourceMaps([request], input(), undefined, {
|
||||
fetch: (url) => {
|
||||
calls.push(String(url));
|
||||
return Promise.resolve(
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: "https://private.example.test/map" },
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
expect(calls).toEqual([request.fetchUrl]);
|
||||
expect(result).toMatchObject({
|
||||
status: "unavailable",
|
||||
items: [{ status: "policy_filtered" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("distinguishes invalid JSON from declared or streamed byte truncation", async () => {
|
||||
for (const response of [
|
||||
new Response("not-json", { status: 200 }),
|
||||
new Response("{}", {
|
||||
status: 200,
|
||||
headers: { "content-length": "999999" },
|
||||
}),
|
||||
]) {
|
||||
const result = await fetchWebSourceMaps(
|
||||
[request],
|
||||
input({ analysis_limits: { max_source_map_bytes: 100 } }),
|
||||
undefined,
|
||||
{ fetch: () => Promise.resolve(response) },
|
||||
);
|
||||
expect(result.items[0]?.status).toBe(
|
||||
response.headers.has("content-length") ? "truncated" : "invalid",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("web source-map aggregate limits", () => {
|
||||
it("bounds aggregate map count and reports omitted requests", async () => {
|
||||
const calls: string[] = [];
|
||||
const requests = [0, 1, 2].map((index) => ({
|
||||
...request,
|
||||
scriptKey: `scr_${String(index + 1).repeat(64)}`,
|
||||
fetchUrl: `${origin}/assets/${String(index)}.js.map`,
|
||||
}));
|
||||
const result = await fetchWebSourceMaps(
|
||||
requests,
|
||||
input({ analysis_limits: { max_source_maps: 1 } }),
|
||||
undefined,
|
||||
{
|
||||
fetch: (url) => {
|
||||
calls.push(String(url));
|
||||
return Promise.resolve(validMapResponse());
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(calls).toEqual([requests[0]?.fetchUrl]);
|
||||
expect(result).toMatchObject({
|
||||
status: "truncated",
|
||||
requested: 3,
|
||||
processed: 1,
|
||||
dropped: 2,
|
||||
dropped_script_keys: [requests[1]?.scriptKey, requests[2]?.scriptKey],
|
||||
});
|
||||
});
|
||||
|
||||
it("stops after exhausting the aggregate response-byte budget", async () => {
|
||||
const requests = [0, 1, 2].map((index) => ({
|
||||
...request,
|
||||
scriptKey: `scr_${String(index + 1).repeat(64)}`,
|
||||
fetchUrl: `${origin}/assets/${String(index)}.js.map`,
|
||||
}));
|
||||
const calls: string[] = [];
|
||||
const result = await fetchWebSourceMaps(
|
||||
requests,
|
||||
input({
|
||||
analysis_limits: {
|
||||
max_source_map_bytes: 128,
|
||||
max_total_source_map_bytes: 128,
|
||||
},
|
||||
}),
|
||||
undefined,
|
||||
{
|
||||
fetch: (url) => {
|
||||
calls.push(String(url));
|
||||
return Promise.resolve(validMapResponse());
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(result).toMatchObject({
|
||||
status: "truncated",
|
||||
requested: 3,
|
||||
processed: 2,
|
||||
dropped: 1,
|
||||
dropped_script_keys: [requests[2]?.scriptKey],
|
||||
items: [{ status: "included" }, { status: "truncated" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a per-map byte limit larger than the aggregate limit", () => {
|
||||
const parsed = analyzeWebBundleInputSchema.safeParse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: [origin],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
source_capture_approved: true,
|
||||
analysis_limits: {
|
||||
max_source_map_bytes: 2,
|
||||
max_total_source_map_bytes: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const validMapResponse = () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["a.js"],
|
||||
sourcesContent: ["export const a = 1"],
|
||||
mappings: "AAAA",
|
||||
}),
|
||||
{ status: 200 },
|
||||
);
|
||||
|
||||
const input = (overrides: Record<string, unknown> = {}) =>
|
||||
analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: [origin],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
source_capture_approved: true,
|
||||
fetch_source_maps: true,
|
||||
source_map_fetch_approved: true,
|
||||
...overrides,
|
||||
});
|
||||
@@ -0,0 +1,387 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const INTEGRATION_TEST_TIMEOUT_MS = 60_000;
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
});
|
||||
|
||||
describe("browser CLI parity", () => {
|
||||
it(
|
||||
"returns the same Evidence v2 discovery and inspection contracts",
|
||||
async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "same_origin",
|
||||
webMcpTools: true,
|
||||
sensitiveShapes: true,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_BROWSER_OBSERVE_ENABLED: "true",
|
||||
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
|
||||
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([
|
||||
browser.allowedOrigin,
|
||||
]),
|
||||
};
|
||||
const listed = await runCli(
|
||||
["list-browser-targets", browser.endpoint, "--approved", "--json"],
|
||||
environment,
|
||||
);
|
||||
expect(listed).toMatchObject({
|
||||
operation: "list_browser_targets",
|
||||
provider: { id: "rea-cdp-browser" },
|
||||
normalized_result: {
|
||||
targets: { items: [{ target_id: "allowed-page" }] },
|
||||
},
|
||||
});
|
||||
const inspected = await runCli(
|
||||
[
|
||||
"inspect-web-page",
|
||||
browser.endpoint,
|
||||
"allowed-page",
|
||||
"--approved",
|
||||
"--observation-ms",
|
||||
"0",
|
||||
"--include-console-text",
|
||||
"--console-text-approved",
|
||||
"--include-json-body-shapes",
|
||||
"--json-body-schema-approved",
|
||||
"--include-websocket-shapes",
|
||||
"--websocket-shape-approved",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(inspected).toMatchObject({
|
||||
operation: "inspect_web_page",
|
||||
provider: { id: "rea-cdp-browser" },
|
||||
normalized_result: {
|
||||
target: { target_id: "allowed-page" },
|
||||
network: {
|
||||
prior_activity_available: false,
|
||||
requests: [
|
||||
expect.objectContaining({
|
||||
body_shapes: expect.objectContaining({ status: "included" }),
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const inspection = normalizedResult(inspected);
|
||||
const compared = await runCli(
|
||||
[
|
||||
"compare-web-captures",
|
||||
JSON.stringify({ inspection }),
|
||||
JSON.stringify({ inspection }),
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(compared).toMatchObject({
|
||||
operation: "compare_web_captures",
|
||||
normalized_result: {
|
||||
overall_status: "unknown",
|
||||
dimensions: {
|
||||
network: { status: "unknown", total_changes: 0 },
|
||||
},
|
||||
},
|
||||
});
|
||||
const scenarioCapture = completeScenarioCapture();
|
||||
const scenarioCompared = await runCli(
|
||||
[
|
||||
"compare-web-captures",
|
||||
JSON.stringify(scenarioCapture),
|
||||
JSON.stringify(scenarioCapture),
|
||||
"--normalization-json",
|
||||
'{"rules":[]}',
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(scenarioCompared).toMatchObject({
|
||||
operation: "compare_web_captures",
|
||||
normalized_result: {
|
||||
comparison_kind: "browser_scenario",
|
||||
overall_status: "unchanged",
|
||||
alignment: { status: "aligned", aligned_steps: 2 },
|
||||
},
|
||||
});
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser CLI capture parity", () => {
|
||||
it(
|
||||
"returns the same analysis, session, WebMCP, screenshot, and policy contracts",
|
||||
async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "same_origin",
|
||||
webMcpTools: true,
|
||||
sensitiveShapes: true,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_BROWSER_OBSERVE_ENABLED: "true",
|
||||
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
|
||||
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([
|
||||
browser.allowedOrigin,
|
||||
]),
|
||||
};
|
||||
const analyzed = await runCli(
|
||||
[
|
||||
"analyze-web-bundle",
|
||||
browser.endpoint,
|
||||
"allowed-page",
|
||||
"--approved",
|
||||
"--source-capture-approved",
|
||||
"--observation-ms",
|
||||
"0",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(analyzed).toMatchObject({
|
||||
operation: "analyze_web_bundle",
|
||||
normalized_result: {
|
||||
capture: { scripts_analyzed: 1 },
|
||||
observations: { source_maps: { status: "not_requested" } },
|
||||
},
|
||||
});
|
||||
const observedSession = await runCli(
|
||||
[
|
||||
"observe-web-session",
|
||||
browser.endpoint,
|
||||
"allowed-page",
|
||||
"--approved",
|
||||
"--observation-ms",
|
||||
"5",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(observedSession).toMatchObject({
|
||||
operation: "observe_web_session",
|
||||
normalized_result: {
|
||||
window: { end_reason: "window_elapsed" },
|
||||
timeline: expect.arrayContaining([
|
||||
expect.objectContaining({ type: "same_origin_reload" }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
const webMcp = await runCli(
|
||||
[
|
||||
"discover-webmcp-tools",
|
||||
browser.endpoint,
|
||||
"allowed-page",
|
||||
"--approved",
|
||||
"--observation-ms",
|
||||
"0",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(webMcp).toMatchObject({
|
||||
operation: "discover_webmcp_tools",
|
||||
normalized_result: {
|
||||
tools: {
|
||||
items: [expect.objectContaining({ name: "search_orders" })],
|
||||
},
|
||||
},
|
||||
});
|
||||
const screenshot = await runCli(
|
||||
[
|
||||
"capture-web-screenshot",
|
||||
browser.endpoint,
|
||||
"allowed-page",
|
||||
"--approved",
|
||||
"--screenshot-approved",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
const artifact = screenshotArtifact(screenshot);
|
||||
expect(artifact).toMatchObject({ media_type: "image/png", bytes: 70 });
|
||||
const visual = await runCli(
|
||||
[
|
||||
"compare-web-screenshots",
|
||||
JSON.stringify(artifact),
|
||||
JSON.stringify(artifact),
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(visual).toMatchObject({
|
||||
operation: "compare_web_screenshots",
|
||||
normalized_result: { status: "identical", changed_pixels: 0 },
|
||||
});
|
||||
const policy = await runCli(
|
||||
[
|
||||
"policy",
|
||||
"explain",
|
||||
"browser_observe",
|
||||
"--origins",
|
||||
browser.endpoint,
|
||||
"--origins",
|
||||
browser.allowedOrigin,
|
||||
"--network",
|
||||
"loopback",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(policy).toEqual({
|
||||
allowed: true,
|
||||
grant_id: "administrator:browser_observe",
|
||||
});
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser CLI approval", () => {
|
||||
it(
|
||||
"requires explicit approval before opening the CDP endpoint",
|
||||
async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
const result = await runCli(
|
||||
["list-browser-targets", browser.endpoint, "--json"],
|
||||
{
|
||||
...process.env,
|
||||
REA_BROWSER_OBSERVE_ENABLED: "true",
|
||||
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
|
||||
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([
|
||||
browser.allowedOrigin,
|
||||
]),
|
||||
},
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
error: "Browser observation failed",
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
});
|
||||
expect(browser.commands).toHaveLength(0);
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
const runCli = async (
|
||||
arguments_: readonly string[],
|
||||
environment: NodeJS.ProcessEnv,
|
||||
): Promise<unknown> => {
|
||||
try {
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
["scripts/rea.mjs", ...arguments_],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: environment,
|
||||
maxBuffer: 16 * 1_024 * 1_024,
|
||||
},
|
||||
);
|
||||
return JSON.parse(stdout);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"stdout" in cause &&
|
||||
typeof cause.stdout === "string"
|
||||
)
|
||||
return JSON.parse(cause.stdout);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const screenshotArtifact = (value: unknown): Record<string, unknown> => {
|
||||
if (
|
||||
!isRecord(value) ||
|
||||
!isRecord(value.normalized_result) ||
|
||||
!isRecord(value.normalized_result.artifact)
|
||||
)
|
||||
throw new TypeError("Missing CLI screenshot artifact");
|
||||
return value.normalized_result.artifact;
|
||||
};
|
||||
|
||||
const normalizedResult = (value: unknown): Record<string, unknown> => {
|
||||
if (!isRecord(value) || !isRecord(value.normalized_result))
|
||||
throw new TypeError("Missing CLI normalized result");
|
||||
return value.normalized_result;
|
||||
};
|
||||
|
||||
const completeScenarioCapture = () => {
|
||||
const url = {
|
||||
url: "https://app.example.test/",
|
||||
origin: "https://app.example.test",
|
||||
query_parameter_names: [],
|
||||
redacted: false,
|
||||
};
|
||||
const completeness = {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
};
|
||||
const artifacts = {
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "not_requested" },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "captured", value: url },
|
||||
history: { state: "not_requested" },
|
||||
storage: { state: "not_requested" },
|
||||
};
|
||||
const step = (stepIndex: number, stepId: string, action: string) => ({
|
||||
step_index: stepIndex,
|
||||
step_id: stepId,
|
||||
action,
|
||||
status: "completed",
|
||||
elapsed_ms: stepIndex,
|
||||
before_url: url,
|
||||
after_url: url,
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts,
|
||||
completeness,
|
||||
});
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "connect",
|
||||
process_ownership: "external",
|
||||
cleanup: "disconnected-external",
|
||||
product: "Chromium",
|
||||
version: "149",
|
||||
},
|
||||
scenario: {
|
||||
start_origin: "https://app.example.test",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
action_count: 1,
|
||||
secret_references: [],
|
||||
},
|
||||
duration_ms: 1,
|
||||
steps: [
|
||||
step(0, "scenario_start", "scenario_start"),
|
||||
step(1, "open-settings", "click"),
|
||||
],
|
||||
events: { retained: 0, dropped: 0, items: [] },
|
||||
completeness,
|
||||
limitations: [],
|
||||
};
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -0,0 +1,53 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
isCliOperationFailure,
|
||||
logCliCommand,
|
||||
} from "../../../src/cliLogging.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
|
||||
const originalExitCode = process.exitCode;
|
||||
|
||||
afterEach(() => {
|
||||
process.exitCode = originalExitCode;
|
||||
});
|
||||
|
||||
describe("CLI operation status", () => {
|
||||
it.each([
|
||||
["typed error", { error: "Analysis failed", category: "timeout" }],
|
||||
["unhealthy diagnostic", { healthy: false, checks: [] }],
|
||||
["failed status", { status: "failed" }],
|
||||
["confirmation requirement", { status: "needs_confirmation" }],
|
||||
["human remediation", { status: "needs_human" }],
|
||||
["unapplied plan", { status: "planned" }],
|
||||
])("classifies %s as failure", (_label, value) => {
|
||||
expect(isCliOperationFailure(value)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["ready setup", { status: "ready" }],
|
||||
["complete uninstall", { status: "complete" }],
|
||||
["current version", { status: "current" }],
|
||||
["completed upgrade", { status: "upgraded" }],
|
||||
["healthy diagnostics", { healthy: true, checks: [] }],
|
||||
["bounded evidence", { evidence: [{ truncated: true }] }],
|
||||
])("keeps %s successful", (_label, value) => {
|
||||
expect(isCliOperationFailure(value)).toBe(false);
|
||||
});
|
||||
|
||||
it("sets a nonzero process status without replacing structured output", async () => {
|
||||
const output = {
|
||||
error: "Analysis failed",
|
||||
category: "integrity_mismatch",
|
||||
message: "Artifact integrity check failed.",
|
||||
details: { logical_path: "main.js" },
|
||||
};
|
||||
|
||||
await expect(
|
||||
logCliCommand(silentLogger, "inventory-artifact", () =>
|
||||
Promise.resolve(output),
|
||||
),
|
||||
).resolves.toBe(output);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { fixtureTest } from "../../support/fixtures.js";
|
||||
|
||||
import {
|
||||
renderCliOutputArgumentError,
|
||||
sanitizeCliOutput,
|
||||
validateCliOutputArguments,
|
||||
} from "../../../src/cliOutput.js";
|
||||
|
||||
const CLI_INTEGRATION_TIMEOUT_MS = 60_000;
|
||||
const CLI_VARIANT_TIMEOUT_MS = 120_000;
|
||||
|
||||
describe("CLI output argument and sanitization boundary", () => {
|
||||
it("rejects token windows that would corrupt structured output", () => {
|
||||
for (const format of ["json", "jsonl", "yaml"] as const) {
|
||||
const validation = validateCliOutputArguments([
|
||||
"providers",
|
||||
"--token-limit",
|
||||
"5",
|
||||
"--format",
|
||||
format,
|
||||
]);
|
||||
expect(validation).toMatchObject({
|
||||
ok: false,
|
||||
format,
|
||||
code: "UNSUPPORTED_OUTPUT_COMBINATION",
|
||||
});
|
||||
if (!validation.ok) {
|
||||
const rendered = renderCliOutputArgumentError(validation);
|
||||
expect(rendered).not.toContain("[truncated:");
|
||||
if (format === "json" || format === "jsonl")
|
||||
expect(JSON.parse(rendered)).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
|
||||
});
|
||||
else
|
||||
expect(rendered).toMatch(
|
||||
/^ok: false\nerror:\n code: UNSUPPORTED_OUTPUT_COMBINATION\n/u,
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(
|
||||
validateCliOutputArguments([
|
||||
"providers",
|
||||
"--token-limit",
|
||||
"5",
|
||||
"--format",
|
||||
"toon",
|
||||
]),
|
||||
).toEqual({ ok: true });
|
||||
expect(
|
||||
validateCliOutputArguments(["providers", "--token-count", "--json"]),
|
||||
).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
fixtureTest(
|
||||
"fails before emitting a truncated JSON document",
|
||||
async ({ cli }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["providers", "--token-limit", "5", "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
|
||||
});
|
||||
},
|
||||
CLI_INTEGRATION_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it("preserves normal output and sanitizes text and JSON validation errors", () => {
|
||||
expect(sanitizeCliOutput("result: ok\n")).toBe("result: ok\n");
|
||||
expect(sanitizeCliOutput("result: VALIDATION_ERROR\n")).toBe(
|
||||
"result: VALIDATION_ERROR\n",
|
||||
);
|
||||
const raw =
|
||||
'code: VALIDATION_ERROR\nmessage: "raw Zod details"\nfieldErrors: SECRET\n';
|
||||
expect(sanitizeCliOutput(raw)).toBe(
|
||||
'code: VALIDATION_ERROR\nmessage: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
|
||||
);
|
||||
expect(
|
||||
JSON.parse(
|
||||
sanitizeCliOutput(
|
||||
JSON.stringify({
|
||||
code: "VALIDATION_ERROR",
|
||||
message: "raw Zod details",
|
||||
fieldErrors: [{ code: "invalid_type" }],
|
||||
}),
|
||||
),
|
||||
),
|
||||
).toEqual({
|
||||
code: "VALIDATION_ERROR",
|
||||
message:
|
||||
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.",
|
||||
});
|
||||
expect(
|
||||
JSON.parse(
|
||||
sanitizeCliOutput(
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
error: {
|
||||
code: "VALIDATION_ERROR",
|
||||
message: "raw Zod details",
|
||||
fieldErrors: [{ code: "invalid_type" }],
|
||||
},
|
||||
meta: { command: "analyze" },
|
||||
}),
|
||||
),
|
||||
),
|
||||
).toEqual({
|
||||
ok: false,
|
||||
error: {
|
||||
code: "VALIDATION_ERROR",
|
||||
message:
|
||||
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.",
|
||||
},
|
||||
meta: { command: "analyze" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("compiled CLI output boundary", () => {
|
||||
fixtureTest(
|
||||
"sanitizes a real missing-argument dispatcher failure",
|
||||
async ({ cli }) => {
|
||||
const ordinary = await cli.run({ arguments: ["analyze"] });
|
||||
expect(ordinary).toMatchObject({
|
||||
exitCode: 1,
|
||||
stdout:
|
||||
'code: VALIDATION_ERROR\nmessage: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
|
||||
});
|
||||
const json = await cli.run({
|
||||
arguments: ["--full-output", "--json", "analyze"],
|
||||
});
|
||||
expect(json).toMatchObject({
|
||||
exitCode: 1,
|
||||
stdout: expect.not.stringContaining("fieldErrors"),
|
||||
});
|
||||
const yaml = await cli.run({
|
||||
arguments: ["--full-output", "analyze"],
|
||||
});
|
||||
expect(yaml).toMatchObject({
|
||||
exitCode: 1,
|
||||
stdout:
|
||||
'ok: false\nerror:\n code: VALIDATION_ERROR\n message: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
|
||||
});
|
||||
},
|
||||
CLI_INTEGRATION_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
fixtureTest(
|
||||
"preserves artifact diagnostics in ordinary and full JSON output",
|
||||
async ({ cli, workspace }) => {
|
||||
const source = workspace.path("source");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "main.js"), "console.log('ok');\n");
|
||||
const archive = workspace.path("fixture.asar");
|
||||
await createPackageWithOptions(source, archive, { unpack: "*.js" });
|
||||
await writeFile(join(`${archive}.unpacked`, "main.js"), "changed();\n");
|
||||
|
||||
for (const flags of [["--json"], ["--full-output", "--json"]]) {
|
||||
const result = await cli.run({
|
||||
arguments: [...flags, "inventory-artifact", archive],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
const output = JSON.stringify(result.json);
|
||||
expect(output).toContain('"logical_path":"main.js"');
|
||||
expect(output).toMatch(/"declared_sha256":"[a-f0-9]{64}"/u);
|
||||
expect(output).toMatch(/"calculated_sha256":"[a-f0-9]{64}"/u);
|
||||
expect(output).toContain('"unpacked":true');
|
||||
}
|
||||
},
|
||||
CLI_INTEGRATION_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
fixtureTest(
|
||||
"keeps operation failure status independent of output controls",
|
||||
async ({ cli }) => {
|
||||
const variants = [
|
||||
["--format", "toon"],
|
||||
["--format", "json"],
|
||||
["--format", "yaml"],
|
||||
["--format", "md"],
|
||||
["--format", "jsonl"],
|
||||
["--full-output", "--json"],
|
||||
["--filter-output", "category", "--json"],
|
||||
["--token-limit", "5", "--json"],
|
||||
["--token-count", "--json"],
|
||||
];
|
||||
|
||||
for (const flags of variants) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
...flags,
|
||||
"investigate-versions",
|
||||
"/tmp/left",
|
||||
"/tmp/right",
|
||||
"/tmp/workspace.json",
|
||||
],
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 1,
|
||||
stdout: expect.any(String),
|
||||
});
|
||||
}
|
||||
},
|
||||
CLI_VARIANT_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
fixtureTest(
|
||||
"keeps failure logs out of structured stdout",
|
||||
async ({ cli }) => {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"--json",
|
||||
"investigate-versions",
|
||||
"/tmp/left",
|
||||
"/tmp/right",
|
||||
"/tmp/workspace.json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "error" },
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 1,
|
||||
stderr: expect.stringContaining('"status":"error"'),
|
||||
});
|
||||
expect(result.json).toMatchObject({ error: "ApprovalRequired" });
|
||||
},
|
||||
CLI_INTEGRATION_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
readProjectPermissionStore,
|
||||
writeProjectPermissionStore,
|
||||
} from "../../../src/application/ProjectPermissionStore.js";
|
||||
import { approvePolicyRevocation } from "../../../src/cliPolicyCommands.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("policy revocation approval", () => {
|
||||
it("accepts --yes without invoking the interactive prompt", async () => {
|
||||
const confirm = vi.fn<() => Promise<boolean>>();
|
||||
|
||||
await expect(
|
||||
approvePolicyRevocation({
|
||||
approved: true,
|
||||
interactive: false,
|
||||
grantId: "grant-1",
|
||||
confirm,
|
||||
}),
|
||||
).resolves.toEqual({ approved: true });
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed for non-interactive revocation without --yes", async () => {
|
||||
const confirm = vi.fn<() => Promise<boolean>>();
|
||||
|
||||
await expect(
|
||||
approvePolicyRevocation({
|
||||
approved: false,
|
||||
interactive: false,
|
||||
grantId: "grant-1",
|
||||
confirm,
|
||||
}),
|
||||
).resolves.toEqual({ approved: false, reason: "required" });
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[true, { approved: true }],
|
||||
[false, { approved: false, reason: "cancelled" }],
|
||||
] as const)(
|
||||
"uses the interactive decision %s",
|
||||
async (decision, expected) => {
|
||||
const confirm = vi.fn(() => Promise.resolve(decision));
|
||||
|
||||
await expect(
|
||||
approvePolicyRevocation({
|
||||
approved: false,
|
||||
interactive: true,
|
||||
grantId: "grant-1",
|
||||
confirm,
|
||||
}),
|
||||
).resolves.toEqual(expected);
|
||||
expect(confirm).toHaveBeenCalledWith("grant-1");
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the packaged project store unchanged until --yes is supplied", async () => {
|
||||
const project = await createTestTempDirectory("rea-policy-cli-");
|
||||
roots.push(project);
|
||||
const store = join(project, ".rea", "permissions.json");
|
||||
const grant = {
|
||||
grant_id: "project:revoke-me",
|
||||
capability: "evidence_read" as const,
|
||||
roots: [project],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: false,
|
||||
lifetime: "project" as const,
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
};
|
||||
expect(
|
||||
await writeProjectPermissionStore(store, project, [grant]),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: { grants: [grant] },
|
||||
});
|
||||
const before = await readFile(store);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_PERMISSION_PROJECT_ROOT: project,
|
||||
REA_PERMISSION_PROJECT_STORE: store,
|
||||
};
|
||||
|
||||
const denied = await runCli(
|
||||
["policy", "revoke", grant.grant_id, "--json"],
|
||||
environment,
|
||||
);
|
||||
expect(denied.status).toBe(1);
|
||||
expect(denied.output).toEqual({
|
||||
error:
|
||||
"Policy revoke requires confirmation. Rerun interactively or with --yes.",
|
||||
grant_id: grant.grant_id,
|
||||
});
|
||||
expect(await readFile(store)).toEqual(before);
|
||||
|
||||
const approved = await runCli(
|
||||
["policy", "revoke", grant.grant_id, "--yes", "--json"],
|
||||
environment,
|
||||
);
|
||||
expect(approved).toEqual({
|
||||
status: 0,
|
||||
output: {
|
||||
revoked: grant.grant_id,
|
||||
reload: "Send SIGHUP to the REA MCP process",
|
||||
},
|
||||
});
|
||||
expect(await readProjectPermissionStore(store, project)).toMatchObject({
|
||||
ok: true,
|
||||
value: { grants: [] },
|
||||
});
|
||||
}, 40_000);
|
||||
});
|
||||
|
||||
const runCli = async (
|
||||
arguments_: readonly string[],
|
||||
environment: NodeJS.ProcessEnv,
|
||||
): Promise<{ readonly status: number; readonly output: unknown }> => {
|
||||
try {
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
["scripts/rea.mjs", ...arguments_],
|
||||
{ cwd: process.cwd(), env: environment },
|
||||
);
|
||||
return { status: 0, output: JSON.parse(stdout) };
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
typeof cause.code === "number" &&
|
||||
"stdout" in cause &&
|
||||
typeof cause.stdout === "string"
|
||||
)
|
||||
return { status: cause.code, output: JSON.parse(cause.stdout) };
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,399 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { spawn } from "@lydell/node-pty";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const decisionMarker = "REA_SETUP_DECISION:";
|
||||
|
||||
const actions = [
|
||||
{
|
||||
id: "configure_client:codex",
|
||||
kind: "configure_client",
|
||||
label: "Codex",
|
||||
target: "/isolated/.codex/config.toml",
|
||||
detail: "Add the REA MCP registration for Codex.",
|
||||
external: false,
|
||||
operation: "create",
|
||||
},
|
||||
{
|
||||
id: "install_skill",
|
||||
kind: "install_skill",
|
||||
label: "REA reverse-engineering skill",
|
||||
target: "/isolated/.agents/skills/reverse-engineering/SKILL.md",
|
||||
detail: "Install the bundled reverse-engineering skill.",
|
||||
external: false,
|
||||
operation: "install",
|
||||
},
|
||||
{
|
||||
id: "install_hopper",
|
||||
kind: "install_hopper",
|
||||
label: "Hopper deep-analysis provider",
|
||||
target: "/isolated/Applications/Hopper Disassembler.app",
|
||||
detail: "Install the verified Hopper package.",
|
||||
external: true,
|
||||
operation: "install",
|
||||
},
|
||||
] as const;
|
||||
|
||||
describe("interactive setup journey", () => {
|
||||
it("leads with value, a compact detected-target summary, and durable key help", async () => {
|
||||
const result = await runJourney([
|
||||
step("What should REA set up?", "\u0003"),
|
||||
]);
|
||||
|
||||
expect(result.output).toContain(
|
||||
"Understand local apps and binaries from your coding agent.",
|
||||
);
|
||||
expect(result.output).toContain(
|
||||
"Trace how a feature works with local evidence.",
|
||||
);
|
||||
expect(result.output).toContain("Found 1 supported agent");
|
||||
expect(result.output).toContain("Codex");
|
||||
expect(result.output).toContain("Hopper deep-analysis provider (provider)");
|
||||
expect(result.output).toContain(
|
||||
"Agent integration (MCP + guided workflow)",
|
||||
);
|
||||
expect(result.output).toContain(
|
||||
"Keys: ↑/↓ navigate · Space toggle · Enter confirm · Ctrl-C cancel",
|
||||
);
|
||||
expect(result.decision.approved).toBe(false);
|
||||
});
|
||||
|
||||
it("allows deselecting the pre-selected agent integration to opt out", async () => {
|
||||
const result = await runJourney([step("What should REA set up?", " \r")]);
|
||||
|
||||
expect(result.output).toContain(
|
||||
"Agent integration (MCP + guided workflow)",
|
||||
);
|
||||
expect(result.output).not.toContain(
|
||||
"REA reverse-engineering skill (skill)",
|
||||
);
|
||||
expect(result.output).toContain("Hopper deep-analysis provider (provider)");
|
||||
expect(result.output).not.toContain("Ready to review");
|
||||
expect(result.output).toContain("Nothing selected. No changes were made.");
|
||||
expect(result.decision).toEqual({
|
||||
approved: false,
|
||||
selectedActionIds: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("pre-selects agent integration and proceeds to the agent picker on Enter", async () => {
|
||||
const result = await runJourney([
|
||||
step("What should REA set up?", "\r"),
|
||||
step("Which agents should use REA?", "\u0003"),
|
||||
]);
|
||||
|
||||
expect(result.output).toContain("Codex (detected)");
|
||||
expect(result.output).toContain("Setup cancelled. No changes were made.");
|
||||
expect(result.decision.approved).toBe(false);
|
||||
});
|
||||
|
||||
it("offers one bundled repair when MCP is aligned but the skill is missing", async () => {
|
||||
const result = await runJourney(
|
||||
[step("What should REA set up?", "\r"), step("Apply this change?", "\r")],
|
||||
false,
|
||||
actions.filter(({ kind }) => kind !== "configure_client"),
|
||||
);
|
||||
|
||||
expect(result.output).toContain("No agent integrations need configuration");
|
||||
expect(result.output).toContain(
|
||||
"Agent integration (MCP + guided workflow)",
|
||||
);
|
||||
expect(result.output).not.toContain(
|
||||
"REA reverse-engineering skill (skill)",
|
||||
);
|
||||
expect(result.decision).toEqual({
|
||||
approved: true,
|
||||
selectedActionIds: ["install_skill"],
|
||||
});
|
||||
});
|
||||
|
||||
it("pre-selects all detected agents in the agent picker", async () => {
|
||||
const result = await runJourney(
|
||||
[
|
||||
step("What should REA set up?", "\r"),
|
||||
step("Which agents should use REA?", "\u0003"),
|
||||
],
|
||||
false,
|
||||
[
|
||||
actions[0],
|
||||
{
|
||||
...actions[0],
|
||||
id: "configure_client:cursor",
|
||||
label: "Cursor",
|
||||
target: "/isolated/.cursor/mcp.json",
|
||||
},
|
||||
...actions.slice(1),
|
||||
],
|
||||
);
|
||||
|
||||
expect(result.output).toContain("Codex (detected)");
|
||||
expect(result.output).toContain("Cursor (detected)");
|
||||
expect(result.decision.approved).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("interactive setup selection and confirmation", () => {
|
||||
it("retains the bundled skill even when all agents are deselected (#399)", async () => {
|
||||
const result = await runJourney([
|
||||
step("What should REA set up?", "\r"),
|
||||
step("Which agents should use REA?", " \r"),
|
||||
step("Apply this change?", "\r"),
|
||||
]);
|
||||
|
||||
expect(result.output).toContain("Ready to review");
|
||||
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
|
||||
expect(result.output).not.toContain("CREATE Codex");
|
||||
expect(result.decision).toEqual({
|
||||
approved: true,
|
||||
selectedActionIds: ["install_skill"],
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults the final confirmation to Yes, apply", async () => {
|
||||
const result = await runJourney([
|
||||
step("What should REA set up?", "\r"),
|
||||
step("Which agents should use REA?", "\r"),
|
||||
step("Apply these 2 changes?", "\r"),
|
||||
]);
|
||||
|
||||
expect(result.output).toContain("Ready to review");
|
||||
expect(result.output).toContain("CREATE Codex");
|
||||
expect(result.output).toContain("/isolated/.codex/config.toml");
|
||||
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
|
||||
expect(result.output).not.toContain(
|
||||
"INSTALL Hopper deep-analysis provider",
|
||||
);
|
||||
expect(result.output).toContain("Yes, apply");
|
||||
expect(result.decision).toEqual({
|
||||
approved: true,
|
||||
selectedActionIds: ["configure_client:codex", "install_skill"],
|
||||
});
|
||||
});
|
||||
|
||||
it("can still be cancelled at the final confirmation", async () => {
|
||||
const result = await runJourney([
|
||||
step("What should REA set up?", "\r"),
|
||||
step("Which agents should use REA?", "\r"),
|
||||
step("Apply these 2 changes?", "\u001b[D\r"),
|
||||
]);
|
||||
|
||||
expect(result.output).toContain("Ready to review");
|
||||
expect(result.output).toContain("Setup cancelled. No changes were made.");
|
||||
expect(result.decision).toEqual({
|
||||
approved: false,
|
||||
selectedActionIds: ["configure_client:codex", "install_skill"],
|
||||
});
|
||||
});
|
||||
|
||||
it("repairs an aligned agent integration through the bundled option", async () => {
|
||||
const result = await runJourney(
|
||||
[step("What should REA set up?", "\r"), step("Apply this change?", "\r")],
|
||||
false,
|
||||
actions.filter(({ kind }) => kind !== "configure_client"),
|
||||
);
|
||||
|
||||
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
|
||||
expect(result.output).toContain(
|
||||
"Agent integration (MCP + guided workflow)",
|
||||
);
|
||||
expect(result.output).not.toContain("CREATE Codex");
|
||||
expect(result.output).not.toContain(
|
||||
"INSTALL Hopper deep-analysis provider",
|
||||
);
|
||||
expect(result.decision).toEqual({
|
||||
approved: true,
|
||||
selectedActionIds: ["install_skill"],
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults accessible agent integration to Yes and others to No", async () => {
|
||||
const result = await runJourney(
|
||||
[
|
||||
step("Set up Agent integration (MCP + guided workflow)?", "\r"),
|
||||
step("Set up Hopper deep-analysis provider (provider)?", "\r"),
|
||||
step("Apply this change?", "\r"),
|
||||
],
|
||||
true,
|
||||
actions.filter(({ kind }) => kind !== "configure_client"),
|
||||
);
|
||||
|
||||
expect(result.output).toContain("Ready to review");
|
||||
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
|
||||
expect(result.decision).toEqual({
|
||||
approved: true,
|
||||
selectedActionIds: ["install_skill"],
|
||||
});
|
||||
});
|
||||
|
||||
it("allows accessible opt-out of the pre-selected agent integration", async () => {
|
||||
const result = await runJourney(
|
||||
[
|
||||
step("Set up Agent integration (MCP + guided workflow)?", "\u001b[B\r"),
|
||||
step("Set up Hopper deep-analysis provider (provider)?", "\r"),
|
||||
],
|
||||
true,
|
||||
);
|
||||
|
||||
expect(result.output).toContain("Nothing selected. No changes were made.");
|
||||
expect(result.decision.selectedActionIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("interactive setup completion", () => {
|
||||
it("frames completion around the capabilities that are now ready", async () => {
|
||||
const { stderr } = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"--eval",
|
||||
[
|
||||
'import { renderInteractiveSetupResult } from "./dist/cliSetup.js";',
|
||||
"renderInteractiveSetupResult({",
|
||||
' status: "ready",',
|
||||
" plannedActions: [],",
|
||||
" appliedActions: [],",
|
||||
' clients: { codex: { status: "configured" } },',
|
||||
" doctor: {",
|
||||
" healthy: true,",
|
||||
' hopperPath: "/Applications/Hopper",',
|
||||
" checks: [],",
|
||||
' providerInspections: [{ id: "ghidra", available: true }],',
|
||||
' identity: { skill: { state: "aligned" }, registrations: [{ client: "codex", state: "aligned" }] },',
|
||||
" },",
|
||||
"});",
|
||||
].join("\n"),
|
||||
],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: { ...process.env, NO_COLOR: "1" },
|
||||
},
|
||||
);
|
||||
|
||||
expect(stderr).toContain("What you can do now");
|
||||
expect(stderr).toContain("Deep analysis: Hopper and Ghidra");
|
||||
expect(stderr).toContain("Agent access: Codex");
|
||||
expect(stderr).toContain("Guided reverse-engineering workflows: installed");
|
||||
expect(stderr).toContain("CLI: rea analyze /path/to/app");
|
||||
expect(stderr).toContain(
|
||||
'Try in Codex: "Explain how a feature works in /path/to/app and show the evidence."',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
interface JourneyStep {
|
||||
readonly prompt: string;
|
||||
readonly input: string;
|
||||
}
|
||||
|
||||
interface JourneyResult {
|
||||
readonly output: string;
|
||||
readonly decision: {
|
||||
readonly approved: boolean;
|
||||
readonly selectedActionIds: readonly string[];
|
||||
};
|
||||
}
|
||||
|
||||
const step = (prompt: string, input: string): JourneyStep => ({
|
||||
prompt,
|
||||
input,
|
||||
});
|
||||
|
||||
const runJourney = async (
|
||||
steps: readonly JourneyStep[],
|
||||
accessible = false,
|
||||
journeyActions: readonly object[] = actions,
|
||||
): Promise<JourneyResult> => {
|
||||
const isolatedHome = await createTestTempDirectory("rea-cli-setup-test-");
|
||||
const script = [
|
||||
'import { confirmInteractiveSetup } from "./dist/cliSetup.js";',
|
||||
`const actions = ${JSON.stringify(journeyActions)};`,
|
||||
`const decision = await confirmInteractiveSetup(actions, ${JSON.stringify(accessible)});`,
|
||||
`process.stdout.write(${JSON.stringify(`\n${decisionMarker}`)} + JSON.stringify(decision) + "\\n");`,
|
||||
].join("\n");
|
||||
|
||||
return new Promise<JourneyResult>((resolvePromise, reject) => {
|
||||
let output = "";
|
||||
let nextStep = 0;
|
||||
let settled = false;
|
||||
const terminal = spawn(
|
||||
process.execPath,
|
||||
["--input-type=module", "--eval", script],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
...process.env,
|
||||
HOME: isolatedHome,
|
||||
NO_COLOR: "1",
|
||||
TERM: "xterm-256color",
|
||||
},
|
||||
name: "xterm-256color",
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
},
|
||||
);
|
||||
const timeout = setTimeout(() => {
|
||||
terminal.kill();
|
||||
finish(new Error(`Timed out after output:\n${output}`));
|
||||
}, 10_000);
|
||||
|
||||
terminal.onData((data) => {
|
||||
output += data;
|
||||
const pending = steps[nextStep];
|
||||
if (pending !== undefined && output.includes(pending.prompt)) {
|
||||
nextStep += 1;
|
||||
terminal.write(pending.input);
|
||||
}
|
||||
});
|
||||
terminal.onExit(({ exitCode }) => {
|
||||
if (exitCode !== 0) {
|
||||
finish(
|
||||
new Error(`Setup journey exited ${String(exitCode)}:\n${output}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (nextStep !== steps.length) {
|
||||
finish(new Error(`Setup journey missed an interaction:\n${output}`));
|
||||
return;
|
||||
}
|
||||
const markerIndex = output.lastIndexOf(decisionMarker);
|
||||
if (markerIndex === -1) {
|
||||
finish(new Error(`Setup journey returned no decision:\n${output}`));
|
||||
return;
|
||||
}
|
||||
const serialized = output
|
||||
.slice(markerIndex + decisionMarker.length)
|
||||
.split(/\r?\n/u, 1)[0];
|
||||
if (serialized === undefined) {
|
||||
finish(
|
||||
new Error(`Setup journey returned an empty decision:\n${output}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
finish(undefined, {
|
||||
output,
|
||||
decision: JSON.parse(serialized) as JourneyResult["decision"],
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
finish(cause instanceof Error ? cause : new Error(String(cause)));
|
||||
}
|
||||
});
|
||||
|
||||
function finish(error?: Error, result?: JourneyResult): void {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
void rm(isolatedHome, { recursive: true, force: true }).finally(() => {
|
||||
if (error !== undefined) reject(error);
|
||||
else if (result !== undefined) resolvePromise(result);
|
||||
else reject(new Error("Setup journey completed without a result"));
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
import { copyFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { fixtureTest } from "../../support/fixtures.js";
|
||||
|
||||
describe("executable dispatcher", () => {
|
||||
fixtureTest(
|
||||
"reserves production MCP routing for bare mode arguments",
|
||||
async ({ processes, workspace }) => {
|
||||
const scripts = await workspace.mkdir("scripts");
|
||||
await workspace.mkdir("dist");
|
||||
await Promise.all([
|
||||
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
|
||||
copyFile(
|
||||
"scripts/package-runner-bootstrap.mjs",
|
||||
join(scripts, "package-runner-bootstrap.mjs"),
|
||||
),
|
||||
workspace.write(
|
||||
"package.json",
|
||||
JSON.stringify({ type: "module", version: "1.0.0" }),
|
||||
),
|
||||
workspace.write(
|
||||
"dist/main.js",
|
||||
'export const runEntrypoint = () => process.stdout.write(JSON.stringify({ adapter: "mcp" }));\n',
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli.js",
|
||||
'export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cliOutput.js",
|
||||
"export const sanitizeCliOutput = (output) => output; export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => '';\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/mcpDoctor.js",
|
||||
'export const runProductionMcpDoctorCli = (args) => Promise.resolve({ output: JSON.stringify({ adapter: "mcp-doctor", args }), exitCode: 0 });\n',
|
||||
),
|
||||
]);
|
||||
|
||||
const invoke = async (args: readonly string[]): Promise<unknown> => {
|
||||
const { exitCode, stdout } = await processes.run(
|
||||
process.execPath,
|
||||
[join(scripts, "rea.mjs"), ...args],
|
||||
{ cwd: workspace.root },
|
||||
);
|
||||
expect(exitCode).toBe(0);
|
||||
return JSON.parse(stdout) as unknown;
|
||||
};
|
||||
|
||||
await expect(invoke(["mcp"])).resolves.toEqual({ adapter: "mcp" });
|
||||
await expect(invoke(["--mcp"])).resolves.toEqual({ adapter: "mcp" });
|
||||
await expect(invoke(["mcp", "doctor", "--json"])).resolves.toEqual({
|
||||
adapter: "mcp-doctor",
|
||||
args: ["--json"],
|
||||
});
|
||||
await expect(invoke(["mcp", "add"])).resolves.toEqual({
|
||||
adapter: "cli",
|
||||
args: ["mcp", "add"],
|
||||
});
|
||||
await expect(invoke(["--mcp", "extra"])).resolves.toEqual({
|
||||
adapter: "cli",
|
||||
args: ["--mcp", "extra"],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fixtureTest(
|
||||
"explains how to restore a missing compiled runtime",
|
||||
async ({ processes, workspace }) => {
|
||||
const scripts = await workspace.mkdir("scripts");
|
||||
await Promise.all([
|
||||
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
|
||||
copyFile(
|
||||
"scripts/package-runner-bootstrap.mjs",
|
||||
join(scripts, "package-runner-bootstrap.mjs"),
|
||||
),
|
||||
workspace.write(
|
||||
"package.json",
|
||||
JSON.stringify({ type: "module", version: "1.0.0" }),
|
||||
),
|
||||
]);
|
||||
|
||||
for (const args of [["mcp"], ["mcp", "doctor"], ["--help"]]) {
|
||||
const result = await processes.run(
|
||||
process.execPath,
|
||||
[join(scripts, "rea.mjs"), ...args],
|
||||
{ cwd: workspace.root },
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 1,
|
||||
stderr: expect.stringContaining(
|
||||
"REA's compiled runtime is missing. Run `npm ci` in",
|
||||
),
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
stderr: expect.not.stringContaining("ERR_MODULE_NOT_FOUND"),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,455 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
|
||||
const host = (overrides: Partial<DoctorHost> = {}): DoctorHost => ({
|
||||
platform: "darwin",
|
||||
architecture: "x64",
|
||||
nodeVersion: "24.18.0",
|
||||
macosVersion: () => Promise.resolve("12.0"),
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
executable: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
supportedLinuxHopper: () => Promise.resolve(true),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
}),
|
||||
brewHopperPath: () => Promise.resolve(undefined),
|
||||
manualHopperPaths: () => Promise.resolve([]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: PRODUCT_IDENTITY.skillVersion,
|
||||
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
|
||||
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("doctor", () => {
|
||||
it("returns exact recovery for every failed diagnostic", async () => {
|
||||
const result = await runDoctor(
|
||||
"/missing/app",
|
||||
host({
|
||||
nodeVersion: "20.0.0",
|
||||
macosVersion: () => Promise.resolve("11.7"),
|
||||
executable: () => Promise.resolve(false),
|
||||
validTarget: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
Object.fromEntries(
|
||||
result.checks.map(({ name, remediation }) => [name, remediation]),
|
||||
),
|
||||
).toEqual({
|
||||
node: "Install Node.js 22.19+ or 24.11+.",
|
||||
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
|
||||
target: "Supply a readable local app or program path.",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["11.7", undefined])(
|
||||
"rejects unsupported macOS version %s",
|
||||
async (version) => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ macosVersion: () => Promise.resolve(version) }),
|
||||
);
|
||||
expect(result.checks.find(({ name }) => name === "host")?.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("admits only the experimental Windows x64 host boundary", async () => {
|
||||
const windows = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
const arm = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "win32",
|
||||
architecture: "arm64",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(windows.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: true,
|
||||
detail: "win32 x64",
|
||||
});
|
||||
expect(arm.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: false,
|
||||
detail: "win32 arm64",
|
||||
});
|
||||
});
|
||||
it("detects a manual configured Hopper before Homebrew", async () => {
|
||||
let brewProbes = 0;
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredHopperPath: "/manual/Hopper",
|
||||
executable: (path) => Promise.resolve(path === "/manual/Hopper"),
|
||||
brewHopperPath: () => {
|
||||
brewProbes += 1;
|
||||
return Promise.resolve(undefined);
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe("/manual/Hopper");
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(brewProbes).toBe(0);
|
||||
});
|
||||
|
||||
it("reports optional BYO ilspycmd diagnostics only when configured", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredIlspyCmdPath: "/tools/ilspycmd",
|
||||
ilspyCmdVersion: (path) =>
|
||||
Promise.resolve(
|
||||
path === "/tools/ilspycmd" ? "ilspycmd: 9.1.0.7988" : undefined,
|
||||
),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "ilspycmd",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
detail: "/tools/ilspycmd (ilspycmd: 9.1.0.7988)",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports configured ilspycmd drift without installing it", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredIlspyCmdPath: "/missing/ilspycmd",
|
||||
ilspyCmdVersion: () => Promise.resolve(undefined),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "ilspycmd",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: "/missing/ilspycmd",
|
||||
remediation:
|
||||
"Unset REA_ILSPY_CMD_PATH or point it at a runnable ilspycmd executable.",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not fall back when the configured Hopper launcher is invalid", async () => {
|
||||
const configuredPath = "/invalid/custom/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ configuredHopperPath: configuredPath }),
|
||||
);
|
||||
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.checks.find(({ name }) => name === "hopper")).toEqual({
|
||||
name: "hopper",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: configuredPath,
|
||||
remediation:
|
||||
"Unset or update HOPPER_LAUNCHER_PATH to an executable Hopper launcher.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor installation identity", () => {
|
||||
it("distinguishes stale skills, path shadowing, and unobservable live state", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
installationPaths: () =>
|
||||
Promise.resolve(["/usr/local/bin/rea", "/home/user/bin/rea"]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: "10",
|
||||
toolCount: null,
|
||||
catalogDigest: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.identity).toMatchObject({
|
||||
live_server: { state: "unknown" },
|
||||
installations: { state: "multiple" },
|
||||
skill: {
|
||||
installed_version: "10",
|
||||
state: "stale",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
},
|
||||
});
|
||||
});
|
||||
it("reports a missing installed skill as unhealthy", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ installedSkillIdentity: () => Promise.resolve(undefined) }),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity?.skill).toMatchObject({
|
||||
state: "missing",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
});
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "skill:identity",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: "Installed REA skill identity is missing.",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
});
|
||||
});
|
||||
it("reports stale client registration paths without claiming live state", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
clientRegistrations: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/home/user/.codex/config.toml",
|
||||
command: ["/old/rea", "mcp"],
|
||||
state: "stale",
|
||||
remediation:
|
||||
"Run rea setup to refresh this registration, then restart the client.",
|
||||
},
|
||||
]),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity).toMatchObject({
|
||||
live_server: { state: "unknown" },
|
||||
registrations: [{ client: "codex", state: "stale" }],
|
||||
});
|
||||
expect(result.checks).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "registration:codex",
|
||||
classification: "config_drift",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor scoped readiness", () => {
|
||||
it("scopes effective readiness to selected clients without hiding drift", async () => {
|
||||
const registrations = [
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/home/user/.codex/config.toml",
|
||||
command: ["/current/rea", "mcp"],
|
||||
state: "aligned" as const,
|
||||
remediation: null,
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
config_path: "/home/user/.cursor/mcp.json",
|
||||
command: ["/old/rea", "mcp"],
|
||||
state: "stale" as const,
|
||||
remediation: "Run rea setup to refresh this registration.",
|
||||
},
|
||||
];
|
||||
const scoped = await runDoctor(
|
||||
undefined,
|
||||
host({ clientRegistrations: () => Promise.resolve(registrations) }),
|
||||
{ clients: ["codex"] },
|
||||
);
|
||||
|
||||
expect(scoped).toMatchObject({
|
||||
healthy: true,
|
||||
environment_healthy: false,
|
||||
scope: { mode: "explicit", clients: ["codex"] },
|
||||
});
|
||||
expect(scoped.scope_checks).toContainEqual(
|
||||
expect.objectContaining({ name: "registration:codex", ok: true }),
|
||||
);
|
||||
expect(scoped.informational_checks).toContainEqual(
|
||||
expect.objectContaining({ name: "registration:cursor", ok: false }),
|
||||
);
|
||||
|
||||
const staleSelected = await runDoctor(
|
||||
undefined,
|
||||
host({ clientRegistrations: () => Promise.resolve(registrations) }),
|
||||
{ clients: ["cursor"] },
|
||||
);
|
||||
expect(staleSelected.healthy).toBe(false);
|
||||
});
|
||||
|
||||
it("requires explicitly selected providers instead of any available provider", async () => {
|
||||
const ghidra = {
|
||||
id: "ghidra",
|
||||
configured: true,
|
||||
available: true,
|
||||
providerVersion: "12.1.2",
|
||||
registrationEnvironment: { GHIDRA_INSTALL_DIR: "/tools/ghidra" },
|
||||
checks: [
|
||||
{
|
||||
name: "configuration",
|
||||
ok: true,
|
||||
code: null,
|
||||
detail: "/tools/ghidra",
|
||||
remediation: null,
|
||||
classification: "config_drift" as const,
|
||||
},
|
||||
],
|
||||
};
|
||||
const noHopper = host({
|
||||
executable: () => Promise.resolve(false),
|
||||
providerInspections: () => Promise.resolve([ghidra]),
|
||||
});
|
||||
|
||||
const hopper = await runDoctor(undefined, noHopper, {
|
||||
providers: ["hopper"],
|
||||
});
|
||||
expect(hopper).toMatchObject({
|
||||
healthy: false,
|
||||
environment_healthy: true,
|
||||
});
|
||||
|
||||
const selectedGhidra = await runDoctor(undefined, noHopper, {
|
||||
providers: ["ghidra"],
|
||||
});
|
||||
expect(selectedGhidra.healthy).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor Linux and Hopper discovery", () => {
|
||||
it("accepts an officially supported Linux distribution", async () => {
|
||||
const path = "/home/user/.local/share/rea/hopper/bin/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
configuredHopperPath: path,
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
it("reports missing Linux demo-session dependencies", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: "Install Xvfb, xauth, Python 3, libX11, and libXtst.",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "hopper-demo-runtime"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: expect.stringContaining("xauth"),
|
||||
});
|
||||
});
|
||||
it("explains how to recover from an unsupported configured launcher", async () => {
|
||||
const path = "/custom/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
configuredHopperPath: path,
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
supportedLinuxHopper: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "hopper-version")?.remediation,
|
||||
).toContain("Unset or update HOPPER_LAUNCHER_PATH");
|
||||
});
|
||||
it("detects a Homebrew cask installed outside /Applications", async () => {
|
||||
const path =
|
||||
"/opt/homebrew/Caskroom/hopper/Hopper Disassembler.app/Contents/MacOS/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
brewHopperPath: () => Promise.resolve(path),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
|
||||
it("detects a manually installed Hopper application", async () => {
|
||||
const path = "/Applications/Hopper v6.app/Contents/MacOS/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
manualHopperPaths: () => Promise.resolve([path]),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
|
||||
it("uses shared app target validation when a target is supplied", async () => {
|
||||
const result = await runDoctor(
|
||||
"/Applications/Notes.app",
|
||||
host({
|
||||
validTarget: (path) =>
|
||||
Promise.resolve(path === "/Applications/Notes.app"),
|
||||
}),
|
||||
);
|
||||
expect(result.checks.find(({ name }) => name === "target")?.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a readable Hopper launcher without execute permission", async () => {
|
||||
const path = "/manual/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredHopperPath: path,
|
||||
validTarget: () => Promise.resolve(true),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.checks.find(({ name }) => name === "hopper")?.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
|
||||
const host = (overrides: Partial<DoctorHost> = {}): DoctorHost => ({
|
||||
platform: "darwin",
|
||||
architecture: "x64",
|
||||
nodeVersion: "24.18.0",
|
||||
macosVersion: () => Promise.resolve("12.0"),
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
executable: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
supportedLinuxHopper: () => Promise.resolve(true),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
}),
|
||||
brewHopperPath: () => Promise.resolve(undefined),
|
||||
manualHopperPaths: () => Promise.resolve([]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: PRODUCT_IDENTITY.skillVersion,
|
||||
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
|
||||
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("doctor runtime executable diagnostics", () => {
|
||||
it("reports a broken shadowed Node candidate without hiding the healthy launcher", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
runtimeExecutables: () =>
|
||||
Promise.resolve({
|
||||
launcher_node: "/healthy/node",
|
||||
candidates: [
|
||||
{
|
||||
tool: "node",
|
||||
lexical_path: "/healthy/node",
|
||||
canonical_path: "/healthy/node",
|
||||
path_index: null,
|
||||
selection: "rea-launcher",
|
||||
version: "v24.18.0",
|
||||
healthy: true,
|
||||
failure: null,
|
||||
},
|
||||
{
|
||||
tool: "node",
|
||||
lexical_path: "/opt/homebrew/bin/node",
|
||||
canonical_path: "/opt/homebrew/Cellar/node/25.2.1/bin/node",
|
||||
path_index: 2,
|
||||
selection: "path-shadowed",
|
||||
version: null,
|
||||
healthy: false,
|
||||
failure: {
|
||||
code: "runtime_dynamic_library_missing",
|
||||
exit_code: 134,
|
||||
signal: null,
|
||||
dependency:
|
||||
"/opt/homebrew/opt/simdjson/lib/libsimdjson.29.dylib",
|
||||
stderr: "dyld: Library not loaded",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity?.runtime_executables).toMatchObject({
|
||||
launcher_node: "/healthy/node",
|
||||
candidates: [
|
||||
{ healthy: true, selection: "rea-launcher" },
|
||||
{
|
||||
healthy: false,
|
||||
failure: { code: "runtime_dynamic_library_missing" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "node-toolchains"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: expect.stringContaining("Do not create"),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
|
||||
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascriptRuntimeReconciliationExample.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const INTEGRATION_TEST_TIMEOUT_MS = 20_000;
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("Electron CLI parity", () => {
|
||||
it(
|
||||
"returns the same root-confined Electron Evidence contracts",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-cli-");
|
||||
temporary.push(root);
|
||||
await writeFile(
|
||||
join(root, "index.html"),
|
||||
"<script src='app.js'></script>",
|
||||
);
|
||||
await writeFile(join(root, "app.js"), "export const app = true;");
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_ELECTRON_OBSERVE_ENABLED: "true",
|
||||
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
|
||||
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
const listed = await runCli(
|
||||
["list-electron-targets", browser.endpoint, "--approved", "--json"],
|
||||
environment,
|
||||
);
|
||||
expect(listed).toMatchObject({
|
||||
operation: "list_electron_targets",
|
||||
normalized_result: {
|
||||
targets: { items: [{ target_id: "electron-page" }] },
|
||||
},
|
||||
});
|
||||
const inspected = await runCli(
|
||||
[
|
||||
"inspect-electron-page",
|
||||
browser.endpoint,
|
||||
"electron-page",
|
||||
"--approved",
|
||||
"--observation-ms",
|
||||
"0",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(inspected).toMatchObject({
|
||||
operation: "inspect_electron_page",
|
||||
provider: { id: "rea-cdp-electron" },
|
||||
normalized_result: {
|
||||
target: { file_path: join(root, "index.html") },
|
||||
},
|
||||
});
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
"returns the static JavaScript application Evidence contract",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-static-cli-");
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const analyzed = await runCli(
|
||||
["analyze-javascript-application", root, "--approved", "--json"],
|
||||
environment,
|
||||
);
|
||||
|
||||
expect(analyzed).toMatchObject({
|
||||
operation: "analyze_javascript_application",
|
||||
provider: { id: "rea-javascript-application" },
|
||||
normalized_result: {
|
||||
input_path: root,
|
||||
summary: {
|
||||
browser_windows: 3,
|
||||
context_bridge_apis: 2,
|
||||
ipc: { paired_renderer_transmissions: 4 },
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
describe("Electron CLI artifact behavior", () => {
|
||||
it(
|
||||
"keeps artifact format separate from structured output format",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-format-cli-");
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const analyzed = await runCli(
|
||||
[
|
||||
"--format",
|
||||
"json",
|
||||
"analyze-javascript-application",
|
||||
root,
|
||||
"--approved",
|
||||
"--artifact-format",
|
||||
"directory",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
|
||||
expect(analyzed).toMatchObject({
|
||||
operation: "analyze_javascript_application",
|
||||
normalized_result: { input_path: root, format: "directory" },
|
||||
});
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
"routes generic approved analysis of a directory to static JavaScript",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-routed-cli-");
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const analyzed = await runCli(
|
||||
["analyze", root, "--approved", "--json"],
|
||||
environment,
|
||||
);
|
||||
|
||||
expect(analyzed).toMatchObject({
|
||||
operation: "analyze_javascript_application",
|
||||
provider: { id: "rea-javascript-application" },
|
||||
normalized_result: {
|
||||
input_path: root,
|
||||
format: "directory",
|
||||
summary: { ipc: { paired_renderer_transmissions: 4 } },
|
||||
},
|
||||
});
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
"requires explicit approval before generic JavaScript analysis",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-electron-unapproved-cli-",
|
||||
);
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const denied = await runCli(["analyze", root, "--json"], environment);
|
||||
|
||||
expect(denied).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "analyze_javascript_application",
|
||||
issues: [
|
||||
{
|
||||
path: ["approved"],
|
||||
reason: "invalid_value",
|
||||
expected: [true],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(denied).not.toHaveProperty("details.candidate_ids");
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
describe("Electron CLI runtime reconciliation", () => {
|
||||
it(
|
||||
"reads a file and returns the derived static/runtime reconciliation contract",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-runtime-cli-");
|
||||
const inputPath = join(root, "reconciliation.json");
|
||||
temporary.push(root);
|
||||
await writeFile(
|
||||
inputPath,
|
||||
JSON.stringify(JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE),
|
||||
);
|
||||
const reconciled = await runCli(
|
||||
["reconcile-javascript-runtime", inputPath, "--json"],
|
||||
process.env,
|
||||
);
|
||||
|
||||
expect(reconciled).toMatchObject({
|
||||
operation: "reconcile_javascript_runtime",
|
||||
provider: { id: "rea-javascript-runtime-reconciliation" },
|
||||
normalized_result: {
|
||||
schema_version: 1,
|
||||
summary: { runtime_scripts: 1, matched: 1 },
|
||||
source_map_authority: { used_for_primary_matching: false },
|
||||
},
|
||||
});
|
||||
const missingPath = join(root, "missing.json");
|
||||
const missing = await runCli(
|
||||
["reconcile-javascript-runtime", missingPath, "--json"],
|
||||
process.env,
|
||||
);
|
||||
expect(missing).toMatchObject({
|
||||
input_path: missingPath,
|
||||
input_reason: "read-failed",
|
||||
maximum_input_bytes: 64 * 1_024 * 1_024,
|
||||
});
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
const runCli = async (
|
||||
arguments_: readonly string[],
|
||||
environment: NodeJS.ProcessEnv,
|
||||
): Promise<unknown> => {
|
||||
try {
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
["scripts/rea.mjs", ...arguments_],
|
||||
{ cwd: process.cwd(), env: environment, maxBuffer: 16 * 1_024 * 1_024 },
|
||||
);
|
||||
return JSON.parse(stdout);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"stdout" in cause &&
|
||||
typeof cause.stdout === "string"
|
||||
)
|
||||
return JSON.parse(cause.stdout);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
|
||||
import { observeJavaScriptRuntime } from "../../../src/application/JavaScriptRuntimeObservationService.js";
|
||||
import { V8InspectorProvider } from "../../../src/browser/V8InspectorProvider.js";
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { startFakeV8Inspector } from "../../fixtures/fakeV8Inspector.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const TIMEOUT_MS = 20_000;
|
||||
|
||||
describe("JavaScript runtime observation CLI parity", () => {
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(resources.splice(0).map((item) => item.close()));
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
"returns the same passive Inspector Evidence contracts",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-v8-cli-");
|
||||
temporary.push(root);
|
||||
const entry = join(root, "entry.js");
|
||||
await writeFile(entry, "export const value = 1;\n");
|
||||
const inspector = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(entry).href,
|
||||
});
|
||||
resources.push(inspector);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
|
||||
REA_V8_INSPECTOR_ENDPOINTS_JSON: JSON.stringify([inspector.endpoint]),
|
||||
REA_V8_INSPECTOR_FILE_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const listed = await runCli(
|
||||
[
|
||||
"list-javascript-runtime-targets",
|
||||
inspector.endpoint,
|
||||
"--approved",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(listed).toMatchObject({
|
||||
operation: "list_javascript_runtime_targets",
|
||||
provider: { id: "rea-v8-inspector" },
|
||||
normalized_result: {
|
||||
targets: { items: [{ target_id: inspector.targetId }] },
|
||||
},
|
||||
});
|
||||
|
||||
const observed = await runCli(
|
||||
[
|
||||
"observe-javascript-runtime",
|
||||
inspector.endpoint,
|
||||
inspector.targetId,
|
||||
"--runtime-kind",
|
||||
"node",
|
||||
"--approved",
|
||||
"--observation-ms",
|
||||
"10",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
);
|
||||
expect(observed).toMatchObject({
|
||||
operation: "observe_javascript_runtime",
|
||||
provider: { id: "rea-v8-inspector" },
|
||||
normalized_result: {
|
||||
target: { target_id: inspector.targetId, runtime_kind: "node" },
|
||||
scripts: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
location: { kind: "file", file_path: entry },
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const config = parseConfig(environment);
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const direct = await observeJavaScriptRuntime(
|
||||
new V8InspectorProvider(),
|
||||
authority.value,
|
||||
{
|
||||
inspector_endpoint: inspector.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
allowed_origins: [],
|
||||
target_id: inspector.targetId,
|
||||
runtime_kind: "node",
|
||||
approved: true,
|
||||
observation_ms: 10,
|
||||
limits: {
|
||||
max_events: 10_000,
|
||||
max_scripts: 2_000,
|
||||
max_execution_contexts: 1_000,
|
||||
max_location_bytes: 16_384,
|
||||
max_total_metadata_bytes: 4_194_304,
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(direct.ok).toBe(true);
|
||||
if (direct.ok)
|
||||
expect(evidenceIdFrom(observed)).toBe(direct.value.evidence_id);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
const runCli = async (
|
||||
arguments_: readonly string[],
|
||||
environment: NodeJS.ProcessEnv,
|
||||
): Promise<unknown> => {
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
["scripts/rea.mjs", ...arguments_],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: environment,
|
||||
maxBuffer: 16 * 1_024 * 1_024,
|
||||
},
|
||||
);
|
||||
return JSON.parse(stdout);
|
||||
};
|
||||
|
||||
const evidenceIdFrom = (value: unknown): string => {
|
||||
if (typeof value !== "object" || value === null)
|
||||
throw new TypeError("Missing CLI Evidence");
|
||||
const id = Reflect.get(value, "evidence_id");
|
||||
if (typeof id !== "string") throw new TypeError("Missing CLI Evidence ID");
|
||||
return id;
|
||||
};
|
||||
@@ -0,0 +1,153 @@
|
||||
import { chmod, readFile, writeFile } from "node:fs/promises";
|
||||
import { delimiter, join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
packageRunnerSetupPlan,
|
||||
runPackageRunnerSetupBootstrap,
|
||||
} from "../../../scripts/package-runner-bootstrap.mjs";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("package-runner setup bootstrap", () => {
|
||||
it("reruns bare setup through the current release when npm selected a local package", () => {
|
||||
expect(
|
||||
packageRunnerSetupPlan({
|
||||
args: ["setup", "--client", "codex"],
|
||||
environment: {
|
||||
npm_lifecycle_event: "npx",
|
||||
npm_config_local_prefix: "/work/project",
|
||||
},
|
||||
packageRoot: "/work/project/node_modules/rea-agents",
|
||||
packageName: "rea-agents",
|
||||
}),
|
||||
).toEqual({
|
||||
command: "npm",
|
||||
args: [
|
||||
"exec",
|
||||
"--yes",
|
||||
"--package=rea-agents@latest",
|
||||
"--",
|
||||
"rea",
|
||||
"setup",
|
||||
"--client",
|
||||
"codex",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves explicit rollback and non-local invocations untouched", () => {
|
||||
const base = {
|
||||
args: ["setup"],
|
||||
packageRoot: "/work/project/node_modules/rea-agents",
|
||||
packageName: "rea-agents",
|
||||
} as const;
|
||||
|
||||
expect(
|
||||
packageRunnerSetupPlan({
|
||||
...base,
|
||||
environment: {
|
||||
npm_lifecycle_event: "npx",
|
||||
npm_config_local_prefix: "/work/project",
|
||||
npm_config_package: "rea-agents@2.4.0",
|
||||
},
|
||||
}),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
packageRunnerSetupPlan({
|
||||
...base,
|
||||
environment: {
|
||||
npm_lifecycle_event: "npx",
|
||||
npm_config_local_prefix: "/work/project",
|
||||
npm_config_package: "rea-agents@^2.4.0",
|
||||
},
|
||||
}),
|
||||
).toEqual(
|
||||
expect.objectContaining({
|
||||
args: expect.arrayContaining(["--package=rea-agents@latest"]),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
packageRunnerSetupPlan({
|
||||
...base,
|
||||
packageRoot: "/root/.npm/_npx/cache/node_modules/rea-agents",
|
||||
environment: {
|
||||
npm_lifecycle_event: "npx",
|
||||
npm_config_local_prefix: "/work/project",
|
||||
},
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not redirect recursively or affect commands other than setup", () => {
|
||||
const environment = {
|
||||
npm_lifecycle_event: "npx",
|
||||
npm_config_local_prefix: "/work/project",
|
||||
REA_PACKAGE_RUNNER_BOOTSTRAPPED: "1",
|
||||
};
|
||||
|
||||
expect(
|
||||
packageRunnerSetupPlan({
|
||||
args: ["setup"],
|
||||
environment,
|
||||
packageRoot: "/work/project/node_modules/rea-agents",
|
||||
packageName: "rea-agents",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
packageRunnerSetupPlan({
|
||||
args: ["doctor"],
|
||||
environment: {
|
||||
npm_lifecycle_event: "npx",
|
||||
npm_config_local_prefix: "/work/project",
|
||||
},
|
||||
packageRoot: "/work/project/node_modules/rea-agents",
|
||||
packageName: "rea-agents",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("forwards setup arguments to npm with a recursion marker", async () => {
|
||||
const directory = await createTestTempDirectory("rea-bootstrap-");
|
||||
const npm = join(directory, "npm");
|
||||
const log = join(directory, "invocation.json");
|
||||
await writeFile(
|
||||
npm,
|
||||
`#!/usr/bin/env node
|
||||
import { writeFileSync } from "node:fs";
|
||||
writeFileSync(process.env.REA_BOOTSTRAP_TEST_LOG, JSON.stringify({
|
||||
args: process.argv.slice(2),
|
||||
marker: process.env.REA_PACKAGE_RUNNER_BOOTSTRAPPED,
|
||||
}));
|
||||
`,
|
||||
);
|
||||
await chmod(npm, 0o755);
|
||||
|
||||
await expect(
|
||||
runPackageRunnerSetupBootstrap({
|
||||
args: ["setup", "--dry-run"],
|
||||
environment: {
|
||||
...process.env,
|
||||
PATH: `${directory}${delimiter}${process.env.PATH ?? ""}`,
|
||||
REA_BOOTSTRAP_TEST_LOG: log,
|
||||
npm_lifecycle_event: "npx",
|
||||
npm_config_local_prefix: "/work/project",
|
||||
},
|
||||
packageRoot: "/work/project/node_modules/rea-agents",
|
||||
packageName: "rea-agents",
|
||||
}),
|
||||
).resolves.toBe(0);
|
||||
await expect(readFile(log, "utf8").then(JSON.parse)).resolves.toEqual({
|
||||
args: [
|
||||
"exec",
|
||||
"--yes",
|
||||
"--package=rea-agents@latest",
|
||||
"--",
|
||||
"rea",
|
||||
"setup",
|
||||
"--dry-run",
|
||||
],
|
||||
marker: "1",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
import { open, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenarioFile,
|
||||
compareProcessEvidenceFiles,
|
||||
projectProcessCliError,
|
||||
} from "../../../src/application/ProcessCli.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
const execFileAsync = promisify(execFile);
|
||||
const CLI_INTEGRATION_TIMEOUT_MS = 60_000;
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
const fixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-process-cli-");
|
||||
roots.push(root);
|
||||
return root;
|
||||
};
|
||||
|
||||
describe("process CLI errors", () => {
|
||||
it(
|
||||
"exits unsuccessfully without writing failure-shaped evidence",
|
||||
async () => {
|
||||
await expect(
|
||||
execFileAsync(
|
||||
process.execPath,
|
||||
["scripts/rea.mjs", "capture-process", "/missing/scenario.json"],
|
||||
{ cwd: process.cwd() },
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining("category: invalid_input"),
|
||||
});
|
||||
},
|
||||
CLI_INTEGRATION_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it("projects unexpected causes without their message or stack", () => {
|
||||
const projected = projectProcessCliError(
|
||||
new Error("SECRET internal failure /private/path"),
|
||||
);
|
||||
expect(projected).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Process command could not complete. Check the input files and run `rea doctor`, then try again.",
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("SECRET");
|
||||
});
|
||||
|
||||
it("projects missing, malformed JSON, and invalid scenario files", async () => {
|
||||
const root = await fixture();
|
||||
const malformed = join(root, "malformed.json");
|
||||
const invalid = join(root, "invalid.json");
|
||||
await writeFile(malformed, "not-json");
|
||||
await writeFile(invalid, "{}");
|
||||
|
||||
expect(
|
||||
await captureProcessScenarioFile(join(root, "missing.json")),
|
||||
).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Process input file could not be read. Check that the path exists and is readable.",
|
||||
});
|
||||
expect(await captureProcessScenarioFile(malformed)).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Process input file is not valid JSON. Repair the file, then try again.",
|
||||
});
|
||||
expect(await captureProcessScenarioFile(invalid)).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Process scenario is invalid. Check its required fields and limits, then try again.",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the exact process-capture policy recovery", async () => {
|
||||
const root = await fixture();
|
||||
const scenario = join(root, "scenario.json");
|
||||
await writeFile(
|
||||
scenario,
|
||||
JSON.stringify({
|
||||
approved: true,
|
||||
executable: "/bin/sh",
|
||||
working_directory: "/tmp",
|
||||
}),
|
||||
);
|
||||
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
|
||||
error: "Process command failed",
|
||||
code: "permission_required",
|
||||
category: "permission_required",
|
||||
message:
|
||||
"This operation needs additional local permission. Review the requested scope and remediation.",
|
||||
details: {
|
||||
capability: "process_capture",
|
||||
ceiling: null,
|
||||
},
|
||||
remediation: {
|
||||
restart_required: false,
|
||||
elicitation_supported: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects oversized process input before parsing", async () => {
|
||||
const root = await fixture();
|
||||
const path = join(root, "large.json");
|
||||
const handle = await open(path, "w");
|
||||
await handle.truncate(64 * 1024 * 1024 + 1);
|
||||
await handle.close();
|
||||
expect(await captureProcessScenarioFile(path)).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "truncated",
|
||||
message:
|
||||
"Process input file is too large. Reduce it below 64 MiB, then try again.",
|
||||
});
|
||||
});
|
||||
|
||||
it("explains unsupported and unrelated capture evidence", async () => {
|
||||
const root = await fixture();
|
||||
const legacy = join(root, "legacy.json");
|
||||
const unrelated = join(root, "unrelated.json");
|
||||
await writeFile(
|
||||
legacy,
|
||||
JSON.stringify(
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture/v3",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: {},
|
||||
}),
|
||||
),
|
||||
);
|
||||
await writeFile(
|
||||
unrelated,
|
||||
JSON.stringify(
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "unrelated/v1",
|
||||
operation: "other",
|
||||
parameters: {},
|
||||
result: {},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const legacyResult = await compareProcessEvidenceFiles(legacy, legacy);
|
||||
expect(legacyResult).toMatchObject({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
});
|
||||
expect(JSON.stringify(legacyResult)).toContain(
|
||||
"Process Capture v3 is unsupported",
|
||||
);
|
||||
expect(await compareProcessEvidenceFiles(unrelated, unrelated)).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies malformed capture evidence as invalid input", async () => {
|
||||
const root = await fixture();
|
||||
const malformed = join(root, "malformed-evidence.json");
|
||||
await writeFile(malformed, "{}");
|
||||
|
||||
expect(await compareProcessEvidenceFiles(malformed, malformed)).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Capture evidence is malformed. Create new capture evidence, then try again.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,303 @@
|
||||
import { readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { SUPPORTED_CLIENT_DEFINITIONS } from "../../../src/application/SupportedClients.js";
|
||||
import {
|
||||
ARTIFACT_GRAPH_PROVIDER,
|
||||
JAVASCRIPT_APPLICATION_PROVIDER,
|
||||
JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
|
||||
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
MANAGED_WORKFLOW_PROVIDER,
|
||||
} from "../../../src/application/InvestigationProviders.js";
|
||||
import { CDP_BROWSER_PROVIDER_IDENTITY } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "../../../src/browser/CdpElectronProvider.js";
|
||||
import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "../../../src/browser/PlaywrightBrowserScenarioProvider.js";
|
||||
import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/browser/V8InspectorProvider.js";
|
||||
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { analysisSnapshotSchema } from "../../../src/domain/analysisSnapshot.js";
|
||||
import { investigationWorkspaceSchema } from "../../../src/domain/investigationWorkspace.js";
|
||||
import {
|
||||
HOPPER_PROVIDER_IDENTITY,
|
||||
HOPPER_PROVIDER_TOOL_CONTRACTS,
|
||||
} from "../../../src/hopper/HopperProvider.js";
|
||||
import {
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
} from "../../../src/ghidra/GhidraProvider.js";
|
||||
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "../../../src/native/NativeMacOSProvider.js";
|
||||
import {
|
||||
assertDocumentationFacts,
|
||||
documentationFactIssues,
|
||||
} from "../../../scripts/lib/docs-facts.mjs";
|
||||
import { ensureGeneratedFile } from "../../../scripts/lib/generated-file.mjs";
|
||||
import {
|
||||
createCliInventory,
|
||||
cliCommandDescriptionIssues,
|
||||
cliCommandOptionNames,
|
||||
createProductCatalog,
|
||||
providerCatalogDigest,
|
||||
serializeProductCatalog,
|
||||
} from "../../../scripts/lib/product-catalog.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../../..", import.meta.url));
|
||||
const temporaryRoots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporaryRoots
|
||||
.splice(0)
|
||||
.map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("canonical product catalog", () => {
|
||||
it("matches every source-derived checked-in product fact", async () => {
|
||||
const catalog = await createProductCatalog(root);
|
||||
expect(catalog.tools.total).toBe(TOOL_CONTRACTS.length);
|
||||
expect(
|
||||
catalog.tools.families.reduce((total, family) => total + family.count, 0),
|
||||
).toBe(TOOL_CONTRACTS.length);
|
||||
expect(catalog.setup_clients.map(({ id }) => id)).toEqual(
|
||||
SUPPORTED_CLIENT_DEFINITIONS.map(({ name }) => name),
|
||||
);
|
||||
expect(catalog.cli.commands).toHaveLength(CLI_COMMAND_NAMES.length);
|
||||
expect(catalog.providers.map(({ id }) => id).sort()).toEqual(
|
||||
[
|
||||
HOPPER_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
NATIVE_MACOS_PROVIDER_IDENTITY,
|
||||
ARTIFACT_GRAPH_PROVIDER,
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
MANAGED_WORKFLOW_PROVIDER,
|
||||
CDP_BROWSER_PROVIDER_IDENTITY,
|
||||
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY,
|
||||
CDP_ELECTRON_PROVIDER_IDENTITY,
|
||||
V8_INSPECTOR_PROVIDER_IDENTITY,
|
||||
JAVASCRIPT_APPLICATION_PROVIDER,
|
||||
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
|
||||
JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
|
||||
]
|
||||
.map(({ id }) => id)
|
||||
.sort(),
|
||||
);
|
||||
expect(
|
||||
catalog.providers.find(({ id }) => id === HOPPER_PROVIDER_IDENTITY.id)
|
||||
?.capabilities,
|
||||
).toEqual(HOPPER_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name).sort());
|
||||
expect(
|
||||
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
|
||||
?.capabilities,
|
||||
).toEqual(GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name).sort());
|
||||
expect(
|
||||
catalog.providers.find(
|
||||
({ id }) => id === CDP_ELECTRON_PROVIDER_IDENTITY.id,
|
||||
)?.capabilities,
|
||||
).toEqual(["inspect_electron_page", "list_electron_targets"]);
|
||||
expect(
|
||||
catalog.providers.find(
|
||||
({ id }) => id === JAVASCRIPT_APPLICATION_PROVIDER.id,
|
||||
)?.capabilities,
|
||||
).toEqual(["analyze_javascript_application"]);
|
||||
expect(
|
||||
catalog.providers.find(
|
||||
({ id }) => id === JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER.id,
|
||||
)?.capabilities,
|
||||
).toEqual(["reconcile_javascript_runtime"]);
|
||||
expect(
|
||||
catalog.providers.find(
|
||||
({ id }) => id === JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER.id,
|
||||
)?.capabilities,
|
||||
).toEqual([
|
||||
"build_reconstruction_obligation_ledger",
|
||||
"commit_reconstruction_coverage",
|
||||
"compare_application_versions",
|
||||
"compare_javascript_export_shapes",
|
||||
"compare_source_to_bundle",
|
||||
"evaluate_reconstruction_readiness",
|
||||
"execute_node_characterization",
|
||||
"prepare_node_characterization",
|
||||
"query_reconstruction_coverage",
|
||||
"run_controlled_replay",
|
||||
"trace_application_feature",
|
||||
"trace_javascript_semantics",
|
||||
]);
|
||||
expect(
|
||||
catalog.providers.find(({ id }) => id === MANAGED_WORKFLOW_PROVIDER.id)
|
||||
?.capabilities,
|
||||
).toEqual([
|
||||
"compare_managed_members",
|
||||
"import_managed_reconstruction",
|
||||
"plan_managed_runtime_correlation",
|
||||
"project_managed_application_graph",
|
||||
"verify_managed_native_boundaries",
|
||||
]);
|
||||
expect(catalog.runtime_catalog.digests.providers_sha256).toBe(
|
||||
providerCatalogDigest(catalog.providers),
|
||||
);
|
||||
expect(
|
||||
z.toJSONSchema(analysisSnapshotSchema).properties?.snapshot_version,
|
||||
).toMatchObject({
|
||||
const: catalog.schemas.find(({ id }) => id === "analysis_snapshot")
|
||||
?.version,
|
||||
});
|
||||
expect(
|
||||
z.toJSONSchema(investigationWorkspaceSchema).properties
|
||||
?.workspace_version,
|
||||
).toMatchObject({
|
||||
const: catalog.schemas.find(({ id }) => id === "investigation_workspace")
|
||||
?.version,
|
||||
});
|
||||
expect(
|
||||
JSON.parse(await readFile("docs/product-catalog.json", "utf8")),
|
||||
).toEqual(catalog);
|
||||
expect(await serializeProductCatalog(catalog)).toBe(
|
||||
await readFile("docs/product-catalog.json", "utf8"),
|
||||
);
|
||||
await expect(
|
||||
assertDocumentationFacts(root, catalog),
|
||||
).resolves.toBeUndefined();
|
||||
await expect(documentationFactIssues(root, catalog)).resolves.toEqual([]);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe("canonical CLI catalog", () => {
|
||||
it("uses the same primary command names as the actual Incur router", () => {
|
||||
const inventory = createCliInventory(createCli());
|
||||
expect(inventory.primary).toEqual([...CLI_COMMAND_NAMES].sort());
|
||||
expect(inventory.aliases).toEqual([
|
||||
{ name: "compare-bundles", target: "compare" },
|
||||
]);
|
||||
}, 30_000);
|
||||
|
||||
it("describes every primary command argument and option", () => {
|
||||
expect(cliCommandDescriptionIssues(createCli())).toEqual([]);
|
||||
});
|
||||
|
||||
it("exposes the shared provider selector on every deep-analysis command", () => {
|
||||
const cli = createCli();
|
||||
for (const name of [
|
||||
"analyze",
|
||||
"inspect",
|
||||
"decompile",
|
||||
"xrefs",
|
||||
"trace",
|
||||
"function",
|
||||
"inspect-native-api",
|
||||
"search",
|
||||
]) {
|
||||
expect(cliCommandOptionNames(cli, name)).toContain("provider");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("canonical product catalog drift", () => {
|
||||
it("reports tool-family, setup-client, and schema fact drift", async () => {
|
||||
const catalog = await createProductCatalog(root);
|
||||
const firstFamily = catalog.tools.families[0];
|
||||
if (firstFamily === undefined) throw new TypeError("Missing tool family");
|
||||
const drifted = {
|
||||
...catalog,
|
||||
tools: {
|
||||
...catalog.tools,
|
||||
families: [
|
||||
{ ...firstFamily, count: firstFamily.count + 1 },
|
||||
...catalog.tools.families.slice(1),
|
||||
],
|
||||
},
|
||||
setup_clients: [
|
||||
...catalog.setup_clients,
|
||||
{
|
||||
id: "future_client",
|
||||
display_name: "Future Client",
|
||||
format: "json",
|
||||
configuration: "managed",
|
||||
},
|
||||
],
|
||||
schemas: catalog.schemas.map((schema) =>
|
||||
schema.id === "process_capture"
|
||||
? { ...schema, version: Number(schema.version) + 1 }
|
||||
: schema,
|
||||
),
|
||||
};
|
||||
const issues = await documentationFactIssues(root, drifted);
|
||||
expect(issues.some((issue) => issue.includes("tool family counts"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(issues.some((issue) => issue.includes("Future Client"))).toBe(true);
|
||||
expect(issues.some((issue) => issue.includes("Process Capture v5"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("changes the provider projection digest when provider facts drift", async () => {
|
||||
const catalog = await createProductCatalog(root);
|
||||
const firstProvider = catalog.providers[0];
|
||||
if (firstProvider === undefined) throw new TypeError("Missing provider");
|
||||
const driftedProviders = [
|
||||
{ ...firstProvider, name: `${firstProvider.name} drifted` },
|
||||
...catalog.providers.slice(1),
|
||||
];
|
||||
expect(providerCatalogDigest(driftedProviders)).not.toBe(
|
||||
catalog.runtime_catalog.digests.providers_sha256,
|
||||
);
|
||||
});
|
||||
|
||||
it("fails check mode without rewriting a stale generated artifact", async () => {
|
||||
const directory = await createTestTempDirectory("rea-generated-check-");
|
||||
temporaryRoots.push(directory);
|
||||
const path = join(directory, "catalog.json");
|
||||
await writeFile(path, "stale\n", "utf8");
|
||||
await expect(
|
||||
ensureGeneratedFile({
|
||||
path,
|
||||
source: "current\n",
|
||||
check: true,
|
||||
generateCommand: "npm run docs:generate",
|
||||
}),
|
||||
).rejects.toThrow("missing or stale");
|
||||
expect(await readFile(path, "utf8")).toBe("stale\n");
|
||||
await expect(
|
||||
ensureGeneratedFile({
|
||||
path,
|
||||
source: "current\n",
|
||||
check: false,
|
||||
generateCommand: "npm run docs:generate",
|
||||
}),
|
||||
).resolves.toEqual({ changed: true });
|
||||
expect(await readFile(path, "utf8")).toBe("current\n");
|
||||
});
|
||||
|
||||
it("accepts and preserves native generated-file line endings", async () => {
|
||||
const directory = await createTestTempDirectory("rea-generated-eol-");
|
||||
temporaryRoots.push(directory);
|
||||
const path = join(directory, "catalog.json");
|
||||
await writeFile(path, "current\r\n", "utf8");
|
||||
await expect(
|
||||
ensureGeneratedFile({
|
||||
path,
|
||||
source: "current\n",
|
||||
check: true,
|
||||
generateCommand: "npm run docs:generate",
|
||||
}),
|
||||
).resolves.toEqual({ changed: false });
|
||||
expect(await readFile(path, "utf8")).toBe("current\r\n");
|
||||
await expect(
|
||||
ensureGeneratedFile({
|
||||
path,
|
||||
source: "updated\n",
|
||||
check: false,
|
||||
generateCommand: "npm run docs:generate",
|
||||
}),
|
||||
).resolves.toEqual({ changed: true });
|
||||
expect(await readFile(path, "utf8")).toBe("updated\r\n");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
describe("reconstruction obligation ledger CLI parity", () => {
|
||||
it("builds the same Evidence-backed empty ledger through the CLI", async () => {
|
||||
const input = {
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
reviewed_obligations: [],
|
||||
manifest: {
|
||||
schema_version: 1,
|
||||
bindings: [],
|
||||
contradictions: [],
|
||||
},
|
||||
limits: { max_obligations: 100 },
|
||||
page: { offset: 0, limit: 50 },
|
||||
};
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/rea.mjs",
|
||||
"build-reconstruction-obligation-ledger",
|
||||
JSON.stringify(input),
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
maxBuffer: 16 * 1_024 * 1_024,
|
||||
},
|
||||
);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
operation: "build_reconstruction_obligation_ledger",
|
||||
predicate_type: "rea.reconstruction-obligation-ledger/v1",
|
||||
normalized_result: {
|
||||
schema: "ReconstructionObligationLedger",
|
||||
status: "unknown",
|
||||
summary: { total: 0 },
|
||||
},
|
||||
});
|
||||
}, 20_000);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { RECONSTRUCTION_READINESS_EXAMPLE } from "../../../src/contracts/reconstructionReadinessExample.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
describe("reconstruction readiness CLI parity", () => {
|
||||
it("emits the same passing report through the public CLI", async () => {
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/rea.mjs",
|
||||
"evaluate-reconstruction-readiness",
|
||||
JSON.stringify(RECONSTRUCTION_READINESS_EXAMPLE),
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
maxBuffer: 32 * 1_024 * 1_024,
|
||||
},
|
||||
);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
operation: "evaluate_reconstruction_readiness",
|
||||
predicate_type: "rea.reconstruction-readiness-report/v1",
|
||||
normalized_result: {
|
||||
schema: "ReconstructionReadinessReport",
|
||||
status: "pass",
|
||||
summary: { passed_required_stages: 9 },
|
||||
},
|
||||
});
|
||||
}, 20_000);
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
|
||||
describe("configuration parsing integration", () => {
|
||||
it("returns defaults when no environment variables are set", () => {
|
||||
const result = parseConfig({});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperLauncherPath).toBe(
|
||||
process.platform === "linux"
|
||||
? "/opt/hopper/bin/Hopper"
|
||||
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
|
||||
);
|
||||
expect(result.value.hopperTargetPath).toBeUndefined();
|
||||
expect(result.value.hopperTargetKind).toBe("executable");
|
||||
expect(result.value.hopperLoaderArgs).toEqual([]);
|
||||
expect(result.value.analysisProvider).toBe("auto");
|
||||
});
|
||||
|
||||
it("parses a complete target-bound configuration", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_PATH: "/usr/bin/true",
|
||||
HOPPER_TARGET_KIND: "executable",
|
||||
HOPPER_LOADER_ARGS_JSON: '["-l","Mach-O","--aarch64"]',
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
REA_EVIDENCE_ROOTS_JSON: '["/tmp/evidence"]',
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/tmp/releases"]',
|
||||
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: '["/tmp/analysis"]',
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperTargetPath).toBe("/usr/bin/true");
|
||||
expect(result.value.hopperTargetKind).toBe("executable");
|
||||
expect(result.value.analysisProvider).toBe("hopper");
|
||||
expect(result.value.hopperLoaderArgs).toEqual([
|
||||
"-l",
|
||||
"Mach-O",
|
||||
"--aarch64",
|
||||
]);
|
||||
expect(result.value.evidenceFilePolicy.roots).toEqual(["/tmp/evidence"]);
|
||||
expect(result.value.investigationInputRoots).toEqual(["/tmp/releases"]);
|
||||
expect(result.value.analysisSnapshotFilePolicy.roots).toEqual([
|
||||
"/tmp/analysis",
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects target kind values outside the enum", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_KIND: "archive",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("Invalid REA environment");
|
||||
});
|
||||
|
||||
it("rejects invalid JSON in loader arguments", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LOADER_ARGS_JSON: "not json",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("valid JSON");
|
||||
});
|
||||
|
||||
it("rejects non-array types in loader arguments JSON", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LOADER_ARGS_JSON: '"just a string"',
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("array of strings");
|
||||
});
|
||||
|
||||
it("allows overriding the launcher path while keeping other defaults", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LAUNCHER_PATH: "/custom/hopper",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperLauncherPath).toBe("/custom/hopper");
|
||||
expect(result.value.hopperTargetPath).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses database target kind correctly", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_PATH: "/path/to/file.hop",
|
||||
HOPPER_TARGET_KIND: "database",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperTargetKind).toBe("database");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
const script = join(process.cwd(), "scripts", "check-dependency-install.mjs");
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true })),
|
||||
);
|
||||
});
|
||||
|
||||
const fixture = async (
|
||||
installedVersion?: string,
|
||||
omitDevDependency = false,
|
||||
) => {
|
||||
const root = await createTestTempDirectory("rea-deps-");
|
||||
roots.push(root);
|
||||
await mkdir(join(root, "node_modules"));
|
||||
await writeFile(
|
||||
join(root, "package-lock.json"),
|
||||
JSON.stringify({
|
||||
packages: {
|
||||
"": {
|
||||
dependencies: { alpha: "1.0.0" },
|
||||
devDependencies: { beta: "2.0.0" },
|
||||
},
|
||||
"node_modules/alpha": { version: "1.0.0" },
|
||||
"node_modules/beta": { version: "2.0.0" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "node_modules", ".package-lock.json"),
|
||||
JSON.stringify({
|
||||
packages: {
|
||||
"node_modules/alpha": { version: installedVersion ?? "1.0.0" },
|
||||
...(omitDevDependency
|
||||
? {}
|
||||
: { "node_modules/beta": { version: "2.0.0" } }),
|
||||
"node_modules/unrelated": { version: "9.0.0" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
return root;
|
||||
};
|
||||
|
||||
describe("dependency install freshness", () => {
|
||||
it("accepts matching direct packages and ignores extraneous packages", async () => {
|
||||
const result = spawnSync(process.execPath, [script], {
|
||||
cwd: await fixture(),
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(result.status, result.stderr).toBe(0);
|
||||
});
|
||||
|
||||
it("reports a direct version mismatch with one remediation", async () => {
|
||||
const result = spawnSync(process.execPath, [script], {
|
||||
cwd: await fixture("0.9.0"),
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("alpha: installed 0.9.0, expected 1.0.0");
|
||||
expect(result.stderr.match(/npm ci/gu)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reports a missing direct development dependency", async () => {
|
||||
const result = spawnSync(process.execPath, [script], {
|
||||
cwd: await fixture(undefined, true),
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain(
|
||||
"beta: missing from the installed dependency lockfile",
|
||||
);
|
||||
expect(result.stderr.match(/npm ci/gu)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("runs from a script path containing URL-escaped characters", async () => {
|
||||
const root = await fixture("0.9.0");
|
||||
const scriptDirectory = join(root, "path with spaces");
|
||||
const copiedScript = join(scriptDirectory, "check-dependency-install.mjs");
|
||||
await mkdir(scriptDirectory);
|
||||
await copyFile(script, copiedScript);
|
||||
|
||||
const result = spawnSync(process.execPath, [copiedScript], {
|
||||
cwd: root,
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("alpha: installed 0.9.0, expected 1.0.0");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
readEvidenceBundle,
|
||||
writeEvidenceBundle,
|
||||
} from "../../../src/application/EvidenceBundleFiles.js";
|
||||
import { compareEvidenceBundlesCommand } from "../../../src/application/EvidenceBundleCommands.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
serializeEvidenceBundle,
|
||||
type EvidenceFilePolicy,
|
||||
} from "../../../src/domain/evidenceBundle.js";
|
||||
|
||||
let directory: string | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
const bundle = () =>
|
||||
createEvidenceBundle([
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "health", parameters: {}, result: true },
|
||||
),
|
||||
]);
|
||||
|
||||
const policy = (root: string): EvidenceFilePolicy => ({
|
||||
roots: [root],
|
||||
maxBytes: 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024,
|
||||
maxNodes: 10_000,
|
||||
});
|
||||
|
||||
describe("evidence bundle filesystem adapter", () => {
|
||||
it("round trips canonical bytes and requires explicit overwrite", async () => {
|
||||
directory = await createTestTempDirectory("rea-evidence-");
|
||||
const path = join(directory, "bundle.json");
|
||||
const evidenceBundle = bundle();
|
||||
const first = await writeEvidenceBundle(
|
||||
evidenceBundle,
|
||||
path,
|
||||
false,
|
||||
policy(directory),
|
||||
);
|
||||
expect(first).toMatchObject({ ok: true, value: { path } });
|
||||
expect(await readFile(path, "utf8")).toBe(
|
||||
serializeEvidenceBundle(evidenceBundle),
|
||||
);
|
||||
expect(await readEvidenceBundle(path, policy(directory))).toEqual({
|
||||
ok: true,
|
||||
value: evidenceBundle,
|
||||
});
|
||||
expect(
|
||||
await compareEvidenceBundlesCommand({
|
||||
leftPath: path,
|
||||
rightPath: path,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
policy: policy(directory),
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
status: "unchanged",
|
||||
summary: { records_unchanged: 1 },
|
||||
},
|
||||
});
|
||||
expect(
|
||||
await writeEvidenceBundle(evidenceBundle, path, false, policy(directory)),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceFileError", reason: "exists" },
|
||||
});
|
||||
expect(
|
||||
await writeEvidenceBundle(evidenceBundle, path, true, policy(directory)),
|
||||
).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("uses valid evidence roots when another configured root is missing", async () => {
|
||||
directory = await createTestTempDirectory("rea-evidence-roots-");
|
||||
const path = join(directory, "bundle.json");
|
||||
const configured = {
|
||||
...policy(directory),
|
||||
roots: [join(directory, "missing"), directory],
|
||||
};
|
||||
expect(
|
||||
await writeEvidenceBundle(bundle(), path, false, configured),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await readEvidenceBundle(path, configured)).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects traversal and symlink escape from approved roots", async () => {
|
||||
directory = await createTestTempDirectory("rea-evidence-");
|
||||
const root = join(directory, "approved");
|
||||
const outside = join(directory, "outside");
|
||||
await mkdir(root);
|
||||
await mkdir(outside);
|
||||
const outsidePath = join(outside, "bundle.json");
|
||||
await writeFile(outsidePath, serializeEvidenceBundle(bundle()));
|
||||
const link = join(root, "escaped.json");
|
||||
await symlink(outsidePath, link);
|
||||
expect(await readEvidenceBundle(link, policy(root))).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceFileError", reason: "outside-root" },
|
||||
});
|
||||
expect(
|
||||
await writeEvidenceBundle(bundle(), outsidePath, true, policy(root)),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceFileError", reason: "outside-root" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects malformed, tampered, oversized, and deeply nested input", async () => {
|
||||
directory = await createTestTempDirectory("rea-evidence-");
|
||||
const malformed = join(directory, "malformed.json");
|
||||
await writeFile(malformed, "{");
|
||||
expect(
|
||||
await readEvidenceBundle(malformed, policy(directory)),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceFileError", reason: "invalid-json" },
|
||||
});
|
||||
|
||||
const tampered = bundle();
|
||||
const tamperedPath = join(directory, "tampered.json");
|
||||
await writeFile(
|
||||
tamperedPath,
|
||||
JSON.stringify({
|
||||
...tampered,
|
||||
records: [{ ...tampered.records[0], normalized_result: "changed" }],
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
await readEvidenceBundle(tamperedPath, policy(directory)),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceIntegrityError" },
|
||||
});
|
||||
|
||||
const oversized = join(directory, "oversized.json");
|
||||
await writeFile(oversized, "x".repeat(100));
|
||||
expect(
|
||||
await readEvidenceBundle(oversized, {
|
||||
...policy(directory),
|
||||
maxBytes: 10,
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceFileError", reason: "too-large" },
|
||||
});
|
||||
|
||||
const deep = join(directory, "deep.json");
|
||||
await writeFile(deep, JSON.stringify({ one: { two: { three: null } } }));
|
||||
expect(
|
||||
await readEvidenceBundle(deep, {
|
||||
...policy(directory),
|
||||
maxDepth: 1,
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceFileError", reason: "too-large" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import {
|
||||
chmod,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
rm,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("curl installer scenarios", { timeout: 20_000 }, () => {
|
||||
it("installs only a pinned REA CLI with closed stdin", async () => {
|
||||
const fixture = await createFixture();
|
||||
const result = await runInstaller(fixture, ["--version", "0.3.0"]);
|
||||
expect(result.stdout).toContain("REA 0.3.0 is installed");
|
||||
expect(result.stdout).toContain("Run ");
|
||||
expect(await readFile(fixture.npmLog, "utf8")).toContain(
|
||||
"install --global --prefix",
|
||||
);
|
||||
expect(await readFile(fixture.reaLog, "utf8")).toBe("--version\n");
|
||||
expect(await readdir(fixture.temporary)).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts Node 25 without installing or replacing it", async () => {
|
||||
const fixture = await createFixture();
|
||||
const result = await runInstaller(fixture, ["--version", "0.3.0"], {
|
||||
FAKE_NODE_VERSION: "25.1.0",
|
||||
});
|
||||
expect(result.stdout).toContain("Runtime: Node.js 25.1.0");
|
||||
});
|
||||
|
||||
it("resolves and validates the latest REA release tag", async () => {
|
||||
const fixture = await createFixture();
|
||||
const result = await runInstaller(fixture);
|
||||
expect(result.stdout).toContain("Version: 0.3.0");
|
||||
});
|
||||
|
||||
it("prints a dry run without invoking npm", async () => {
|
||||
const fixture = await createFixture();
|
||||
const result = await runInstaller(fixture, [
|
||||
"--version",
|
||||
"0.3.0",
|
||||
"--dry-run",
|
||||
]);
|
||||
expect(result.stdout).toContain("no changes made");
|
||||
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"unsupported Node",
|
||||
{ FAKE_NODE_VERSION: "20.0.0" },
|
||||
"REA installation failed: Node.js 20.0.0 is unsupported; use Node.js 22.19+ or 24.11+.\n",
|
||||
],
|
||||
[
|
||||
"npm failure",
|
||||
{ FAKE_NPM_FAIL: "1" },
|
||||
"REA installation failed: npm could not install REA. Check registry access and npm permissions, then retry.\n",
|
||||
],
|
||||
[
|
||||
"version mismatch",
|
||||
{ FAKE_REA_VERSION: "9.9.9" },
|
||||
"REA installation failed: installed version 9.9.9 does not match 0.3.0.\n",
|
||||
],
|
||||
] as const)("fails closed on %s", async (_name, overrides, message) => {
|
||||
const fixture = await createFixture();
|
||||
await expect(
|
||||
runInstaller(fixture, ["--version", "0.3.0"], overrides),
|
||||
).rejects.toMatchObject({ stderr: message });
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"unreadable Node version",
|
||||
["--version", "0.3.0"],
|
||||
{ FAKE_NODE_VERSION: "invalid" },
|
||||
"REA installation failed: the active Node.js version could not be read. Check that node works and is on PATH, then retry.\n",
|
||||
],
|
||||
[
|
||||
"release lookup",
|
||||
[],
|
||||
{ FAKE_CURL_FAIL: "1" },
|
||||
"REA installation failed: the latest REA release could not be resolved. Check network access or pass --version VERSION, then retry.\n",
|
||||
],
|
||||
[
|
||||
"release response",
|
||||
[],
|
||||
{ FAKE_CURL_BODY: "not-json" },
|
||||
"REA installation failed: the release response was invalid. Retry later or pass --version VERSION.\n",
|
||||
],
|
||||
[
|
||||
"release tag",
|
||||
[],
|
||||
{ FAKE_CURL_BODY: '{"tag_name":"unrelated-1.0.0"}' },
|
||||
"REA installation failed: the latest release tag was invalid. Retry later or pass --version VERSION.\n",
|
||||
],
|
||||
[
|
||||
"npm prefix",
|
||||
["--version", "0.3.0"],
|
||||
{ FAKE_PLATFORM: "Darwin", FAKE_NPM_PREFIX_FAIL: "1" },
|
||||
"REA installation failed: the npm global prefix could not be read. Repair the npm configuration, then retry.\n",
|
||||
],
|
||||
[
|
||||
"missing installed command",
|
||||
["--version", "0.3.0"],
|
||||
{ FAKE_NPM_SKIP_BINARY: "1" },
|
||||
"REA installation failed: npm completed without installing the rea command. Check the npm global bin directory and PATH, then retry.\n",
|
||||
],
|
||||
[
|
||||
"unreadable installed version",
|
||||
["--version", "0.3.0"],
|
||||
{ FAKE_REA_VERSION_FAIL: "1" },
|
||||
"REA installation failed: the installed REA version could not be read. Reinstall the requested version, then retry.\n",
|
||||
],
|
||||
] as const)(
|
||||
"reports exact recovery for %s failure",
|
||||
async (_name, args, overrides, message) => {
|
||||
const fixture = await createFixture();
|
||||
await expect(
|
||||
runInstaller(fixture, args, overrides),
|
||||
).rejects.toMatchObject({
|
||||
stderr: message,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("reports exact recovery when curl is missing", async () => {
|
||||
const fixture = await createFixture();
|
||||
await rm(join(fixture.bin, "curl"));
|
||||
await expect(
|
||||
runInstaller(fixture, ["--version", "0.3.0"], {
|
||||
PATH: fixture.bin,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
stderr:
|
||||
"REA installation failed: curl is required. Install curl, then rerun this installer.\n",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
interface InstallerFixture {
|
||||
readonly home: string;
|
||||
readonly bin: string;
|
||||
readonly temporary: string;
|
||||
readonly npmLog: string;
|
||||
readonly reaLog: string;
|
||||
}
|
||||
|
||||
const createFixture = async (): Promise<InstallerFixture> => {
|
||||
const root = await createTestTempDirectory("rea-install-test-");
|
||||
roots.push(root);
|
||||
const home = join(root, "home");
|
||||
const bin = join(root, "bin");
|
||||
const temporary = join(root, "tmp");
|
||||
const npmLog = join(root, "npm.log");
|
||||
const reaLog = join(root, "rea.log");
|
||||
await Promise.all([mkdir(home), mkdir(bin), mkdir(temporary)]);
|
||||
await executable(
|
||||
join(bin, "uname"),
|
||||
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || printf \'%s\\n\' "${FAKE_PLATFORM:-Linux}"\n',
|
||||
);
|
||||
await executable(
|
||||
join(bin, "node"),
|
||||
`#!/bin/sh
|
||||
if [ "$1" = "-p" ]; then printf '%s\n' "\${FAKE_NODE_VERSION:-24.18.0}"; else exec ${shellQuote(process.execPath)} "$@"; fi
|
||||
`,
|
||||
);
|
||||
await executable(
|
||||
join(bin, "npm"),
|
||||
`#!/bin/sh
|
||||
printf '%s\n' "$*" >> "$FAKE_NPM_LOG"
|
||||
[ "$1" = "prefix" ] && { [ "\${FAKE_NPM_PREFIX_FAIL:-}" = "1" ] && exit 1; printf '%s\n' "$FAKE_NPM_PREFIX"; exit 0; }
|
||||
[ "\${FAKE_NPM_FAIL:-}" = "1" ] && exit 1
|
||||
prefix="$HOME/.local"
|
||||
while [ "$#" -gt 0 ]; do
|
||||
if [ "$1" = "--prefix" ]; then shift; prefix="$1"; fi
|
||||
shift
|
||||
done
|
||||
[ "\${FAKE_NPM_SKIP_BINARY:-}" = "1" ] && exit 0
|
||||
mkdir -p "$prefix/bin"
|
||||
cp "$FAKE_REA_SOURCE" "$prefix/bin/rea"
|
||||
chmod +x "$prefix/bin/rea"
|
||||
`,
|
||||
);
|
||||
await executable(
|
||||
join(bin, "curl"),
|
||||
`#!/bin/sh
|
||||
[ "\${FAKE_CURL_FAIL:-}" = "1" ] && exit 1
|
||||
if [ -n "\${FAKE_CURL_BODY:-}" ]; then printf '%s' "$FAKE_CURL_BODY"; else printf '%s' '{"tag_name":"rea-agents-0.3.0"}'; fi
|
||||
`,
|
||||
);
|
||||
await executable(
|
||||
join(bin, "rea-source"),
|
||||
`#!/bin/sh
|
||||
printf '%s\n' "$*" >> "$FAKE_REA_LOG"
|
||||
[ "\${FAKE_REA_VERSION_FAIL:-}" = "1" ] && exit 1
|
||||
[ "$1" = "--version" ] && printf '%s\n' "\${FAKE_REA_VERSION:-0.3.0}"
|
||||
exit 0
|
||||
`,
|
||||
);
|
||||
for (const command of ["chmod", "cp", "mkdir", "tr"])
|
||||
await symlink(`/usr/bin/${command}`, join(bin, command));
|
||||
return { home, bin, temporary, npmLog, reaLog };
|
||||
};
|
||||
|
||||
const executable = async (path: string, source: string): Promise<void> => {
|
||||
await writeFile(path, source);
|
||||
await chmod(path, 0o755);
|
||||
};
|
||||
|
||||
const runInstaller = async (
|
||||
fixture: InstallerFixture,
|
||||
args: readonly string[] = [],
|
||||
overrides: Readonly<Record<string, string>> = {},
|
||||
): Promise<{ readonly stdout: string; readonly stderr: string }> =>
|
||||
execFileAsync("/bin/bash", [join(process.cwd(), "install.sh"), ...args], {
|
||||
env: {
|
||||
...process.env,
|
||||
HOME: fixture.home,
|
||||
TMPDIR: fixture.temporary,
|
||||
PATH: `${fixture.bin}:/usr/bin:/bin`,
|
||||
FAKE_NPM_LOG: fixture.npmLog,
|
||||
FAKE_REA_LOG: fixture.reaLog,
|
||||
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
|
||||
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
|
||||
const shellQuote = (value: string): string =>
|
||||
`'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
@@ -0,0 +1,222 @@
|
||||
import fs from "node:fs";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { add, commit, init } from "isomorphic-git";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
importReferenceSource,
|
||||
normalizeHistoricalSourceParseFailures,
|
||||
} from "../../../src/application/ReferenceSourceImport.js";
|
||||
import { projectReferenceSourceEntryFailure } from "../../../src/application/ReferenceSourceImportEntries.js";
|
||||
import {
|
||||
projectReferenceSourceImportError,
|
||||
type ReferenceSourceImportError,
|
||||
} from "../../../src/application/ReferenceSourceImportTypes.js";
|
||||
import { createHistoricalSourceManifest } from "../../../src/domain/referenceSourceGraph.js";
|
||||
|
||||
const limits = {
|
||||
maxBytes: 1024 * 1024,
|
||||
maxEntries: 1_000,
|
||||
maxDepth: 16,
|
||||
maxPathBytes: 4_096,
|
||||
};
|
||||
|
||||
const fixture = async (parent: string, name: string): Promise<string> => {
|
||||
const root = join(parent, name);
|
||||
await mkdir(join(root, "src"), { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(join(root, "src", "main.ts"), 'import "./dep";\n'),
|
||||
writeFile(join(root, "src", "dep.ts"), "export const value = 1;\n"),
|
||||
writeFile(join(root, "src", "broken.ts"), "const = ;\n"),
|
||||
writeFile(join(root, ".env"), "SECRET_SENTINEL=do-not-record\n"),
|
||||
writeFile(join(root, "package.json"), '{"name":"fixture"}\n'),
|
||||
]);
|
||||
return root;
|
||||
};
|
||||
|
||||
const importTree = (
|
||||
root: string,
|
||||
approvedRoot: string | readonly string[],
|
||||
signal?: AbortSignal,
|
||||
) =>
|
||||
importReferenceSource({
|
||||
root,
|
||||
caller: "reference-import-test",
|
||||
policy: {
|
||||
roots: typeof approvedRoot === "string" ? [approvedRoot] : approvedRoot,
|
||||
secretPatterns: [".env", ".env.*"],
|
||||
...limits,
|
||||
},
|
||||
limits,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
|
||||
describe("reference source import error projection", () => {
|
||||
it("deduplicates exact parse failures without collapsing distinct reasons", () => {
|
||||
const malformed = {
|
||||
path: "src/main.ts",
|
||||
parser: "babel",
|
||||
reason: "Malformed input",
|
||||
};
|
||||
const unexpected = {
|
||||
path: "src/main.ts",
|
||||
parser: "babel",
|
||||
reason: "Unexpected token",
|
||||
};
|
||||
|
||||
expect(
|
||||
normalizeHistoricalSourceParseFailures([
|
||||
unexpected,
|
||||
malformed,
|
||||
unexpected,
|
||||
]),
|
||||
).toEqual([malformed, unexpected]);
|
||||
});
|
||||
|
||||
it("projects entry failures without low-level reader diagnostics", () => {
|
||||
for (const [kind, code] of [
|
||||
["directory", "io"],
|
||||
["symlink", "io"],
|
||||
["file", "io"],
|
||||
["file", "cancelled"],
|
||||
["file", "limit"],
|
||||
["unknown", "unsupported"],
|
||||
] as const) {
|
||||
const message = projectReferenceSourceEntryFailure({
|
||||
status: "failed",
|
||||
path: "safe/path",
|
||||
kind,
|
||||
code,
|
||||
message: "SECRET internal diagnostic /private/path",
|
||||
});
|
||||
expect(message).not.toContain("SECRET");
|
||||
expect(message).not.toContain("/private/path");
|
||||
expect(message).toMatch(/Check|try again|when ready|smaller|supported/u);
|
||||
}
|
||||
});
|
||||
|
||||
it("projects every import failure without raw parser or policy text", () => {
|
||||
const expectedCategories = {
|
||||
cancelled: "cancelled",
|
||||
"invalid-limits": "invalid_input",
|
||||
"invalid-root": "invalid_input",
|
||||
io: "execution_failure",
|
||||
parse: "execution_failure",
|
||||
policy: "permission_required",
|
||||
} as const;
|
||||
for (const [code, category] of Object.entries(expectedCategories)) {
|
||||
const projected = projectReferenceSourceImportError({
|
||||
tag: "reference-source-import",
|
||||
code: code as ReferenceSourceImportError["code"],
|
||||
message: "SECRET parser stack and /private/path",
|
||||
});
|
||||
expect(projected.category).toBe(category);
|
||||
expect(projected.message).not.toContain("SECRET");
|
||||
expect(projected.message).not.toContain("/private/path");
|
||||
expect(projected.message).toMatch(
|
||||
/try again|when ready|positive integer|Check that|REA_REFERENCE_ROOTS_JSON/u,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("reference source import behavior", () => {
|
||||
it("is relocation-stable, resolves imports, and excludes secrets before capture", async () => {
|
||||
const parent = await createTestTempDirectory("rea-reference-import-");
|
||||
try {
|
||||
const leftRoot = await fixture(parent, "left");
|
||||
const rightRoot = await fixture(parent, "right");
|
||||
const [left, right] = await Promise.all([
|
||||
importTree(leftRoot, parent),
|
||||
importTree(rightRoot, parent),
|
||||
]);
|
||||
expect(left.ok).toBe(true);
|
||||
expect(right.ok).toBe(true);
|
||||
if (!left.ok || !right.ok) throw new Error("expected imports to pass");
|
||||
expect(createHistoricalSourceManifest(left.value)).toEqual(
|
||||
createHistoricalSourceManifest(right.value),
|
||||
);
|
||||
expect(left.value.relationships).toContainEqual(
|
||||
expect.objectContaining({
|
||||
from_path: "src/main.ts",
|
||||
to: "src/dep.ts",
|
||||
resolution: "internal",
|
||||
}),
|
||||
);
|
||||
expect(left.value.parse_failures).toHaveLength(1);
|
||||
expect(left.value.exclusions).toContainEqual({
|
||||
path: ".env",
|
||||
reason: "configured-secret",
|
||||
});
|
||||
expect(JSON.stringify(left.value)).not.toContain("SECRET_SENTINEL");
|
||||
expect(JSON.stringify(left.value)).not.toContain(leftRoot);
|
||||
} finally {
|
||||
await rm(parent, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("fails closed outside policy and honors cancellation", async () => {
|
||||
const parent = await createTestTempDirectory("rea-reference-policy-");
|
||||
const outside = await createTestTempDirectory("rea-reference-outside-");
|
||||
try {
|
||||
const root = await fixture(outside, "tree");
|
||||
const denied = await importTree(root, parent);
|
||||
expect(denied).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "policy" },
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const cancelled = await importTree(root, outside, controller.signal);
|
||||
expect(cancelled).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "cancelled" },
|
||||
});
|
||||
} finally {
|
||||
await Promise.all([
|
||||
rm(parent, { recursive: true, force: true }),
|
||||
rm(outside, { recursive: true, force: true }),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses a valid reference root when another configured root is missing", async () => {
|
||||
const parent = await createTestTempDirectory("rea-reference-roots-");
|
||||
try {
|
||||
const root = await fixture(parent, "tree");
|
||||
const imported = await importTree(root, [
|
||||
join(parent, "missing"),
|
||||
parent,
|
||||
]);
|
||||
expect(imported).toMatchObject({ ok: true });
|
||||
} finally {
|
||||
await rm(parent, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("records bounded local Git state without invoking Git", async () => {
|
||||
const parent = await createTestTempDirectory("rea-reference-git-");
|
||||
try {
|
||||
const root = await fixture(parent, "repo");
|
||||
await init({ fs, dir: root, defaultBranch: "main" });
|
||||
for (const filepath of ["package.json", "src/main.ts", "src/dep.ts"])
|
||||
await add({ fs, dir: root, filepath });
|
||||
const oid = await commit({
|
||||
fs,
|
||||
dir: root,
|
||||
author: { name: "REA Test", email: "rea@example.invalid" },
|
||||
message: "fixture",
|
||||
});
|
||||
const result = await importTree(root, parent);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.vcs).toEqual({ kind: "git", head: oid, dirty: null });
|
||||
} finally {
|
||||
await rm(parent, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
import { mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { readReferenceSource } from "../../../src/reference/ReferenceSourceReader.js";
|
||||
|
||||
const limits = {
|
||||
maxBytes: 1_024,
|
||||
maxEntries: 10,
|
||||
maxDepth: 4,
|
||||
maxPathBytes: 100,
|
||||
} as const;
|
||||
|
||||
describe("readReferenceSource entries", () => {
|
||||
it("returns explicit entries in canonical code-point path order", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-");
|
||||
await mkdir(join(root, "nested"));
|
||||
await writeFile(join(root, "z.js"), "z");
|
||||
await writeFile(join(root, "a.js"), "a");
|
||||
await writeFile(join(root, "nested", "b.js"), "b");
|
||||
await writeFile(join(root, "\u{e000}"), "p");
|
||||
await writeFile(join(root, "\u{10000}"), "a");
|
||||
|
||||
const result = await readReferenceSource(root, limits);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.entries.map(({ path }) => path)).toEqual([
|
||||
"a.js",
|
||||
"nested",
|
||||
"nested/b.js",
|
||||
"z.js",
|
||||
"",
|
||||
"𐀀",
|
||||
]);
|
||||
expect(result.value.bytesRead).toBe(5);
|
||||
expect(result.value.truncated).toBe(false);
|
||||
expect(
|
||||
result.value.entries.map((entry) =>
|
||||
entry.status === "read" && entry.kind === "file"
|
||||
? Buffer.from(entry.bytes).toString()
|
||||
: entry.status === "read"
|
||||
? entry.kind
|
||||
: entry.code,
|
||||
),
|
||||
).toEqual(["a", "directory", "b", "z", "p", "a"]);
|
||||
expect(result.value.limitations).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("sanitizes internal, external, and missing symlink targets", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-");
|
||||
const outside = await createTestTempDirectory("rea-outside-");
|
||||
await writeFile(join(outside, "secret"), "secret");
|
||||
await writeFile(join(root, "local"), "local");
|
||||
await symlink("local", join(root, "internal"));
|
||||
await symlink(join(outside, "secret"), join(root, "external"));
|
||||
await symlink("absent", join(root, "missing"));
|
||||
|
||||
const result = await readReferenceSource(root, limits);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.entries).toEqual([
|
||||
{
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
path: "external",
|
||||
target: "<outside-root>",
|
||||
targetState: "external",
|
||||
},
|
||||
{
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
path: "internal",
|
||||
target: "local",
|
||||
targetState: "internal",
|
||||
},
|
||||
{
|
||||
status: "read",
|
||||
kind: "file",
|
||||
path: "local",
|
||||
bytes: expect.any(Uint8Array),
|
||||
size: 5,
|
||||
},
|
||||
{
|
||||
status: "read",
|
||||
kind: "symlink",
|
||||
path: "missing",
|
||||
target: "absent",
|
||||
targetState: "missing",
|
||||
},
|
||||
]);
|
||||
expect(result.value.bytesRead).toBe(5);
|
||||
expect(JSON.stringify(result.value.entries)).not.toContain(outside);
|
||||
});
|
||||
|
||||
it("makes byte, file, depth, and path limits explicit per entry", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-");
|
||||
await writeFile(join(root, "a"), "too large");
|
||||
await writeFile(join(root, "b"), "b");
|
||||
await mkdir(join(root, "deep"));
|
||||
await writeFile(join(root, "deep", "c"), "c");
|
||||
|
||||
const result = await readReferenceSource(root, {
|
||||
maxBytes: 1,
|
||||
maxEntries: 1,
|
||||
maxDepth: 1,
|
||||
maxPathBytes: 4,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.truncated).toBe(true);
|
||||
expect(result.value.entries).toEqual([
|
||||
expect.objectContaining({
|
||||
path: "a",
|
||||
kind: "file",
|
||||
status: "failed",
|
||||
code: "limit",
|
||||
size: 9,
|
||||
}),
|
||||
]);
|
||||
expect(result.value.limitations).toContain(
|
||||
"Traversal stopped because the entry limit was reached.",
|
||||
);
|
||||
expect(result.value.entries).not.toContainEqual(
|
||||
expect.objectContaining({ path: "<tree>" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("applies maxEntries as a global limit across every entry kind", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-");
|
||||
await writeFile(join(root, "a"), "a");
|
||||
await writeFile(join(root, "b"), "b");
|
||||
await writeFile(join(root, "c"), "c");
|
||||
|
||||
const result = await readReferenceSource(root, {
|
||||
...limits,
|
||||
maxEntries: 1,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.entries.map(({ path }) => path)).toEqual(["a"]);
|
||||
expect(result.value.bytesRead).toBe(1);
|
||||
expect(result.value.truncated).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readReferenceSource failures and exclusions", () => {
|
||||
it("applies exclusions to normalized paths before reading entries", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-");
|
||||
await mkdir(join(root, "ignored"));
|
||||
await writeFile(join(root, "ignored", "secret"), "secret");
|
||||
await writeFile(join(root, "kept"), "kept");
|
||||
const checked: string[] = [];
|
||||
|
||||
const result = await readReferenceSource(root, limits, {
|
||||
shouldExclude: (path) => {
|
||||
checked.push(path);
|
||||
return path === "ignored";
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(checked).toEqual(["ignored", "kept"]);
|
||||
expect(result.value.entries.map(({ path }) => path)).toEqual(["kept"]);
|
||||
});
|
||||
|
||||
it("sanitizes exclusion callback failures", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-");
|
||||
await writeFile(join(root, "file"), "value");
|
||||
const result = await readReferenceSource(root, limits, {
|
||||
shouldExclude: () => {
|
||||
throw new Error("private callback detail");
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
error: {
|
||||
tag: "reference-source-reader",
|
||||
code: "io",
|
||||
message: "Reference source exclusion check failed",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("sanitizes filesystem errors", async () => {
|
||||
const missing = join(tmpdir(), "rea-secret-root-that-does-not-exist");
|
||||
const result = await readReferenceSource(missing, limits);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error.message).toBe(
|
||||
"Reference source root could not be resolved",
|
||||
);
|
||||
expect(result.error.message).not.toContain(missing);
|
||||
});
|
||||
|
||||
it("returns typed failures for cancellation and invalid roots", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const cancelled = await readReferenceSource("/unused", limits, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(cancelled).toEqual({
|
||||
ok: false,
|
||||
error: {
|
||||
tag: "reference-source-reader",
|
||||
code: "cancelled",
|
||||
message: "Reference source traversal cancelled",
|
||||
},
|
||||
});
|
||||
|
||||
const invalid = await readReferenceSource(
|
||||
"/path/that/does/not/exist",
|
||||
limits,
|
||||
);
|
||||
expect(invalid.ok).toBe(false);
|
||||
if (invalid.ok) return;
|
||||
expect(invalid.error.code).toBe("invalid-root");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { access, readFile, readdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { SafeOutputTree } from "../../../src/artifacts/SafeOutputTree.js";
|
||||
|
||||
const LIMITS = {
|
||||
maxEntries: 10,
|
||||
maxTotalBytes: 1_024,
|
||||
maxEntryBytes: 512,
|
||||
maxCompressionRatio: 10,
|
||||
maxDepth: 8,
|
||||
maxPathBytes: 256,
|
||||
} as const;
|
||||
|
||||
describe("safe artifact output tree", () => {
|
||||
it("removes only its owned tree after digest failure and proves absence", async () => {
|
||||
const parent = await createTestTempDirectory("rea-safe-output-");
|
||||
const output = join(parent, "published");
|
||||
const tree = await SafeOutputTree.create(output, LIMITS);
|
||||
await expect(
|
||||
tree.write(
|
||||
"nested/file.txt",
|
||||
Readable.from(Buffer.from("unexpected")),
|
||||
"0".repeat(64),
|
||||
),
|
||||
).rejects.toThrow(/disagrees/u);
|
||||
expect(await tree.rollback()).toMatchObject({
|
||||
attempted: true,
|
||||
verified: true,
|
||||
residualPaths: [],
|
||||
});
|
||||
await expect(access(output)).rejects.toThrow();
|
||||
expect(await readdir(parent)).toEqual([]);
|
||||
});
|
||||
|
||||
it("publishes files while building and preserves them after sealing", async () => {
|
||||
const parent = await createTestTempDirectory("rea-safe-output-");
|
||||
const output = join(parent, "published");
|
||||
const tree = await SafeOutputTree.create(output, LIMITS);
|
||||
const bytes = Buffer.from("visible before seal");
|
||||
const digest = createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
await tree.write("file.txt", Readable.from(bytes), digest);
|
||||
expect(await readFile(join(output, "file.txt"), "utf8")).toBe(
|
||||
"visible before seal",
|
||||
);
|
||||
|
||||
await tree.commit();
|
||||
expect(await tree.rollback()).toMatchObject({ attempted: false });
|
||||
expect(await readFile(join(output, "file.txt"), "utf8")).toBe(
|
||||
"visible before seal",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns detached cleanup reports", async () => {
|
||||
const parent = await createTestTempDirectory("rea-safe-output-");
|
||||
const tree = await SafeOutputTree.create(join(parent, "published"), LIMITS);
|
||||
const cleanup = await tree.rollback();
|
||||
(cleanup.residualPaths as string[]).push("/forged/path");
|
||||
|
||||
expect(tree.cleanup.residualPaths).toEqual([]);
|
||||
expect((await tree.rollback()).residualPaths).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { access, realpath, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe.sequential("test temporary directory ownership", () => {
|
||||
let completedDirectory: string | undefined;
|
||||
|
||||
it("creates a canonical directory owned by the current test", async () => {
|
||||
const directory = await createTestTempDirectory("rea-owned-temp-");
|
||||
completedDirectory = directory;
|
||||
|
||||
expect(directory).toBe(await realpath(directory));
|
||||
expect(dirname(directory)).toBe(await realpath(tmpdir()));
|
||||
await writeFile(join(directory, "nested.txt"), "owned");
|
||||
});
|
||||
|
||||
it("removes the prior test directory after that test finishes", async () => {
|
||||
const directory = completedDirectory;
|
||||
if (directory === undefined)
|
||||
throw new Error("Prior test did not create a directory");
|
||||
await expect(access(directory)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["", "../escape-", "/absolute-", "missing-dash"])(
|
||||
"rejects unsafe prefix %j",
|
||||
async (prefix) => {
|
||||
await expect(createTestTempDirectory(prefix)).rejects.toThrow(TypeError);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,467 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
composeBinarySessionFromFactory,
|
||||
composeBinarySessionFromProvider,
|
||||
} from "../../../src/application/BinarySessionComposition.js";
|
||||
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
|
||||
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
it.each([
|
||||
{ unpacked: false, label: "embedded" },
|
||||
{ unpacked: true, label: "unpacked" },
|
||||
])(
|
||||
"returns actionable local details for an $label ASAR integrity error",
|
||||
async ({ unpacked }) => {
|
||||
const root = await createTestTempDirectory("rea-asar-integrity-mcp-");
|
||||
const source = join(root, "source");
|
||||
const original = "console.log('ok');\n";
|
||||
const changed = "console.log('no');\n";
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "main.js"), original);
|
||||
const archive = join(root, "fixture.asar");
|
||||
await createPackageWithOptions(
|
||||
source,
|
||||
archive,
|
||||
unpacked ? { unpack: "*.js" } : {},
|
||||
);
|
||||
if (unpacked) {
|
||||
await writeFile(join(`${archive}.unpacked`, "main.js"), changed);
|
||||
} else {
|
||||
const bytes = await readFile(archive);
|
||||
const contentOffset = bytes.indexOf(original);
|
||||
expect(contentOffset).toBeGreaterThanOrEqual(0);
|
||||
bytes.write(changed, contentOffset, "utf8");
|
||||
await writeFile(archive, bytes);
|
||||
}
|
||||
|
||||
const session = composeBinarySessionFromProvider(new ArtifactProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "asar-integrity-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.structuredContent).toEqual({
|
||||
error: {
|
||||
code: "artifact_integrity_mismatch",
|
||||
category: "integrity_mismatch",
|
||||
message:
|
||||
"Artifact is invalid or has changed. Get a fresh copy and try again.",
|
||||
details: {
|
||||
logical_path: "main.js",
|
||||
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
calculated_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
unpacked,
|
||||
},
|
||||
retryable: false,
|
||||
remediation: {
|
||||
action:
|
||||
"Artifact is invalid or has changed. Get a fresh copy and try again.",
|
||||
restart_required: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
const artifactInventoryResultSchema = z.object({
|
||||
occurrences: z.object({
|
||||
items: z.array(
|
||||
z.object({ logical_path: z.string(), hash_status: z.string() }),
|
||||
),
|
||||
}),
|
||||
integrity_contradictions: z.array(
|
||||
z.object({
|
||||
logical_path: z.string(),
|
||||
declared_sha256: z.string(),
|
||||
observed_sha256: z.string(),
|
||||
trust: z.literal("observed-untrusted"),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
it("records an approved mismatch, preserves verified siblings, and never reports equivalence", async () => {
|
||||
const root = await createTestTempDirectory("rea-asar-continue-mcp-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
const original = "console.log('ok');\n",
|
||||
changed = "console.log('no');\n",
|
||||
secondOriginal = "console.log('up');\n",
|
||||
secondChanged = "console.log('dn');\n";
|
||||
await writeFile(join(source, "main.js"), original);
|
||||
await writeFile(join(source, "second.js"), secondOriginal);
|
||||
await writeFile(join(source, "sibling.js"), "console.log('sibling');\n");
|
||||
const archive = join(root, "fixture.asar");
|
||||
await createPackageWithOptions(source, archive, {});
|
||||
const bytes = await readFile(archive);
|
||||
const contentOffset = bytes.indexOf(original);
|
||||
const secondOffset = bytes.indexOf(secondOriginal);
|
||||
expect(contentOffset).toBeGreaterThanOrEqual(0);
|
||||
expect(secondOffset).toBeGreaterThanOrEqual(0);
|
||||
bytes.write(changed, contentOffset, "utf8");
|
||||
bytes.write(secondChanged, secondOffset, "utf8");
|
||||
await writeFile(archive, bytes);
|
||||
|
||||
const session = composeBinarySessionFromProvider(
|
||||
new ArtifactProvider(false, true),
|
||||
);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "asar-continue-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
const limited = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {
|
||||
integrity_policy: "record-and-continue",
|
||||
integrity_continue_approved: true,
|
||||
max_integrity_mismatches: 1,
|
||||
},
|
||||
});
|
||||
expect(limited).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { code: "truncated" } },
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {
|
||||
integrity_policy: "record-and-continue",
|
||||
integrity_continue_approved: true,
|
||||
},
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
const compact = compactResult(result.structuredContent);
|
||||
const evidence = session.evidenceById(compact.evidence_id);
|
||||
if (evidence === undefined) throw new Error("missing inventory Evidence");
|
||||
const inventory = artifactInventoryResultSchema.parse(compact.result);
|
||||
expect(inventory.integrity_contradictions).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
logical_path: "main.js",
|
||||
trust: "observed-untrusted",
|
||||
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
observed_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
}),
|
||||
expect.objectContaining({ logical_path: "second.js" }),
|
||||
]),
|
||||
);
|
||||
expect(inventory.integrity_contradictions).toHaveLength(2);
|
||||
expect(inventory.occurrences.items).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
logical_path: "main.js",
|
||||
hash_status: "mismatched",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
logical_path: "sibling.js",
|
||||
hash_status: "verified",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
logical_path: "second.js",
|
||||
hash_status: "mismatched",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const inspected = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: {
|
||||
integrity_policy: "record-and-continue",
|
||||
integrity_continue_approved: true,
|
||||
},
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
expect(compactResult(inspected.structuredContent).result).toMatchObject({
|
||||
contradictions: [
|
||||
expect.objectContaining({ occurrence_id: expect.any(String) }),
|
||||
expect.objectContaining({ occurrence_id: expect.any(String) }),
|
||||
],
|
||||
substeps: [
|
||||
expect.objectContaining({
|
||||
operation: "inventory_artifact",
|
||||
status: "completed",
|
||||
}),
|
||||
],
|
||||
});
|
||||
const compared = await client.callTool({
|
||||
name: "compare_artifacts",
|
||||
arguments: {
|
||||
left_evidence_ids: [evidence.evidence_id],
|
||||
right_evidence_ids: [evidence.evidence_id],
|
||||
},
|
||||
});
|
||||
expect(compared.isError).not.toBe(true);
|
||||
expect(compactResult(compared.structuredContent).result).toMatchObject({
|
||||
status: "contradiction",
|
||||
summary: { contradiction: 2 },
|
||||
changes: {
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
logical_path: "main.js",
|
||||
classification: "contradiction",
|
||||
dimensions: ["integrity"],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
logical_path: "second.js",
|
||||
classification: "contradiction",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects altered payloads that reuse session Evidence IDs", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
session.recordEvidence(ARTIFACT_COMPARISON_EXAMPLE.left);
|
||||
session.recordEvidence(ARTIFACT_COMPARISON_EXAMPLE.right);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "artifact-authority-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "compare_artifacts",
|
||||
arguments: {
|
||||
...ARTIFACT_COMPARISON_EXAMPLE,
|
||||
left: {
|
||||
...ARTIFACT_COMPARISON_EXAMPLE.left,
|
||||
limitations: ["caller altered this record"],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toHaveLength(2);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects comparison Evidence that is not owned by the session", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "artifact-ownership-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "compare_artifacts",
|
||||
arguments: ARTIFACT_COMPARISON_EXAMPLE,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toEqual([]);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("opens archives without Hopper, compares them, and exports linked evidence", async () => {
|
||||
const directory = await createTestTempDirectory("rea-artifact-mcp-");
|
||||
const archive = join(directory, "fixture.ipa");
|
||||
const changedArchive = join(directory, "changed.ipa");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("Payload/Fixture.app/main.js", new TextReader("main();"));
|
||||
await writeFile(archive, await writer.close());
|
||||
const changedWriter = new ZipWriter(new Uint8ArrayWriter());
|
||||
await changedWriter.add(
|
||||
"Payload/Fixture.app/main.js",
|
||||
new TextReader("changed();"),
|
||||
);
|
||||
await writeFile(changedArchive, await changedWriter.close());
|
||||
const session = composeBinarySessionFromProvider(new ArtifactProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "artifact-mcp-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const inspected = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: { max_observations: 1, max_relationships: 1 },
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
const inspectionResult = compactResult(inspected.structuredContent);
|
||||
const inspectionEvidence = session.evidenceById(
|
||||
inspectionResult.evidence_id,
|
||||
);
|
||||
if (inspectionEvidence === undefined)
|
||||
throw new Error("missing inspection Evidence");
|
||||
const inspection = z
|
||||
.object({
|
||||
substeps: z.array(
|
||||
z.object({
|
||||
evidence_id: z.string(),
|
||||
status: z.literal("completed"),
|
||||
}),
|
||||
),
|
||||
coverage: z.object({
|
||||
status: z.literal("truncated"),
|
||||
substeps_completed: z.literal(1),
|
||||
}),
|
||||
unexplored_branches: z.array(z.object({ reason: z.string() })),
|
||||
})
|
||||
.parse(inspectionResult.result);
|
||||
expect(inspection.substeps).toHaveLength(1);
|
||||
expect(
|
||||
session.evidenceById(inspection.substeps[0]?.evidence_id ?? ""),
|
||||
).toMatchObject({ operation: "inventory_artifact" });
|
||||
expect(inspectionEvidence.evidence_links).toEqual([
|
||||
inspection.substeps[0]?.evidence_id,
|
||||
]);
|
||||
expect(inspection.unexplored_branches).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ reason: "page-limit" }),
|
||||
]),
|
||||
);
|
||||
const inventory = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(inventory.isError).not.toBe(true);
|
||||
const inventoryResult = compactResult(inventory.structuredContent);
|
||||
const evidence = session.evidenceById(inventoryResult.evidence_id);
|
||||
if (evidence === undefined) throw new Error("missing inventory Evidence");
|
||||
expect(evidence).toMatchObject({
|
||||
provider: { id: "rea-artifact-graph" },
|
||||
subject: { format: "ipa" },
|
||||
});
|
||||
expect(inventoryResult.result).toMatchObject({
|
||||
manifest: { root_format: "ipa" },
|
||||
});
|
||||
const openedChanged = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: changedArchive },
|
||||
});
|
||||
expect(openedChanged.isError).not.toBe(true);
|
||||
const changedInventory = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
const changedResult = compactResult(changedInventory.structuredContent);
|
||||
const changedEvidence = session.evidenceById(changedResult.evidence_id);
|
||||
if (changedEvidence === undefined)
|
||||
throw new Error("missing changed Evidence");
|
||||
const compared = await client.callTool({
|
||||
name: "compare_artifacts",
|
||||
arguments: {
|
||||
left_evidence_ids: [evidence.evidence_id],
|
||||
right_evidence_ids: [changedEvidence.evidence_id],
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(compared.isError).not.toBe(true);
|
||||
expect(compactResult(compared.structuredContent)).toMatchObject({
|
||||
result: { status: "changed" },
|
||||
evidence_id: expect.stringMatching(/^ev_/u),
|
||||
});
|
||||
const unknowns = await client.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: { domain: "artifact-comparison" },
|
||||
});
|
||||
expect(unknowns.structuredContent).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
unknown: expect.objectContaining({
|
||||
domain: "artifact-comparison",
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
const snapshotted = await client.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
const bundleUri = z
|
||||
.object({ result: z.object({ bundle_uri: z.string() }) })
|
||||
.parse(snapshotted.structuredContent).result.bundle_uri;
|
||||
const bundleResource = await client.readResource({ uri: bundleUri });
|
||||
const bundle = evidenceBundleSchema.parse(
|
||||
JSON.parse(
|
||||
z.object({ text: z.string() }).parse(bundleResource.contents[0]).text,
|
||||
),
|
||||
);
|
||||
expect(bundle.records).toHaveLength(6);
|
||||
expect(bundle.artifacts).toContainEqual({
|
||||
digest: { sha256: evidence.subject?.digest.sha256 },
|
||||
format: "ipa",
|
||||
architecture: null,
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
const compactResult = (value: unknown) =>
|
||||
z
|
||||
.object({
|
||||
result: z.unknown(),
|
||||
evidence_id: z.string(),
|
||||
evidence_uri: z.string(),
|
||||
})
|
||||
.parse(value);
|
||||
@@ -0,0 +1,330 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascriptRuntimeReconciliationExample.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const INTEGRATION_TEST_TIMEOUT_MS = 20_000;
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
});
|
||||
|
||||
it(
|
||||
"exposes CLI-equivalent Evidence v2 and session resources",
|
||||
async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "same_origin",
|
||||
webMcpTools: true,
|
||||
sensitiveShapes: true,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const connected = await connectBrowser(browser);
|
||||
|
||||
const tools = await connected.client.listTools();
|
||||
expect(tools.tools.length).toBeLessThan(TOOL_CONTRACTS.length);
|
||||
expect(tools.tools.map(({ name }) => name)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"list_browser_targets",
|
||||
"inspect_web_page",
|
||||
"analyze_web_bundle",
|
||||
"observe_web_session",
|
||||
"discover_webmcp_tools",
|
||||
"compare_web_captures",
|
||||
"capture_web_screenshot",
|
||||
"compare_web_screenshots",
|
||||
]),
|
||||
);
|
||||
const status = await connected.client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
tool_availability: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "inspect_web_page",
|
||||
available: true,
|
||||
reason: "available",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
const listed = await connected.client.callTool({
|
||||
name: "list_browser_targets",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
approved: true,
|
||||
},
|
||||
});
|
||||
expect(listed.isError).not.toBe(true);
|
||||
expect(listed.structuredContent).toMatchObject({
|
||||
result: {
|
||||
targets: { items: [{ target_id: "allowed-page" }] },
|
||||
},
|
||||
});
|
||||
const inspected = await connected.client.callTool({
|
||||
name: "inspect_web_page",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_console_text: true,
|
||||
console_text_approved: true,
|
||||
include_json_body_shapes: true,
|
||||
json_body_schema_approved: true,
|
||||
include_websocket_shapes: true,
|
||||
websocket_shape_approved: true,
|
||||
include_script_sources: true,
|
||||
},
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
expect(inspected.structuredContent).toMatchObject({
|
||||
result: {
|
||||
target: { target_id: "allowed-page" },
|
||||
console: { prior_activity_available: false },
|
||||
network: {
|
||||
prior_activity_available: false,
|
||||
requests: [
|
||||
expect.objectContaining({
|
||||
body_shapes: expect.objectContaining({ status: "included" }),
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const reconciled = await connected.client.callTool({
|
||||
name: "reconcile_javascript_runtime",
|
||||
arguments: {
|
||||
static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers,
|
||||
runtime_observations: [
|
||||
evidenceFor(connected.session, inspected.structuredContent),
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(reconciled.isError).not.toBe(true);
|
||||
expect(reconciled.structuredContent).toMatchObject({
|
||||
result: { summary: { runtime_scripts: 1 } },
|
||||
});
|
||||
expect(JSON.stringify(reconciled.structuredContent)).not.toContain(
|
||||
"source-secret",
|
||||
);
|
||||
const analyzed = await connected.client.callTool({
|
||||
name: "analyze_web_bundle",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
source_capture_approved: true,
|
||||
observation_ms: 0,
|
||||
},
|
||||
});
|
||||
expect(analyzed.isError).not.toBe(true);
|
||||
expect(analyzed.structuredContent).toMatchObject({
|
||||
result: {
|
||||
capture: { scripts_analyzed: 1 },
|
||||
observations: { source_maps: { status: "not_requested" } },
|
||||
},
|
||||
});
|
||||
await verifySessionAndComparisonTools(connected, browser, inspected);
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
const verifySessionAndComparisonTools = async (
|
||||
connected: Awaited<ReturnType<typeof connectBrowser>>,
|
||||
browser: FakeCdpBrowser,
|
||||
inspected: Awaited<ReturnType<Client["callTool"]>>,
|
||||
): Promise<void> => {
|
||||
const observedSession = await connected.client.callTool({
|
||||
name: "observe_web_session",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 5,
|
||||
},
|
||||
});
|
||||
expect(observedSession.isError).not.toBe(true);
|
||||
expect(observedSession.structuredContent).toMatchObject({
|
||||
result: {
|
||||
window: { end_reason: "window_elapsed" },
|
||||
timeline: expect.arrayContaining([
|
||||
expect.objectContaining({ type: "same_origin_reload" }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
const webMcp = await connected.client.callTool({
|
||||
name: "discover_webmcp_tools",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
},
|
||||
});
|
||||
expect(webMcp.isError).not.toBe(true);
|
||||
expect(webMcp.structuredContent).toMatchObject({
|
||||
result: {
|
||||
tools: {
|
||||
items: [expect.objectContaining({ name: "search_orders" })],
|
||||
},
|
||||
},
|
||||
});
|
||||
const capture = normalizedResultOf(inspected.structuredContent);
|
||||
const compared = await connected.client.callTool({
|
||||
name: "compare_web_captures",
|
||||
arguments: {
|
||||
before: { inspection: capture },
|
||||
after: { inspection: capture },
|
||||
},
|
||||
});
|
||||
expect(compared.isError).not.toBe(true);
|
||||
expect(compared.structuredContent).toMatchObject({
|
||||
result: { overall_status: "unknown" },
|
||||
});
|
||||
const screenshot = await connected.client.callTool({
|
||||
name: "capture_web_screenshot",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
screenshot_approved: true,
|
||||
},
|
||||
});
|
||||
expect(screenshot.isError).not.toBe(true);
|
||||
const screenshotArtifact = artifactOf(screenshot.structuredContent);
|
||||
const visual = await connected.client.callTool({
|
||||
name: "compare_web_screenshots",
|
||||
arguments: {
|
||||
before: screenshotArtifact,
|
||||
after: screenshotArtifact,
|
||||
},
|
||||
});
|
||||
expect(visual.isError).not.toBe(true);
|
||||
expect(visual.structuredContent).toMatchObject({
|
||||
result: { status: "identical", changed_pixels: 0 },
|
||||
});
|
||||
const evidenceId = evidenceIdOf(inspected.structuredContent);
|
||||
const evidence = await connected.client.readResource({
|
||||
uri: `rea://evidence/${evidenceId}`,
|
||||
});
|
||||
expect(evidence.contents[0]).toEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining(evidenceId) }),
|
||||
);
|
||||
};
|
||||
|
||||
it("denies origins outside the administrator ceiling before CDP attach", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
browsers.push(browser);
|
||||
const connected = await connectBrowser(browser);
|
||||
const denied = await connected.client.callTool({
|
||||
name: "inspect_web_page",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: ["https://unapproved.example.test"],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
},
|
||||
});
|
||||
expect(denied.isError).toBe(true);
|
||||
expect(denied.structuredContent).toMatchObject({
|
||||
error: {
|
||||
code: "permission_required",
|
||||
details: {
|
||||
missing: { origins: ["https://unapproved.example.test"] },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(browser.commands).toHaveLength(0);
|
||||
});
|
||||
|
||||
const connectBrowser = async (browser: FakeCdpBrowser) => {
|
||||
const config = parseConfig({
|
||||
REA_BROWSER_OBSERVE_ENABLED: "true",
|
||||
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
|
||||
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([browser.allowedOrigin]),
|
||||
});
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
browserObservation: new CdpBrowserProvider(),
|
||||
permissionAuthority: authority.value,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 0,
|
||||
browserObservationEnabled: true,
|
||||
}),
|
||||
});
|
||||
const client = new Client({ name: "browser-mcp-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return { client, session };
|
||||
};
|
||||
|
||||
const evidenceIdOf = (value: unknown): string => {
|
||||
if (
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
!("evidence_id" in value) ||
|
||||
typeof value.evidence_id !== "string"
|
||||
)
|
||||
throw new TypeError("Missing browser evidence ID");
|
||||
return value.evidence_id;
|
||||
};
|
||||
|
||||
const normalizedResultOf = (value: unknown): unknown => {
|
||||
if (typeof value !== "object" || value === null || !("result" in value))
|
||||
throw new TypeError("Missing normalized browser result");
|
||||
return value.result;
|
||||
};
|
||||
|
||||
const evidenceFor = (session: BinarySession, value: unknown) => {
|
||||
const evidence = session.evidenceById(evidenceIdOf(value));
|
||||
if (evidence === undefined) throw new TypeError("Missing session Evidence");
|
||||
return evidence;
|
||||
};
|
||||
|
||||
const artifactOf = (value: unknown): unknown => {
|
||||
const normalized = normalizedResultOf(value);
|
||||
if (
|
||||
typeof normalized !== "object" ||
|
||||
normalized === null ||
|
||||
!("artifact" in normalized)
|
||||
)
|
||||
throw new TypeError("Missing screenshot artifact");
|
||||
return normalized.artifact;
|
||||
};
|
||||
@@ -0,0 +1,278 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { dirname } from "node:path";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
|
||||
import type { BrowserScenarioCapturePort } from "../../../src/application/BrowserScenarioCapturePort.js";
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { sanitizeBrowserUrl } from "../../../src/domain/browserObservation.js";
|
||||
import type { BrowserScenario } from "../../../src/domain/browserScenario.js";
|
||||
import {
|
||||
browserScenarioCaptureSchema,
|
||||
type BrowserScenarioCapture,
|
||||
} from "../../../src/domain/browserScenarioCapture.js";
|
||||
import type { AnalysisError } from "../../../src/domain/errors.js";
|
||||
import { ok, type Result } from "../../../src/domain/result.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const providerIdentity: ProviderIdentity = {
|
||||
id: "test-browser-scenario",
|
||||
name: "Test browser scenario provider",
|
||||
version: "1",
|
||||
};
|
||||
|
||||
class FakeBrowserScenarioProvider implements BrowserScenarioCapturePort {
|
||||
readonly scenarios: BrowserScenario[] = [];
|
||||
|
||||
identity(): ProviderIdentity {
|
||||
return providerIdentity;
|
||||
}
|
||||
|
||||
captureScenario(
|
||||
scenario: BrowserScenario,
|
||||
_options?: ExecutionOptions,
|
||||
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
|
||||
this.scenarios.push(scenario);
|
||||
return Promise.resolve(ok(captureFor(scenario)));
|
||||
}
|
||||
}
|
||||
|
||||
const artifacts = {
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "not_requested" },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "not_requested" },
|
||||
history: { state: "not_requested" },
|
||||
storage: { state: "not_requested" },
|
||||
} as const;
|
||||
|
||||
const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
|
||||
const start = scenario.start_url.url;
|
||||
const step = (stepIndex: number, stepId: string, action: string) => ({
|
||||
step_index: stepIndex,
|
||||
step_id: stepId,
|
||||
action,
|
||||
status: "completed",
|
||||
elapsed_ms: 1,
|
||||
before_url: sanitizeBrowserUrl(start),
|
||||
after_url: sanitizeBrowserUrl(start),
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts,
|
||||
completeness: {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
},
|
||||
});
|
||||
return browserScenarioCaptureSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: scenario.browser.mode,
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
product: "Test Browser",
|
||||
version: "1",
|
||||
},
|
||||
scenario: {
|
||||
start_origin: new URL(start).origin,
|
||||
allowed_origins: scenario.allowed_origins,
|
||||
action_count: scenario.actions.length,
|
||||
secret_references: scenario.secrets.map(({ secret_id: id }) => id),
|
||||
},
|
||||
duration_ms: 2,
|
||||
steps: [
|
||||
step(0, "scenario_start", "goto_start"),
|
||||
...scenario.actions.map((action, index) =>
|
||||
step(index + 1, action.step_id, action.action),
|
||||
),
|
||||
],
|
||||
events: { retained: 0, dropped: 0, items: [] },
|
||||
completeness: {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
};
|
||||
|
||||
const scenario = (origin = "https://app.example.test") => ({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: process.execPath,
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: `${origin}/`, query: [] },
|
||||
allowed_origins: [origin],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "login-input",
|
||||
action: "fill",
|
||||
locator: { kind: "test_id", value: "password" },
|
||||
value: { source: "secret", secret_id: "login_input" },
|
||||
},
|
||||
],
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [
|
||||
{
|
||||
secret_id: "login_input",
|
||||
environment_variable: "REA_TEST_PASSWORD",
|
||||
purpose: "input",
|
||||
redaction: "replace-with-secret-reference",
|
||||
},
|
||||
],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: { after_each_step: [], at_end: [], events: [] },
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 100,
|
||||
max_frames: 10,
|
||||
max_workers: 5,
|
||||
max_popups: 2,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 1_000,
|
||||
max_accessibility_nodes: 1_000,
|
||||
max_screenshots: 2,
|
||||
max_screenshot_bytes: 1_048_576,
|
||||
max_storage_entries: 100,
|
||||
max_total_metadata_bytes: 1_048_576,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
describe("browser scenario MCP tool", () => {
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(resources.splice(0).map((item) => item.close()));
|
||||
});
|
||||
|
||||
test("authorizes exact scope, records Evidence, and retains no secret value", async () => {
|
||||
const configured = parseConfig({
|
||||
REA_BROWSER_SCENARIO_ENABLED: "true",
|
||||
REA_BROWSER_SCENARIO_AUTO_GRANT: "true",
|
||||
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: JSON.stringify([
|
||||
dirname(process.execPath),
|
||||
]),
|
||||
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
|
||||
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: '["REA_TEST_PASSWORD"]',
|
||||
});
|
||||
if (!configured.ok) throw configured.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(configured.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const provider = new FakeBrowserScenarioProvider();
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
browserObservation: new CdpBrowserProvider(),
|
||||
browserScenarioCapture: provider,
|
||||
permissionAuthority: authority.value,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 0,
|
||||
browserObservationEnabled: true,
|
||||
browserScenarioEnabled: true,
|
||||
}),
|
||||
});
|
||||
const client = new Client({ name: "browser-scenario-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const captured = await client.callTool({
|
||||
name: "capture_browser_scenario",
|
||||
arguments: scenario(),
|
||||
});
|
||||
expect(captured.isError, JSON.stringify(captured)).not.toBe(true);
|
||||
expect(captured.structuredContent).toMatchObject({
|
||||
result: {
|
||||
scenario: {
|
||||
secret_references: ["login_input"],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(provider.scenarios).toHaveLength(1);
|
||||
expect(JSON.stringify(captured.structuredContent)).not.toContain(
|
||||
"correct horse battery staple",
|
||||
);
|
||||
const evidenceId = Reflect.get(
|
||||
captured.structuredContent ?? {},
|
||||
"evidence_id",
|
||||
);
|
||||
expect(session.evidenceById(String(evidenceId))).toMatchObject({
|
||||
predicate_type: "rea.browser-scenario-capture/v1",
|
||||
});
|
||||
const captureResult = Reflect.get(
|
||||
captured.structuredContent ?? {},
|
||||
"result",
|
||||
);
|
||||
const compared = await client.callTool({
|
||||
name: "compare_web_captures",
|
||||
arguments: {
|
||||
before_scenario: captureResult,
|
||||
after_scenario: captureResult,
|
||||
normalization: { rules: [] },
|
||||
},
|
||||
});
|
||||
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
|
||||
expect(compared.structuredContent).toMatchObject({
|
||||
result: {
|
||||
comparison_kind: "browser_scenario",
|
||||
overall_status: "unchanged",
|
||||
alignment: { status: "aligned", aligned_steps: 2 },
|
||||
},
|
||||
});
|
||||
|
||||
const denied = await client.callTool({
|
||||
name: "capture_browser_scenario",
|
||||
arguments: scenario("https://other.example.test"),
|
||||
});
|
||||
expect(denied.isError).toBe(true);
|
||||
expect(provider.scenarios).toHaveLength(1);
|
||||
|
||||
const unapprovedEnvironment = scenario();
|
||||
const secretDeclaration = unapprovedEnvironment.secrets.at(0);
|
||||
if (secretDeclaration === undefined)
|
||||
throw new Error("Scenario secret fixture disappeared");
|
||||
secretDeclaration.environment_variable = "REA_UNAPPROVED_SECRET";
|
||||
const deniedSecret = await client.callTool({
|
||||
name: "capture_browser_scenario",
|
||||
arguments: unapprovedEnvironment,
|
||||
});
|
||||
expect(deniedSecret.isError).toBe(true);
|
||||
expect(provider.scenarios).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
serializeEvidenceBundle,
|
||||
} from "../../../src/domain/evidenceBundle.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
const sourceEvidence = (label: string) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
operation: "observe",
|
||||
parameters: { label },
|
||||
result: { label },
|
||||
confidence: "observed",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
|
||||
describe("bundle comparison MCP integration", () => {
|
||||
it("reads two approved bounded bundle files and records a compact result", async () => {
|
||||
const root = await createTestTempDirectory("rea-bundle-mcp-");
|
||||
roots.push(root);
|
||||
const leftPath = join(root, "left.json");
|
||||
const rightPath = join(root, "right.json");
|
||||
const leftRecord = sourceEvidence("left");
|
||||
const rightRecord = sourceEvidence("right");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
leftPath,
|
||||
serializeEvidenceBundle(createEvidenceBundle([leftRecord])),
|
||||
),
|
||||
writeFile(
|
||||
rightPath,
|
||||
serializeEvidenceBundle(createEvidenceBundle([rightRecord])),
|
||||
),
|
||||
]);
|
||||
const connected = await connect(root);
|
||||
try {
|
||||
const result = await connected.client.callTool({
|
||||
name: "compare_bundles",
|
||||
arguments: {
|
||||
left_bundle_path: leftPath,
|
||||
right_bundle_path: rightPath,
|
||||
record_pairs: [
|
||||
{
|
||||
left_evidence_id: leftRecord.evidence_id,
|
||||
right_evidence_id: rightRecord.evidence_id,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: { status: "changed" },
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
|
||||
});
|
||||
} finally {
|
||||
await connected.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a bundle path outside the approved root", async () => {
|
||||
const root = await createTestTempDirectory("rea-bundle-root-");
|
||||
const outside = await createTestTempDirectory("rea-bundle-outside-");
|
||||
roots.push(root, outside);
|
||||
const leftPath = join(root, "left.json");
|
||||
const rightPath = join(outside, "right.json");
|
||||
const encoded = serializeEvidenceBundle(createEvidenceBundle([]));
|
||||
await Promise.all([
|
||||
writeFile(leftPath, encoded),
|
||||
writeFile(rightPath, encoded),
|
||||
]);
|
||||
const connected = await connect(root);
|
||||
try {
|
||||
const result = await connected.client.callTool({
|
||||
name: "compare_bundles",
|
||||
arguments: {
|
||||
left_bundle_path: leftPath,
|
||||
right_bundle_path: rightPath,
|
||||
},
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { code: "outside_approved_root" } },
|
||||
});
|
||||
} finally {
|
||||
await connected.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects an oversized approved bundle", async () => {
|
||||
const root = await createTestTempDirectory("rea-bundle-size-");
|
||||
roots.push(root);
|
||||
const leftPath = join(root, "left.json");
|
||||
const rightPath = join(root, "right.json");
|
||||
await Promise.all([
|
||||
writeFile(leftPath, " ".repeat(2_000)),
|
||||
writeFile(rightPath, serializeEvidenceBundle(createEvidenceBundle([]))),
|
||||
]);
|
||||
const connected = await connect(root, 1_024);
|
||||
try {
|
||||
const result = await connected.client.callTool({
|
||||
name: "compare_bundles",
|
||||
arguments: {
|
||||
left_bundle_path: leftPath,
|
||||
right_bundle_path: rightPath,
|
||||
},
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { code: "truncated" } },
|
||||
});
|
||||
} finally {
|
||||
await connected.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const connect = async (root: string, maxBytes = 1024 * 1024) => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
evidenceFilePolicy: {
|
||||
roots: [root],
|
||||
maxBytes,
|
||||
maxDepth: 68,
|
||||
maxStringLength: 1024 * 1024,
|
||||
maxNodes: 100_000,
|
||||
},
|
||||
});
|
||||
const client = new Client({ name: "bundle-comparison-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return {
|
||||
client,
|
||||
close: async () => {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { mcpTest } from "../../support/mcp/mcpFixture.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
const analysis = {
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
};
|
||||
|
||||
describe("MCP server composition", () => {
|
||||
it("constructs independent MCP server instances", () => {
|
||||
expect(createServer(analysis)).not.toBe(createServer(analysis));
|
||||
});
|
||||
|
||||
mcpTest("does not advertise unavailable session tools", async ({ mcp }) => {
|
||||
const server = createServer(analysis);
|
||||
const client = await mcp.connect(server, {
|
||||
name: "composition-test",
|
||||
version: "1.0.0",
|
||||
});
|
||||
expect(client.getInstructions()).not.toContain("open_binary");
|
||||
const names = (await client.listTools()).tools.map(({ name }) => name);
|
||||
expect(names).not.toContain("compare_managed_members");
|
||||
expect(names).not.toContain("plan_managed_runtime_correlation");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runDerivedOperation } from "../../../src/server/runDerivedOperation.js";
|
||||
|
||||
const context = (
|
||||
controller: AbortController,
|
||||
notifications: unknown[] = [],
|
||||
) => ({
|
||||
mcpReq: {
|
||||
signal: controller.signal,
|
||||
_meta: { progressToken: "derived-test" },
|
||||
notify: (notification: unknown) => {
|
||||
notifications.push(notification);
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe("derived MCP operation boundary", () => {
|
||||
it("cancels before computation and never evaluates the operation", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
let computed = false;
|
||||
const result = await runDerivedOperation(
|
||||
context(controller),
|
||||
"compare",
|
||||
() => {
|
||||
computed = true;
|
||||
return "impossible";
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(computed).toBe(false);
|
||||
});
|
||||
|
||||
it("lets cancellation win immediately before result publication", async () => {
|
||||
const controller = new AbortController();
|
||||
const result = await runDerivedOperation(
|
||||
context(controller),
|
||||
"compare",
|
||||
() => {
|
||||
controller.abort();
|
||||
return "must-not-publish";
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("emits bounded monotonic progress with one terminal state", async () => {
|
||||
const controller = new AbortController();
|
||||
const notifications: Array<{
|
||||
params?: { progress?: number; total?: number };
|
||||
}> = [];
|
||||
const result = await runDerivedOperation(
|
||||
context(controller, notifications),
|
||||
"compare",
|
||||
() => "complete",
|
||||
);
|
||||
|
||||
expect(result).toEqual({ ok: true, value: "complete" });
|
||||
expect(notifications.map(({ params }) => params?.progress)).toEqual([0, 2]);
|
||||
expect(notifications.every(({ params }) => params?.total === 2)).toBe(true);
|
||||
});
|
||||
|
||||
it("projects synchronous computation failures into a typed result", async () => {
|
||||
const result = await runDerivedOperation(
|
||||
context(new AbortController()),
|
||||
"compare_artifacts",
|
||||
() => {
|
||||
throw new TypeError("malformed comparison evidence");
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
operation: "compare_artifacts",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,351 @@
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
|
||||
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
|
||||
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(resources.splice(0).map(async (item) => item.close()));
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("exposes root-confined Electron discovery and inspection as Evidence v2", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-mcp-");
|
||||
temporary.push(root);
|
||||
await writeFile(join(root, "index.html"), "<script src='app.js'></script>");
|
||||
await writeFile(
|
||||
join(root, "app.js"),
|
||||
"export const observed = 'source-secret';",
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({ name: "runtime-fixture", renderer: "index.html" }),
|
||||
);
|
||||
await writeFile(join(root, "worker.js"), "self.onmessage = () => {};\n");
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const config = parseConfig({
|
||||
REA_ELECTRON_OBSERVE_ENABLED: "true",
|
||||
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
|
||||
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
});
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
electronObservation: new CdpElectronProvider(),
|
||||
permissionAuthority: authority.value,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 1,
|
||||
electronObservationEnabled: true,
|
||||
}),
|
||||
});
|
||||
const client = new Client({ name: "electron-mcp-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const listed = await client.callTool({
|
||||
name: "list_electron_targets",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
approved: true,
|
||||
},
|
||||
});
|
||||
expect(listed.isError).not.toBe(true);
|
||||
expect(listed.structuredContent).toMatchObject({
|
||||
result: {
|
||||
targets: { items: [{ target_id: "electron-page" }] },
|
||||
},
|
||||
});
|
||||
const inspected = await client.callTool({
|
||||
name: "inspect_electron_page",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
target_id: "electron-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_script_sources: true,
|
||||
source_capture_approved: true,
|
||||
},
|
||||
});
|
||||
const analyzed = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root, approved: true, detail: "full" },
|
||||
});
|
||||
expect(analyzed.isError).not.toBe(true);
|
||||
expect(analyzed.structuredContent).toMatchObject({
|
||||
result: { graph: { nodes: expect.any(Array), edges: expect.any(Array) } },
|
||||
});
|
||||
const analysisText = analyzed.content.find(({ type }) => type === "text");
|
||||
expect(analysisText).toBeDefined();
|
||||
if (analysisText?.type !== "text")
|
||||
throw new TypeError("Missing JavaScript analysis text projection");
|
||||
expect(analysisText.text).not.toContain('"nodes":[');
|
||||
const reconciled = await client.callTool({
|
||||
name: "reconcile_javascript_runtime",
|
||||
arguments: {
|
||||
static_layers: [
|
||||
{
|
||||
role: "application",
|
||||
analysis: evidenceFor(session, analyzed.structuredContent),
|
||||
},
|
||||
],
|
||||
runtime_observations: [evidenceFor(session, inspected.structuredContent)],
|
||||
},
|
||||
});
|
||||
expect(reconciled.isError).not.toBe(true);
|
||||
expect(reconciled.structuredContent).toMatchObject({
|
||||
result: {
|
||||
summary: { runtime_scripts: 1, matched: expect.any(Number) },
|
||||
source_map_authority: { used_for_primary_matching: false },
|
||||
},
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
expect(inspected.structuredContent).toMatchObject({
|
||||
result: {
|
||||
target: { file_path: expect.stringMatching(/\/index\.html$/u) },
|
||||
scripts: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
frame_id: "frame-main",
|
||||
file_path: expect.stringMatching(/\/app\.js$/u),
|
||||
}),
|
||||
],
|
||||
},
|
||||
workers: [
|
||||
expect.objectContaining({
|
||||
target_id: "electron-worker",
|
||||
opener_target_id: "electron-page",
|
||||
file_path: expect.stringMatching(/\/worker\.js$/u),
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
const outside = join(root, "..", `outside-${Date.now().toString(16)}`);
|
||||
await mkdir(outside);
|
||||
temporary.push(outside);
|
||||
const commandsBeforeDenial = browser.commands.length;
|
||||
const denied = await client.callTool({
|
||||
name: "list_electron_targets",
|
||||
arguments: {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [outside],
|
||||
approved: true,
|
||||
},
|
||||
});
|
||||
expect(denied.isError).toBe(true);
|
||||
expect(denied.structuredContent).toMatchObject({
|
||||
error: {
|
||||
code: "permission_required",
|
||||
details: { missing: { roots: [expect.stringMatching(/outside-/u)] } },
|
||||
},
|
||||
});
|
||||
expect(browser.commands).toHaveLength(commandsBeforeDenial);
|
||||
}, 20_000);
|
||||
|
||||
it("exposes the target-free static JavaScript application workflow", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-static-mcp-");
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const config = parseConfig({
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
});
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
permissionAuthority: authority.value,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 1,
|
||||
}),
|
||||
});
|
||||
const client = new Client({
|
||||
name: "electron-static-mcp-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const analyzed = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root, approved: true },
|
||||
});
|
||||
|
||||
expect(analyzed.isError).not.toBe(true);
|
||||
const projected = z
|
||||
.object({
|
||||
evidence_id: z.string(),
|
||||
result: z.object({
|
||||
schema_version: z.literal(2),
|
||||
input_path: z.string(),
|
||||
unknowns: z.array(z.string()),
|
||||
summary: z.object({
|
||||
browser_windows: z.number(),
|
||||
context_bridge_apis: z.number(),
|
||||
ipc: z.object({ paired_renderer_transmissions: z.number() }),
|
||||
}),
|
||||
graph: z.object({
|
||||
graph_id: z.string(),
|
||||
node_count: z.number(),
|
||||
edge_count: z.number(),
|
||||
top_findings: z.array(z.unknown()),
|
||||
pages: z.object({ nodes: z.string(), edges: z.string() }),
|
||||
}),
|
||||
semantic_graph: z.object({
|
||||
graph_id: z.string(),
|
||||
nodes: z.number(),
|
||||
relations: z.number(),
|
||||
unknown_frontiers: z.number(),
|
||||
query_tool: z.literal("trace_javascript_semantics"),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(analyzed.structuredContent);
|
||||
expect(projected.result).toMatchObject({
|
||||
input_path: expect.stringMatching(/rea-electron-static-mcp-/u),
|
||||
summary: {
|
||||
browser_windows: 3,
|
||||
context_bridge_apis: 2,
|
||||
ipc: { paired_renderer_transmissions: 4 },
|
||||
},
|
||||
});
|
||||
expect(projected.result.graph.node_count).toBeGreaterThan(0);
|
||||
expect(projected.result.semantic_graph.nodes).toBeGreaterThan(0);
|
||||
expect(JSON.stringify(analyzed.structuredContent)).not.toContain('"nodes":[');
|
||||
|
||||
const nodePage = await client.readResource({
|
||||
uri: projected.result.graph.pages.nodes,
|
||||
});
|
||||
const nodeContent = nodePage.contents[0];
|
||||
if (nodeContent === undefined || !("text" in nodeContent))
|
||||
throw new TypeError("Missing JavaScript application graph node page");
|
||||
expect(JSON.parse(nodeContent.text)).toMatchObject({
|
||||
evidence_id: projected.evidence_id,
|
||||
graph_id: projected.result.graph.graph_id,
|
||||
collection: "nodes",
|
||||
items: expect.any(Array),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an unconfigured investigation ceiling before static analysis", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-denied-mcp-");
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const config = parseConfig({});
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
permissionAuthority: authority.value,
|
||||
});
|
||||
const client = new Client({
|
||||
name: "electron-denied-mcp-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {
|
||||
detail: "capabilities",
|
||||
capability_family: "electron-provider",
|
||||
limit: 100,
|
||||
},
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
capabilities: {
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "analyze_javascript_application",
|
||||
available: false,
|
||||
reason: "policy_disabled",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "reconcile_javascript_runtime",
|
||||
available: true,
|
||||
reason: "available",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
(await client.listTools()).tools.some(
|
||||
({ name }) => name === "analyze_javascript_application",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
const evidenceFor = (session: BinarySession, value: unknown) => {
|
||||
if (
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
!("evidence_id" in value) ||
|
||||
typeof value.evidence_id !== "string"
|
||||
)
|
||||
throw new TypeError("Missing compact Evidence ID");
|
||||
const evidence = session.evidenceById(value.evidence_id);
|
||||
if (evidence === undefined) throw new TypeError("Missing session Evidence");
|
||||
return evidence;
|
||||
};
|
||||
@@ -0,0 +1,315 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managedWorkflowToolContracts.js";
|
||||
import {
|
||||
ENHANCED_TOOL_CONTRACTS,
|
||||
SESSION_TOOL_CONTRACTS,
|
||||
TOOL_CONTRACTS,
|
||||
} from "../../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../../../src/domain/jsonValue.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const PROCEDURES = {
|
||||
"0x1": "_TtC7Fixture5Class",
|
||||
"0x2": "_TtV7Fixture6Struct",
|
||||
"0x3": "_TtP7Fixture8Protocol",
|
||||
"0x4": "_TtO7Fixture4Enum",
|
||||
"0x5": "_TtE7Fixture9Extension",
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
const jsonResult = (result: CallToolResult): JsonValue => {
|
||||
if (result.structuredContent === undefined)
|
||||
throw new Error("Tool result omitted structured content");
|
||||
const structured = jsonValueSchema.safeParse(result.structuredContent);
|
||||
if (!structured.success)
|
||||
throw new Error("Tool structured result was not JSON");
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"normalized_result" in structured.data
|
||||
) {
|
||||
return structured.data.normalized_result ?? null;
|
||||
}
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"evidence_id" in structured.data &&
|
||||
"result" in structured.data
|
||||
)
|
||||
return structured.data.result ?? null;
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
if (text?.type !== "text")
|
||||
throw new Error("Tool result omitted text content");
|
||||
const decoded: unknown = JSON.parse(text.text);
|
||||
const parsed = jsonValueSchema.safeParse(decoded);
|
||||
if (!parsed.success) throw new Error("Tool result was not JSON");
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("lists the complete target-open analysis surface", async () => {
|
||||
const client = await connect();
|
||||
const listed = await client.listTools();
|
||||
expect(listed.tools).toHaveLength(
|
||||
TOOL_CONTRACTS.length -
|
||||
SESSION_TOOL_CONTRACTS.length -
|
||||
MANAGED_WORKFLOW_TOOL_CONTRACTS.length,
|
||||
);
|
||||
expect(
|
||||
listed.tools
|
||||
.map(({ name }) => name)
|
||||
.filter((name) =>
|
||||
ENHANCED_TOOL_CONTRACTS.some((tool) => tool.name === name),
|
||||
)
|
||||
.sort(),
|
||||
).toEqual(ENHANCED_TOOL_CONTRACTS.map(({ name }) => name).sort());
|
||||
});
|
||||
|
||||
it("executes all thirteen tools through production registration", async () => {
|
||||
const client = await connect();
|
||||
const calls = [
|
||||
["swift_classes", { pattern: "Fixture" }],
|
||||
["get_objc_classes", { pattern: "Fixture" }],
|
||||
["get_objc_protocols", {}],
|
||||
["batch_decompile", { addresses: ["0x1", "0x2"] }],
|
||||
["get_call_graph", { address: "0x1", direction: "forward", depth: 2 }],
|
||||
["analyze_swift_types", {}],
|
||||
["find_xrefs_to_name", { name: "entry" }],
|
||||
["binary_overview", {}],
|
||||
["analyze_function", { procedure: "0x1" }],
|
||||
["inspect_native_api", { procedure: "0x1" }],
|
||||
["trace_feature", { query: "hello", max_operations: 10 }],
|
||||
["find_code_for_string", { query: "hello", max_operations: 10 }],
|
||||
["trace_call_path", { start: "0x1", goal: "0x2", max_operations: 10 }],
|
||||
] as const;
|
||||
const results = await Promise.all(
|
||||
calls.map(async ([name, arguments_]) =>
|
||||
jsonResult(await client.callTool({ name, arguments: arguments_ })),
|
||||
),
|
||||
);
|
||||
expect(results[0]).toMatchObject({ count: 1 });
|
||||
expect(results[1]).toMatchObject({ count: 1 });
|
||||
expect(results[2]).toMatchObject({ count: 1 });
|
||||
expect(results[3]).toEqual({
|
||||
items: [
|
||||
{ address: "0x1", status: "ok", pseudocode: "pseudo:0x1" },
|
||||
{ address: "0x2", status: "ok", pseudocode: "pseudo:0x2" },
|
||||
],
|
||||
total: 2,
|
||||
succeeded: 2,
|
||||
failed: 0,
|
||||
});
|
||||
expect(results[4]).toEqual({
|
||||
"0": [{ address: "0x1", status: "ok", calls: ["0x2", "0x3"] }],
|
||||
"1": [
|
||||
{ address: "0x2", status: "ok", calls: ["0x1"] },
|
||||
{ address: "0x3", status: "ok", calls: [] },
|
||||
],
|
||||
});
|
||||
expect(results[5]).toMatchObject({ total: 6 });
|
||||
expect(results[6]).toEqual({
|
||||
status: "resolved",
|
||||
name: "entry",
|
||||
address: "0x13",
|
||||
xrefs: ["0x20", "0x21"],
|
||||
});
|
||||
expect(results[7]).toMatchObject({
|
||||
document: "fixture",
|
||||
segment_count: 1,
|
||||
procedure_count: 6,
|
||||
string_count: 1,
|
||||
});
|
||||
expect(results[8]).toMatchObject({
|
||||
procedure: { address: "0x1", name: "entry" },
|
||||
pseudocode: { text: "return 0;" },
|
||||
});
|
||||
expect(results[9]).toMatchObject({
|
||||
procedure: { address: "0x1", name: "entry" },
|
||||
boundary: { available: false },
|
||||
unsupported_branches: [
|
||||
"structured-boundary-types",
|
||||
"jump-table-data-mapping",
|
||||
],
|
||||
residual_unknowns: expect.arrayContaining([
|
||||
expect.stringContaining("boundary types"),
|
||||
]),
|
||||
substeps: [
|
||||
{ operation: "analyze_function", status: "completed" },
|
||||
{ operation: "project_native_api_boundary", status: "unsupported" },
|
||||
{ operation: "preserve_residual_unknowns", status: "completed" },
|
||||
],
|
||||
});
|
||||
expect(results[10]).toMatchObject({
|
||||
query: "hello",
|
||||
search_mode: "literal",
|
||||
truncated: false,
|
||||
references: [
|
||||
{ target_address: "0x30", source_address: "0x20" },
|
||||
{ target_address: "0x30", source_address: "0x21" },
|
||||
],
|
||||
});
|
||||
expect(results[11]).toMatchObject({
|
||||
query: "hello",
|
||||
matches: [{ type: "string", address: "0x30", value: "hello" }],
|
||||
truncated: false,
|
||||
});
|
||||
expect(results[12]).toMatchObject({
|
||||
start: "0x1",
|
||||
goal: "0x2",
|
||||
direction: "forward",
|
||||
goal_status: "reached",
|
||||
traversal_path: ["0x1", "0x2"],
|
||||
nodes: [
|
||||
{ address: "0x1", depth: 0 },
|
||||
{ address: "0x2", depth: 1 },
|
||||
],
|
||||
truncated: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,262 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
|
||||
import { AnalysisOutputError } from "../../../src/domain/errors.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const PROCEDURES = {
|
||||
"0x1": "_TtC7Fixture5Class",
|
||||
"0x2": "_TtV7Fixture6Struct",
|
||||
"0x3": "_TtP7Fixture8Protocol",
|
||||
"0x4": "_TtO7Fixture4Enum",
|
||||
"0x5": "_TtE7Fixture9Extension",
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("returns Evidence IDs and explicit call-path frontiers at limits", async () => {
|
||||
const client = await connect();
|
||||
const result = await client.callTool({
|
||||
name: "trace_call_path",
|
||||
arguments: {
|
||||
start: "0x1",
|
||||
goal: "0x3",
|
||||
max_nodes: 1,
|
||||
max_operations: 10,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
result: {
|
||||
goal_status: "not_reached",
|
||||
nodes: [{ address: "0x1", depth: 0 }],
|
||||
frontier: ["0x2"],
|
||||
truncated: true,
|
||||
residual_unknowns: expect.arrayContaining([
|
||||
expect.stringContaining("reached the node limit"),
|
||||
expect.stringContaining("reached the edge limit"),
|
||||
]),
|
||||
limits: {
|
||||
max_nodes: 1,
|
||||
nodes_visited: 1,
|
||||
operations_used: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds batch concurrency at the parsed maximum of 20", async () => {
|
||||
let active = 0;
|
||||
let maximum = 0;
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: async (name) => {
|
||||
if (name !== "procedure_pseudo_code") return ok(null);
|
||||
active += 1;
|
||||
maximum = Math.max(maximum, active);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2));
|
||||
active -= 1;
|
||||
return ok("pseudo");
|
||||
},
|
||||
};
|
||||
const client = await connect(analysis);
|
||||
const result = await client.callTool({
|
||||
name: "batch_decompile",
|
||||
arguments: {
|
||||
addresses: Array.from(
|
||||
{ length: 20 },
|
||||
(_, index) => `0x${String(index)}`,
|
||||
),
|
||||
},
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(maximum).toBe(20);
|
||||
});
|
||||
|
||||
it("returns ordered typed batch failures and zero counts for empty input", async () => {
|
||||
const tools = new EnhancedTools({
|
||||
execute: (_name, arguments_) =>
|
||||
arguments_.procedure === "0x2"
|
||||
? Promise.resolve(err(new AnalysisOutputError("decompile", "failed")))
|
||||
: Promise.resolve(ok("pseudo")),
|
||||
});
|
||||
|
||||
const result = await tools.execute("batch_decompile", {
|
||||
addresses: ["0x1", "0x2"],
|
||||
});
|
||||
const empty = await tools.execute("batch_decompile", { addresses: [] });
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
items: [
|
||||
{ address: "0x1", status: "ok", pseudocode: "pseudo" },
|
||||
{
|
||||
address: "0x2",
|
||||
status: "error",
|
||||
error: {
|
||||
code: "unreadable_output",
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
retryable: false,
|
||||
remediation: {
|
||||
action:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
restart_required: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
succeeded: 1,
|
||||
failed: 1,
|
||||
},
|
||||
});
|
||||
expect(empty).toEqual({
|
||||
ok: true,
|
||||
value: { items: [], total: 0, succeeded: 0, failed: 0 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
|
||||
import { AnalysisOutputError } from "../../../src/domain/errors.js";
|
||||
import {
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../../../src/domain/jsonValue.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const PROCEDURES = {
|
||||
"0x1": "_TtC7Fixture5Class",
|
||||
"0x2": "_TtV7Fixture6Struct",
|
||||
"0x3": "_TtP7Fixture8Protocol",
|
||||
"0x4": "_TtO7Fixture4Enum",
|
||||
"0x5": "_TtE7Fixture9Extension",
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
const jsonResult = (result: CallToolResult): JsonValue => {
|
||||
if (result.structuredContent === undefined)
|
||||
throw new Error("Tool result omitted structured content");
|
||||
const structured = jsonValueSchema.safeParse(result.structuredContent);
|
||||
if (!structured.success)
|
||||
throw new Error("Tool structured result was not JSON");
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"normalized_result" in structured.data
|
||||
) {
|
||||
return structured.data.normalized_result ?? null;
|
||||
}
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"evidence_id" in structured.data &&
|
||||
"result" in structured.data
|
||||
)
|
||||
return structured.data.result ?? null;
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
if (text?.type !== "text")
|
||||
throw new Error("Tool result omitted text content");
|
||||
const decoded: unknown = JSON.parse(text.text);
|
||||
const parsed = jsonValueSchema.safeParse(decoded);
|
||||
if (!parsed.success) throw new Error("Tool result was not JSON");
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("returns typed graph failures and stable unresolved-name results", async () => {
|
||||
const tools = new EnhancedTools({
|
||||
execute: (name) =>
|
||||
name === "procedure_callees"
|
||||
? Promise.resolve(err(new AnalysisOutputError(name, "failed")))
|
||||
: Promise.resolve(ok(page({}))),
|
||||
});
|
||||
|
||||
const graph = await tools.execute("get_call_graph", {
|
||||
address: "0x1",
|
||||
direction: "forward",
|
||||
depth: 1,
|
||||
});
|
||||
const unresolved = await tools.execute("find_xrefs_to_name", {
|
||||
name: "missing",
|
||||
});
|
||||
|
||||
expect(graph).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
"0": [
|
||||
{
|
||||
address: "0x1",
|
||||
status: "error",
|
||||
error: {
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(unresolved).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
status: "unresolved",
|
||||
name: "missing",
|
||||
reason: "name_not_found",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("follows procedure pagination for whole-binary workflows", async () => {
|
||||
const offsets: number[] = [];
|
||||
const client = await connect({
|
||||
execute: (_name, arguments_) => {
|
||||
const offset = arguments_.offset;
|
||||
offsets.push(typeof offset === "number" ? offset : 0);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: offset === 500 ? "0x2" : "0x1",
|
||||
value: offset === 500 ? "_TtC4Last" : "_TtC5First",
|
||||
},
|
||||
],
|
||||
offset: typeof offset === "number" ? offset : 0,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: offset === 500 ? null : 500,
|
||||
has_more: offset !== 500,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = jsonResult(
|
||||
await client.callTool({ name: "swift_classes", arguments: {} }),
|
||||
);
|
||||
expect(offsets).toEqual([0, 500]);
|
||||
expect(result).toMatchObject({ count: 2 });
|
||||
});
|
||||
|
||||
it("does not start another page after cancellation", async () => {
|
||||
const controller = new AbortController();
|
||||
let calls = 0;
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: () => {
|
||||
calls += 1;
|
||||
controller.abort();
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [{ address: "0x1", value: "_TtC5First" }],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: 500,
|
||||
has_more: true,
|
||||
}),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const result = await new EnhancedTools(analysis).execute(
|
||||
"swift_classes",
|
||||
{},
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
expect(calls).toBe(1);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected cancellation");
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,316 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import {
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../../../src/domain/jsonValue.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const PROCEDURES = {
|
||||
"0x1": "_TtC7Fixture5Class",
|
||||
"0x2": "_TtV7Fixture6Struct",
|
||||
"0x3": "_TtP7Fixture8Protocol",
|
||||
"0x4": "_TtO7Fixture4Enum",
|
||||
"0x5": "_TtE7Fixture9Extension",
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
const jsonResult = (result: CallToolResult): JsonValue => {
|
||||
if (result.structuredContent === undefined)
|
||||
throw new Error("Tool result omitted structured content");
|
||||
const structured = jsonValueSchema.safeParse(result.structuredContent);
|
||||
if (!structured.success)
|
||||
throw new Error("Tool structured result was not JSON");
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"normalized_result" in structured.data
|
||||
) {
|
||||
return structured.data.normalized_result ?? null;
|
||||
}
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"evidence_id" in structured.data &&
|
||||
"result" in structured.data
|
||||
)
|
||||
return structured.data.result ?? null;
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
if (text?.type !== "text")
|
||||
throw new Error("Tool result omitted text content");
|
||||
const decoded: unknown = JSON.parse(text.text);
|
||||
const parsed = jsonValueSchema.safeParse(decoded);
|
||||
if (!parsed.success) throw new Error("Tool result was not JSON");
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("follows name pagination for exhaustive Objective-C discovery", async () => {
|
||||
const offsets: number[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
expect(name).toBe("list_names");
|
||||
const offset =
|
||||
typeof arguments_.offset === "number" ? arguments_.offset : 0;
|
||||
offsets.push(offset);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: offset === 500 ? "0x2" : "0x1",
|
||||
value:
|
||||
offset === 500 ? "_OBJC_CLASS_$_Last" : "_OBJC_CLASS_$_First",
|
||||
},
|
||||
],
|
||||
offset,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: offset === 500 ? null : 500,
|
||||
has_more: offset !== 500,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = jsonResult(
|
||||
await client.callTool({ name: "get_objc_classes", arguments: {} }),
|
||||
);
|
||||
expect(offsets).toEqual([0, 500]);
|
||||
expect(result).toMatchObject({ count: 2 });
|
||||
});
|
||||
|
||||
it("honors overview detail and limit while reporting exhaustive totals", async () => {
|
||||
const procedureOffsets: number[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([
|
||||
{ name: "__TEXT", start: "0x1000", end: "0x1800" },
|
||||
{ name: "__DATA", start: "0x1800", end: "0x2000" },
|
||||
]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [{ address: "0x30", value: "first page only" }],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 700,
|
||||
next_offset: 100,
|
||||
has_more: true,
|
||||
}),
|
||||
);
|
||||
case "list_procedures": {
|
||||
const offset =
|
||||
typeof arguments_.offset === "number" ? arguments_.offset : 0;
|
||||
procedureOffsets.push(offset);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: offset === 500 ? "0x2" : "0x1",
|
||||
value: offset === 500 ? "last" : "first",
|
||||
},
|
||||
],
|
||||
offset,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: offset === 500 ? null : 500,
|
||||
has_more: offset !== 500,
|
||||
}),
|
||||
);
|
||||
}
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
const result = jsonResult(
|
||||
await client.callTool({
|
||||
name: "binary_overview",
|
||||
arguments: { detail: "detailed", limit: 1 },
|
||||
}),
|
||||
);
|
||||
expect(procedureOffsets).toEqual([0]);
|
||||
expect(result).toEqual({
|
||||
document: "fixture",
|
||||
detail: "detailed",
|
||||
segments: [
|
||||
{ name: "__TEXT", start: "0x1000", end: "0x1800", length: 2048 },
|
||||
],
|
||||
segment_count: 2,
|
||||
procedure_count: 2,
|
||||
string_count: 700,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects non-advancing pagination metadata", async () => {
|
||||
const client = await connect({
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
items: [{ address: "0x1", value: "_TtC5First" }],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: 0,
|
||||
has_more: true,
|
||||
}),
|
||||
),
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "swift_classes",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
expect(text?.type === "text" ? text.text : "").toBe(
|
||||
JSON.stringify(result.structuredContent),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,304 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import {
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../../../src/domain/jsonValue.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const PROCEDURES = {
|
||||
"0x1": "_TtC7Fixture5Class",
|
||||
"0x2": "_TtV7Fixture6Struct",
|
||||
"0x3": "_TtP7Fixture8Protocol",
|
||||
"0x4": "_TtO7Fixture4Enum",
|
||||
"0x5": "_TtE7Fixture9Extension",
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
const jsonResult = (result: CallToolResult): JsonValue => {
|
||||
if (result.structuredContent === undefined)
|
||||
throw new Error("Tool result omitted structured content");
|
||||
const structured = jsonValueSchema.safeParse(result.structuredContent);
|
||||
if (!structured.success)
|
||||
throw new Error("Tool structured result was not JSON");
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"normalized_result" in structured.data
|
||||
) {
|
||||
return structured.data.normalized_result ?? null;
|
||||
}
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"evidence_id" in structured.data &&
|
||||
"result" in structured.data
|
||||
)
|
||||
return structured.data.result ?? null;
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
if (text?.type !== "text")
|
||||
throw new Error("Tool result omitted text content");
|
||||
const decoded: unknown = JSON.parse(text.text);
|
||||
const parsed = jsonValueSchema.safeParse(decoded);
|
||||
if (!parsed.success) throw new Error("Tool result was not JSON");
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("stops trace_feature at its explicit operation budget", async () => {
|
||||
let operations = 0;
|
||||
const client = await connect({
|
||||
execute: () => {
|
||||
operations += 1;
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [{ address: "0x1", value: "needle" }],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: 1,
|
||||
has_more: true,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = jsonResult(
|
||||
await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operations: 1 },
|
||||
}),
|
||||
);
|
||||
expect(operations).toBe(1);
|
||||
expect(result).toMatchObject({
|
||||
operations_used: 1,
|
||||
operation_budget: 1,
|
||||
truncated: true,
|
||||
});
|
||||
expect(JSON.stringify(result)).toContain("operation budget");
|
||||
});
|
||||
|
||||
it("returns correction-only structured validation issues", async () => {
|
||||
const client = await connect();
|
||||
const valid = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operations: 1 },
|
||||
});
|
||||
expect(valid.isError).not.toBe(true);
|
||||
const misspelled = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operatons: 1 },
|
||||
});
|
||||
expect(misspelled).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
retryable: true,
|
||||
details: {
|
||||
issues: [{ path: ["max_operatons"], reason: "unknown_argument" }],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const nestedMisspelled = await client.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: {
|
||||
procedure: "0x1",
|
||||
collection_offset: { commentz: 1 },
|
||||
},
|
||||
});
|
||||
expect(nestedMisspelled).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["collection_offset", "commentz"],
|
||||
reason: "unknown_argument",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const bounded = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operations: 101 },
|
||||
});
|
||||
expect(bounded.structuredContent).toMatchObject({
|
||||
error: {
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["max_operations"],
|
||||
reason: "out_of_range",
|
||||
maximum: 100,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(bounded.content[0]).toEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(bounded.structuredContent),
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a typed tool error for malformed Hopper boundary values", async () => {
|
||||
const client = await connect({
|
||||
execute: () => Promise.resolve(ok(["not", "a", "procedure", "map"])),
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "swift_classes",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
expect(text?.type === "text" ? text.text : "").toBe(
|
||||
JSON.stringify(result.structuredContent),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const PROCEDURES = {
|
||||
"0x1": "_TtC7Fixture5Class",
|
||||
"0x2": "_TtV7Fixture6Struct",
|
||||
"0x3": "_TtP7Fixture8Protocol",
|
||||
"0x4": "_TtO7Fixture4Enum",
|
||||
"0x5": "_TtE7Fixture9Extension",
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
"0x13": "entry",
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "procedure_pseudo_code": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
|
||||
);
|
||||
}
|
||||
case "procedure_callees": {
|
||||
const procedure = arguments_.procedure;
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
case "procedure_callers":
|
||||
return Promise.resolve(ok(["0x9"]));
|
||||
case "address_name":
|
||||
return Promise.resolve(ok(arguments_.address ?? null));
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x20", "0x21"]));
|
||||
case "resolve_containing_procedure":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
query_address:
|
||||
typeof arguments_.address === "string"
|
||||
? arguments_.address
|
||||
: "0x0",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
}),
|
||||
);
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
|
||||
);
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("rejects incomplete function dossiers at the application boundary", async () => {
|
||||
const client = await connect({
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
procedure: { address: "0x1", name: "entry" },
|
||||
pseudocode: { text: "plausible but incomplete" },
|
||||
}),
|
||||
),
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "0x1" },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
expect(text?.type === "text" ? text.text : "").toBe(
|
||||
JSON.stringify(result.structuredContent),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects deceptive function dossier collection metadata", async () => {
|
||||
const malformedPort = fixturePort();
|
||||
const client = await connect({
|
||||
execute: async (name, arguments_, options) => {
|
||||
const result = await malformedPort.execute(name, arguments_, options);
|
||||
if (!result.ok || name !== "analyze_function") return result;
|
||||
const dossier = result.value.result;
|
||||
if (
|
||||
typeof dossier !== "object" ||
|
||||
dossier === null ||
|
||||
Array.isArray(dossier)
|
||||
)
|
||||
return result;
|
||||
return ok({
|
||||
...dossier,
|
||||
comments: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 1,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "0x1" },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
expect(text?.type === "text" ? text.text : "").toBe(
|
||||
JSON.stringify(result.structuredContent),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts a final dossier page whose total exceeds returned", async () => {
|
||||
const malformedPort = fixturePort();
|
||||
const client = await connect({
|
||||
execute: async (name, arguments_, options) => {
|
||||
const result = await malformedPort.execute(name, arguments_, options);
|
||||
if (!result.ok || name !== "analyze_function") return result;
|
||||
const dossier = result.value.result;
|
||||
if (
|
||||
typeof dossier !== "object" ||
|
||||
dossier === null ||
|
||||
Array.isArray(dossier)
|
||||
)
|
||||
return result;
|
||||
return ok({
|
||||
...dossier,
|
||||
callers: {
|
||||
items: [],
|
||||
total: 1,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "0x1" },
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createInvestigationWorkspace } from "../../../src/domain/investigationWorkspace.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
|
||||
interface ResourceFixture {
|
||||
readonly evidence: ReturnType<typeof createEvidence>;
|
||||
readonly capture: ReturnType<typeof createEvidence>;
|
||||
readonly workspace: ReturnType<typeof createInvestigationWorkspace>;
|
||||
readonly unknown: ReturnType<BinarySession["recordUnknown"]>;
|
||||
}
|
||||
|
||||
function seedResourceFixture(session: BinarySession): ResourceFixture {
|
||||
const evidence = createEvidence(undefined, provider, {
|
||||
operation: "resource_probe",
|
||||
parameters: {},
|
||||
result: { observed: true },
|
||||
});
|
||||
session.recordEvidence(evidence);
|
||||
const capture = createEvidence(undefined, provider, {
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: {
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "ready" }],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
},
|
||||
});
|
||||
session.recordEvidence(capture);
|
||||
const workspace = createInvestigationWorkspace(
|
||||
"resource test",
|
||||
createEvidenceBundle([]),
|
||||
[],
|
||||
);
|
||||
session.retainInvestigationWorkspace(workspace);
|
||||
const unknown = session.recordUnknown({
|
||||
approved: true,
|
||||
question: "Was every branch observed?",
|
||||
severity: "medium",
|
||||
domain: "control-flow",
|
||||
supporting_evidence_ids: [evidence.evidence_id],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
});
|
||||
expect(unknown.ok).toBe(true);
|
||||
return { evidence, capture, workspace, unknown };
|
||||
}
|
||||
|
||||
async function verifyResourceProtocol(
|
||||
client: Client,
|
||||
fixture: ResourceFixture,
|
||||
): Promise<void> {
|
||||
const { evidence, capture, workspace, unknown } = fixture;
|
||||
const templates = await client.listResourceTemplates();
|
||||
expect(templates.resourceTemplates).toContainEqual(
|
||||
expect.objectContaining({ uriTemplate: "rea://evidence/{evidenceId}" }),
|
||||
);
|
||||
expect(
|
||||
templates.resourceTemplates.map(({ uriTemplate }) => uriTemplate),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
"rea://artifact/{manifestId}/{collection}",
|
||||
"rea://function/{targetSha256}/{address}",
|
||||
"rea://evidence-bundle/{bundleDigest}",
|
||||
"rea://workspace/{workspaceId}/revision/{revision}",
|
||||
]),
|
||||
);
|
||||
expect(templates.resourceTemplates).toContainEqual(
|
||||
expect.objectContaining({
|
||||
uriTemplate: "rea://evidence/{evidenceId}/section/{section}",
|
||||
}),
|
||||
);
|
||||
const listed = await client.listResources();
|
||||
expect(listed.resources).toContainEqual(
|
||||
expect.objectContaining({ uri: "rea://snapshot/current" }),
|
||||
);
|
||||
expect(listed.resources).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
uri: `rea://evidence/${evidence.evidence_id}`,
|
||||
}),
|
||||
);
|
||||
const read = await client.readResource({
|
||||
uri: `rea://evidence/${evidence.evidence_id}`,
|
||||
});
|
||||
expect(read.contents).toEqual([
|
||||
expect.objectContaining({
|
||||
uri: `rea://evidence/${evidence.evidence_id}`,
|
||||
mimeType: "application/json",
|
||||
text: expect.stringContaining(evidence.evidence_id),
|
||||
}),
|
||||
]);
|
||||
const firstSnapshot = await client.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
const secondSnapshot = await client.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(secondSnapshot.structuredContent).toEqual(
|
||||
firstSnapshot.structuredContent,
|
||||
);
|
||||
expect(firstSnapshot.content).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "text",
|
||||
text: expect.stringContaining("Copy the opaque URI exactly"),
|
||||
}),
|
||||
);
|
||||
const bundleUri = z
|
||||
.object({ result: z.object({ bundle_uri: z.string() }) })
|
||||
.parse(firstSnapshot.structuredContent).result.bundle_uri;
|
||||
const retainedBundle = await client.readResource({ uri: bundleUri });
|
||||
expect(retainedBundle.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
uri: bundleUri,
|
||||
text: expect.stringContaining(evidence.evidence_id),
|
||||
}),
|
||||
);
|
||||
const terminal = await client.readResource({
|
||||
uri: `rea://evidence/${capture.evidence_id}/section/terminal`,
|
||||
});
|
||||
const workspaceResource = await client.readResource({
|
||||
uri: `rea://workspace/${workspace.workspace_id}/revision/${String(workspace.revision)}`,
|
||||
});
|
||||
expect(workspaceResource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(workspace.revision_digest),
|
||||
}),
|
||||
);
|
||||
expect(terminal.contents[0]).toEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining("ready") }),
|
||||
);
|
||||
if (unknown.ok) {
|
||||
const unknownResource = await client.readResource({
|
||||
uri: `rea://unknown/${unknown.value.unknown_id}`,
|
||||
});
|
||||
expect(unknownResource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(unknown.value.revision_digest),
|
||||
}),
|
||||
);
|
||||
}
|
||||
await expect(
|
||||
client.readResource({ uri: `rea://evidence/ev_${"0".repeat(64)}` }),
|
||||
).rejects.toThrow(/not found/iu);
|
||||
}
|
||||
|
||||
describe("evidence MCP resources", () => {
|
||||
it("publishes mutable snapshot changes for every Evidence mutation", () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
let updates = 0;
|
||||
session.onAnalysisSnapshotChanged(() => {
|
||||
updates += 1;
|
||||
});
|
||||
const first = createEvidence(undefined, provider, {
|
||||
operation: "notification_probe",
|
||||
parameters: {},
|
||||
result: 1,
|
||||
});
|
||||
expect(session.recordEvidence(first)).toEqual({ ok: true, value: "added" });
|
||||
expect(session.recordEvidence(first)).toEqual({
|
||||
ok: true,
|
||||
value: "duplicate",
|
||||
});
|
||||
const imported = createEvidence(undefined, provider, {
|
||||
operation: "import_notification_probe",
|
||||
parameters: {},
|
||||
result: 2,
|
||||
});
|
||||
expect(
|
||||
session.importEvidenceBundle(createEvidenceBundle([imported])),
|
||||
).toEqual({ ok: true, value: 1 });
|
||||
expect(
|
||||
session.recordUnknown({
|
||||
approved: true,
|
||||
question: "Does mutation publish a snapshot update?",
|
||||
severity: "low",
|
||||
domain: "notifications",
|
||||
supporting_evidence_ids: [first.evidence_id],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
expect(updates).toBe(3);
|
||||
});
|
||||
|
||||
it("retains bundles without eviction and rejects a seventeenth digest", () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const first = session.snapshotEvidenceBundle();
|
||||
expect(first.ok).toBe(true);
|
||||
for (let index = 0; index < 15; index += 1) {
|
||||
session.recordEvidence(
|
||||
createEvidence(undefined, provider, {
|
||||
operation: `retention_probe_${String(index)}`,
|
||||
parameters: {},
|
||||
result: index,
|
||||
}),
|
||||
);
|
||||
expect(session.snapshotEvidenceBundle().ok).toBe(true);
|
||||
}
|
||||
session.recordEvidence(
|
||||
createEvidence(undefined, provider, {
|
||||
operation: "retention_probe_overflow",
|
||||
parameters: {},
|
||||
result: true,
|
||||
}),
|
||||
);
|
||||
expect(session.snapshotEvidenceBundle()).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceLimitError", limit: "records", maximum: 16 },
|
||||
});
|
||||
if (first.ok)
|
||||
expect(session.retainedEvidenceBundle(first.value.bundleDigest)).toEqual(
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
it("lists and reads only evidence owned by the current session", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const fixture = seedResourceFixture(session);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "evidence-resource-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await verifyResourceProtocol(client, fixture);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
}, 10_000);
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
describe("function comparison MCP integration", () => {
|
||||
it("records linked comparison Evidence and an approved residual unknown", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.left).ok).toBe(
|
||||
true,
|
||||
);
|
||||
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.right).ok).toBe(
|
||||
true,
|
||||
);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "function-comparison-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "compare_functions",
|
||||
arguments: {
|
||||
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
|
||||
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: { status: expect.any(String) },
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
|
||||
});
|
||||
const unknowns = await client.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: { domain: "function-comparison" },
|
||||
});
|
||||
expect(unknowns.structuredContent).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
unknown: expect.objectContaining({
|
||||
domain: "function-comparison",
|
||||
recommended_probes: [
|
||||
expect.objectContaining({
|
||||
rationale:
|
||||
"Capture complete dossiers for both functions under the same target context and analysis limits.",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects dangling Evidence links before recording output", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "function-link-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "compare_functions",
|
||||
arguments: {
|
||||
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
|
||||
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toEqual([]);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects Evidence IDs with the wrong operation", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const wrong = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: {},
|
||||
},
|
||||
);
|
||||
session.recordEvidence(wrong);
|
||||
session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.right);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "function-authority-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "compare_functions",
|
||||
arguments: {
|
||||
left_evidence_ids: [wrong.evidence_id],
|
||||
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toHaveLength(2);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
|
||||
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
|
||||
|
||||
describe("Ghidra MCP evidence parity", () => {
|
||||
it("preserves provider evidence, composed parity, and capability routing", async () => {
|
||||
const harness = await connectGhidraMcp("ghidra-parity");
|
||||
const { mcp, session } = harness;
|
||||
try {
|
||||
const listed = sessionEvidence(
|
||||
session,
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "list_procedures",
|
||||
arguments: {},
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
expect(listed).toMatchObject({
|
||||
operation: "list_procedures",
|
||||
provider: { id: "ghidra", name: "Ghidra", version: "12.1.2" },
|
||||
analysis_profile: {
|
||||
provider: { id: "ghidra", version: "12.1.2" },
|
||||
parameters: {
|
||||
import_mode: "ephemeral-read-only",
|
||||
analyzer_preset: "ghidra-default",
|
||||
},
|
||||
},
|
||||
normalized_result: {
|
||||
items: [
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
},
|
||||
raw_result: {
|
||||
items: [{ value_truncated: false }],
|
||||
},
|
||||
});
|
||||
|
||||
const mcpOverview = sessionEvidence(
|
||||
session,
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "binary_overview",
|
||||
arguments: { detail: "detailed", limit: 5 },
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
const directOverview = await new EnhancedTools(session).execute(
|
||||
"binary_overview",
|
||||
{ detail: "detailed", limit: 5 },
|
||||
);
|
||||
expect(directOverview.ok).toBe(true);
|
||||
if (!directOverview.ok) return;
|
||||
expect(mcpOverview.normalized_result).toEqual(directOverview.value);
|
||||
expect(mcpOverview).toMatchObject({
|
||||
provider: { id: "rea-workflow" },
|
||||
confidence: "derived",
|
||||
normalized_result: {
|
||||
document: "fixture",
|
||||
segment_count: 1,
|
||||
procedure_count: 1,
|
||||
string_count: 2,
|
||||
segments: [{ name: ".text", length: 256 }],
|
||||
},
|
||||
});
|
||||
|
||||
const pseudocode = sessionEvidence(
|
||||
session,
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "procedure_pseudo_code",
|
||||
arguments: { procedure: "fixture_main" },
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
expect(pseudocode).toMatchObject({
|
||||
operation: "procedure_pseudo_code",
|
||||
provider: { id: "ghidra", version: "12.1.2" },
|
||||
normalized_result: expect.stringContaining("return 42"),
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("not text-equivalent to Hopper"),
|
||||
expect.stringContaining("30-second native deadline"),
|
||||
]),
|
||||
});
|
||||
|
||||
const analyzed = sessionEvidence(
|
||||
session,
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "fixture_main", include_assembly: true },
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
expect(analyzed).toMatchObject({
|
||||
operation: "analyze_function",
|
||||
provider: { id: "rea-workflow", version: "1" },
|
||||
normalized_result: {
|
||||
procedure: {
|
||||
address: "0x401000",
|
||||
name: "fixture_main",
|
||||
classification: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
provenance: "ghidra-function-manager",
|
||||
},
|
||||
},
|
||||
pseudocode: { truncated: false },
|
||||
outgoing_references: {
|
||||
items: [
|
||||
{
|
||||
kind: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("indirect flows without target addresses"),
|
||||
expect.stringContaining(
|
||||
"not original source or Hopper-equivalent text",
|
||||
),
|
||||
]),
|
||||
},
|
||||
limitations: [
|
||||
"Derived by an REA workflow from one or more provider observations.",
|
||||
],
|
||||
});
|
||||
const directAnalyzed = await new EnhancedTools(session).execute(
|
||||
"analyze_function",
|
||||
{ procedure: "fixture_main", include_assembly: true },
|
||||
);
|
||||
expect(directAnalyzed.ok).toBe(true);
|
||||
if (!directAnalyzed.ok) return;
|
||||
expect(analyzed.normalized_result).toEqual(directAnalyzed.value);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,299 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { composeBinarySession } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { AnalysisProviderRegistry } from "../../../src/application/AnalysisProviderRegistry.js";
|
||||
import { SessionProviderRouter } from "../../../src/application/SessionProviderRouter.js";
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import type { GhidraInstallationHost } from "../../../src/ghidra/GhidraInstallation.js";
|
||||
import type { GhidraOperation } from "../../../src/ghidra/GhidraClient.js";
|
||||
import {
|
||||
GhidraProvider,
|
||||
type GhidraProviderClientFactory,
|
||||
} from "../../../src/ghidra/GhidraProvider.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../../../src/ghidra/GhidraSessionValues.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
ghidraBounded,
|
||||
ghidraFunctionClassification,
|
||||
ghidraFunctionDossier,
|
||||
ghidraFunctionIdentity,
|
||||
ghidraReferenceEdge,
|
||||
} from "../../fixtures/ghidraFunction.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
|
||||
export const connectGhidraMcp = async (name: string) => {
|
||||
const calls: GhidraOperation[] = [];
|
||||
const factory: GhidraProviderClientFactory = (options) => ({
|
||||
start: () =>
|
||||
Promise.resolve(
|
||||
ok(sessionInfo(options.profileDigest, options.targetSha256)),
|
||||
),
|
||||
callTool: (operation, input) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(ok(resultFor(operation, input)));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
|
||||
if (!config.ok) throw config.error;
|
||||
const provider = new GhidraProvider(
|
||||
config.value,
|
||||
silentLogger,
|
||||
installationHost(),
|
||||
factory,
|
||||
);
|
||||
const session = composeBinarySession(
|
||||
SessionProviderRouter.selectable(
|
||||
new AnalysisProviderRegistry([provider]),
|
||||
[],
|
||||
),
|
||||
);
|
||||
const server = createServer(session, session, { logger: silentLogger });
|
||||
const mcp = new Client({ name, version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const close = async () => {
|
||||
await Promise.allSettled([mcp.close(), server.close()]);
|
||||
await session.close();
|
||||
};
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await mcp.connect(clientTransport);
|
||||
const opened = await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath },
|
||||
});
|
||||
if (opened.isError === true)
|
||||
throw new Error("The Ghidra MCP harness could not open its target");
|
||||
} catch (cause: unknown) {
|
||||
await close();
|
||||
throw cause;
|
||||
}
|
||||
return {
|
||||
calls,
|
||||
mcp,
|
||||
session,
|
||||
close,
|
||||
};
|
||||
};
|
||||
|
||||
export const sessionEvidence = (session: BinarySession, value: unknown) => {
|
||||
if (
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
!("evidence_id" in value) ||
|
||||
typeof value.evidence_id !== "string"
|
||||
)
|
||||
throw new TypeError(
|
||||
`Missing compact Evidence ID: ${JSON.stringify(value)}`,
|
||||
);
|
||||
const evidence = session.evidenceById(value.evidence_id);
|
||||
if (evidence === undefined) throw new TypeError("Missing session Evidence");
|
||||
return evidence;
|
||||
};
|
||||
|
||||
const installationHost = (): GhidraInstallationHost => ({
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
readText: () => "application.version=12.1.2\n",
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
jdk: true,
|
||||
}),
|
||||
});
|
||||
|
||||
const sessionInfo = (profileDigest: string, targetSha256: string) => ({
|
||||
name: "REA Ghidra bridge" as const,
|
||||
bridge_version: 6 as const,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: profileDigest,
|
||||
provider: { id: "ghidra" as const, version: "12.1.2" },
|
||||
read_only: true as const,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
|
||||
target: {
|
||||
name: "fixture",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x400000",
|
||||
default_address_space: "ram",
|
||||
sha256: targetSha256,
|
||||
},
|
||||
});
|
||||
|
||||
type GhidraResultBuilder = (
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
limit: number,
|
||||
) => JsonValue;
|
||||
|
||||
const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
|
||||
["list_documents", () => ["fixture"]],
|
||||
[
|
||||
"list_procedures",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
limit,
|
||||
),
|
||||
],
|
||||
[
|
||||
"list_strings",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
stringItem("0x402000", "inventory fixture"),
|
||||
stringItem("0x402020", "external fixture"),
|
||||
],
|
||||
limit,
|
||||
),
|
||||
],
|
||||
[
|
||||
"list_segments",
|
||||
() => [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x401000",
|
||||
end: "0x401100",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x400000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
],
|
||||
],
|
||||
[
|
||||
"list_names",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: false,
|
||||
type: "function",
|
||||
source: "user_defined",
|
||||
},
|
||||
},
|
||||
],
|
||||
limit,
|
||||
),
|
||||
],
|
||||
["search_procedures", (_input, limit) => page([], limit)],
|
||||
["search_strings", (_input, limit) => page([], limit)],
|
||||
["address_name", () => "fixture_main"],
|
||||
["procedure_address", () => "0x401000"],
|
||||
[
|
||||
"resolve_containing_procedure",
|
||||
() => ({
|
||||
query_address: "0x401001",
|
||||
found: true,
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
}),
|
||||
],
|
||||
["procedure_assembly", () => "0x401000: CALL 0x401020\n0x401005: RET"],
|
||||
["procedure_callees", () => []],
|
||||
["procedure_callers", () => []],
|
||||
[
|
||||
"procedure_info",
|
||||
() => ({
|
||||
name: "fixture_main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 6,
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [],
|
||||
classification: ghidraFunctionClassification(),
|
||||
}),
|
||||
],
|
||||
["procedure_pseudo_code", () => "int fixture_main(void) { return 42; }"],
|
||||
[
|
||||
"read_function_instructions",
|
||||
() => ({
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
instructions: ghidraBounded(["0x401000: CALL 0x401020", "0x401005: RET"]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
limitations: ["Ghidra-specific instruction text."],
|
||||
}),
|
||||
],
|
||||
[
|
||||
"procedure_references",
|
||||
(input, _limit) => ({
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: input.direction ?? "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
}),
|
||||
],
|
||||
["xrefs", () => ["0x401001"]],
|
||||
[
|
||||
"analyze_function",
|
||||
(input, _limit) =>
|
||||
ghidraFunctionDossier(
|
||||
input.include_assembly === true,
|
||||
input.procedure === "fixture_truncated",
|
||||
),
|
||||
],
|
||||
]);
|
||||
|
||||
const resultFor = (
|
||||
operation: GhidraOperation,
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
): JsonValue => {
|
||||
const limit = typeof input.limit === "number" ? input.limit : 100;
|
||||
const builder = resultBuilders.get(operation);
|
||||
if (builder === undefined)
|
||||
throw new TypeError(`Unexpected Ghidra operation: ${operation}`);
|
||||
return builder(input, limit);
|
||||
};
|
||||
|
||||
const page = (items: readonly JsonValue[], limit: number): JsonValue => ({
|
||||
items: items.slice(0, limit),
|
||||
offset: 0,
|
||||
limit,
|
||||
total: items.length,
|
||||
next_offset: items.length > limit ? limit : null,
|
||||
has_more: items.length > limit,
|
||||
});
|
||||
|
||||
const stringItem = (address: string, value: string): JsonValue => ({
|
||||
address,
|
||||
value,
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "present_or_not_required",
|
||||
byte_length: value.length + 1,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
|
||||
|
||||
describe("Ghidra MCP native API evidence", () => {
|
||||
it("records approved native API truncation once and links its evidence", async () => {
|
||||
const harness = await connectGhidraMcp("ghidra-native-api");
|
||||
const { mcp, session } = harness;
|
||||
try {
|
||||
const unapprovedInspection = sessionEvidence(
|
||||
session,
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "inspect_native_api",
|
||||
arguments: { procedure: "fixture_truncated" },
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
expect(unapprovedInspection.normalized_result).toMatchObject({
|
||||
boundary: {
|
||||
available: true,
|
||||
jump_tables: [{ mappings_truncated: true }],
|
||||
},
|
||||
residual_unknowns: [
|
||||
expect.stringContaining("additional data sources or targets"),
|
||||
],
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: {},
|
||||
})
|
||||
).structuredContent,
|
||||
).toMatchObject({ result: { items: [] } });
|
||||
|
||||
const approvedInspection = sessionEvidence(
|
||||
session,
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "inspect_native_api",
|
||||
arguments: {
|
||||
procedure: "fixture_truncated",
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
await mcp.callTool({
|
||||
name: "inspect_native_api",
|
||||
arguments: {
|
||||
procedure: "fixture_truncated",
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: {},
|
||||
})
|
||||
).structuredContent,
|
||||
).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
unknown: {
|
||||
status: "open",
|
||||
domain: "native-api",
|
||||
question: expect.stringContaining(
|
||||
"additional data sources or targets",
|
||||
),
|
||||
supporting_evidence_ids: [approvedInspection.evidence_id],
|
||||
recommended_probes: [
|
||||
{
|
||||
operation: "inspect_native_api",
|
||||
rationale: expect.stringContaining("ABI probe"),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
|
||||
|
||||
describe("Ghidra MCP capability routing", () => {
|
||||
it("routes composed and capability tools", async () => {
|
||||
const harness = await connectGhidraMcp("ghidra-routing");
|
||||
const { calls, mcp } = harness;
|
||||
try {
|
||||
const batch = await mcp.callTool({
|
||||
name: "batch_decompile",
|
||||
arguments: { addresses: ["fixture_main"] },
|
||||
});
|
||||
expect(batch.isError).not.toBe(true);
|
||||
expect(batch.structuredContent).toMatchObject({
|
||||
result: {
|
||||
succeeded: 1,
|
||||
failed: 0,
|
||||
items: [{ status: "ok" }],
|
||||
},
|
||||
});
|
||||
|
||||
const availableNames = (await mcp.listTools()).tools.map(
|
||||
({ name }) => name,
|
||||
);
|
||||
expect(availableNames).not.toContain("set_comment");
|
||||
expect(calls).not.toContain("set_comment");
|
||||
|
||||
const status = await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
open: true,
|
||||
analysis_provider_binding: {
|
||||
provider: { id: "ghidra", version: "12.1.2" },
|
||||
},
|
||||
tool_availability: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "binary_overview",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({ name: "swift_classes", available: true }),
|
||||
expect.objectContaining({
|
||||
name: "get_objc_classes",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "batch_decompile",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "trace_feature",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "get_call_graph",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "find_xrefs_to_name",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "set_comment",
|
||||
available: false,
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,348 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
|
||||
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
|
||||
import {
|
||||
FUNCTION_COMPARISON_EVIDENCE,
|
||||
PROCESS_CAPTURE_RECONSTRUCTION,
|
||||
PROCESS_CAPTURE_REFERENCE,
|
||||
PROCESS_COMPARISON_EVIDENCE,
|
||||
} from "../../../src/contracts/investigationExamples.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
} from "../../../src/domain/jsonValue.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import type { EvidenceFilePolicy } from "../../../src/domain/evidenceBundle.js";
|
||||
import type { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
|
||||
it("aggregates comparison Evidence and records an approved runtime gap", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
const comparison =
|
||||
INVESTIGATION_EXAMPLES.find_changed_behavior.comparisons[0];
|
||||
if (comparison === undefined) throw new Error("missing comparison fixture");
|
||||
for (const evidence of [
|
||||
FUNCTION_COMPARISON_EXAMPLE.left,
|
||||
FUNCTION_COMPARISON_EXAMPLE.right,
|
||||
comparison,
|
||||
])
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: {
|
||||
comparisons: [comparison],
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const evidence = sessionEvidence(session, response.structuredContent);
|
||||
expect(evidence).toMatchObject({
|
||||
provider: { id: "rea-changed-behavior" },
|
||||
normalized_result: { behavior_status: "unknown" },
|
||||
});
|
||||
expect(session.listUnknowns({ domain: "changed-behavior" })).toMatchObject([
|
||||
{
|
||||
question:
|
||||
"Did both versions behave the same under a complete controlled replay?",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
it("builds a zero-hop exact-address path with dossier citations", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.left).ok).toBe(
|
||||
true,
|
||||
);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "build_call_path",
|
||||
arguments: INVESTIGATION_EXAMPLES.build_call_path,
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const evidence = sessionEvidence(session, response.structuredContent);
|
||||
expect(evidence).toMatchObject({
|
||||
provider: { id: "rea-call-path" },
|
||||
normalized_result: {
|
||||
status: "found",
|
||||
shortest_hops: 0,
|
||||
paths: { total: 1 },
|
||||
},
|
||||
evidence_links: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
|
||||
});
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
});
|
||||
|
||||
it("records a safe unresolved call-path question", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
const base = FUNCTION_COMPARISON_EXAMPLE.left;
|
||||
if (base.subject === null) throw new Error("missing dossier subject");
|
||||
const dossier = createEvidence(
|
||||
{
|
||||
path: base.subject.local_path,
|
||||
sha256: base.subject.digest.sha256,
|
||||
format: base.subject.format,
|
||||
...(base.subject.architecture === null
|
||||
? {}
|
||||
: { architecture: base.subject.architecture }),
|
||||
},
|
||||
base.provider,
|
||||
{
|
||||
predicateType: base.predicate_type,
|
||||
operation: base.operation,
|
||||
parameters: base.parameters,
|
||||
result: jsonValueSchema.parse({
|
||||
...jsonObjectSchema.parse(base.normalized_result),
|
||||
callees: {
|
||||
items: [{ address: "0x2000", name: "next" }],
|
||||
total: 1,
|
||||
returned: 1,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
}),
|
||||
rawResult: base.raw_result,
|
||||
confidence: base.confidence,
|
||||
authority: base.authority,
|
||||
limitations: base.limitations,
|
||||
locations: base.locations,
|
||||
evidenceLinks: base.evidence_links,
|
||||
},
|
||||
);
|
||||
expect(session.recordEvidence(dossier).ok).toBe(true);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "build_call_path",
|
||||
arguments: {
|
||||
...INVESTIGATION_EXAMPLES.build_call_path,
|
||||
functions: [dossier],
|
||||
start: { address: "0x1000" },
|
||||
goal: { address: "0x3000" },
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(session.listUnknowns({ domain: "call-path" })).toMatchObject([
|
||||
{
|
||||
question:
|
||||
"Can the requested call path be established from complete analysis?",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
});
|
||||
|
||||
it("records an explicit non-causal static/runtime hypothesis", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
for (const evidence of [
|
||||
FUNCTION_COMPARISON_EXAMPLE.left,
|
||||
FUNCTION_COMPARISON_EXAMPLE.right,
|
||||
FUNCTION_COMPARISON_EVIDENCE,
|
||||
PROCESS_CAPTURE_REFERENCE,
|
||||
PROCESS_CAPTURE_RECONSTRUCTION,
|
||||
PROCESS_COMPARISON_EVIDENCE,
|
||||
])
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "correlate_static_and_runtime",
|
||||
arguments: INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const evidence = sessionEvidence(session, response.structuredContent);
|
||||
expect(evidence).toMatchObject({
|
||||
provider: { id: "rea-static-runtime-correlation" },
|
||||
confidence: "inferred",
|
||||
normalized_result: {
|
||||
status: "correlated",
|
||||
summary: { hypotheses: 1 },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
});
|
||||
|
||||
it("records a safe unresolved static/runtime question", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
for (const evidence of [
|
||||
FUNCTION_COMPARISON_EXAMPLE.left,
|
||||
FUNCTION_COMPARISON_EXAMPLE.right,
|
||||
FUNCTION_COMPARISON_EVIDENCE,
|
||||
PROCESS_CAPTURE_REFERENCE,
|
||||
PROCESS_CAPTURE_RECONSTRUCTION,
|
||||
PROCESS_COMPARISON_EVIDENCE,
|
||||
])
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
const mapping =
|
||||
INVESTIGATION_EXAMPLES.correlate_static_and_runtime.mappings[0];
|
||||
if (mapping === undefined) throw new Error("missing correlation fixture");
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "correlate_static_and_runtime",
|
||||
arguments: {
|
||||
...INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
|
||||
mappings: [
|
||||
{
|
||||
...mapping,
|
||||
static: {
|
||||
...mapping.static,
|
||||
selector: { kind: "function", dimension: "assembly" },
|
||||
},
|
||||
},
|
||||
],
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(
|
||||
session.listUnknowns({ domain: "static-runtime-correlation" }),
|
||||
).toMatchObject([
|
||||
{
|
||||
question: "Does runtime behavior match the available static analysis?",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
});
|
||||
|
||||
it("passes only the finite declared reconstruction specification", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
for (const evidence of [
|
||||
PROCESS_CAPTURE_REFERENCE,
|
||||
PROCESS_CAPTURE_RECONSTRUCTION,
|
||||
PROCESS_COMPARISON_EVIDENCE,
|
||||
])
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "verify_reconstruction",
|
||||
arguments: {
|
||||
...INVESTIGATION_EXAMPLES.verify_reconstruction,
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const evidence = sessionEvidence(session, response.structuredContent);
|
||||
expect(evidence).toMatchObject({
|
||||
provider: { id: "rea-reconstruction-verifier" },
|
||||
normalized_result: { status: "pass", summary: { passed: 1 } },
|
||||
});
|
||||
expect(evidence.limitations).toContain(
|
||||
"Pass means every declared claim passed; it does not establish global implementation equivalence.",
|
||||
);
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
});
|
||||
|
||||
it("cannot omit a session-owned active unknown from reconstruction input", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
for (const evidence of [
|
||||
PROCESS_CAPTURE_REFERENCE,
|
||||
PROCESS_CAPTURE_RECONSTRUCTION,
|
||||
PROCESS_COMPARISON_EVIDENCE,
|
||||
])
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
expect(
|
||||
session.recordUnknown({
|
||||
approved: true,
|
||||
question: "Was terminal equivalence reproduced independently?",
|
||||
severity: "high",
|
||||
domain: "reconstruction-verification",
|
||||
supporting_evidence_ids: [PROCESS_COMPARISON_EVIDENCE.evidence_id],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [
|
||||
{
|
||||
operation: "capture_process_scenario",
|
||||
rationale: "Repeat both sides under one controlled environment.",
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "verify_reconstruction",
|
||||
arguments: {
|
||||
...INVESTIGATION_EXAMPLES.verify_reconstruction,
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const evidence = sessionEvidence(session, response.structuredContent);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
status: "unknown",
|
||||
summary: { unknown: 1 },
|
||||
});
|
||||
expect(
|
||||
session.listUnknowns({ domain: "reconstruction-verification" }),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
question: "Does the reconstruction satisfy every declared claim?",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
});
|
||||
|
||||
const connected = async (
|
||||
evidenceFilePolicy?: EvidenceFilePolicy,
|
||||
investigationInputRoots: readonly string[] = evidenceFilePolicy?.roots ?? [],
|
||||
permissionAuthority?: PermissionAuthority,
|
||||
) => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
...(evidenceFilePolicy === undefined
|
||||
? {}
|
||||
: {
|
||||
evidenceFilePolicy,
|
||||
investigationInputRoots,
|
||||
}),
|
||||
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
|
||||
});
|
||||
const client = new Client({ name: "investigation-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return { session, server, client };
|
||||
};
|
||||
|
||||
const sessionEvidence = (session: BinarySession, value: unknown) => {
|
||||
const parsed = z
|
||||
.object({ evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u) })
|
||||
.parse(value);
|
||||
const evidence = session.evidenceById(parsed.evidence_id);
|
||||
if (evidence === undefined) throw new TypeError("Missing session Evidence");
|
||||
return evidence;
|
||||
};
|
||||
|
||||
const close = async (
|
||||
session: BinarySession,
|
||||
server: Awaited<ReturnType<typeof createServer>>,
|
||||
client: Client,
|
||||
) => {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
};
|
||||
@@ -0,0 +1,395 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
|
||||
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
|
||||
import {
|
||||
FUNCTION_COMPARISON_EVIDENCE,
|
||||
PROCESS_CAPTURE_RECONSTRUCTION,
|
||||
PROCESS_CAPTURE_REFERENCE,
|
||||
PROCESS_COMPARISON_EVIDENCE,
|
||||
} from "../../../src/contracts/investigationExamples.js";
|
||||
import { changedBehaviorResultSchema } from "../../../src/domain/changedBehavior.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { readInvestigationWorkspace } from "../../../src/application/InvestigationWorkspaceStore.js";
|
||||
import type { EvidenceFilePolicy } from "../../../src/domain/evidenceBundle.js";
|
||||
import type { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
it("never retains derived evidence after request cancellation", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
const inputs = [
|
||||
{
|
||||
name: "find_changed_behavior",
|
||||
arguments: INVESTIGATION_EXAMPLES.find_changed_behavior,
|
||||
},
|
||||
{
|
||||
name: "build_call_path",
|
||||
arguments: INVESTIGATION_EXAMPLES.build_call_path,
|
||||
},
|
||||
{
|
||||
name: "correlate_static_and_runtime",
|
||||
arguments: INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
|
||||
},
|
||||
] as const;
|
||||
for (const evidence of [
|
||||
FUNCTION_COMPARISON_EXAMPLE.left,
|
||||
FUNCTION_COMPARISON_EXAMPLE.right,
|
||||
FUNCTION_COMPARISON_EVIDENCE,
|
||||
PROCESS_CAPTURE_REFERENCE,
|
||||
PROCESS_CAPTURE_RECONSTRUCTION,
|
||||
PROCESS_COMPARISON_EVIDENCE,
|
||||
])
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
const initialCount = session.exportEvidenceBundle().records.length;
|
||||
try {
|
||||
for (const input of inputs) {
|
||||
const controller = new AbortController();
|
||||
const request = client.callTool(input, {
|
||||
signal: controller.signal,
|
||||
onprogress: () => controller.abort(),
|
||||
});
|
||||
await expect(request).rejects.toThrow(/abort/iu);
|
||||
}
|
||||
await expect
|
||||
.poll(() => session.exportEvidenceBundle().records.length)
|
||||
.toBe(initialCount);
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
it("runs and reuses a persistent cross-version workspace", async () => {
|
||||
const directory = await createTestTempDirectory("rea-investigation-mcp-");
|
||||
const left = join(directory, "left");
|
||||
const right = join(directory, "right");
|
||||
const workspace = join(directory, "workspace.json");
|
||||
await Promise.all([mkdir(left), mkdir(right)]);
|
||||
await Promise.all([
|
||||
writeFile(join(left, "feature.txt"), "old\n"),
|
||||
writeFile(join(right, "feature.txt"), "new\n"),
|
||||
]);
|
||||
const filePolicy = evidencePolicy(directory);
|
||||
const { session, server, client } = await connected(filePolicy);
|
||||
try {
|
||||
const arguments_ = {
|
||||
investigation_run: {
|
||||
approved: true,
|
||||
workspace_path: workspace,
|
||||
workspace_name: "mcp-release-diff",
|
||||
left_path: left,
|
||||
right_path: right,
|
||||
options: { page_size: 500, change_limit: 100 },
|
||||
},
|
||||
};
|
||||
const first = await client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(first.isError).not.toBe(true);
|
||||
const firstEvidence = sessionEvidence(session, first.structuredContent);
|
||||
expect(firstEvidence.normalized_result).toMatchObject({
|
||||
behavior_status: "unknown",
|
||||
summary: { static_candidates: 2 },
|
||||
investigation_run: { inventory_evidence_count: 2 },
|
||||
});
|
||||
expect(session.hasEvidence(firstEvidence.evidence_id)).toBe(true);
|
||||
const loaded = await readInvestigationWorkspace(workspace, filePolicy);
|
||||
expect(loaded).toMatchObject({
|
||||
ok: true,
|
||||
value: { revision: 3, runs: [{ status: "complete" }] },
|
||||
});
|
||||
expect(first.content).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "resource_link",
|
||||
uri: expect.stringMatching(
|
||||
/^rea:\/\/workspace\/ws_[a-f0-9]{64}\/revision\/3$/u,
|
||||
),
|
||||
}),
|
||||
);
|
||||
const retainedWorkspace = session.investigationWorkspaces()[0];
|
||||
expect(retainedWorkspace).toBeDefined();
|
||||
if (retainedWorkspace !== undefined) {
|
||||
const resource = await client.readResource({
|
||||
uri: `rea://workspace/${retainedWorkspace.workspace_id}/revision/${String(retainedWorkspace.revision)}`,
|
||||
});
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(retainedWorkspace.revision_digest),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const second = await client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(second.isError, JSON.stringify(second)).not.toBe(true);
|
||||
const secondEvidence = sessionEvidence(session, second.structuredContent);
|
||||
expect(secondEvidence.evidence_id).toBe(firstEvidence.evidence_id);
|
||||
expect(
|
||||
await readInvestigationWorkspace(workspace, filePolicy),
|
||||
).toMatchObject({ ok: true, value: { revision: 3 } });
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("replays a complete workspace without write authority", async () => {
|
||||
const directory = await createTestTempDirectory("rea-investigation-read-");
|
||||
const left = join(directory, "left");
|
||||
const right = join(directory, "right");
|
||||
const workspace = join(directory, "workspace.json");
|
||||
await Promise.all([mkdir(left), mkdir(right)]);
|
||||
await Promise.all([
|
||||
writeFile(join(left, "feature.txt"), "old\n"),
|
||||
writeFile(join(right, "feature.txt"), "new\n"),
|
||||
]);
|
||||
const filePolicy = evidencePolicy(directory);
|
||||
const arguments_ = {
|
||||
investigation_run: {
|
||||
approved: true,
|
||||
workspace_path: workspace,
|
||||
workspace_name: "read-only-replay",
|
||||
left_path: left,
|
||||
right_path: right,
|
||||
options: { page_size: 500, change_limit: 100 },
|
||||
},
|
||||
};
|
||||
const writer = await investigationAuthority(directory, true);
|
||||
const initial = await connected(filePolicy, [directory], writer);
|
||||
try {
|
||||
const created = await initial.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(created.isError, JSON.stringify(created)).not.toBe(true);
|
||||
} finally {
|
||||
await close(initial.session, initial.server, initial.client);
|
||||
}
|
||||
|
||||
const reader = await investigationAuthority(directory, false);
|
||||
const replay = await connected(filePolicy, [directory], reader);
|
||||
try {
|
||||
const cached = await replay.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(cached.isError, JSON.stringify(cached)).not.toBe(true);
|
||||
expect(
|
||||
await readInvestigationWorkspace(workspace, filePolicy),
|
||||
).toMatchObject({ ok: true, value: { revision: 3 } });
|
||||
|
||||
await writeFile(join(right, "feature.txt"), "changed again\n");
|
||||
const denied = await replay.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(denied).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
code: "permission_required",
|
||||
details: { capability: "investigation_workspace_write" },
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await close(replay.session, replay.server, replay.client);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("defers input permission for an explicit replay with deleted inputs", async () => {
|
||||
const directory = await createTestTempDirectory("rea-investigation-replay-");
|
||||
const left = join(directory, "left");
|
||||
const right = join(directory, "right");
|
||||
const workspace = join(directory, "workspace.json");
|
||||
await Promise.all([mkdir(left), mkdir(right)]);
|
||||
await Promise.all([
|
||||
writeFile(join(left, "feature.txt"), "old\n"),
|
||||
writeFile(join(right, "feature.txt"), "new\n"),
|
||||
]);
|
||||
const filePolicy = evidencePolicy(directory);
|
||||
const investigationRun = {
|
||||
approved: true,
|
||||
workspace_path: workspace,
|
||||
workspace_name: "selected-replay",
|
||||
left_path: left,
|
||||
right_path: right,
|
||||
options: { page_size: 500, change_limit: 100 },
|
||||
};
|
||||
const writer = await investigationAuthority(directory, true);
|
||||
const initial = await connected(filePolicy, [directory], writer);
|
||||
let runId: string | undefined;
|
||||
try {
|
||||
const created = await initial.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: { investigation_run: investigationRun },
|
||||
});
|
||||
expect(created.isError, JSON.stringify(created)).not.toBe(true);
|
||||
const evidence = sessionEvidence(
|
||||
initial.session,
|
||||
created.structuredContent,
|
||||
);
|
||||
const result = changedBehaviorResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
runId = result.investigation_run?.run_id;
|
||||
} finally {
|
||||
await close(initial.session, initial.server, initial.client);
|
||||
}
|
||||
if (runId === undefined) throw new Error("missing completed run ID");
|
||||
|
||||
await Promise.all([
|
||||
rm(left, { recursive: true, force: true }),
|
||||
rm(right, { recursive: true, force: true }),
|
||||
]);
|
||||
const workspaceOnly = await permissionAuthorityForRoot(
|
||||
directory,
|
||||
[
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"investigation_input",
|
||||
],
|
||||
["investigation_workspace_read"],
|
||||
);
|
||||
const replay = await connected(filePolicy, [], workspaceOnly);
|
||||
try {
|
||||
const cached = await replay.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: {
|
||||
investigation_run: {
|
||||
...investigationRun,
|
||||
replay_run_id: runId,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(cached.isError, JSON.stringify(cached)).not.toBe(true);
|
||||
expect(
|
||||
await readInvestigationWorkspace(workspace, filePolicy),
|
||||
).toMatchObject({ ok: true, value: { revision: 3 } });
|
||||
} finally {
|
||||
await close(replay.session, replay.server, replay.client);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses automatic artifact reads outside operator-approved roots", async () => {
|
||||
const directory = await createTestTempDirectory("rea-investigation-mcp-");
|
||||
const approvedInputs = join(directory, "approved-inputs");
|
||||
const outsideInputs = join(directory, "outside-inputs");
|
||||
const evidenceRoot = join(directory, "evidence");
|
||||
await Promise.all([
|
||||
mkdir(approvedInputs),
|
||||
mkdir(outsideInputs),
|
||||
mkdir(evidenceRoot),
|
||||
]);
|
||||
const left = join(outsideInputs, "left");
|
||||
const right = join(outsideInputs, "right");
|
||||
await Promise.all([mkdir(left), mkdir(right)]);
|
||||
const { session, server, client } = await connected(
|
||||
evidencePolicy(evidenceRoot),
|
||||
[approvedInputs],
|
||||
);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: {
|
||||
investigation_run: {
|
||||
approved: true,
|
||||
workspace_path: join(evidenceRoot, "workspace.json"),
|
||||
left_path: left,
|
||||
right_path: right,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(response.content[0]).toEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(response.structuredContent),
|
||||
});
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const connected = async (
|
||||
evidenceFilePolicy?: EvidenceFilePolicy,
|
||||
investigationInputRoots: readonly string[] = evidenceFilePolicy?.roots ?? [],
|
||||
permissionAuthority?: PermissionAuthority,
|
||||
) => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
...(evidenceFilePolicy === undefined
|
||||
? {}
|
||||
: {
|
||||
evidenceFilePolicy,
|
||||
investigationInputRoots,
|
||||
}),
|
||||
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
|
||||
});
|
||||
const client = new Client({ name: "investigation-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return { session, server, client };
|
||||
};
|
||||
|
||||
const evidencePolicy = (root: string): EvidenceFilePolicy => ({
|
||||
roots: [root],
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024 * 1024,
|
||||
maxNodes: 1_000_000,
|
||||
});
|
||||
|
||||
const sessionEvidence = (session: BinarySession, value: unknown) => {
|
||||
const parsed = z
|
||||
.object({ evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u) })
|
||||
.parse(value);
|
||||
const evidence = session.evidenceById(parsed.evidence_id);
|
||||
if (evidence === undefined) throw new TypeError("Missing session Evidence");
|
||||
return evidence;
|
||||
};
|
||||
|
||||
const investigationAuthority = async (
|
||||
root: string,
|
||||
includeWrite: boolean,
|
||||
): Promise<PermissionAuthority> =>
|
||||
permissionAuthorityForRoot(
|
||||
root,
|
||||
[
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"investigation_input",
|
||||
],
|
||||
[
|
||||
"investigation_workspace_read",
|
||||
"investigation_input",
|
||||
...(includeWrite ? (["investigation_workspace_write"] as const) : []),
|
||||
],
|
||||
);
|
||||
|
||||
const close = async (
|
||||
session: BinarySession,
|
||||
server: Awaited<ReturnType<typeof createServer>>,
|
||||
client: Client,
|
||||
) => {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
};
|
||||
@@ -0,0 +1,152 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
|
||||
import { observeJavaScriptRuntime } from "../../../src/application/JavaScriptRuntimeObservationService.js";
|
||||
import { V8InspectorProvider } from "../../../src/browser/V8InspectorProvider.js";
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { startFakeV8Inspector } from "../../fixtures/fakeV8Inspector.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("JavaScript runtime observation MCP tools", () => {
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(resources.splice(0).map((item) => item.close()));
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
test("lists and observes one target as retained Evidence", async () => {
|
||||
const root = await createTestTempDirectory("rea-v8-mcp-");
|
||||
temporary.push(root);
|
||||
const entry = join(root, "entry.js");
|
||||
await writeFile(entry, "export const value = 1;\n");
|
||||
const inspector = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(entry).href,
|
||||
});
|
||||
resources.push(inspector);
|
||||
const config = parseConfig({
|
||||
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
|
||||
REA_V8_INSPECTOR_ENDPOINTS_JSON: JSON.stringify([inspector.endpoint]),
|
||||
REA_V8_INSPECTOR_FILE_ROOTS_JSON: JSON.stringify([root]),
|
||||
});
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
javascriptRuntimeObservation: new V8InspectorProvider(),
|
||||
permissionAuthority: authority.value,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 0,
|
||||
v8InspectorObservationEnabled: true,
|
||||
}),
|
||||
});
|
||||
const client = new Client({ name: "v8-mcp-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const listed = await client.callTool({
|
||||
name: "list_javascript_runtime_targets",
|
||||
arguments: {
|
||||
inspector_endpoint: inspector.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
allowed_origins: [],
|
||||
approved: true,
|
||||
},
|
||||
});
|
||||
expect(listed.isError).not.toBe(true);
|
||||
expect(listed.structuredContent).toMatchObject({
|
||||
result: {
|
||||
targets: { items: [{ target_id: inspector.targetId }] },
|
||||
},
|
||||
});
|
||||
|
||||
const observedRuntime = await client.callTool({
|
||||
name: "observe_javascript_runtime",
|
||||
arguments: {
|
||||
inspector_endpoint: inspector.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
allowed_origins: [],
|
||||
target_id: inspector.targetId,
|
||||
runtime_kind: "node",
|
||||
approved: true,
|
||||
observation_ms: 10,
|
||||
},
|
||||
});
|
||||
expect(observedRuntime.isError).not.toBe(true);
|
||||
expect(observedRuntime.structuredContent).toMatchObject({
|
||||
result: {
|
||||
target: {
|
||||
target_id: inspector.targetId,
|
||||
runtime_kind: "node",
|
||||
runtime_kind_authority: "caller-declared-unverified",
|
||||
},
|
||||
scripts: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
location: { kind: "file", file_path: entry },
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const evidenceId = evidenceIdFrom(observedRuntime.structuredContent);
|
||||
expect(session.evidenceById(evidenceId)).toBeDefined();
|
||||
expect(inspector.commands.map(({ method }) => method)).toEqual([
|
||||
"Runtime.enable",
|
||||
"Debugger.enable",
|
||||
]);
|
||||
const direct = await observeJavaScriptRuntime(
|
||||
new V8InspectorProvider(),
|
||||
authority.value,
|
||||
{
|
||||
inspector_endpoint: inspector.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
allowed_origins: [],
|
||||
target_id: inspector.targetId,
|
||||
runtime_kind: "node",
|
||||
approved: true,
|
||||
observation_ms: 10,
|
||||
limits: {
|
||||
max_events: 10_000,
|
||||
max_scripts: 2_000,
|
||||
max_execution_contexts: 1_000,
|
||||
max_location_bytes: 16_384,
|
||||
max_total_metadata_bytes: 4_194_304,
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(direct.ok).toBe(true);
|
||||
if (direct.ok) expect(evidenceId).toBe(direct.value.evidence_id);
|
||||
});
|
||||
});
|
||||
|
||||
const evidenceIdFrom = (value: unknown): string => {
|
||||
if (typeof value !== "object" || value === null)
|
||||
throw new TypeError("Missing structured result");
|
||||
const evidenceId = Reflect.get(value, "evidence_id");
|
||||
if (typeof evidenceId !== "string")
|
||||
throw new TypeError("Missing Evidence ID");
|
||||
return evidenceId;
|
||||
};
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { ServeStdioOptions } from "@modelcontextprotocol/server/stdio";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { run, runEntrypoint } from "../../../src/main.js";
|
||||
|
||||
type RuntimeDependencies = NonNullable<Parameters<typeof run>[0]>;
|
||||
|
||||
const nextTurn = (): Promise<void> =>
|
||||
new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
const dependencies = ({
|
||||
serve,
|
||||
output,
|
||||
shutdown,
|
||||
exitCodes,
|
||||
shutdownUnregistrations = [],
|
||||
}: {
|
||||
readonly serve: RuntimeDependencies["serve"];
|
||||
readonly output: string[];
|
||||
readonly shutdown: Array<() => void>;
|
||||
readonly exitCodes: number[];
|
||||
readonly shutdownUnregistrations?: string[];
|
||||
}): RuntimeDependencies => ({
|
||||
env: {},
|
||||
serve,
|
||||
writeStderr: (text) => output.push(text),
|
||||
setExitCode: (code) => exitCodes.push(code),
|
||||
registerShutdown: (handler) => {
|
||||
shutdown.push(handler);
|
||||
return () => shutdownUnregistrations.push("shutdown");
|
||||
},
|
||||
});
|
||||
|
||||
describe("MCP runtime errors", () => {
|
||||
it("reports connection loss without the transport cause", async () => {
|
||||
const output: string[] = [];
|
||||
const shutdown: Array<() => void> = [];
|
||||
const shutdownUnregistrations: string[] = [];
|
||||
let options: ServeStdioOptions | undefined;
|
||||
let closeCalls = 0;
|
||||
const close = (): Promise<void> => {
|
||||
closeCalls += 1;
|
||||
return Promise.resolve();
|
||||
};
|
||||
const exitCodes: number[] = [];
|
||||
expect(
|
||||
await run(
|
||||
dependencies({
|
||||
serve: (_factory, received) => {
|
||||
options = received;
|
||||
return { close };
|
||||
},
|
||||
output,
|
||||
shutdown,
|
||||
exitCodes,
|
||||
shutdownUnregistrations,
|
||||
}),
|
||||
),
|
||||
).toBe(0);
|
||||
options?.onerror?.(new Error("SECRET transport stack"));
|
||||
expect(output).toEqual([
|
||||
"REA lost its MCP client connection. Restart REA from your MCP client.\n",
|
||||
]);
|
||||
shutdown[0]?.();
|
||||
await nextTurn();
|
||||
expect(closeCalls).toBe(1);
|
||||
expect(shutdownUnregistrations).toEqual(["shutdown"]);
|
||||
});
|
||||
|
||||
it("unregisters every process-lifetime handler during idempotent shutdown", async () => {
|
||||
const shutdown: Array<() => void> = [];
|
||||
const reload: Array<() => void> = [];
|
||||
const unregistrations: string[] = [];
|
||||
let closeCalls = 0;
|
||||
const runtime: RuntimeDependencies = {
|
||||
...dependencies({
|
||||
serve: () => ({
|
||||
close: async () => {
|
||||
closeCalls += 1;
|
||||
},
|
||||
}),
|
||||
output: [],
|
||||
shutdown,
|
||||
exitCodes: [],
|
||||
shutdownUnregistrations: unregistrations,
|
||||
}),
|
||||
registerReload: (handler) => {
|
||||
reload.push(handler);
|
||||
return () => unregistrations.push("reload");
|
||||
},
|
||||
};
|
||||
|
||||
expect(await run(runtime)).toBe(0);
|
||||
expect(shutdown).toHaveLength(1);
|
||||
expect(reload).toHaveLength(1);
|
||||
|
||||
shutdown[0]?.();
|
||||
shutdown[0]?.();
|
||||
await nextTurn();
|
||||
|
||||
expect(closeCalls).toBe(1);
|
||||
expect(unregistrations).toEqual(["reload", "shutdown"]);
|
||||
});
|
||||
|
||||
it("reports transport startup failure without its cause", async () => {
|
||||
const output: string[] = [];
|
||||
expect(
|
||||
await run(
|
||||
dependencies({
|
||||
serve: () => {
|
||||
throw new Error("SECRET startup stack");
|
||||
},
|
||||
output,
|
||||
shutdown: [],
|
||||
exitCodes: [],
|
||||
}),
|
||||
),
|
||||
).toBe(1);
|
||||
expect(output).toEqual([
|
||||
"REA could not start its MCP connection. Restart REA from your MCP client; run `rea doctor` if it fails again.\n",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports shutdown failure and sets a failing exit code", async () => {
|
||||
const output: string[] = [];
|
||||
const shutdown: Array<() => void> = [];
|
||||
const exitCodes: number[] = [];
|
||||
await run(
|
||||
dependencies({
|
||||
serve: () => ({
|
||||
close: () => Promise.reject(new Error("SECRET close")),
|
||||
}),
|
||||
output,
|
||||
shutdown,
|
||||
exitCodes,
|
||||
}),
|
||||
);
|
||||
shutdown[0]?.();
|
||||
await nextTurn();
|
||||
expect(exitCodes).toEqual([1]);
|
||||
expect(output).toEqual([
|
||||
"REA could not close cleanly. End the REA process before starting it again.\n",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports an unexpected entrypoint failure without its cause", async () => {
|
||||
const output: string[] = [];
|
||||
const exitCodes: number[] = [];
|
||||
await runEntrypoint(
|
||||
() => Promise.reject(new Error("SECRET entrypoint stack")),
|
||||
(text) => output.push(text),
|
||||
(code) => exitCodes.push(code),
|
||||
);
|
||||
expect(output).toEqual([
|
||||
"REA could not start. Run `rea doctor`, then restart REA from your MCP client.\n",
|
||||
]);
|
||||
expect(exitCodes).toEqual([1]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import type { ProjectPermissionStore } from "../../../src/application/ProjectPermissionStore.js";
|
||||
import type { PermissionGrant } from "../../../src/domain/permissionPolicy.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { run } from "../../../src/main.js";
|
||||
import {
|
||||
createServer,
|
||||
type CreateServerOptions,
|
||||
} from "../../../src/server/createServer.js";
|
||||
|
||||
type RuntimeDependencies = NonNullable<Parameters<typeof run>[0]>;
|
||||
|
||||
const directories: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
directories
|
||||
.splice(0)
|
||||
.map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("runtime permission reload", () => {
|
||||
it("keeps live state unchanged after a late grant failure, then commits together", async () => {
|
||||
const fixture = await reloadFixture();
|
||||
const invalid = projectStore(fixture.projectRoot, [
|
||||
projectGrant("invalid", fixture.outsideRoot),
|
||||
]);
|
||||
const valid = projectStore(fixture.projectRoot, [
|
||||
projectGrant("valid", fixture.newRoot),
|
||||
]);
|
||||
const validReadStarted = deferred<void>();
|
||||
const releaseValidRead = deferred<void>();
|
||||
let reads = 0;
|
||||
const runtime = await startRuntime(fixture.env, async () => {
|
||||
reads += 1;
|
||||
if (reads === 1) return ok(invalid);
|
||||
validReadStarted.resolve();
|
||||
await releaseValidRead.promise;
|
||||
return ok(valid);
|
||||
});
|
||||
|
||||
configure(fixture.env, fixture.newRoot, true);
|
||||
runtime.reload();
|
||||
runtime.reload();
|
||||
await validReadStarted.promise;
|
||||
|
||||
expect(runtime.notifications()).toBe(0);
|
||||
expect(runtime.options.processPolicy?.enabled).toBe(false);
|
||||
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
|
||||
fixture.oldRoot,
|
||||
]);
|
||||
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(false);
|
||||
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(true);
|
||||
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(false);
|
||||
|
||||
releaseValidRead.resolve();
|
||||
await runtime.notificationCount(1);
|
||||
|
||||
expect(runtime.options.processPolicy?.enabled).toBe(true);
|
||||
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
|
||||
fixture.newRoot,
|
||||
]);
|
||||
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
|
||||
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(false);
|
||||
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(true);
|
||||
});
|
||||
|
||||
it("serializes overlapping reloads so an older read cannot commit last", async () => {
|
||||
const fixture = await reloadFixture();
|
||||
const firstReadStarted = deferred<void>();
|
||||
const releaseFirstRead = deferred<void>();
|
||||
const secondReadStarted = deferred<void>();
|
||||
let secondStarted = false;
|
||||
let reads = 0;
|
||||
const runtime = await startRuntime(fixture.env, async () => {
|
||||
reads += 1;
|
||||
if (reads === 1) {
|
||||
firstReadStarted.resolve();
|
||||
await releaseFirstRead.promise;
|
||||
return ok(projectStore(fixture.projectRoot, []));
|
||||
}
|
||||
secondStarted = true;
|
||||
secondReadStarted.resolve();
|
||||
return ok(projectStore(fixture.projectRoot, []));
|
||||
});
|
||||
|
||||
configure(fixture.env, fixture.newRoot, true);
|
||||
runtime.reload();
|
||||
await firstReadStarted.promise;
|
||||
configure(fixture.env, fixture.latestRoot, false);
|
||||
runtime.reload();
|
||||
|
||||
expect(secondStarted).toBe(false);
|
||||
releaseFirstRead.resolve();
|
||||
await secondReadStarted.promise;
|
||||
await runtime.notificationCount(2);
|
||||
|
||||
expect(runtime.options.processPolicy?.enabled).toBe(false);
|
||||
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
|
||||
fixture.latestRoot,
|
||||
]);
|
||||
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(false);
|
||||
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(false);
|
||||
expect(await canRead(runtime.authority, fixture.latestRoot)).toBe(true);
|
||||
});
|
||||
|
||||
it("continues with later reloads after an unexpected reload rejection", async () => {
|
||||
const fixture = await reloadFixture();
|
||||
let reads = 0;
|
||||
const runtime = await startRuntime(fixture.env, async () => {
|
||||
reads += 1;
|
||||
if (reads === 1) throw new Error("synthetic unexpected read failure");
|
||||
return ok(projectStore(fixture.projectRoot, []));
|
||||
});
|
||||
|
||||
configure(fixture.env, fixture.newRoot, true);
|
||||
runtime.reload();
|
||||
runtime.reload();
|
||||
await runtime.notificationCount(1);
|
||||
|
||||
expect(reads).toBe(2);
|
||||
expect(runtime.options.processPolicy?.enabled).toBe(true);
|
||||
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
|
||||
fixture.newRoot,
|
||||
]);
|
||||
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
|
||||
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(false);
|
||||
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
const reloadFixture = async () => {
|
||||
const directory = await createTestTempDirectory("rea-main-reload-");
|
||||
directories.push(directory);
|
||||
const oldRoot = join(directory, "old");
|
||||
const newRoot = join(directory, "new");
|
||||
const latestRoot = join(directory, "latest");
|
||||
const outsideRoot = join(directory, "outside");
|
||||
const projectRoot = join(directory, "project");
|
||||
await Promise.all(
|
||||
[oldRoot, newRoot, latestRoot, outsideRoot, projectRoot].map((path) =>
|
||||
mkdir(path),
|
||||
),
|
||||
);
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
REA_EVIDENCE_ROOTS_JSON: JSON.stringify([oldRoot]),
|
||||
REA_PERMISSION_PROJECT_ROOT: projectRoot,
|
||||
REA_PERMISSION_PROJECT_STORE: join(directory, "permissions.json"),
|
||||
};
|
||||
return { env, oldRoot, newRoot, latestRoot, outsideRoot, projectRoot };
|
||||
};
|
||||
|
||||
const configure = (
|
||||
env: NodeJS.ProcessEnv,
|
||||
root: string,
|
||||
enabled: boolean,
|
||||
): void => {
|
||||
env.REA_EVIDENCE_ROOTS_JSON = JSON.stringify([root]);
|
||||
env.REA_PROCESS_CAPTURE_ENABLED = String(enabled);
|
||||
env.REA_PROCESS_EXECUTABLE_ROOTS_JSON = JSON.stringify([root]);
|
||||
env.REA_PROCESS_WORKING_ROOTS_JSON = JSON.stringify([root]);
|
||||
env.REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED = String(enabled);
|
||||
};
|
||||
|
||||
const startRuntime = async (
|
||||
env: NodeJS.ProcessEnv,
|
||||
readStore: NonNullable<RuntimeDependencies["readProjectPermissionStore"]>,
|
||||
) => {
|
||||
let reload: (() => void) | undefined;
|
||||
let options: CreateServerOptions | undefined;
|
||||
let notificationCount = 0;
|
||||
let notification = deferred<void>();
|
||||
const waiters = new Map<number, ReturnType<typeof deferred<void>>>();
|
||||
const result = await run({
|
||||
env,
|
||||
serve: (factory) => {
|
||||
void factory({ era: "legacy" });
|
||||
return { close: () => Promise.resolve() };
|
||||
},
|
||||
writeStderr: () => undefined,
|
||||
setExitCode: () => undefined,
|
||||
registerShutdown: () => () => undefined,
|
||||
registerReload: (handler) => {
|
||||
reload = handler;
|
||||
return () => undefined;
|
||||
},
|
||||
readProjectPermissionStore: readStore,
|
||||
createServer: (analysis, session, received) => {
|
||||
options = received;
|
||||
const server = createServer(analysis, session, received);
|
||||
server.sendToolListChanged = () => {
|
||||
notificationCount += 1;
|
||||
notification.resolve(undefined);
|
||||
notification = deferred<void>();
|
||||
waiters.get(notificationCount)?.resolve(undefined);
|
||||
};
|
||||
return server;
|
||||
},
|
||||
});
|
||||
expect(result).toBe(0);
|
||||
const authority = options?.permissionAuthority;
|
||||
if (reload === undefined || options === undefined || authority === undefined)
|
||||
throw new Error("Runtime reload seam was not initialized");
|
||||
const capturedOptions = options;
|
||||
return {
|
||||
reload,
|
||||
options: capturedOptions,
|
||||
authority,
|
||||
notifications: () => notificationCount,
|
||||
notificationCount: (count: number) => {
|
||||
if (notificationCount >= count) return Promise.resolve();
|
||||
const waiter = deferred<void>();
|
||||
waiters.set(count, waiter);
|
||||
return waiter.promise;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const projectStore = (
|
||||
projectRoot: string,
|
||||
grants: readonly ReturnType<typeof projectGrant>[],
|
||||
): ProjectPermissionStore => ({
|
||||
schema_version: 1,
|
||||
project_id: `project_${createHash("sha256").update(projectRoot).digest("hex")}`,
|
||||
project_root: projectRoot,
|
||||
grants: [...grants],
|
||||
});
|
||||
|
||||
const projectGrant = (id: string, root: string) =>
|
||||
({
|
||||
grant_id: `project:${id}`,
|
||||
capability: "evidence_read",
|
||||
roots: [root],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
lifetime: "project",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
}) satisfies PermissionGrant;
|
||||
|
||||
const canRead = async (
|
||||
authority: PermissionAuthority,
|
||||
root: string,
|
||||
): Promise<boolean> =>
|
||||
(
|
||||
await authority.explain(
|
||||
{
|
||||
capability: "evidence_read",
|
||||
roots: [root],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: `read:${root}`,
|
||||
},
|
||||
"read",
|
||||
)
|
||||
).ok;
|
||||
|
||||
const deferred = <T>() => {
|
||||
let resolvePromise!: (value: T | PromiseLike<T>) => void;
|
||||
const promise = new Promise<T>((resolve) => {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
return { promise, resolve: resolvePromise };
|
||||
};
|
||||
@@ -0,0 +1,400 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { AnalysisProviderRegistry } from "../../../src/application/AnalysisProviderRegistry.js";
|
||||
import { composeBinarySession } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { createPermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { SessionProviderRouter } from "../../../src/application/SessionProviderRouter.js";
|
||||
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managedWorkflowExamples.js";
|
||||
import type { PermissionCeiling } from "../../../src/domain/permissionPolicy.js";
|
||||
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { buildManagedPeFixture } from "../../fixtures/managedPe.js";
|
||||
|
||||
it("opens a managed PE and executes the managed static provider through MCP", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-mcp-");
|
||||
const path = join(directory, "fixture.exe");
|
||||
const rightPath = join(directory, "fixture-renamed.exe");
|
||||
const runtimePath = join(directory, "dotnet");
|
||||
await writeFile(path, buildManagedPeFixture());
|
||||
await writeFile(runtimePath, "#!/bin/sh\n");
|
||||
await writeFile(rightPath, buildManagedPeFixture({ methodName: "Renamed" }));
|
||||
const session = composeBinarySession(
|
||||
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
|
||||
new ManagedStaticProvider(),
|
||||
]),
|
||||
);
|
||||
const runtimeCeiling: PermissionCeiling = {
|
||||
capability: "managed_runtime",
|
||||
roots: [directory],
|
||||
executables: [runtimePath],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
};
|
||||
const authority = await createPermissionAuthority(
|
||||
[runtimeCeiling],
|
||||
[
|
||||
{
|
||||
...runtimeCeiling,
|
||||
grant_id: "administrator:managed_runtime",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const server = createServer(session, session, {
|
||||
permissionAuthority: authority.value,
|
||||
managedRuntimePolicy: {
|
||||
enabled: true,
|
||||
roots: [directory],
|
||||
executablePath: runtimePath,
|
||||
},
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 0,
|
||||
browserObservationEnabled: false,
|
||||
electronObservationEnabled: false,
|
||||
javascriptReplayEnabled: false,
|
||||
managedRuntimeEnabled: true,
|
||||
}),
|
||||
});
|
||||
const client = new Client({ name: "managed-mcp-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await verifyManagedCatalogAndNativeWorkflow(client, session);
|
||||
const members = await inspectManagedStaticWorkflow(client, session, path);
|
||||
await verifyManagedComparisonAndReconstruction(
|
||||
client,
|
||||
session,
|
||||
members,
|
||||
rightPath,
|
||||
);
|
||||
} finally {
|
||||
await Promise.all([client.close(), server.close()]);
|
||||
await session.close();
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
const verifyManagedCatalogAndNativeWorkflow = async (
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
): Promise<void> => {
|
||||
const names = (await client.listTools()).tools.map(({ name }) => name);
|
||||
expect(names).toEqual(
|
||||
expect.arrayContaining([
|
||||
"inspect_managed_artifact",
|
||||
"inspect_managed_members",
|
||||
"inspect_managed_native_boundaries",
|
||||
"compare_managed_members",
|
||||
"import_managed_reconstruction",
|
||||
"verify_managed_native_boundaries",
|
||||
"plan_managed_runtime_correlation",
|
||||
]),
|
||||
);
|
||||
for (const evidence of [
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
|
||||
...MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations,
|
||||
])
|
||||
expect(session.recordEvidence(evidence)).toMatchObject({ ok: true });
|
||||
const verified = structured(
|
||||
await client.callTool({
|
||||
name: "verify_managed_native_boundaries",
|
||||
arguments: {
|
||||
managed_boundaries_evidence_id:
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries.evidence_id,
|
||||
native_observation_evidence_ids:
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations.map(
|
||||
({ evidence_id: evidenceId }) => evidenceId,
|
||||
),
|
||||
limits: MANAGED_NATIVE_VERIFICATION_EXAMPLE.limits,
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(verified).toMatchObject({
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
|
||||
result: {
|
||||
summary: { verified: 1 },
|
||||
algorithm: { token_to_address_mapping: "not-inferred" },
|
||||
},
|
||||
});
|
||||
const native = MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations[0];
|
||||
if (native === undefined) throw new Error("missing native Evidence");
|
||||
const wrong = await client.callTool({
|
||||
name: "verify_managed_native_boundaries",
|
||||
arguments: {
|
||||
managed_boundaries_evidence_id: native.evidence_id,
|
||||
native_observation_evidence_ids: [
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries.evidence_id,
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(wrong).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
code: "evidence_integrity_mismatch",
|
||||
details: { reason: "wrong_operation", actual: "inspect_macho" },
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const inspectManagedStaticWorkflow = async (
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
path: string,
|
||||
): Promise<Record<string, unknown>> => {
|
||||
const inspected = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_artifact",
|
||||
arguments: { path, reference_limit: 1 },
|
||||
}),
|
||||
);
|
||||
expect(inspected).toMatchObject({
|
||||
result: {
|
||||
classification: { status: "managed", runtime_family: "modern-dotnet" },
|
||||
references: { limit: 1 },
|
||||
},
|
||||
});
|
||||
const members = sessionEvidence(
|
||||
session,
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_members",
|
||||
arguments: { method_limit: 1 },
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(members).toMatchObject({
|
||||
operation: "inspect_managed_members",
|
||||
provider: { id: "rea-dotnet-static" },
|
||||
subject: { local_path: path, format: "pe" },
|
||||
normalized_result: {
|
||||
identity_scope: { token_identity: "build-local" },
|
||||
methods: { total: 1, returned: 1 },
|
||||
call_edges: { total: 1 },
|
||||
field_accesses: { total: 1 },
|
||||
},
|
||||
});
|
||||
const boundaries = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_native_boundaries",
|
||||
arguments: { import_limit: 1 },
|
||||
}),
|
||||
);
|
||||
expect(boundaries).toMatchObject({
|
||||
result: {
|
||||
identity_scope: { token_identity: "build-local" },
|
||||
pinvoke_imports: { total: 0, limit: 1 },
|
||||
native_implementations: { total: 0 },
|
||||
},
|
||||
});
|
||||
return members;
|
||||
};
|
||||
|
||||
const methodFrom = (members: Record<string, unknown>) =>
|
||||
z
|
||||
.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
token: z.string(),
|
||||
signature: z.object({ raw_sha256: z.string() }),
|
||||
body: z.object({ normalized_il_sha256: z.string().nullable() }),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.parse(
|
||||
z.record(z.string(), z.unknown()).parse(members.normalized_result)
|
||||
.methods,
|
||||
).items[0];
|
||||
|
||||
const verifyManagedComparisonAndReconstruction = async (
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
members: Record<string, unknown>,
|
||||
rightPath: string,
|
||||
): Promise<void> => {
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: rightPath },
|
||||
});
|
||||
const right = sessionEvidence(
|
||||
session,
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_members",
|
||||
arguments: { method_limit: 1 },
|
||||
}),
|
||||
),
|
||||
);
|
||||
const compared = sessionEvidence(
|
||||
session,
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "compare_managed_members",
|
||||
arguments: {
|
||||
left_evidence_id: members.evidence_id,
|
||||
right_evidence_id: right.evidence_id,
|
||||
limits: {
|
||||
max_method_matches: 100,
|
||||
max_field_matches: 100,
|
||||
max_candidates: 10,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(compared).toMatchObject({
|
||||
operation: "compare_managed_members",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
confidence: "inferred",
|
||||
normalized_result: {
|
||||
algorithm: { name_matching: "not-used" },
|
||||
matching: { exact_il_signature: 1 },
|
||||
},
|
||||
});
|
||||
const method = methodFrom(members);
|
||||
expect(method).toBeDefined();
|
||||
if (method === undefined) return;
|
||||
await verifyImport(client, session, members, method);
|
||||
await verifyRuntimePlan(client, session, members, method);
|
||||
};
|
||||
|
||||
type ManagedMethod = NonNullable<ReturnType<typeof methodFrom>>;
|
||||
|
||||
const verifyImport = async (
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
members: Record<string, unknown>,
|
||||
method: ManagedMethod,
|
||||
): Promise<void> => {
|
||||
const imported = sessionEvidence(
|
||||
session,
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "import_managed_reconstruction",
|
||||
arguments: {
|
||||
static_members_evidence_id: members.evidence_id,
|
||||
decompiler: {
|
||||
name: "ilspycmd",
|
||||
version: "9.1.0.7988",
|
||||
family: "ilspy",
|
||||
executable_sha256: null,
|
||||
options: ["--type", "Example.Program"],
|
||||
},
|
||||
methods: [
|
||||
{
|
||||
token: method.token,
|
||||
signature_sha256: method.signature.raw_sha256,
|
||||
normalized_il_sha256: method.body.normalized_il_sha256,
|
||||
reconstruction: {
|
||||
kind: "decompiled-csharp",
|
||||
language: "csharp",
|
||||
text: "internal static void Main() { }",
|
||||
},
|
||||
},
|
||||
],
|
||||
notes: ["synthetic MCP import"],
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(imported).toMatchObject({
|
||||
operation: "import_managed_reconstruction",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
confidence: "inferred",
|
||||
normalized_result: {
|
||||
executed: false,
|
||||
summary: { imported_methods: 1, decompiled_csharp_methods: 1 },
|
||||
methods: [
|
||||
{
|
||||
token: method.token,
|
||||
validation: { canonical_observation: false },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const verifyRuntimePlan = async (
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
members: Record<string, unknown>,
|
||||
method: ManagedMethod,
|
||||
): Promise<void> => {
|
||||
const planned = sessionEvidence(
|
||||
session,
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "plan_managed_runtime_correlation",
|
||||
arguments: {
|
||||
static_members_evidence_id: members.evidence_id,
|
||||
method: {
|
||||
token: method.token,
|
||||
signature_sha256: method.signature.raw_sha256,
|
||||
normalized_il_sha256: method.body.normalized_il_sha256,
|
||||
},
|
||||
requested_effect: "attach",
|
||||
host: {
|
||||
os: "linux",
|
||||
clr_family: "dotnet",
|
||||
architecture: "x86_64",
|
||||
},
|
||||
bounds: {
|
||||
timeout_ms: 5000,
|
||||
max_threads: 32,
|
||||
max_output_bytes: 65536,
|
||||
allow_network: false,
|
||||
allow_ui: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(planned).toMatchObject({
|
||||
operation: "plan_managed_runtime_correlation",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
confidence: "derived",
|
||||
normalized_result: {
|
||||
executed: false,
|
||||
authority_model: { capability: "managed_runtime" },
|
||||
requested_runtime: { effect: "attach", network: "none" },
|
||||
effect_taxonomy: { attaches_process: true },
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
if (
|
||||
typeof result.structuredContent !== "object" ||
|
||||
result.structuredContent === null
|
||||
)
|
||||
throw new Error("missing structured result");
|
||||
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
|
||||
};
|
||||
|
||||
const sessionEvidence = (
|
||||
session: BinarySession,
|
||||
result: Readonly<Record<string, unknown>>,
|
||||
): Record<string, unknown> => {
|
||||
const evidenceId = z.string().parse(result.evidence_id);
|
||||
const evidence = session.evidenceById(evidenceId);
|
||||
if (evidence === undefined) throw new Error("missing session Evidence");
|
||||
return z.record(z.string(), z.unknown()).parse(evidence);
|
||||
};
|
||||
@@ -0,0 +1,112 @@
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
compareInventory,
|
||||
runProductionMcpDoctor,
|
||||
} from "../../../src/mcpDoctor.js";
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("production MCP doctor", () => {
|
||||
it("connects to the production stdio child and verifies the canonical catalog", async () => {
|
||||
const result = await runProductionMcpDoctor({
|
||||
command: process.execPath,
|
||||
args: [resolve("scripts/rea.mjs"), "mcp"],
|
||||
cwd: process.cwd(),
|
||||
environment: process.env,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
healthy: true,
|
||||
adapter: "production-stdio",
|
||||
inventory: {
|
||||
tools: {
|
||||
expected: expect.any(Number),
|
||||
observed: expect.any(Number),
|
||||
missing: [],
|
||||
unexpected: [],
|
||||
},
|
||||
},
|
||||
request_flow: { tool: "binary_session", ok: true },
|
||||
});
|
||||
expect(result.inventory?.tools.expected).toBe(
|
||||
result.inventory?.tools.observed,
|
||||
);
|
||||
expect(result.inventory?.tools.expected).toBeLessThan(
|
||||
CATALOG_IDENTITY.counts.mcp_tools,
|
||||
);
|
||||
}, 30_000);
|
||||
|
||||
it("reports exact missing, unexpected, and duplicate inventory names", () => {
|
||||
expect(compareInventory(["a", "b"], ["b", "c", "c"])).toEqual({
|
||||
expected: 2,
|
||||
observed: 3,
|
||||
missing: ["a"],
|
||||
unexpected: ["c"],
|
||||
duplicates: ["c"],
|
||||
});
|
||||
});
|
||||
|
||||
it("captures startup exit diagnostics", async () => {
|
||||
const result = await runProductionMcpDoctor({
|
||||
command: process.execPath,
|
||||
args: [resolve("tests/fixtures/mcpDoctorExit.mjs")],
|
||||
cwd: process.cwd(),
|
||||
environment: process.env,
|
||||
deadlineMs: 2_000,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
healthy: false,
|
||||
checks: [{ name: "transport", ok: false }],
|
||||
diagnostics: { stderr: expect.stringContaining("startup exit") },
|
||||
});
|
||||
});
|
||||
|
||||
it("kills a child that misses the absolute startup deadline", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-doctor-");
|
||||
temporary.push(root);
|
||||
const pidPath = join(root, "pid");
|
||||
const result = await runProductionMcpDoctor({
|
||||
command: process.execPath,
|
||||
args: [resolve("tests/fixtures/mcpDoctorHang.mjs")],
|
||||
cwd: process.cwd(),
|
||||
environment: { ...process.env, REA_MCP_DOCTOR_PID_PATH: pidPath },
|
||||
deadlineMs: 250,
|
||||
});
|
||||
expect(result.healthy).toBe(false);
|
||||
const pid = Number.parseInt(await readFile(pidPath, "utf8"), 10);
|
||||
await expect(waitForExit(pid)).resolves.toBeUndefined();
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
const waitForExit = async (pid: number): Promise<void> => {
|
||||
for (let attempt = 0; attempt < 50; attempt += 1) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause as NodeJS.ErrnoException).code === "ESRCH"
|
||||
)
|
||||
return;
|
||||
throw cause;
|
||||
}
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
throw new Error(`MCP doctor fixture process ${String(pid)} remained alive`);
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { MCP_STARTUP_POLICY } from "../../../src/mcpStartupPolicy.js";
|
||||
import {
|
||||
createEsmModuleProfileCollector,
|
||||
parseLinuxVmRssBytes,
|
||||
} from "../../../scripts/lib/mcp-startup-probe.mjs";
|
||||
|
||||
describe("MCP startup policy", () => {
|
||||
it("preserves headroom beneath the configured Codex timeout", () => {
|
||||
const codexTimeoutMs =
|
||||
MCP_STARTUP_POLICY.codexStartupTimeoutSeconds * 1_000;
|
||||
|
||||
expect(MCP_STARTUP_POLICY.initializeBudgetMs).toBeLessThan(codexTimeoutMs);
|
||||
expect(MCP_STARTUP_POLICY.firstCatalogBudgetMs).toBeLessThan(
|
||||
codexTimeoutMs,
|
||||
);
|
||||
expect(MCP_STARTUP_POLICY.firstCatalogBudgetMs).toBe(
|
||||
MCP_STARTUP_POLICY.initializeBudgetMs +
|
||||
MCP_STARTUP_POLICY.toolsListBudgetMs,
|
||||
);
|
||||
expect(MCP_STARTUP_POLICY.doctorDeadlineMs).toBeGreaterThanOrEqual(
|
||||
codexTimeoutMs,
|
||||
);
|
||||
});
|
||||
|
||||
it("parses Linux resident memory without accepting other fields", () => {
|
||||
expect(
|
||||
parseLinuxVmRssBytes("Name:\tnode\nVmRSS:\t 12345 kB\nThreads:\t7\n"),
|
||||
).toBe(12_641_280);
|
||||
expect(parseLinuxVmRssBytes("VmSize:\t12345 kB\n")).toBeNull();
|
||||
});
|
||||
|
||||
it("profiles unique file-backed ESM modules without retaining paths", () => {
|
||||
const collector = createEsmModuleProfileCollector();
|
||||
collector.append(
|
||||
"ESM 1: Storing file:///opt/rea/dist/main.js\n" +
|
||||
"ESM 1: Translating StandardModule file:///opt/rea/dist/main.js\n" +
|
||||
"ESM 1: Storing file:///opt/rea/node_modules/zod/index.js",
|
||||
);
|
||||
|
||||
expect(collector.result()).toEqual({
|
||||
supported: true,
|
||||
method: "node-debug-esm",
|
||||
unique_file_modules: 2,
|
||||
unique_package_modules: 0,
|
||||
unique_dependency_modules: 1,
|
||||
debug_lines: 3,
|
||||
truncated: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { HopperRemoteError } from "../../../src/domain/errors.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
const VALID_INPUTS: Readonly<
|
||||
Record<string, Readonly<Record<string, JsonValue>>>
|
||||
> = {
|
||||
address_name: {},
|
||||
comment: {},
|
||||
current_address: {},
|
||||
current_procedure: {},
|
||||
current_document: {},
|
||||
goto_address: { address: "0x1000" },
|
||||
inline_comment: {},
|
||||
list_bookmarks: {},
|
||||
list_documents: {},
|
||||
list_names: {},
|
||||
list_procedures: {},
|
||||
list_segments: {},
|
||||
list_strings: {},
|
||||
next_address: {},
|
||||
prev_address: {},
|
||||
procedure_address: { procedure: "main" },
|
||||
procedure_assembly: { procedure: "main" },
|
||||
procedure_callees: { procedure: "main" },
|
||||
procedure_callers: { procedure: "main" },
|
||||
procedure_info: { procedure: "main" },
|
||||
read_function_instructions: { procedure: "main" },
|
||||
read_bytes: { address: "0x1000", length: 4 },
|
||||
address_to_file_offset: { address: "0x1000" },
|
||||
procedure_references: { procedure: "main" },
|
||||
procedure_pseudo_code: { procedure: "main" },
|
||||
resolve_containing_procedure: { address: "0x1000" },
|
||||
search_procedures: { pattern: "main" },
|
||||
search_strings: { pattern: "hello" },
|
||||
set_address_name: { address: "0x1000", name: "entry" },
|
||||
set_addresses_names: { names: { "0x1000": "entry" } },
|
||||
set_bookmark: { address: "0x1000" },
|
||||
set_comment: { address: "0x1000", comment: "entry point" },
|
||||
set_current_document: { document: "fixture" },
|
||||
set_inline_comment: { address: "0x1000", comment: "entry point" },
|
||||
unset_bookmark: { address: "0x1000" },
|
||||
xrefs: {},
|
||||
};
|
||||
|
||||
interface Invocation {
|
||||
readonly name: string;
|
||||
readonly arguments_: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "contract-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
const page: JsonValue = {
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 0,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
};
|
||||
|
||||
const outputFor = (name: string): JsonValue => {
|
||||
if (["list_procedures", "list_names", "list_strings"].includes(name))
|
||||
return page;
|
||||
if (["address_name", "comment", "inline_comment"].includes(name)) return null;
|
||||
if (["procedure_callees", "procedure_callers", "xrefs"].includes(name))
|
||||
return [];
|
||||
if (["list_bookmarks", "list_documents", "list_segments"].includes(name))
|
||||
return [];
|
||||
if (
|
||||
[
|
||||
"set_address_name",
|
||||
"set_bookmark",
|
||||
"set_comment",
|
||||
"set_inline_comment",
|
||||
"unset_bookmark",
|
||||
].includes(name)
|
||||
)
|
||||
return true;
|
||||
if (name === "set_addresses_names") return { "0x1000": true };
|
||||
if (["search_procedures", "search_strings"].includes(name)) return page;
|
||||
if (name === "procedure_info")
|
||||
return {
|
||||
name: "main",
|
||||
entrypoint: "0x1000",
|
||||
basicblock_count: 1,
|
||||
length: 4,
|
||||
signature: null,
|
||||
locals: [],
|
||||
};
|
||||
if (name === "resolve_containing_procedure")
|
||||
return {
|
||||
query_address: "0x1000",
|
||||
found: true,
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
};
|
||||
if (name === "read_function_instructions")
|
||||
return {
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
instructions: {
|
||||
items: ["0x1000: ret"],
|
||||
total: 1,
|
||||
returned: 1,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
limitations: ["Provider-specific instruction text."],
|
||||
};
|
||||
if (name === "read_bytes")
|
||||
return {
|
||||
address: "0x1000",
|
||||
requested_bytes: 4,
|
||||
returned_bytes: 4,
|
||||
bytes_hex: "c3c3c3c3",
|
||||
complete: true,
|
||||
};
|
||||
if (name === "address_to_file_offset")
|
||||
return { address: "0x1000", file_offset: 0 };
|
||||
if (name === "procedure_references")
|
||||
return {
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
direction: "outgoing",
|
||||
references: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
};
|
||||
return name.includes("address") ? "0x1000" : "fixture";
|
||||
};
|
||||
|
||||
describe("official Hopper proxy tools", () => {
|
||||
it("lists every official contract", async () => {
|
||||
const client = await connect({
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
});
|
||||
const listed = await client.listTools();
|
||||
const officialNames = new Set<string>(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
expect(
|
||||
listed.tools
|
||||
.map(({ name }) => name)
|
||||
.filter((name) => officialNames.has(name))
|
||||
.sort(),
|
||||
).toEqual(OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name).sort());
|
||||
});
|
||||
|
||||
it("executes every handler and projects omitted Python optionals to null", async () => {
|
||||
const invocations: Invocation[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
invocations.push({ name, arguments_ });
|
||||
return Promise.resolve(ok(outputFor(name)));
|
||||
},
|
||||
});
|
||||
|
||||
for (const contract of OFFICIAL_TOOL_CONTRACTS) {
|
||||
const result = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: VALID_INPUTS[contract.name],
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.content).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ type: "resource_link" }),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
expect(invocations.map(({ name }) => name)).toEqual(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
expect(
|
||||
invocations.find(({ name }) => name === "address_name")?.arguments_,
|
||||
).toEqual({
|
||||
document: null,
|
||||
address: null,
|
||||
});
|
||||
expect(
|
||||
invocations.find(({ name }) => name === "search_procedures")?.arguments_,
|
||||
).toEqual({
|
||||
pattern: "main",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns stable safe MCP error content", async () => {
|
||||
const client = await connect({
|
||||
execute: () => Promise.resolve(err(new HopperRemoteError(-1, "denied"))),
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "list_documents",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0]).toEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(result.structuredContent),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
describe("MCP permission preflight", () => {
|
||||
it("denies extraction before dispatch and returns exact typed remediation", async () => {
|
||||
const outputRoot = join(await realpath("/tmp"), "rea-permission-denied");
|
||||
let dispatches = 0;
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: () => {
|
||||
dispatches += 1;
|
||||
throw new Error("provider must not run");
|
||||
},
|
||||
};
|
||||
const server = createServer(analysis, undefined, {
|
||||
permissionAuthority: new PermissionAuthority(createPermissionPolicy([])),
|
||||
});
|
||||
const client = new Client({ name: "permission-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "extract_artifact",
|
||||
arguments: {
|
||||
approved: true,
|
||||
output_root: outputRoot,
|
||||
occurrence_ids: [`occ_${"0".repeat(64)}`],
|
||||
},
|
||||
});
|
||||
|
||||
expect(dispatches).toBe(0);
|
||||
expect(result).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
code: "permission_required",
|
||||
details: {
|
||||
capability: "artifact_extract",
|
||||
missing: { roots: [outputRoot] },
|
||||
},
|
||||
remediation: {
|
||||
restart_required: true,
|
||||
elicitation_supported: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { PROCESS_CAPTURE_ELICITATION_POLICY } from "../../../src/server/ProcessCaptureElicitation.js";
|
||||
describe("process-capture MCP elicitation handshake", () => {
|
||||
it("completes signed consent through the modern MCP client and server", async () => {
|
||||
const root = await createTestTempDirectory("rea-elicit-mcp-");
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy([
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: [root],
|
||||
executables: [process.execPath],
|
||||
environment_names: [],
|
||||
network: "external",
|
||||
mount: false,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const createTestServer = () =>
|
||||
createServer(session, session, {
|
||||
logger: silentLogger,
|
||||
permissionAuthority: authority,
|
||||
processPolicy: {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
});
|
||||
const client = new Client(
|
||||
{ name: "process-elicit", version: "1" },
|
||||
{
|
||||
capabilities: { elicitation: { form: {} } },
|
||||
versionNegotiation: {
|
||||
mode: {
|
||||
pin: PROCESS_CAPTURE_ELICITATION_POLICY.protocolVersions[0],
|
||||
},
|
||||
},
|
||||
inputRequired: { autoFulfill: true, maxRounds: 3 },
|
||||
},
|
||||
);
|
||||
let prompts = 0;
|
||||
client.setRequestHandler("elicitation/create", () => {
|
||||
prompts += 1;
|
||||
return Promise.resolve({
|
||||
action: "accept" as const,
|
||||
content: { lifetime: "session" },
|
||||
});
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const server = serveStdio(createTestServer, {
|
||||
transport: serverTransport,
|
||||
legacy: "reject",
|
||||
});
|
||||
try {
|
||||
await client.connect(clientTransport);
|
||||
const captured = await client.callTool({
|
||||
name: "capture_process_scenario",
|
||||
arguments: {
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: ["-e", "process.exit(0)"],
|
||||
working_directory: root,
|
||||
},
|
||||
});
|
||||
expect(captured.isError).not.toBe(true);
|
||||
expect(prompts).toBe(1);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 20000);
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { isInputRequiredResult } from "@modelcontextprotocol/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import {
|
||||
authorizeProcessCaptureWithElicitation,
|
||||
type ProcessCaptureElicitationState,
|
||||
} from "../../../src/server/ProcessCaptureElicitation.js";
|
||||
const request = {
|
||||
capability: "process_capture" as const,
|
||||
roots: ["/tmp"],
|
||||
executables: [process.execPath],
|
||||
environment_names: ["PATH"],
|
||||
network: "external" as const,
|
||||
mount: false,
|
||||
operation_identity: "capture:test",
|
||||
};
|
||||
const now = Date.parse("2026-07-18T00:00:00.000Z");
|
||||
const ceilingOnlyAuthority = (
|
||||
origins?: readonly string[],
|
||||
): PermissionAuthority =>
|
||||
new PermissionAuthority(
|
||||
createPermissionPolicy([
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: request.roots,
|
||||
executables: request.executables,
|
||||
environment_names: request.environment_names,
|
||||
...(origins === undefined ? {} : { origins }),
|
||||
network: request.network,
|
||||
mount: request.mount,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const requestContext = (
|
||||
state?: ProcessCaptureElicitationState,
|
||||
response?: Record<string, unknown>,
|
||||
) => ({
|
||||
mcpReq: {
|
||||
requestState: () => state,
|
||||
...(response === undefined
|
||||
? {}
|
||||
: { inputResponses: { process_capture_grant: response } }),
|
||||
},
|
||||
});
|
||||
const verifiedState = (
|
||||
state: ProcessCaptureElicitationState | undefined,
|
||||
): Promise<ProcessCaptureElicitationState> => {
|
||||
if (state === undefined) throw new Error("state was not minted");
|
||||
return Promise.resolve(state);
|
||||
};
|
||||
describe("process-capture MCP elicitation grants", () => {
|
||||
it("grants and reuses a signed session scope on the modern protocol", async () => {
|
||||
const authority = ceilingOnlyAuthority();
|
||||
let state: ProcessCaptureElicitationState | undefined;
|
||||
const elicitation = {
|
||||
stateCodec: {
|
||||
mint: (value: ProcessCaptureElicitationState) => {
|
||||
state = value;
|
||||
return Promise.resolve("signed-state");
|
||||
},
|
||||
verify: () => verifiedState(state),
|
||||
},
|
||||
supported: () => true,
|
||||
now: () => now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
};
|
||||
const first = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(first)).toBe(true);
|
||||
expect(first).toMatchObject({ requestState: "signed-state" });
|
||||
expect(first).toMatchObject({
|
||||
inputRequests: {
|
||||
process_capture_grant: {
|
||||
params: {
|
||||
message: expect.stringContaining("Mount access: no"),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(state?.request).toEqual(request);
|
||||
const accepted = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(state, {
|
||||
action: "accept",
|
||||
content: { lifetime: "session" },
|
||||
}),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(accepted)).toBe(false);
|
||||
if (isInputRequiredResult(accepted)) return;
|
||||
expect(accepted.ok).toBe(true);
|
||||
const reused = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(reused)).toBe(false);
|
||||
if (!isInputRequiredResult(reused)) expect(reused.ok).toBe(true);
|
||||
});
|
||||
it("fails closed for legacy clients and altered continuations", async () => {
|
||||
const authority = ceilingOnlyAuthority();
|
||||
let state: ProcessCaptureElicitationState | undefined;
|
||||
const elicitation = {
|
||||
stateCodec: {
|
||||
mint: (value: ProcessCaptureElicitationState) => {
|
||||
state = value;
|
||||
return Promise.resolve("signed-state");
|
||||
},
|
||||
verify: () => verifiedState(state),
|
||||
},
|
||||
supported: () => false,
|
||||
now: () => now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
};
|
||||
const legacy = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(legacy)).toBe(false);
|
||||
if (!isInputRequiredResult(legacy)) expect(legacy.ok).toBe(false);
|
||||
const modern = { ...elicitation, supported: () => true };
|
||||
await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(),
|
||||
modern,
|
||||
);
|
||||
const altered = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
{ ...request, operation_identity: "capture:altered" },
|
||||
requestContext(state, {
|
||||
action: "accept",
|
||||
content: { lifetime: "session" },
|
||||
}),
|
||||
modern,
|
||||
);
|
||||
expect(isInputRequiredResult(altered)).toBe(false);
|
||||
if (!isInputRequiredResult(altered)) expect(altered.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import { isInputRequiredResult } from "@modelcontextprotocol/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import {
|
||||
authorizeProcessCaptureWithElicitation,
|
||||
type ProcessCaptureElicitationState,
|
||||
} from "../../../src/server/ProcessCaptureElicitation.js";
|
||||
const request = {
|
||||
capability: "process_capture" as const,
|
||||
roots: ["/tmp"],
|
||||
executables: [process.execPath],
|
||||
environment_names: ["PATH"],
|
||||
network: "external" as const,
|
||||
mount: false,
|
||||
operation_identity: "capture:test",
|
||||
};
|
||||
const now = Date.parse("2026-07-18T00:00:00.000Z");
|
||||
const ceilingOnlyAuthority = (
|
||||
origins?: readonly string[],
|
||||
): PermissionAuthority =>
|
||||
new PermissionAuthority(
|
||||
createPermissionPolicy([
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: request.roots,
|
||||
executables: request.executables,
|
||||
environment_names: request.environment_names,
|
||||
...(origins === undefined ? {} : { origins }),
|
||||
network: request.network,
|
||||
mount: request.mount,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const requestContext = (
|
||||
state?: ProcessCaptureElicitationState,
|
||||
response?: Record<string, unknown>,
|
||||
) => ({
|
||||
mcpReq: {
|
||||
requestState: () => state,
|
||||
...(response === undefined
|
||||
? {}
|
||||
: { inputResponses: { process_capture_grant: response } }),
|
||||
},
|
||||
});
|
||||
const verifiedState = (
|
||||
state: ProcessCaptureElicitationState | undefined,
|
||||
): Promise<ProcessCaptureElicitationState> => {
|
||||
if (state === undefined) throw new Error("state was not minted");
|
||||
return Promise.resolve(state);
|
||||
};
|
||||
describe("process-capture MCP elicitation grants", () => {
|
||||
it("binds signed continuation state to exact origins", async () => {
|
||||
const authority = ceilingOnlyAuthority([
|
||||
"https://example.test",
|
||||
"https://other.test",
|
||||
]);
|
||||
let state: ProcessCaptureElicitationState | undefined;
|
||||
const elicitation = {
|
||||
stateCodec: {
|
||||
mint: (value: ProcessCaptureElicitationState) => {
|
||||
state = value;
|
||||
return Promise.resolve("signed-state");
|
||||
},
|
||||
verify: () => verifiedState(state),
|
||||
},
|
||||
supported: () => true,
|
||||
now: () => now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
};
|
||||
const scoped = { ...request, origins: ["https://example.test"] };
|
||||
const prompted = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
scoped,
|
||||
requestContext(),
|
||||
elicitation,
|
||||
);
|
||||
expect(prompted).toMatchObject({
|
||||
inputRequests: {
|
||||
process_capture_grant: {
|
||||
params: {
|
||||
message: expect.stringContaining("Origins: https://example.test"),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const altered = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
{ ...scoped, origins: ["https://other.test"] },
|
||||
requestContext(state, {
|
||||
action: "accept",
|
||||
content: { lifetime: "session" },
|
||||
}),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(altered)).toBe(false);
|
||||
if (!isInputRequiredResult(altered)) expect(altered.ok).toBe(false);
|
||||
});
|
||||
it("consumes once grants and rejects continuation replay", async () => {
|
||||
const authority = ceilingOnlyAuthority();
|
||||
let state: ProcessCaptureElicitationState | undefined;
|
||||
const elicitation = {
|
||||
stateCodec: {
|
||||
mint: (value: ProcessCaptureElicitationState) => {
|
||||
state = value;
|
||||
return Promise.resolve("signed-state");
|
||||
},
|
||||
verify: () => verifiedState(state),
|
||||
},
|
||||
supported: () => true,
|
||||
now: () => now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
};
|
||||
await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(),
|
||||
elicitation,
|
||||
);
|
||||
const response = {
|
||||
action: "accept",
|
||||
content: { lifetime: "once" },
|
||||
};
|
||||
const accepted = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(state, response),
|
||||
elicitation,
|
||||
);
|
||||
if (isInputRequiredResult(accepted)) throw new Error("grant was not used");
|
||||
expect(accepted.ok).toBe(true);
|
||||
const replayed = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(state, response),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(replayed)).toBe(false);
|
||||
if (!isInputRequiredResult(replayed)) expect(replayed.ok).toBe(false);
|
||||
const next = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(next)).toBe(true);
|
||||
const declined = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(state, { action: "decline" }),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(declined)).toBe(false);
|
||||
const acceptedAfterDecline = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(state, {
|
||||
action: "accept",
|
||||
content: { lifetime: "session" },
|
||||
}),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(acceptedAfterDecline)).toBe(false);
|
||||
if (!isInputRequiredResult(acceptedAfterDecline))
|
||||
expect(acceptedAfterDecline.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import { isInputRequiredResult } from "@modelcontextprotocol/server";
|
||||
import { mkdir, rm } from "node:fs/promises";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import {
|
||||
authorizeProcessCaptureWithElicitation,
|
||||
type ProcessCaptureElicitationState,
|
||||
} from "../../../src/server/ProcessCaptureElicitation.js";
|
||||
const request = {
|
||||
capability: "process_capture" as const,
|
||||
roots: ["/tmp"],
|
||||
executables: [process.execPath],
|
||||
environment_names: ["PATH"],
|
||||
network: "external" as const,
|
||||
mount: false,
|
||||
operation_identity: "capture:test",
|
||||
};
|
||||
const now = Date.parse("2026-07-18T00:00:00.000Z");
|
||||
const ceilingOnlyAuthority = (
|
||||
origins?: readonly string[],
|
||||
): PermissionAuthority =>
|
||||
new PermissionAuthority(
|
||||
createPermissionPolicy([
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: request.roots,
|
||||
executables: request.executables,
|
||||
environment_names: request.environment_names,
|
||||
...(origins === undefined ? {} : { origins }),
|
||||
network: request.network,
|
||||
mount: request.mount,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const requestContext = (
|
||||
state?: ProcessCaptureElicitationState,
|
||||
response?: Record<string, unknown>,
|
||||
) => ({
|
||||
mcpReq: {
|
||||
requestState: () => state,
|
||||
...(response === undefined
|
||||
? {}
|
||||
: { inputResponses: { process_capture_grant: response } }),
|
||||
},
|
||||
});
|
||||
const verifiedState = (
|
||||
state: ProcessCaptureElicitationState | undefined,
|
||||
): Promise<ProcessCaptureElicitationState> => {
|
||||
if (state === undefined) throw new Error("state was not minted");
|
||||
return Promise.resolve(state);
|
||||
};
|
||||
describe("process-capture MCP elicitation grants", () => {
|
||||
it("bounds replay state and prunes entries at the signed-state TTL", async () => {
|
||||
const authority = ceilingOnlyAuthority();
|
||||
let state: ProcessCaptureElicitationState | undefined;
|
||||
const consumedNonces = new Map<string, number>();
|
||||
const elicitation = {
|
||||
stateCodec: {
|
||||
mint: (value: ProcessCaptureElicitationState) => {
|
||||
state = value;
|
||||
return Promise.resolve("signed-state");
|
||||
},
|
||||
verify: () => verifiedState(state),
|
||||
},
|
||||
supported: () => true,
|
||||
now: () => now,
|
||||
consumedNonces,
|
||||
};
|
||||
await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(),
|
||||
elicitation,
|
||||
);
|
||||
const future = now + 600000;
|
||||
for (let index = 0; index < 4096; index += 1)
|
||||
consumedNonces.set(`occupied-${String(index)}`, future);
|
||||
const rejectedAtCapacity = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(state, {
|
||||
action: "accept",
|
||||
content: { lifetime: "session" },
|
||||
}),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(rejectedAtCapacity)).toBe(false);
|
||||
if (!isInputRequiredResult(rejectedAtCapacity))
|
||||
expect(rejectedAtCapacity.ok).toBe(false);
|
||||
consumedNonces.set("occupied-0", now - 1);
|
||||
const acceptedAfterPrune = await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
request,
|
||||
requestContext(state, {
|
||||
action: "accept",
|
||||
content: { lifetime: "session" },
|
||||
}),
|
||||
elicitation,
|
||||
);
|
||||
expect(isInputRequiredResult(acceptedAfterPrune)).toBe(false);
|
||||
if (!isInputRequiredResult(acceptedAfterPrune))
|
||||
expect(acceptedAfterPrune.ok).toBe(true);
|
||||
expect(consumedNonces.has("occupied-0")).toBe(false);
|
||||
expect(consumedNonces.size).toBe(4096);
|
||||
});
|
||||
it.each(["result", "throw"] as const)(
|
||||
"revokes an elicited grant when final authorization ends with %s",
|
||||
async (failure) => {
|
||||
const root = await createTestTempDirectory("rea-elicit-rollback-");
|
||||
const scoped = { ...request, roots: [root] };
|
||||
const policy = createPermissionPolicy([
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: scoped.roots,
|
||||
executables: scoped.executables,
|
||||
environment_names: scoped.environment_names,
|
||||
network: scoped.network,
|
||||
mount: scoped.mount,
|
||||
},
|
||||
]);
|
||||
class FailingFinalAuthority extends PermissionAuthority {
|
||||
private authorizationCount = 0;
|
||||
override async authorize(
|
||||
...arguments_: Parameters<PermissionAuthority["authorize"]>
|
||||
): ReturnType<PermissionAuthority["authorize"]> {
|
||||
this.authorizationCount += 1;
|
||||
const result = await super.authorize(...arguments_);
|
||||
if (failure === "result" && this.authorizationCount === 2)
|
||||
await rm(root, { recursive: true, force: true });
|
||||
if (failure === "throw" && this.authorizationCount === 3)
|
||||
throw new Error("synthetic final authorization rejection");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
const authority = new FailingFinalAuthority(policy);
|
||||
let state: ProcessCaptureElicitationState | undefined;
|
||||
const elicitation = {
|
||||
stateCodec: {
|
||||
mint: (value: ProcessCaptureElicitationState) => {
|
||||
state = value;
|
||||
return Promise.resolve("signed-state");
|
||||
},
|
||||
verify: () => verifiedState(state),
|
||||
},
|
||||
supported: () => true,
|
||||
now: () => now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
};
|
||||
await authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
scoped,
|
||||
requestContext(),
|
||||
elicitation,
|
||||
);
|
||||
const finalAuthorization = authorizeProcessCaptureWithElicitation(
|
||||
authority,
|
||||
scoped,
|
||||
requestContext(state, {
|
||||
action: "accept",
|
||||
content: { lifetime: "session" },
|
||||
}),
|
||||
elicitation,
|
||||
);
|
||||
if (failure === "throw")
|
||||
await expect(finalAuthorization).rejects.toThrow(
|
||||
"synthetic final authorization rejection",
|
||||
);
|
||||
else {
|
||||
const failed = await finalAuthorization;
|
||||
expect(isInputRequiredResult(failed)).toBe(false);
|
||||
if (!isInputRequiredResult(failed)) expect(failed.ok).toBe(false);
|
||||
await mkdir(root);
|
||||
}
|
||||
const retry = await authority.authorize(scoped, "read", {
|
||||
elicitationSupported: true,
|
||||
});
|
||||
expect(retry.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { isInputRequiredResult } from "@modelcontextprotocol/server";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { PROCESS_CAPTURE_ELICITATION_POLICY } from "../../../src/server/ProcessCaptureElicitation.js";
|
||||
describe("process-capture MCP elicitation handshake", () => {
|
||||
it.each(["tampered", "expired"] as const)(
|
||||
"rejects %s signed state through the modern MCP client and server",
|
||||
async (failure) => {
|
||||
const startedAt = Date.parse("2026-07-23T00:00:00.000Z");
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(startedAt);
|
||||
const root = await createTestTempDirectory("rea-elicit-state-");
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy([
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: [root],
|
||||
executables: [process.execPath],
|
||||
environment_names: [],
|
||||
network: "external",
|
||||
mount: false,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const client = new Client(
|
||||
{ name: "process-elicit-state", version: "1" },
|
||||
{
|
||||
capabilities: { elicitation: { form: {} } },
|
||||
versionNegotiation: {
|
||||
mode: {
|
||||
pin: PROCESS_CAPTURE_ELICITATION_POLICY.protocolVersions[0],
|
||||
},
|
||||
},
|
||||
inputRequired: { autoFulfill: false, maxRounds: 3 },
|
||||
},
|
||||
);
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const server = serveStdio(
|
||||
() =>
|
||||
createServer(session, session, {
|
||||
logger: silentLogger,
|
||||
permissionAuthority: authority,
|
||||
processPolicy: {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
}),
|
||||
{ transport: serverTransport, legacy: "reject" },
|
||||
);
|
||||
const call = {
|
||||
name: "capture_process_scenario",
|
||||
arguments: {
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: ["-e", "process.exit(0)"],
|
||||
working_directory: root,
|
||||
},
|
||||
};
|
||||
try {
|
||||
await client.connect(clientTransport);
|
||||
const required = await client.callTool(call, {
|
||||
allowInputRequired: true,
|
||||
});
|
||||
expect(isInputRequiredResult(required)).toBe(true);
|
||||
if (!isInputRequiredResult(required)) return;
|
||||
const requestState = required.requestState;
|
||||
expect(requestState).toEqual(expect.any(String));
|
||||
if (requestState === undefined) return;
|
||||
if (failure === "expired")
|
||||
vi.setSystemTime(
|
||||
startedAt +
|
||||
(PROCESS_CAPTURE_ELICITATION_POLICY.stateTtlSeconds + 1) * 1000,
|
||||
);
|
||||
const echoedState =
|
||||
failure === "tampered"
|
||||
? `${requestState.startsWith("A") ? "B" : "A"}${requestState.slice(1)}`
|
||||
: requestState;
|
||||
const retryMethod: string = "tools/call";
|
||||
await expect(
|
||||
client.request(
|
||||
{
|
||||
method: retryMethod,
|
||||
params: {
|
||||
...call,
|
||||
requestState: echoedState,
|
||||
inputResponses: {
|
||||
process_capture_grant: {
|
||||
action: "accept",
|
||||
content: { lifetime: "session" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
z.unknown(),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
code: -32602,
|
||||
data: { reason: "invalid_request_state" },
|
||||
});
|
||||
expect(
|
||||
await authority.authorize(
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: [root],
|
||||
executables: [process.execPath],
|
||||
environment_names: [],
|
||||
network: "external",
|
||||
mount: false,
|
||||
operation_identity: `capture_process_scenario:${process.execPath}`,
|
||||
},
|
||||
"read",
|
||||
),
|
||||
).toMatchObject({ ok: false });
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
20000,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
|
||||
import { compareProcessEvidenceFiles } from "../../../src/application/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import type { ProcessTraceSpecification } from "../../../src/domain/processTraceComparison.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
const temporaryRoots: string[] = [];
|
||||
const beforeCheckpoint = {
|
||||
name: "before",
|
||||
at_ms: 0,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
};
|
||||
const afterCheckpoint = {
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
};
|
||||
const capture = {
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
event_journal: [
|
||||
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 2, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
|
||||
],
|
||||
} as const;
|
||||
const traceSpecification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "before",
|
||||
source: "filesystem",
|
||||
exact: beforeCheckpoint,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "exit",
|
||||
source: "lifecycle",
|
||||
exact: { event: "exit", ...capture.exit },
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "settlement",
|
||||
source: "lifecycle",
|
||||
exact: { event: "settlement", ...capture.settlement },
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "after",
|
||||
source: "filesystem",
|
||||
exact: afterCheckpoint,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [
|
||||
{
|
||||
id: "normal",
|
||||
trace: ["before", "exit", "settlement", "after"],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const captureEvidence = (side: "left" | "right") =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture/v4",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: { side },
|
||||
result: jsonValueSchema.parse(capture),
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
locations: [{ kind: "artifact-path", path: `/fixture/${side}` }],
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(resources.splice(0).map((resource) => resource.close()));
|
||||
await Promise.all(
|
||||
temporaryRoots
|
||||
.splice(0)
|
||||
.map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("declared trace adapter parity", () => {
|
||||
it("returns identical CLI and MCP results and Evidence identity", async () => {
|
||||
const left = captureEvidence("left");
|
||||
const right = captureEvidence("right");
|
||||
const root = await createTestTempDirectory("rea-trace-adapters-");
|
||||
temporaryRoots.push(root);
|
||||
const leftPath = join(root, "left.json");
|
||||
const rightPath = join(root, "right.json");
|
||||
const specificationPath = join(root, "trace.json");
|
||||
await Promise.all([
|
||||
writeFile(leftPath, JSON.stringify(left)),
|
||||
writeFile(rightPath, JSON.stringify(right)),
|
||||
writeFile(specificationPath, JSON.stringify(traceSpecification)),
|
||||
]);
|
||||
const cliEvidence = parseEvidence(
|
||||
await compareProcessEvidenceFiles(leftPath, rightPath, specificationPath),
|
||||
);
|
||||
const session = composeBinarySessionFromFactory(
|
||||
(_path) =>
|
||||
({
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}) satisfies AnalysisClient,
|
||||
);
|
||||
expect(session.recordEvidence(left).ok).toBe(true);
|
||||
expect(session.recordEvidence(right).ok).toBe(true);
|
||||
const server = createServer(
|
||||
{ execute: () => Promise.resolve(ok(null)) },
|
||||
session,
|
||||
);
|
||||
const client = new Client({ name: "trace-parity", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const response = await client.callTool({
|
||||
name: "compare_process_captures",
|
||||
arguments: {
|
||||
left_evidence_id: left.evidence_id,
|
||||
right_evidence_id: right.evidence_id,
|
||||
trace_spec: traceSpecification,
|
||||
},
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
result: { trace: { verdict: "equivalent" } },
|
||||
evidence_id: cliEvidence.evidence_id,
|
||||
});
|
||||
const structuredResult =
|
||||
typeof response.structuredContent === "object" &&
|
||||
response.structuredContent !== null
|
||||
? Reflect.get(response.structuredContent, "result")
|
||||
: undefined;
|
||||
expect(structuredResult).toEqual(cliEvidence.normalized_result);
|
||||
expect(cliEvidence.locations).toEqual([
|
||||
{ kind: "artifact-path", path: "/fixture/left" },
|
||||
{ kind: "artifact-path", path: "/fixture/right" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { AnalysisCancelledError } from "../../../src/domain/errors.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
describe("ordinary MCP progress and cancellation", () => {
|
||||
it("emits bounded progress for a normal tool request", async () => {
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: () => Promise.resolve(observed("0x1000")),
|
||||
};
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "progress-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const progress: number[] = [];
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool(
|
||||
{ name: "current_address", arguments: {} },
|
||||
{ onprogress: (update) => progress.push(update.progress) },
|
||||
);
|
||||
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(progress).toEqual([0, 1]);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("propagates client cancellation to the active provider request", async () => {
|
||||
let providerObservedCancellation = false;
|
||||
let markProviderStarted: (() => void) | undefined;
|
||||
const providerStarted = new Promise<void>((resolve) => {
|
||||
markProviderStarted = resolve;
|
||||
});
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: async (operation, _parameters, options) => {
|
||||
markProviderStarted?.();
|
||||
await new Promise<void>((resolve) => {
|
||||
options?.signal?.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
providerObservedCancellation = true;
|
||||
resolve();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
},
|
||||
};
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "cancellation-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const controller = new AbortController();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const request = client.callTool(
|
||||
{ name: "current_address", arguments: {} },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
await providerStarted;
|
||||
controller.abort();
|
||||
await expect(request).rejects.toThrow(/abort/iu);
|
||||
await expect.poll(() => providerObservedCancellation).toBe(true);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,300 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
|
||||
import { PROCESS_CAPTURE_REFERENCE } from "../../../src/contracts/investigationExamples.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createPromptCompletionSource } from "../../../src/server/promptCompletion.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
let directory: string | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
describe("guided prompt completion from live analysis", () => {
|
||||
it("reads live documents and paged procedures without ambiguous names", async () => {
|
||||
const requests: Array<Readonly<Record<string, unknown>>> = [];
|
||||
const session = composeBinarySessionFromFactory(() => client(requests));
|
||||
directory = await createTestTempDirectory("rea-prompt-completion-");
|
||||
const target = join(directory, "fixture.hop");
|
||||
await writeFile(target, "fixture");
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
const completion = createPromptCompletionSource(session, session);
|
||||
|
||||
expect(await completion.complete("document", "app")).toEqual([
|
||||
"App",
|
||||
"AppTests",
|
||||
]);
|
||||
expect(
|
||||
await completion.complete("procedure", "", {
|
||||
arguments: { document: "App" },
|
||||
}),
|
||||
).toEqual(["0x1000", "0x2000", "0x3000", "0x4000", "tail", "unique"]);
|
||||
expect(requests).toEqual([
|
||||
{ offset: 0, limit: 500, document: "App" },
|
||||
{ offset: 2, limit: 500, document: "App" },
|
||||
]);
|
||||
expect(await completion.complete("provider", "uni")).toEqual([
|
||||
"unidentified",
|
||||
]);
|
||||
expect(await completion.complete("document", "x".repeat(4_097))).toEqual(
|
||||
[],
|
||||
);
|
||||
|
||||
await session.close();
|
||||
expect(await completion.complete("document", "")).toEqual([]);
|
||||
expect(await completion.complete("procedure", "")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("guided prompt completion from investigation records", () => {
|
||||
it("projects only validated typed identifiers from the evidence ledger", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => client([]));
|
||||
const invalidCapture = createEvidence(undefined, fixtureProvider, {
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: { schema_version: 4 },
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
environment: fixtureEnvironment,
|
||||
});
|
||||
const invalidInventory = createEvidence(undefined, fixtureProvider, {
|
||||
operation: "fixture_inventory",
|
||||
parameters: {},
|
||||
result: ARTIFACT_COMPARISON_EXAMPLE.right.normalized_result,
|
||||
confidence: "observed",
|
||||
authority: "shipped-artifact",
|
||||
});
|
||||
for (const evidence of [
|
||||
ARTIFACT_COMPARISON_EXAMPLE.left,
|
||||
PROCESS_CAPTURE_REFERENCE,
|
||||
invalidCapture,
|
||||
invalidInventory,
|
||||
])
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
const unknown = session.recordUnknown({
|
||||
approved: true,
|
||||
question: "Which branch handles the fallback?",
|
||||
severity: "medium",
|
||||
domain: "control-flow",
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "analyst-inference",
|
||||
required_confidence: "derived",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
});
|
||||
if (!unknown.ok) throw unknown.error;
|
||||
const completion = createPromptCompletionSource(session, session);
|
||||
|
||||
expect(await completion.complete("capture", "ev_")).toEqual([
|
||||
PROCESS_CAPTURE_REFERENCE.evidence_id,
|
||||
]);
|
||||
expect(await completion.complete("manifest", "agm_")).toEqual([
|
||||
`agm_${"0".repeat(64)}`,
|
||||
]);
|
||||
expect(await completion.complete("occurrence", "occ_")).toEqual([
|
||||
`occ_${"0".repeat(64)}`,
|
||||
]);
|
||||
expect(await completion.complete("unknown", "unk_")).toEqual([
|
||||
unknown.value.unknown_id,
|
||||
]);
|
||||
|
||||
const resolved = session.updateUnknown({
|
||||
approved: true,
|
||||
unknown_id: unknown.value.unknown_id,
|
||||
expected_revision: unknown.value.revision,
|
||||
status: "resolved",
|
||||
severity: unknown.value.severity,
|
||||
supporting_evidence_ids: unknown.value.supporting_evidence_ids,
|
||||
contradicting_evidence_ids: unknown.value.contradicting_evidence_ids,
|
||||
required_authority: unknown.value.required_authority,
|
||||
required_confidence: unknown.value.required_confidence,
|
||||
required_environment: unknown.value.required_environment,
|
||||
recommended_probes: unknown.value.recommended_probes,
|
||||
relationships: unknown.value.relationships,
|
||||
resolution: {
|
||||
disposition: "withdrawn",
|
||||
rationale: "The requested fallback is outside the current scope.",
|
||||
evidence_ids: [],
|
||||
},
|
||||
});
|
||||
expect(resolved.ok).toBe(true);
|
||||
expect(await completion.complete("unknown", "")).toEqual([]);
|
||||
|
||||
await session.close();
|
||||
expect(await completion.complete("evidence", "ev_")).toEqual([]);
|
||||
});
|
||||
|
||||
it("deduplicates, case-folds, and returns deterministic live evidence IDs", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => client([]));
|
||||
for (let index = 149; index >= 0; index -= 1) {
|
||||
const evidence = createEvidence(undefined, fixtureProvider, {
|
||||
operation: `fixture-${String(index)}`,
|
||||
parameters: { index },
|
||||
result: index,
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
});
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
}
|
||||
const completion = createPromptCompletionSource(session, session);
|
||||
const values = await completion.complete("evidence", "EV_");
|
||||
expect(values).toHaveLength(150);
|
||||
expect(values).toEqual([...values].sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe("guided prompt completion validation and limits", () => {
|
||||
it("does not offer procedure names from an incomplete discovery", async () => {
|
||||
let calls = 0;
|
||||
const completion = createPromptCompletionSource({
|
||||
execute() {
|
||||
calls += 1;
|
||||
return Promise.resolve(
|
||||
observed(
|
||||
calls === 1
|
||||
? page(0, [{ address: "0x1000", value: "possibly_ambiguous" }], 1)
|
||||
: null,
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(await completion.complete("procedure", "")).toEqual(["0x1000"]);
|
||||
});
|
||||
|
||||
it("bounds procedure scans and rejects non-advancing continuation metadata", async () => {
|
||||
let calls = 0;
|
||||
const bounded = createPromptCompletionSource({
|
||||
execute(_operation, parameters) {
|
||||
calls += 1;
|
||||
const offset = Number(parameters.offset);
|
||||
const items = Array.from({ length: 500 }, (_, index) => {
|
||||
const address = offset + index;
|
||||
return {
|
||||
address: `0x${address.toString(16).padStart(8, "0")}`,
|
||||
value: `procedure_${String(address)}`,
|
||||
};
|
||||
});
|
||||
return Promise.resolve(
|
||||
observed({
|
||||
items,
|
||||
offset,
|
||||
limit: 500,
|
||||
total: 6_000,
|
||||
next_offset: offset + 500,
|
||||
has_more: true,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const values = await bounded.complete("procedure", "");
|
||||
expect(calls).toBe(10);
|
||||
expect(values).toHaveLength(5_000);
|
||||
expect(values.every((value) => value.startsWith("0x"))).toBe(true);
|
||||
|
||||
let nonAdvancingCalls = 0;
|
||||
const nonAdvancing = createPromptCompletionSource({
|
||||
execute() {
|
||||
nonAdvancingCalls += 1;
|
||||
return Promise.resolve(
|
||||
observed(page(0, [{ address: "0x5000", value: "unsafe_name" }], 0)),
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(await nonAdvancing.complete("procedure", "")).toEqual(["0x5000"]);
|
||||
expect(nonAdvancingCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("normalizes Unicode prefixes while preserving distinct exact identifiers", async () => {
|
||||
const completion = createPromptCompletionSource({
|
||||
execute(operation) {
|
||||
return Promise.resolve(
|
||||
observed(
|
||||
operation === "list_documents"
|
||||
? ["App", "App", "app", "Zulu"]
|
||||
: null,
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(await completion.complete("document", "AP")).toEqual([
|
||||
"App",
|
||||
"app",
|
||||
"App",
|
||||
]);
|
||||
|
||||
const malformed = createPromptCompletionSource({
|
||||
execute: () => Promise.resolve(observed(["valid", 1])),
|
||||
});
|
||||
expect(await malformed.complete("document", "")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
const fixtureProvider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const fixtureEnvironment = {
|
||||
id: "fixture-linux",
|
||||
platform: "linux",
|
||||
architecture: "x86_64",
|
||||
isolation: "process" as const,
|
||||
};
|
||||
|
||||
const client = (
|
||||
requests: Array<Readonly<Record<string, unknown>>>,
|
||||
): AnalysisClient => ({
|
||||
execute(operation, parameters) {
|
||||
if (operation === "list_documents")
|
||||
return Promise.resolve(observed(["AppTests", "App", "App"]));
|
||||
if (operation === "list_procedures") {
|
||||
requests.push(parameters);
|
||||
const offset = parameters.offset;
|
||||
return Promise.resolve(
|
||||
observed(
|
||||
offset === 0
|
||||
? page(
|
||||
0,
|
||||
[
|
||||
{ address: "0x1000", value: "duplicate" },
|
||||
{ address: "0x2000", value: "unique" },
|
||||
],
|
||||
2,
|
||||
)
|
||||
: page(
|
||||
2,
|
||||
[
|
||||
{ address: "0x3000", value: "duplicate" },
|
||||
{ address: "0x4000", value: "tail" },
|
||||
],
|
||||
null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
|
||||
const page = (
|
||||
offset: number,
|
||||
items: readonly { readonly address: string; readonly value: string }[],
|
||||
nextOffset: number | null,
|
||||
) => ({
|
||||
items,
|
||||
offset,
|
||||
limit: 500,
|
||||
total: 4,
|
||||
next_offset: nextOffset,
|
||||
has_more: nextOffset !== null,
|
||||
});
|
||||
@@ -0,0 +1,430 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { basename, join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { PROMPT_CONTRACTS } from "../../../src/contracts/promptContracts.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { registerGuidedPrompts } from "../../../src/server/registerPrompts.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
const temporaryDirectories: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.allSettled(
|
||||
resources.splice(0).map((resource) => resource.close()),
|
||||
);
|
||||
await Promise.all(
|
||||
temporaryDirectories
|
||||
.splice(0)
|
||||
.map((directory) => rm(directory, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("guided prompts over MCP", () => {
|
||||
it("lists and renders all workflows without changing the tool inventory", async () => {
|
||||
const session = fixtureSession();
|
||||
const client = await connect(createServer(session, session));
|
||||
resources.push(session);
|
||||
|
||||
const toolsBeforePrompts = (await client.listTools()).tools;
|
||||
const prompts = await client.listPrompts();
|
||||
expect(prompts.prompts.map(({ name }) => name)).toEqual(
|
||||
PROMPT_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
expect(client.getServerCapabilities()).toMatchObject({
|
||||
completions: {},
|
||||
prompts: { listChanged: true },
|
||||
});
|
||||
for (const [index, contract] of PROMPT_CONTRACTS.entries()) {
|
||||
const advertised = prompts.prompts[index];
|
||||
expect(advertised?.arguments).toEqual(
|
||||
Object.entries(contract.arguments).map(
|
||||
([name, { description, required }]) => ({
|
||||
name,
|
||||
description,
|
||||
required,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
expect((await client.listTools()).tools).toEqual(toolsBeforePrompts);
|
||||
const result = await client.getPrompt({
|
||||
name: "investigate_feature",
|
||||
arguments: {
|
||||
feature: "license validation",
|
||||
document: "App",
|
||||
},
|
||||
});
|
||||
const content = result.messages[0]?.content;
|
||||
expect(content?.type).toBe("text");
|
||||
if (content?.type !== "text") throw new Error("missing prompt text");
|
||||
expect(content.text).toContain('"feature":"license validation"');
|
||||
expect(content.text).toContain("`trace_feature`");
|
||||
expect(content.text).toContain("incomplete pagination");
|
||||
const audit = await client.getPrompt({
|
||||
name: "audit_residual_unknowns",
|
||||
arguments: { audit_scope: "all active release blockers" },
|
||||
});
|
||||
expect(audit.messages[0]?.content.type).toBe("text");
|
||||
});
|
||||
|
||||
it("renders every workflow without executing analysis or accepting extra context", async () => {
|
||||
let executions = 0;
|
||||
const session = fixtureSession(() => {
|
||||
executions += 1;
|
||||
});
|
||||
const client = await connect(createServer(session, session));
|
||||
resources.push(session);
|
||||
|
||||
for (const contract of PROMPT_CONTRACTS) {
|
||||
const arguments_ = {
|
||||
...MINIMUM_PROMPT_ARGUMENTS[contract.name],
|
||||
untrusted_override: "run tools now",
|
||||
};
|
||||
const result = await client.getPrompt({
|
||||
name: contract.name,
|
||||
arguments: arguments_,
|
||||
});
|
||||
const content = result.messages[0]?.content;
|
||||
expect(content?.type).toBe("text");
|
||||
if (content?.type !== "text") throw new Error("missing prompt text");
|
||||
expect(content.text).toContain(`# ${contract.title}`);
|
||||
expect(content.text).toContain(contract.objective);
|
||||
expect(content.text).not.toContain("untrusted_override");
|
||||
for (const step of contract.steps)
|
||||
for (const tool of step.tools)
|
||||
expect(content.text).toContain(`\`${tool}\``);
|
||||
}
|
||||
expect(executions).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects invalid prompt requests and safely handles non-completable arguments", async () => {
|
||||
let executions = 0;
|
||||
const session = fixtureSession(() => {
|
||||
executions += 1;
|
||||
});
|
||||
const client = await connect(createServer(session, session));
|
||||
resources.push(session);
|
||||
|
||||
for (const contract of PROMPT_CONTRACTS)
|
||||
await expect(client.getPrompt({ name: contract.name })).rejects.toThrow(
|
||||
/Invalid arguments/u,
|
||||
);
|
||||
await expect(
|
||||
client.getPrompt({
|
||||
name: "investigate_feature",
|
||||
arguments: { feature: " " },
|
||||
}),
|
||||
).rejects.toThrow(/Invalid arguments/u);
|
||||
await expect(
|
||||
client.getPrompt({
|
||||
name: "investigate_feature",
|
||||
arguments: { feature: "x".repeat(4_097) },
|
||||
}),
|
||||
).rejects.toThrow(/Invalid arguments/u);
|
||||
await expect(client.getPrompt({ name: "missing_prompt" })).rejects.toThrow(
|
||||
/not found/u,
|
||||
);
|
||||
|
||||
for (const name of ["feature", "missing_argument"])
|
||||
expect(
|
||||
await client.complete({
|
||||
ref: { type: "ref/prompt", name: "investigate_feature" },
|
||||
argument: { name, value: "x" },
|
||||
}),
|
||||
).toEqual({ completion: { values: [], hasMore: false } });
|
||||
await expect(
|
||||
client.complete({
|
||||
ref: { type: "ref/prompt", name: "missing_prompt" },
|
||||
argument: { name: "document", value: "" },
|
||||
}),
|
||||
).rejects.toThrow(/not found/u);
|
||||
expect(
|
||||
await client.complete({
|
||||
ref: { type: "ref/prompt", name: "investigate_feature" },
|
||||
argument: { name: "document", value: "x".repeat(4_097) },
|
||||
}),
|
||||
).toEqual({
|
||||
completion: { values: [], total: 0, hasMore: false },
|
||||
});
|
||||
expect(executions).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("guided prompt completion registry", () => {
|
||||
it("applies the MCP 100-value limit while reporting total and hasMore", async () => {
|
||||
const session = fixtureSession();
|
||||
for (let index = 0; index < 150; index += 1)
|
||||
expect(
|
||||
session.recordEvidence(
|
||||
createEvidence(undefined, fixtureProvider, {
|
||||
operation: `fixture-${String(index)}`,
|
||||
parameters: { index },
|
||||
result: index,
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
}),
|
||||
).ok,
|
||||
).toBe(true);
|
||||
const client = await connect(createServer(session, session));
|
||||
resources.push(session);
|
||||
|
||||
const result = await client.complete({
|
||||
ref: { type: "ref/prompt", name: "verify_reconstruction" },
|
||||
argument: { name: "comparison_evidence_id", value: "ev_" },
|
||||
});
|
||||
expect(result.completion.values).toHaveLength(100);
|
||||
expect(result.completion.total).toBe(150);
|
||||
expect(result.completion.hasMore).toBe(true);
|
||||
expect(result.completion.values).toEqual(
|
||||
[...result.completion.values].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it("emits prompts/list_changed and exposes the updated prompt", async () => {
|
||||
const session = fixtureSession();
|
||||
const server = new McpServer({
|
||||
name: "prompt-registry-test",
|
||||
version: "1",
|
||||
});
|
||||
const registry = registerGuidedPrompts(server, session, session);
|
||||
const client = new Client({ name: "prompt-registry-client", version: "1" });
|
||||
const changed = new Promise<void>((resolve) => {
|
||||
client.setNotificationHandler("notifications/prompts/list_changed", () =>
|
||||
resolve(),
|
||||
);
|
||||
});
|
||||
await connectPair(server, client);
|
||||
resources.push(session);
|
||||
expect((await client.listPrompts()).prompts[0]?.title).toBe(
|
||||
"Investigate a feature",
|
||||
);
|
||||
|
||||
registry.update({
|
||||
...PROMPT_CONTRACTS[0],
|
||||
title: "Investigate a feature (updated)",
|
||||
arguments: {
|
||||
...PROMPT_CONTRACTS[0].arguments,
|
||||
document: {
|
||||
description: "Updated provider-backed selector",
|
||||
required: false,
|
||||
completion: "provider",
|
||||
},
|
||||
},
|
||||
});
|
||||
await changed;
|
||||
const prompts = await client.listPrompts();
|
||||
expect(prompts.prompts[0]?.title).toBe("Investigate a feature (updated)");
|
||||
expect(await complete(client, "document", "uni")).toEqual(["unidentified"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("guided prompt completion lifecycle", () => {
|
||||
it("survives a cancelled completion and ignores its late result", async () => {
|
||||
let calls = 0;
|
||||
let markStarted = (): void => undefined;
|
||||
let release = (): void => undefined;
|
||||
const started = new Promise<void>((resolve) => {
|
||||
markStarted = resolve;
|
||||
});
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const server = new McpServer({
|
||||
name: "prompt-cancellation-test",
|
||||
version: "1",
|
||||
});
|
||||
registerGuidedPrompts(server, {
|
||||
async execute() {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
markStarted();
|
||||
await gate;
|
||||
return observed(["late-document"]);
|
||||
}
|
||||
return observed(["fresh-document"]);
|
||||
},
|
||||
});
|
||||
const client = new Client({ name: "prompt-cancel-client", version: "1" });
|
||||
await connectPair(server, client);
|
||||
const controller = new AbortController();
|
||||
const pending = client.complete(
|
||||
{
|
||||
ref: { type: "ref/prompt", name: "investigate_feature" },
|
||||
argument: { name: "document", value: "" },
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
await started;
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toThrow();
|
||||
release();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(await complete(client, "document", "fresh")).toEqual([
|
||||
"fresh-document",
|
||||
]);
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it("refreshes wire completions across open, switch, concurrency, and close", async () => {
|
||||
const directory = await createTestTempDirectory("rea-prompt-mcp-");
|
||||
temporaryDirectories.push(directory);
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await Promise.all([writeFile(first, "first"), writeFile(second, "second")]);
|
||||
const procedureRequests: Array<Readonly<Record<string, unknown>>> = [];
|
||||
const session = composeBinarySessionFromFactory((target) =>
|
||||
lifecycleClient(basename(target.path, ".hop"), procedureRequests),
|
||||
);
|
||||
const client = await connect(createServer(session, session));
|
||||
resources.push(session);
|
||||
|
||||
expect(await complete(client, "document", "")).toEqual([]);
|
||||
expect(
|
||||
(
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: first },
|
||||
})
|
||||
).isError,
|
||||
).not.toBe(true);
|
||||
expect(await complete(client, "document", "first")).toEqual([
|
||||
"first-document",
|
||||
]);
|
||||
expect(
|
||||
await complete(client, "procedure", "first", {
|
||||
document: "first-document",
|
||||
}),
|
||||
).toEqual(["first-procedure"]);
|
||||
|
||||
const concurrent = await Promise.all(
|
||||
Array.from({ length: 16 }, () => complete(client, "procedure", "0x")),
|
||||
);
|
||||
expect(concurrent.every((values) => values[0] === "0x1000")).toBe(true);
|
||||
expect(
|
||||
(
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: second },
|
||||
})
|
||||
).isError,
|
||||
).not.toBe(true);
|
||||
expect(await complete(client, "document", "first")).toEqual([]);
|
||||
expect(await complete(client, "document", "second")).toEqual([
|
||||
"second-document",
|
||||
]);
|
||||
expect(
|
||||
procedureRequests.some(({ document }) => document === "first-document"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
(await client.callTool({ name: "close_binary", arguments: {} })).isError,
|
||||
).not.toBe(true);
|
||||
expect(await complete(client, "document", "")).toEqual([]);
|
||||
expect(await complete(client, "procedure", "")).toEqual([]);
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
const fixtureProvider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
|
||||
const fixtureSession = (
|
||||
onExecute: () => void = () => undefined,
|
||||
): BinarySession =>
|
||||
composeBinarySessionFromFactory(() => ({
|
||||
execute: () => {
|
||||
onExecute();
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
|
||||
const MINIMUM_PROMPT_ARGUMENTS: Readonly<
|
||||
Record<string, Readonly<Record<string, string>>>
|
||||
> = {
|
||||
investigate_feature: { feature: "offline search" },
|
||||
compare_application_versions: {
|
||||
left_target_path: "/tmp/left.app",
|
||||
right_target_path: "/tmp/right.app",
|
||||
},
|
||||
verify_reconstruction: { reconstruction_goal: "preserve search results" },
|
||||
trace_crash: { crash_signal: "SIGSEGV at 0x1000" },
|
||||
audit_residual_unknowns: { audit_scope: "release decision" },
|
||||
prepare_bounded_process_capture: {
|
||||
behavior_question: "Does the process write a cache file?",
|
||||
executable: "/usr/bin/true",
|
||||
working_directory: "/tmp",
|
||||
},
|
||||
};
|
||||
|
||||
const lifecycleClient = (
|
||||
target: string,
|
||||
requests: Array<Readonly<Record<string, unknown>>>,
|
||||
): AnalysisClient => ({
|
||||
execute(operation, parameters) {
|
||||
if (operation === "list_documents")
|
||||
return Promise.resolve(observed([`${target}-document`]));
|
||||
if (operation === "list_procedures") {
|
||||
requests.push(parameters);
|
||||
return Promise.resolve(
|
||||
observed({
|
||||
items: [
|
||||
{
|
||||
address: target === "first" ? "0x1000" : "0x2000",
|
||||
value: `${target}-procedure`,
|
||||
},
|
||||
],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
|
||||
const complete = async (
|
||||
client: Client,
|
||||
argument: "document" | "procedure",
|
||||
value: string,
|
||||
context?: Readonly<Record<string, string>>,
|
||||
): Promise<string[]> =>
|
||||
(
|
||||
await client.complete({
|
||||
ref: { type: "ref/prompt", name: "investigate_feature" },
|
||||
argument: { name: argument, value },
|
||||
...(context === undefined ? {} : { context: { arguments: context } }),
|
||||
})
|
||||
).completion.values;
|
||||
|
||||
const connect = async (
|
||||
server: Awaited<ReturnType<typeof createServer>>,
|
||||
): Promise<Client> => {
|
||||
const client = new Client({ name: "prompt-test", version: "1" });
|
||||
await connectPair(server, client);
|
||||
return client;
|
||||
};
|
||||
|
||||
const connectPair = async (
|
||||
server: McpServer,
|
||||
client: Client,
|
||||
): Promise<void> => {
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
};
|
||||
@@ -0,0 +1,242 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisProviderCandidate,
|
||||
type CapabilityDescriptor,
|
||||
type ProviderIdentity,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { AnalysisProviderRegistry } from "../../../src/application/AnalysisProviderRegistry.js";
|
||||
import { composeBinarySession } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { SessionProviderRouter } from "../../../src/application/SessionProviderRouter.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
let directory: string | undefined;
|
||||
afterEach(async () => {
|
||||
await Promise.all(resources.splice(0).map((resource) => resource.close()));
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
describe("provider selection over MCP", () => {
|
||||
it("keeps open_binary and binary_session binding semantics exact", async () => {
|
||||
directory = await createTestTempDirectory("rea-provider-mcp-");
|
||||
const target = join(directory, "fixture.hop");
|
||||
await writeFile(target, "fixture");
|
||||
const starts: string[] = [];
|
||||
const session = composeBinarySession(
|
||||
SessionProviderRouter.selectable(
|
||||
new AnalysisProviderRegistry([
|
||||
candidate("beta", starts),
|
||||
candidate("alpha", starts),
|
||||
]),
|
||||
[],
|
||||
),
|
||||
);
|
||||
const server = createServer(session, session, { logger: silentLogger });
|
||||
const mcp = new Client({ name: "provider-selection", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(mcp, server);
|
||||
await server.connect(serverTransport);
|
||||
await mcp.connect(clientTransport);
|
||||
|
||||
const before = structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
}),
|
||||
);
|
||||
expect(before.result).toMatchObject({
|
||||
open: false,
|
||||
analysis_run: null,
|
||||
analysis_provider_binding: null,
|
||||
analysis_provider_candidates: [
|
||||
{
|
||||
provider: { id: "alpha" },
|
||||
target_support: { status: "unknown" },
|
||||
selected: false,
|
||||
},
|
||||
{
|
||||
provider: { id: "beta" },
|
||||
target_support: { status: "unknown" },
|
||||
selected: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(starts).toEqual([]);
|
||||
|
||||
const malformed = await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: target, provider_id: "Beta" },
|
||||
});
|
||||
expect(malformed.isError).toBe(true);
|
||||
expect(starts).toEqual([]);
|
||||
|
||||
const ambiguous = await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: target },
|
||||
});
|
||||
expect(ambiguous.isError).toBe(true);
|
||||
expect(structured(ambiguous)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
selection_reason: "ambiguous",
|
||||
requested_provider_id: "auto",
|
||||
candidate_ids: ["alpha", "beta"],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(starts).toEqual([]);
|
||||
|
||||
const opened = await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: target, provider_id: "beta" },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
expect(starts).toEqual([]);
|
||||
|
||||
const observed = await mcp.callTool({
|
||||
name: "address_name",
|
||||
arguments: {},
|
||||
});
|
||||
expect(observed.isError).not.toBe(true);
|
||||
expect(structured(observed)).toMatchObject({
|
||||
result: "beta:address_name",
|
||||
evidence_id: expect.stringMatching(/^ev_/u),
|
||||
});
|
||||
expect(starts).toEqual(["beta"]);
|
||||
|
||||
const status = structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
}),
|
||||
);
|
||||
expect(status.result).toMatchObject({
|
||||
open: true,
|
||||
analysis_run: {
|
||||
run_id: expect.stringMatching(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
|
||||
),
|
||||
process_lineage: { status: "not_observed" },
|
||||
},
|
||||
analysis_provider_binding: {
|
||||
provider: { id: "beta", version: "1" },
|
||||
selection_source: "request",
|
||||
},
|
||||
analysis_provider_candidates: [
|
||||
{ provider: { id: "alpha" }, selected: false },
|
||||
{ provider: { id: "beta", version: "1" }, selected: true },
|
||||
],
|
||||
});
|
||||
|
||||
const unknown = await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: target, provider_id: "missing" },
|
||||
});
|
||||
expect(unknown.isError).toBe(true);
|
||||
expect(structured(unknown)).toMatchObject({
|
||||
error: { details: { selection_reason: "unknown_provider" } },
|
||||
});
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
}),
|
||||
).result,
|
||||
).toMatchObject({
|
||||
analysis_provider_binding: { provider: { id: "beta" } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const candidate = (id: string, starts: string[]): AnalysisProviderCandidate => {
|
||||
const identity: ProviderIdentity = {
|
||||
id,
|
||||
name: `${id} provider`,
|
||||
version: null,
|
||||
};
|
||||
return {
|
||||
identity: () => identity,
|
||||
capabilities: () => [capability(identity)],
|
||||
inspectAvailability: () => ({
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
|
||||
}),
|
||||
inspectTargetSupport: () => ({
|
||||
status: "supported",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: {},
|
||||
}),
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
profile: createAnalysisProfile(
|
||||
{ id, name: identity.name, version: "1" },
|
||||
1,
|
||||
{ fixture: id },
|
||||
),
|
||||
compatibility: {},
|
||||
}),
|
||||
),
|
||||
createClient: (_target, profile) => {
|
||||
starts.push(id);
|
||||
return {
|
||||
execute: (operation) =>
|
||||
Promise.resolve(
|
||||
ok(
|
||||
createAnalysisExecution(
|
||||
`${id}:${operation}`,
|
||||
profile?.provider ?? identity,
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation: "address_name",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: { maxResults: null, maxPayloadBytes: 1_000, timeoutMs: 1_000 },
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> =>
|
||||
z.record(z.string(), z.unknown()).parse(result.structuredContent);
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import {
|
||||
createReconstructionCoverageWorkspace,
|
||||
createReconstructionVerifierContract,
|
||||
} from "../../../src/domain/reconstructionCoverage.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
const digest = (character: string): string => character.repeat(64);
|
||||
|
||||
describe("reconstruction coverage MCP parity", () => {
|
||||
it("commits and queries the same evidence-backed fail-closed workspace", async () => {
|
||||
const root = await createTestTempDirectory("rea-coverage-mcp-");
|
||||
const path = join(root, "coverage.json");
|
||||
const policy = {
|
||||
roots: [root],
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024 * 1024,
|
||||
maxNodes: 1_000_000,
|
||||
};
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_workspace_read", "investigation_workspace_write"],
|
||||
["investigation_workspace_read", "investigation_workspace_write"],
|
||||
);
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
evidenceFilePolicy: policy,
|
||||
permissionAuthority: authority,
|
||||
});
|
||||
const client = new Client({ name: "coverage-mcp-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const workspace = fixtureWorkspace();
|
||||
const committed = await client.callTool({
|
||||
name: "commit_reconstruction_coverage",
|
||||
arguments: {
|
||||
approved: true,
|
||||
workspace_path: path,
|
||||
expected_revision: null,
|
||||
workspace,
|
||||
},
|
||||
});
|
||||
expect(committed.isError).not.toBe(true);
|
||||
expect(committed.structuredContent).toMatchObject({
|
||||
revision: 1,
|
||||
revision_sha256: workspace.revision_sha256,
|
||||
});
|
||||
const resourceUri = `rea://reconstruction-coverage/${workspace.workspace_id}/revision/1`;
|
||||
expect(committed.content).toContainEqual(
|
||||
expect.objectContaining({ type: "resource_link", uri: resourceUri }),
|
||||
);
|
||||
const resource = await client.readResource({ uri: resourceUri });
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(workspace.revision_sha256),
|
||||
}),
|
||||
);
|
||||
const queried = await client.callTool({
|
||||
name: "query_reconstruction_coverage",
|
||||
arguments: {
|
||||
workspace_path: path,
|
||||
boundary_id: "replacement.cli",
|
||||
},
|
||||
});
|
||||
expect(queried.isError).not.toBe(true);
|
||||
expect(queried.structuredContent).toMatchObject({
|
||||
status: "ready",
|
||||
summary: { reasons: 0 },
|
||||
});
|
||||
const staleVerification = await client.callTool({
|
||||
name: "verify_reconstruction",
|
||||
arguments: {
|
||||
...INVESTIGATION_EXAMPLES.verify_reconstruction,
|
||||
coverage: {
|
||||
workspace_id: workspace.workspace_id,
|
||||
revision: workspace.revision,
|
||||
revision_sha256: digest("9"),
|
||||
boundary_id: "replacement.cli",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(staleVerification.isError).toBe(true);
|
||||
expect(staleVerification.structuredContent).toMatchObject({
|
||||
error: { code: "evidence_integrity_mismatch" },
|
||||
});
|
||||
const unknownBoundary = await client.callTool({
|
||||
name: "verify_reconstruction",
|
||||
arguments: {
|
||||
...INVESTIGATION_EXAMPLES.verify_reconstruction,
|
||||
coverage: {
|
||||
workspace_id: workspace.workspace_id,
|
||||
revision: workspace.revision,
|
||||
revision_sha256: workspace.revision_sha256,
|
||||
boundary_id: "replacement.unknown",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(unknownBoundary.isError).toBe(true);
|
||||
expect(unknownBoundary.structuredContent).toMatchObject({
|
||||
error: { code: "invalid_request" },
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const fixtureWorkspace = () => {
|
||||
const record = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType: "rea.coverage-fixture/v1",
|
||||
operation: "verify-cli",
|
||||
parameters: {},
|
||||
result: { status: "pass" },
|
||||
authority: "controlled-replay",
|
||||
environment: {
|
||||
id: "fixture",
|
||||
platform: "linux",
|
||||
architecture: "x86_64",
|
||||
isolation: "container",
|
||||
},
|
||||
},
|
||||
);
|
||||
const contract = createReconstructionVerifierContract({
|
||||
verifier_id: "verify.cli",
|
||||
claim_ids: ["claim.cli"],
|
||||
dimensions: ["output"],
|
||||
authority: "controlled-replay",
|
||||
max_age_ms: Number.MAX_SAFE_INTEGER,
|
||||
minimum_repeats: 1,
|
||||
normalization_sha256: digest("4"),
|
||||
normalization_removes_dimensions: false,
|
||||
});
|
||||
return createReconstructionCoverageWorkspace({
|
||||
name: "mcp-fixture",
|
||||
revision: 1,
|
||||
previous_revision_sha256: null,
|
||||
evidence_bundle: createEvidenceBundle([record]),
|
||||
artifacts: [
|
||||
{
|
||||
artifact_id: "authority",
|
||||
artifact_sha256: digest("1"),
|
||||
version: "1",
|
||||
environment_sha256: digest("2"),
|
||||
evidence_ids: [record.evidence_id],
|
||||
},
|
||||
],
|
||||
surfaces: [
|
||||
{
|
||||
surface_id: "cli.help",
|
||||
family: "cli-command",
|
||||
artifact_id: "authority",
|
||||
occurrence_id: null,
|
||||
location: "app --help",
|
||||
authority: "observed",
|
||||
dependency_surface_ids: [],
|
||||
evidence_ids: [record.evidence_id],
|
||||
},
|
||||
],
|
||||
owners: [
|
||||
{
|
||||
surface_id: "cli.help",
|
||||
ownership: {
|
||||
disposition: "implemented",
|
||||
owner_path: "src/cli.ts",
|
||||
owner_export: null,
|
||||
owner_sha256: digest("3"),
|
||||
path_state: "present",
|
||||
package_state: "distributed",
|
||||
authority_route: "none",
|
||||
},
|
||||
},
|
||||
],
|
||||
claims: [
|
||||
{
|
||||
claim_id: "claim.cli",
|
||||
title: "CLI help matches",
|
||||
kind: "behavioral",
|
||||
surface_ids: ["cli.help"],
|
||||
required_dimensions: ["output"],
|
||||
required_authority: "controlled-replay",
|
||||
},
|
||||
],
|
||||
verifier_contracts: [contract],
|
||||
verifier_results: [
|
||||
{
|
||||
verifier_id: contract.verifier_id,
|
||||
contract_sha256: contract.contract_sha256,
|
||||
observed_at: "2026-07-16T00:00:00.000Z",
|
||||
status: "pass",
|
||||
covered_claim_ids: ["claim.cli"],
|
||||
covered_dimensions: ["output"],
|
||||
artifact_sha256s: [digest("1")],
|
||||
owner_sha256s: [digest("3")],
|
||||
normalization_sha256: digest("4"),
|
||||
repeats: 1,
|
||||
evidence_ids: [record.evidence_id],
|
||||
},
|
||||
],
|
||||
residual_unknown_ids: [],
|
||||
contradictions: [],
|
||||
package_proofs: [
|
||||
{
|
||||
proof_id: "proof.install",
|
||||
kind: "clean-install",
|
||||
status: "pass",
|
||||
artifact_sha256s: [digest("1")],
|
||||
evidence_ids: [record.evidence_id],
|
||||
},
|
||||
],
|
||||
boundaries: [
|
||||
{
|
||||
boundary_id: "replacement.cli",
|
||||
title: "CLI replacement",
|
||||
required_surface_ids: ["cli.help"],
|
||||
required_claim_ids: ["claim.cli"],
|
||||
required_package_proof_kinds: ["clean-install"],
|
||||
allowed_dispositions: [],
|
||||
allowed_unknown_ids: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
describe("reconstruction obligation ledger MCP parity", () => {
|
||||
it("builds an Evidence-backed page and exposes the retained resource", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "obligation-ledger-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "build_reconstruction_obligation_ledger",
|
||||
arguments: {
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
reviewed_obligations: [],
|
||||
manifest: {
|
||||
schema_version: 1,
|
||||
bindings: [],
|
||||
contradictions: [],
|
||||
},
|
||||
limits: { max_obligations: 100 },
|
||||
page: { offset: 0, limit: 50 },
|
||||
},
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
evidence_uri: expect.stringMatching(
|
||||
/^rea:\/\/evidence\/ev_[a-f0-9]{64}$/u,
|
||||
),
|
||||
result: {
|
||||
schema: "ReconstructionObligationLedger",
|
||||
status: "unknown",
|
||||
summary: { total: 0 },
|
||||
},
|
||||
});
|
||||
const evidence = result.structuredContent;
|
||||
if (
|
||||
evidence === undefined ||
|
||||
evidence === null ||
|
||||
typeof evidence !== "object" ||
|
||||
!("evidence_id" in evidence) ||
|
||||
typeof evidence.evidence_id !== "string"
|
||||
)
|
||||
throw new TypeError("Missing obligation ledger Evidence ID");
|
||||
const resource = await client.readResource({
|
||||
uri: `rea://evidence/${evidence.evidence_id}/reconstruction-obligation-ledger`,
|
||||
});
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(
|
||||
'"schema": "ReconstructionObligationLedger"',
|
||||
),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { RECONSTRUCTION_READINESS_EXAMPLE } from "../../../src/contracts/reconstructionReadinessExample.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
describe("reconstruction readiness MCP parity", () => {
|
||||
it("returns a passing compact result and retains the full report resource", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "readiness-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "evaluate_reconstruction_readiness",
|
||||
arguments: RECONSTRUCTION_READINESS_EXAMPLE,
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
result: {
|
||||
schema: "ReconstructionReadinessReport",
|
||||
status: "pass",
|
||||
summary: { passed_required_stages: 9 },
|
||||
report_resource_uri: expect.stringMatching(
|
||||
/^rea:\/\/evidence\/ev_[a-f0-9]{64}\/reconstruction-readiness-report$/u,
|
||||
),
|
||||
},
|
||||
});
|
||||
expect(result.structuredContent).not.toHaveProperty("result.snapshot");
|
||||
expect(result.structuredContent).not.toHaveProperty("result.stages");
|
||||
const content = result.structuredContent;
|
||||
if (
|
||||
content === undefined ||
|
||||
content === null ||
|
||||
typeof content !== "object" ||
|
||||
!("evidence_id" in content) ||
|
||||
typeof content.evidence_id !== "string"
|
||||
)
|
||||
throw new TypeError("Missing readiness Evidence ID");
|
||||
const resource = await client.readResource({
|
||||
uri: `rea://evidence/${content.evidence_id}/reconstruction-readiness-report`,
|
||||
});
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(
|
||||
'"schema": "ReconstructionReadinessReport"',
|
||||
),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { REPLAY_MACHINE_RUN_EXAMPLE } from "../../../src/contracts/replayMachineExample.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
describe("direct replay machine MCP parity", () => {
|
||||
it("returns typed journal output and safe validation failures", async () => {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "replay-machine-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const example = REPLAY_MACHINE_RUN_EXAMPLE;
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "run_replay_machine",
|
||||
arguments: example,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
structuredContent: {
|
||||
result: {
|
||||
schema_version: 1,
|
||||
final_state: "complete",
|
||||
terminal: true,
|
||||
decisions: [{ outcome: "matched", transition_sequence: 0 }],
|
||||
transition_journal: [
|
||||
{
|
||||
transition_id: "accept_callback",
|
||||
captured_aliases: [{ name: "token", sensitive: true }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("opaque");
|
||||
|
||||
const invalid = await client.callTool({
|
||||
name: "run_replay_machine",
|
||||
arguments: {
|
||||
...example,
|
||||
events: [
|
||||
{
|
||||
protocol: "http",
|
||||
connection: "not_applicable",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/callback",
|
||||
headers: {},
|
||||
body: "private-request-body",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(invalid).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { code: "invalid_request" } },
|
||||
});
|
||||
expect(JSON.stringify(invalid)).not.toContain("private-request-body");
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,386 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromProvider } from "../../../src/application/BinarySessionComposition.js";
|
||||
import {
|
||||
CATALOG_IDENTITY,
|
||||
CLI_COMMAND_NAMES,
|
||||
} from "../../../src/catalogIdentity.js";
|
||||
import { PACKAGE_METADATA } from "../../../src/generatedPackageMetadata.js";
|
||||
import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../../../src/identity.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { TOOL_KINDS } from "../../../src/contracts/toolContractTypes.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createServerIdentity } from "../../../src/serverIdentity.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { buildCapabilityInventory } from "../../../src/application/CapabilityInventory.js";
|
||||
import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
|
||||
const availabilityProvider = (): AnalysisProvider => {
|
||||
const identity = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const capability: CapabilityDescriptor = {
|
||||
provider: identity,
|
||||
operation: "current_address",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
};
|
||||
return {
|
||||
identity: () => identity,
|
||||
capabilities: () => [capability],
|
||||
createClient: () => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
describe("server and catalog identity", () => {
|
||||
it("derives package and SDK versions from canonical package metadata", async () => {
|
||||
const packageJson = JSON.parse(await readFile("package.json", "utf8"));
|
||||
const packageLock = JSON.parse(await readFile("package-lock.json", "utf8"));
|
||||
expect(PACKAGE_METADATA).toMatchObject({
|
||||
name: packageJson.name,
|
||||
version: packageJson.version,
|
||||
serverSdkVersion:
|
||||
packageJson.dependencies["@modelcontextprotocol/server"],
|
||||
clientSdkVersion:
|
||||
packageJson.dependencies["@modelcontextprotocol/client"],
|
||||
coreSdkVersion:
|
||||
packageLock.packages["node_modules/@modelcontextprotocol/core"].version,
|
||||
});
|
||||
expect(PRODUCT_IDENTITY.packageVersion).toBe(packageJson.version);
|
||||
expect(SDK_IDENTITY.server).toBe(
|
||||
packageJson.dependencies["@modelcontextprotocol/server"],
|
||||
);
|
||||
expect(CLI_COMMAND_NAMES).toHaveLength(67);
|
||||
expect(new Set(CLI_COMMAND_NAMES).size).toBe(67);
|
||||
expect(CATALOG_IDENTITY.counts).toEqual({
|
||||
cli_commands: 67,
|
||||
mcp_tools: TOOL_CONTRACTS.length,
|
||||
mcp_prompts: 6,
|
||||
mcp_resources: 2,
|
||||
mcp_resource_templates: 11,
|
||||
});
|
||||
expect(CATALOG_IDENTITY.digests.combined_sha256).toMatch(/^[a-f0-9]{64}$/u);
|
||||
});
|
||||
|
||||
it("reports unknown without a live comparison and distinguishes aligned from stale", () => {
|
||||
const unknown = createServerIdentity({
|
||||
startedAt: "2026-07-13T00:00:00.000Z",
|
||||
});
|
||||
expect(unknown.alignment.state).toBe("unknown");
|
||||
const aligned = createServerIdentity({
|
||||
startedAt: "2026-07-13T00:00:00.000Z",
|
||||
expected: {
|
||||
package_version: PRODUCT_IDENTITY.packageVersion,
|
||||
catalog_digest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
server_path: process.argv[1] ?? "unknown",
|
||||
},
|
||||
});
|
||||
expect(aligned.alignment).toMatchObject({ state: "aligned", reasons: [] });
|
||||
const stale = createServerIdentity({
|
||||
startedAt: "2026-07-13T00:00:00.000Z",
|
||||
expected: {
|
||||
package_version: "1.2.0",
|
||||
catalog_digest: "0".repeat(64),
|
||||
},
|
||||
});
|
||||
expect(stale.alignment).toMatchObject({
|
||||
state: "mcp_server_restart_required",
|
||||
reasons: ["package_version_mismatch", "catalog_digest_mismatch"],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports composed, host, and target-specific availability truthfully", () => {
|
||||
const policy = {
|
||||
processCaptureEnabled: true,
|
||||
evidenceFileRoots: 1,
|
||||
investigationInputRoots: 1,
|
||||
};
|
||||
const composed = buildCapabilityInventory(
|
||||
{
|
||||
open: true,
|
||||
kind: "executable",
|
||||
format: "mach-o",
|
||||
capabilities: [
|
||||
"list_segments",
|
||||
"list_documents",
|
||||
"list_procedures",
|
||||
"list_strings",
|
||||
].map((operation) => ({ operation, available: true, reason: null })),
|
||||
},
|
||||
policy,
|
||||
);
|
||||
expect(composed).toContainEqual(
|
||||
expect.objectContaining({ name: "binary_overview", available: true }),
|
||||
);
|
||||
const artifactTarget = buildCapabilityInventory(
|
||||
{
|
||||
open: true,
|
||||
kind: "artifact",
|
||||
format: "javascript",
|
||||
capabilities: [
|
||||
{ operation: "current_address", available: true, reason: null },
|
||||
],
|
||||
},
|
||||
policy,
|
||||
);
|
||||
expect(artifactTarget).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "current_address",
|
||||
available: false,
|
||||
reason: "target_unsupported",
|
||||
}),
|
||||
);
|
||||
const unsupportedHost = buildCapabilityInventory(
|
||||
{
|
||||
open: true,
|
||||
kind: "executable",
|
||||
format: "elf",
|
||||
capabilities: [
|
||||
{
|
||||
operation: "inspect_macho",
|
||||
available: false,
|
||||
availability_code: "unsupported_host",
|
||||
reason: "Native macOS utilities require macOS.",
|
||||
},
|
||||
],
|
||||
},
|
||||
policy,
|
||||
);
|
||||
expect(unsupportedHost).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "inspect_macho",
|
||||
available: false,
|
||||
reason: "unsupported_host",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("live server identity over MCP", () => {
|
||||
it("exposes live identity, labeled inventories, availability, and list changes", async () => {
|
||||
const session = composeBinarySessionFromProvider(availabilityProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client(
|
||||
{ name: "identity-test", version: "9" },
|
||||
{
|
||||
capabilities: {
|
||||
elicitation: { form: {} },
|
||||
},
|
||||
},
|
||||
);
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
let toolListChanges = 0;
|
||||
client.setNotificationHandler("notifications/tools/list_changed", () => {
|
||||
toolListChanges += 1;
|
||||
});
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await assertLiveIdentity(client);
|
||||
await assertSessionIdentity(client);
|
||||
await assertCapabilityViews(client);
|
||||
expect(
|
||||
(await client.listTools()).tools.map(({ name }) => name),
|
||||
).not.toContain("current_address");
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath },
|
||||
});
|
||||
await expect.poll(() => toolListChanges).toBeGreaterThan(0);
|
||||
expect(
|
||||
(await client.listTools()).tools.map(({ name }) => name),
|
||||
).toContain("current_address");
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
const assertLiveIdentity = async (client: Client): Promise<void> => {
|
||||
const instructions = client.getInstructions();
|
||||
expect(instructions?.length).toBeLessThanOrEqual(640);
|
||||
expect(instructions).toContain(
|
||||
"ASAR/JavaScript -> analyze_javascript_application",
|
||||
);
|
||||
expect(instructions).toContain(
|
||||
"native binary/database -> open_binary, then binary_overview",
|
||||
);
|
||||
expect(instructions).toContain("Never repeat identical analysis");
|
||||
expect(instructions).toContain("cite Evidence IDs");
|
||||
const resource = await client.readResource({ uri: "rea://server/identity" });
|
||||
const content = resource.contents[0];
|
||||
expect(content).toBeDefined();
|
||||
if (content === undefined || !("text" in content))
|
||||
throw new Error("missing identity resource text");
|
||||
expect(JSON.parse(content.text)).toMatchObject({
|
||||
package: { version: PRODUCT_IDENTITY.packageVersion },
|
||||
server: { version: PRODUCT_IDENTITY.packageVersion },
|
||||
sdk: {
|
||||
server: SDK_IDENTITY.server,
|
||||
client_test: PACKAGE_METADATA.clientSdkVersion,
|
||||
},
|
||||
client: { name: "identity-test", version: "9" },
|
||||
alignment: { state: "unknown" },
|
||||
});
|
||||
};
|
||||
|
||||
const assertSessionIdentity = async (client: Client): Promise<void> => {
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full", expected_package_version: "1.2.0" },
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
server_identity: {
|
||||
catalog: {
|
||||
counts: {
|
||||
mcp_tools: TOOL_CONTRACTS.length,
|
||||
cli_commands: CLI_COMMAND_NAMES.length,
|
||||
},
|
||||
},
|
||||
alignment: { state: "mcp_server_restart_required" },
|
||||
},
|
||||
tool_availability: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "current_address",
|
||||
available: false,
|
||||
reason: "target_required",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "capture_process_scenario",
|
||||
available: false,
|
||||
reason: "policy_disabled",
|
||||
client_requirements: {
|
||||
required: [],
|
||||
optional: ["elicitation_form"],
|
||||
missing_required: [],
|
||||
missing_optional: [],
|
||||
},
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "inspect_web_page",
|
||||
available: false,
|
||||
reason: "policy_disabled",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "analyze_javascript_application",
|
||||
available: false,
|
||||
reason: "policy_disabled",
|
||||
remediation: expect.stringContaining(
|
||||
"REA_INVESTIGATION_INPUT_ROOTS_JSON",
|
||||
),
|
||||
}),
|
||||
]),
|
||||
client_features: {
|
||||
elicitation_form: true,
|
||||
elicitation_url: false,
|
||||
roots: false,
|
||||
sampling: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
const summary = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { expected_package_version: "1.2.0" },
|
||||
});
|
||||
expect(summary.structuredContent).toMatchObject({
|
||||
result: {
|
||||
view: "summary",
|
||||
open: false,
|
||||
target: null,
|
||||
alignment: { state: "mcp_server_restart_required" },
|
||||
recommended_actions: expect.arrayContaining([
|
||||
"For a supplied target, route by format: ASAR/JavaScript to analyze_javascript_application; archive/package to open_binary(path), then inspect_artifact or inventory_artifact on the active target; managed PE/CLI to inspect_managed_artifact; browser/Electron runtimes to their list-target tools; native binaries to open_binary.",
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(summary.structuredContent)).not.toContain(
|
||||
"tool_availability",
|
||||
);
|
||||
};
|
||||
|
||||
const assertCapabilityViews = async (client: Client): Promise<void> => {
|
||||
const capabilities = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {
|
||||
detail: "capabilities",
|
||||
capability_family: "browser-provider",
|
||||
cursor: 0,
|
||||
limit: 1,
|
||||
},
|
||||
});
|
||||
expect(capabilities.structuredContent).toMatchObject({
|
||||
result: {
|
||||
view: "capabilities",
|
||||
capability_family: "browser-provider",
|
||||
capabilities: {
|
||||
items: [expect.objectContaining({ surface: "browser-provider" })],
|
||||
cursor: 0,
|
||||
limit: 1,
|
||||
total: expect.any(Number),
|
||||
next_cursor: expect.any(Number),
|
||||
has_more: true,
|
||||
},
|
||||
client_features: {
|
||||
elicitation_form: true,
|
||||
elicitation_url: false,
|
||||
roots: false,
|
||||
sampling: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
for (const capabilityFamily of TOOL_KINDS) {
|
||||
const familyCapabilities = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {
|
||||
detail: "capabilities",
|
||||
capability_family: capabilityFamily,
|
||||
limit: 100,
|
||||
},
|
||||
});
|
||||
expect(familyCapabilities.structuredContent).toMatchObject({
|
||||
result: {
|
||||
view: "capabilities",
|
||||
capability_family: capabilityFamily,
|
||||
capabilities: {
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ surface: capabilityFamily }),
|
||||
]),
|
||||
total: expect.any(Number),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { HopperRemoteError } from "../../../src/domain/errors.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
SESSION_TOOL_CONTRACTS,
|
||||
TOOL_CONTRACTS,
|
||||
} from "../../../src/contracts/toolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managedWorkflowToolContracts.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({
|
||||
name: "integration-test",
|
||||
version: "1.0.0",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
const text = (result: CallToolResult): string => {
|
||||
const content = result.content.find((item) => item.type === "text");
|
||||
if (content?.type !== "text") throw new Error("missing text result");
|
||||
return content.text;
|
||||
};
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
if (
|
||||
typeof result.structuredContent !== "object" ||
|
||||
result.structuredContent === null
|
||||
)
|
||||
throw new Error("missing structured result");
|
||||
return Object.fromEntries(Object.entries(result.structuredContent));
|
||||
};
|
||||
|
||||
it("preserves the target-open tool inventory without a session", async () => {
|
||||
const client = await connect({
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
});
|
||||
const listed = await client.listTools();
|
||||
expect(listed.tools).toHaveLength(
|
||||
TOOL_CONTRACTS.length -
|
||||
SESSION_TOOL_CONTRACTS.length -
|
||||
MANAGED_WORKFLOW_TOOL_CONTRACTS.length,
|
||||
);
|
||||
const names = listed.tools.map((t) => t.name);
|
||||
expect(names).toContain("binary_overview");
|
||||
expect(names).toContain("batch_decompile");
|
||||
expect(names).not.toContain("open_binary");
|
||||
});
|
||||
|
||||
it("projects remote failures without provider or bridge details", async () => {
|
||||
const client = await connect({
|
||||
execute: () =>
|
||||
Promise.resolve(err(new HopperRemoteError(-32000, "bridge timeout"))),
|
||||
});
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "list_documents",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(structured(result)).toMatchObject({
|
||||
error: {
|
||||
category: "execution_failure",
|
||||
},
|
||||
});
|
||||
expect(text(result)).toBe(JSON.stringify(result.structuredContent));
|
||||
});
|
||||
|
||||
it("handles concurrent tool calls without corruption", async () => {
|
||||
const invocations: string[] = [];
|
||||
const client = await connect({
|
||||
execute: (name) => {
|
||||
invocations.push(name);
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
["list_procedures", "list_strings"].includes(name)
|
||||
? {
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 0,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}
|
||||
: [],
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const results = await Promise.all([
|
||||
client.callTool({ name: "list_procedures", arguments: {} }),
|
||||
client.callTool({ name: "list_segments", arguments: {} }),
|
||||
client.callTool({ name: "list_strings", arguments: {} }),
|
||||
]);
|
||||
|
||||
expect(results.every((r) => !r.isError)).toBe(true);
|
||||
expect(invocations).toHaveLength(3);
|
||||
expect(new Set(invocations).size).toBe(3);
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
composeBinarySessionFromFactory,
|
||||
composeBinarySessionFromProvider,
|
||||
} from "../../../src/application/BinarySessionComposition.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisOperationPort,
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/errors.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/server/sessionToolPolicies.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const providerWithCapabilities = (
|
||||
operations: readonly CapabilityDescriptor["operation"][],
|
||||
): AnalysisProvider => {
|
||||
const identity = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const capabilities: readonly CapabilityDescriptor[] = operations.map(
|
||||
(operation) => ({
|
||||
provider: identity,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
}),
|
||||
);
|
||||
return {
|
||||
identity: () => identity,
|
||||
capabilities: () => capabilities,
|
||||
createClient: () => ({
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
if (
|
||||
typeof result.structuredContent !== "object" ||
|
||||
result.structuredContent === null
|
||||
)
|
||||
throw new Error("missing structured result");
|
||||
return Object.fromEntries(Object.entries(result.structuredContent));
|
||||
};
|
||||
|
||||
it("records approved trace truncation as a deduplicated residual unknown", async () => {
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 0,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
),
|
||||
};
|
||||
const session = composeBinarySessionFromProvider(
|
||||
providerWithCapabilities([
|
||||
"list_strings",
|
||||
"list_procedures",
|
||||
"xrefs",
|
||||
"resolve_containing_procedure",
|
||||
]),
|
||||
);
|
||||
const server = createServer(analysis, session);
|
||||
const client = new Client({ name: "unknown-workflow", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath },
|
||||
});
|
||||
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const traced = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: {
|
||||
query: "license",
|
||||
max_operations: 1,
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(traced.isError).not.toBe(true);
|
||||
}
|
||||
const listed = structured(
|
||||
await client.callTool({ name: "list_unknowns", arguments: {} }),
|
||||
);
|
||||
expect(listed).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
unknown: {
|
||||
status: "open",
|
||||
domain: "control-flow",
|
||||
question: "Investigation reached the operation budget.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}, 10_000);
|
||||
|
||||
it("records approved typed capability unavailability without forwarding the flag", async () => {
|
||||
const received: Array<Readonly<Record<string, unknown>>> = [];
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: (name, arguments_) => {
|
||||
received.push(arguments_);
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"partial",
|
||||
name,
|
||||
"Decompiler is not installed.",
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
const session = composeBinarySessionFromProvider(
|
||||
providerWithCapabilities(["procedure_pseudo_code"]),
|
||||
);
|
||||
const server = createServer(analysis, session);
|
||||
const client = new Client({ name: "unavailable-unknown", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath },
|
||||
});
|
||||
|
||||
const unavailable = await client.callTool({
|
||||
name: "procedure_pseudo_code",
|
||||
arguments: {
|
||||
procedure: "main",
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(unavailable.isError).toBe(true);
|
||||
expect(structured(unavailable)).toMatchObject({
|
||||
error: {
|
||||
category: "unsupported_provider",
|
||||
},
|
||||
});
|
||||
expect(received[0]).not.toHaveProperty("unknown_registry_approved");
|
||||
expect(
|
||||
structured(await client.callTool({ name: "list_unknowns", arguments: {} })),
|
||||
).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
unknown: {
|
||||
domain: "analysis-capability",
|
||||
question:
|
||||
"The requested analysis is unavailable for the current target.",
|
||||
recommended_probes: [
|
||||
{
|
||||
rationale:
|
||||
"Choose another analysis or target that can answer this question.",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("records approved capture disagreement as a contradicted unknown", async () => {
|
||||
const session = composeBinarySessionFromFactory(
|
||||
() =>
|
||||
({
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}) satisfies AnalysisClient,
|
||||
);
|
||||
const left = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const right = processCaptureSchema.parse({
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
interaction_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
scheduled_at_ms: 0,
|
||||
dispatched_at_ms: 0,
|
||||
type: "input",
|
||||
data: "fixture",
|
||||
outcome: "dispatched",
|
||||
},
|
||||
],
|
||||
shim_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
command: "fixture",
|
||||
route_index: null,
|
||||
arguments: [],
|
||||
working_directory: "/tmp",
|
||||
outcome: "unmatched",
|
||||
},
|
||||
],
|
||||
});
|
||||
const captureEvidence = (capture: typeof left) =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture/v4",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(capture),
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
});
|
||||
const leftEvidence = captureEvidence(left);
|
||||
const rightEvidence = captureEvidence(right);
|
||||
expect(session.recordEvidence(leftEvidence).ok).toBe(true);
|
||||
expect(session.recordEvidence(rightEvidence).ok).toBe(true);
|
||||
const server = createServer(
|
||||
{ execute: () => Promise.resolve(ok(null)) },
|
||||
session,
|
||||
);
|
||||
const client = new Client({ name: "comparison-unknown", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const mismatched = await client.callTool({
|
||||
name: "compare_process_captures",
|
||||
arguments: {
|
||||
left_evidence_id: leftEvidence.evidence_id,
|
||||
left: right,
|
||||
right_evidence_id: rightEvidence.evidence_id,
|
||||
right,
|
||||
},
|
||||
});
|
||||
expect(mismatched.isError).toBe(true);
|
||||
|
||||
const compared = await client.callTool({
|
||||
name: "compare_process_captures",
|
||||
arguments: {
|
||||
left_evidence_id: leftEvidence.evidence_id,
|
||||
right_evidence_id: rightEvidence.evidence_id,
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(compared.isError).not.toBe(true);
|
||||
expect(
|
||||
structured(await client.callTool({ name: "list_unknowns", arguments: {} })),
|
||||
).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
unknown: {
|
||||
status: "contradicted",
|
||||
domain: "process-comparison",
|
||||
question: "Process captures disagree across: interaction, shim",
|
||||
contradicting_evidence_ids: [rightEvidence.evidence_id],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisOperationPort,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
const connect = async (analysis: AnalysisOperationPort) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({
|
||||
name: "integration-test",
|
||||
version: "1.0.0",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
if (
|
||||
typeof result.structuredContent !== "object" ||
|
||||
result.structuredContent === null
|
||||
)
|
||||
throw new Error("missing structured result");
|
||||
return Object.fromEntries(Object.entries(result.structuredContent));
|
||||
};
|
||||
|
||||
const objectEntries = (value: unknown): readonly [string, unknown][] =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? Object.entries(value)
|
||||
: [];
|
||||
|
||||
const referencedSchema = (schema: unknown, root: unknown): unknown => {
|
||||
const object = Object.fromEntries(objectEntries(schema));
|
||||
const reference = object.$ref;
|
||||
if (typeof reference !== "string" || !reference.startsWith("#/$defs/"))
|
||||
return schema;
|
||||
return Object.fromEntries(objectEntries(root)).$defs instanceof Object
|
||||
? Object.fromEntries(
|
||||
objectEntries(Object.fromEntries(objectEntries(root)).$defs),
|
||||
)[reference.slice(8)]
|
||||
: schema;
|
||||
};
|
||||
|
||||
const assertDescribedStrictObjects = (
|
||||
schema: unknown,
|
||||
root = schema,
|
||||
path = "$",
|
||||
): void => {
|
||||
for (const [key, value] of objectEntries(schema)) {
|
||||
if (key === "examples") continue;
|
||||
if (key === "properties") {
|
||||
const properties = objectEntries(value);
|
||||
for (const [property, propertySchema] of properties) {
|
||||
const resolved = referencedSchema(propertySchema, root);
|
||||
const propertyObject = Object.fromEntries(
|
||||
objectEntries(propertySchema),
|
||||
);
|
||||
expect(
|
||||
propertyObject.description ??
|
||||
Object.fromEntries(objectEntries(resolved)).description,
|
||||
`${path}.properties.${property}`,
|
||||
).toEqual(expect.any(String));
|
||||
assertDescribedStrictObjects(
|
||||
propertySchema,
|
||||
root,
|
||||
`${path}.properties.${property}`,
|
||||
);
|
||||
}
|
||||
expect(
|
||||
Object.fromEntries(objectEntries(schema)).additionalProperties,
|
||||
).toBe(false);
|
||||
continue;
|
||||
}
|
||||
assertDescribedStrictObjects(value, root, `${path}.${key}`);
|
||||
}
|
||||
if (Array.isArray(schema))
|
||||
for (const [index, value] of schema.entries())
|
||||
assertDescribedStrictObjects(value, root, `${path}[${String(index)}]`);
|
||||
};
|
||||
|
||||
const assertDescribedRootObject = (schema: unknown, path: string): void => {
|
||||
const object = Object.fromEntries(objectEntries(schema));
|
||||
expect(object.additionalProperties, path).toBe(false);
|
||||
for (const [property, propertySchema] of objectEntries(object.properties))
|
||||
expect(
|
||||
Object.fromEntries(objectEntries(propertySchema)).description,
|
||||
`${path}.properties.${property}`,
|
||||
).toEqual(expect.any(String));
|
||||
};
|
||||
|
||||
it("executes a realistic workflow: list methods, decompile selected, get xrefs", async () => {
|
||||
const client = await connect({
|
||||
execute: (name, args) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{ address: "0x1000", value: "main" },
|
||||
{ address: "0x2000", value: "helper" },
|
||||
],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 2,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
);
|
||||
case "procedure_pseudo_code":
|
||||
return Promise.resolve(
|
||||
ok(`pseudo for ${(args as { procedure: string }).procedure}`),
|
||||
);
|
||||
case "xrefs":
|
||||
return Promise.resolve(ok(["0x1000"]));
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const listResult = await client.callTool({
|
||||
name: "list_procedures",
|
||||
arguments: {},
|
||||
});
|
||||
expect(listResult.isError).not.toBe(true);
|
||||
expect(structured(listResult)).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
{ address: "0x1000", value: "main" },
|
||||
{ address: "0x2000", value: "helper" },
|
||||
],
|
||||
total: 2,
|
||||
has_more: false,
|
||||
},
|
||||
});
|
||||
|
||||
const decompileResult = await client.callTool({
|
||||
name: "procedure_pseudo_code",
|
||||
arguments: { procedure: "0x1000" },
|
||||
});
|
||||
expect(structured(decompileResult)).toMatchObject({
|
||||
result: "pseudo for 0x1000",
|
||||
});
|
||||
|
||||
const xrefResult = await client.callTool({
|
||||
name: "xrefs",
|
||||
arguments: {},
|
||||
});
|
||||
expect(structured(xrefResult)).toMatchObject({
|
||||
result: ["0x1000"],
|
||||
});
|
||||
});
|
||||
|
||||
it("advertises the complete currently available inventory with a session", async () => {
|
||||
const session = composeBinarySessionFromFactory(
|
||||
(_path) =>
|
||||
({
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}) satisfies AnalysisClient,
|
||||
);
|
||||
const server = createServer(
|
||||
{ execute: () => Promise.resolve(ok(null)) },
|
||||
session,
|
||||
);
|
||||
const client = new Client({
|
||||
name: "integration-test",
|
||||
version: "1.0.0",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const listed = await client.listTools();
|
||||
const names = listed.tools.map((t) => t.name);
|
||||
expect(names).toContain("open_binary");
|
||||
expect(names).toContain("close_binary");
|
||||
expect(names).toContain("binary_session");
|
||||
expect(names).not.toContain("binary_overview");
|
||||
expect(names).not.toContain("batch_decompile");
|
||||
const status = structured(
|
||||
await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
}),
|
||||
);
|
||||
const available = new Set(
|
||||
z
|
||||
.object({
|
||||
result: z.object({
|
||||
tool_availability: z.array(
|
||||
z.object({ name: z.string(), available: z.boolean() }),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.parse(status)
|
||||
.result.tool_availability.filter((item) => item.available)
|
||||
.map(({ name }) => name),
|
||||
);
|
||||
expect(new Set(names)).toEqual(available);
|
||||
|
||||
const contracts = new Map<string, (typeof TOOL_CONTRACTS)[number]>(
|
||||
TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
|
||||
);
|
||||
for (const tool of listed.tools) {
|
||||
const contract = contracts.get(tool.name);
|
||||
expect(contract, tool.name).toBeDefined();
|
||||
expect(tool.title, tool.name).toBe(contract?.title);
|
||||
expect(tool.description, tool.name).toBe(contract?.description);
|
||||
expect(tool.annotations, tool.name).toEqual(contract?.annotations);
|
||||
expect(tool.outputSchema, tool.name).toBeDefined();
|
||||
assertDescribedStrictObjects(tool.inputSchema, tool.inputSchema, tool.name);
|
||||
assertDescribedRootObject(tool.outputSchema, `${tool.name}.output`);
|
||||
}
|
||||
}, 10_000);
|
||||
@@ -0,0 +1,351 @@
|
||||
import { readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
composeBinarySessionFromFactory,
|
||||
composeBinarySessionFromProvider,
|
||||
} from "../../../src/application/BinarySessionComposition.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { probeProcessCaptureCapability } from "../../../src/application/ProcessHarness.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { ok as resultOk } from "../../../src/domain/result.js";
|
||||
import {
|
||||
createSessionMcpHarness,
|
||||
snapshotAndRecordUnknown,
|
||||
} from "./sessionMcpHarness.js";
|
||||
|
||||
const SNAPSHOT_PROFILE = createAnalysisProfile(
|
||||
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
|
||||
1,
|
||||
{ fixture: true },
|
||||
);
|
||||
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
const processFixture = fileURLToPath(
|
||||
new URL("../../fixtures/processFidelity.mjs", import.meta.url),
|
||||
);
|
||||
let directory: string | undefined;
|
||||
afterEach(async () => {
|
||||
await Promise.all(resources.splice(0).map((resource) => resource.close()));
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
describe("target-free MCP lifecycle", () => {
|
||||
it("reopens replaced content at one canonical path through MCP", async () => {
|
||||
directory = await createTestTempDirectory("rea-mcp-replaced-target-");
|
||||
const targetPath = join(directory, "mutable.hop");
|
||||
await writeFile(targetPath, "first");
|
||||
const closed: string[] = [];
|
||||
const session = composeBinarySessionFromProvider(provider(closed), {
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({ profile: SNAPSHOT_PROFILE, compatibility: {} }),
|
||||
),
|
||||
});
|
||||
const server = createServer(session, session, { logger: silentLogger });
|
||||
const mcp = new Client({ name: "replaced-target", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(mcp, server);
|
||||
await server.connect(serverTransport);
|
||||
await mcp.connect(clientTransport);
|
||||
|
||||
const first = structured(
|
||||
await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: targetPath },
|
||||
}),
|
||||
).result;
|
||||
await writeFile(targetPath, "second");
|
||||
const second = structured(
|
||||
await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: targetPath },
|
||||
}),
|
||||
).result;
|
||||
|
||||
const canonicalTargetPath = await realpath(targetPath);
|
||||
expect(first).toMatchObject({ path: canonicalTargetPath });
|
||||
expect(second).toMatchObject({ path: canonicalTargetPath });
|
||||
expect(z.object({ sha256: z.string() }).parse(second).sha256).not.toBe(
|
||||
z.object({ sha256: z.string() }).parse(first).sha256,
|
||||
);
|
||||
expect(closed).toEqual([canonicalTargetPath]);
|
||||
expect(
|
||||
z
|
||||
.object({
|
||||
result: z.object({ path: z.string(), sha256: z.string() }),
|
||||
})
|
||||
.parse(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
}),
|
||||
),
|
||||
).result,
|
||||
).toEqual({
|
||||
path: canonicalTargetPath,
|
||||
sha256: z.object({ sha256: z.string() }).parse(second).sha256,
|
||||
});
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
describe("target-free MCP workflow", () => {
|
||||
it("reports no-target, opens, analyzes, switches, reports status, and closes", async () => {
|
||||
directory = await createTestTempDirectory("rea-mcp-session-");
|
||||
const lifecycle = await createSessionMcpHarness(
|
||||
directory,
|
||||
provider,
|
||||
resources,
|
||||
);
|
||||
const { mcp, first, second, closed } = lifecycle;
|
||||
|
||||
const beforeTools = (await mcp.listTools()).tools;
|
||||
const beforeNames = beforeTools.map(({ name }) => name);
|
||||
expect(mcp.getInstructions()).toContain(
|
||||
"archive/package -> open_binary(path), then inspect_artifact/inventory_artifact (active target)",
|
||||
);
|
||||
expect(
|
||||
beforeTools.find(({ name }) => name === "inventory_artifact")
|
||||
?.description,
|
||||
).toContain(
|
||||
"This tool accepts no path; in a target-free session open the target first.",
|
||||
);
|
||||
expect(beforeNames).toContain("open_binary");
|
||||
expect(beforeNames).toContain("binary_session");
|
||||
expect(beforeNames).not.toContain("current_document");
|
||||
expect(beforeNames).not.toContain("capture_process_scenario");
|
||||
expect(
|
||||
(await mcp.callTool({ name: "open_binary", arguments: { path: first } }))
|
||||
.isError,
|
||||
).not.toBe(true);
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ result: { path: await realpath(first) } });
|
||||
expect(
|
||||
text(await mcp.callTool({ name: "current_document", arguments: {} })),
|
||||
).toContain("first.hop");
|
||||
const { recordedUnknown, changesBeforeMutation } =
|
||||
await snapshotAndRecordUnknown(lifecycle, directory);
|
||||
const resolved = await mcp.callTool({
|
||||
name: "update_unknown",
|
||||
arguments: {
|
||||
approved: true,
|
||||
unknown_id: recordedUnknown.unknown_id,
|
||||
expected_revision: 1,
|
||||
status: "resolved",
|
||||
severity: "medium",
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
resolution: {
|
||||
disposition: "out-of-scope",
|
||||
rationale: "Operator explicitly excluded this branch from scope.",
|
||||
evidence_ids: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(resolved.isError).not.toBe(true);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(lifecycle.unknownResourceUpdates()).toBe(1);
|
||||
expect(lifecycle.resourceListChanges()).toBe(changesBeforeMutation);
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "verify_unknown_resolution",
|
||||
arguments: { unknown_id: recordedUnknown.unknown_id },
|
||||
}),
|
||||
).result,
|
||||
).toMatchObject({ valid: true, truthVerified: false });
|
||||
await mcp.callTool({ name: "open_binary", arguments: { path: second } });
|
||||
expect(closed.some((path) => path.endsWith("first.hop"))).toBe(true);
|
||||
expect(
|
||||
text(await mcp.callTool({ name: "binary_session", arguments: {} })),
|
||||
).toContain("second.hop");
|
||||
const snapshotPath = join(directory, "analysis.json");
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "close_binary",
|
||||
arguments: { snapshot_path: snapshotPath },
|
||||
}),
|
||||
).result,
|
||||
).toMatchObject({ path: snapshotPath, entries: 0 });
|
||||
expect(JSON.parse(await readFile(snapshotPath, "utf8"))).toMatchObject({
|
||||
evidence_bundle: { records: [], unknowns: [] },
|
||||
});
|
||||
expect(
|
||||
text(await mcp.callTool({ name: "binary_session", arguments: {} })),
|
||||
).toContain('"open":false');
|
||||
expect(
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: first, snapshot_path: snapshotPath },
|
||||
})
|
||||
).isError,
|
||||
).toBe(true);
|
||||
expect(
|
||||
structured(await mcp.callTool({ name: "list_unknowns", arguments: {} }))
|
||||
.result,
|
||||
).toMatchObject({ items: [] });
|
||||
expect(
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: second, snapshot_path: snapshotPath },
|
||||
})
|
||||
).isError,
|
||||
).not.toBe(true);
|
||||
await mcp.callTool({ name: "close_binary", arguments: {} });
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
describe("process residuals over MCP", () => {
|
||||
it("records approved process residuals in the unknown registry", async () => {
|
||||
if (!(await probeProcessCaptureCapability()).available) return;
|
||||
const session = composeBinarySessionFromFactory(() =>
|
||||
client("fixture", []),
|
||||
);
|
||||
const server = createServer(session, session, {
|
||||
logger: silentLogger,
|
||||
processPolicy: {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [dirname(processFixture)],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
});
|
||||
const mcp = new Client({ name: "process-unknown", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(mcp, server);
|
||||
await server.connect(serverTransport);
|
||||
await mcp.connect(clientTransport);
|
||||
|
||||
const captured = await mcp.callTool({
|
||||
name: "capture_process_scenario",
|
||||
arguments: {
|
||||
approved: true,
|
||||
unknown_registry_approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "partial"],
|
||||
working_directory: dirname(processFixture),
|
||||
limits: { output_bytes: 1 },
|
||||
},
|
||||
});
|
||||
expect(captured.isError, text(captured)).not.toBe(true);
|
||||
const listedUnknowns = await mcp.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: {},
|
||||
});
|
||||
expect(listedUnknowns.isError, text(listedUnknowns)).not.toBe(true);
|
||||
const listed = z
|
||||
.object({
|
||||
result: z.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
unknown: z.object({
|
||||
question: z.string(),
|
||||
domain: z.string(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.parse(structured(listedUnknowns)).result.items;
|
||||
expect(listed).toContainEqual({
|
||||
unknown: expect.objectContaining({
|
||||
question: "Was network behavior fully observed during capture?",
|
||||
domain: "process-network",
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const client = (path: string, closed: string[]): AnalysisClient => ({
|
||||
execute: (name) =>
|
||||
Promise.resolve(
|
||||
ok(name === "health" ? null : name === "current_document" ? path : null),
|
||||
),
|
||||
close: () => {
|
||||
closed.push(path);
|
||||
return Promise.resolve();
|
||||
},
|
||||
});
|
||||
|
||||
const provider = (closed: string[]): AnalysisProvider => {
|
||||
const identity = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const capability: CapabilityDescriptor = {
|
||||
provider: identity,
|
||||
operation: "current_document",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
};
|
||||
return {
|
||||
identity: () => identity,
|
||||
capabilities: () => [capability],
|
||||
createClient: (target) => client(target.path, closed),
|
||||
};
|
||||
};
|
||||
|
||||
const text = (result: CallToolResult): string => {
|
||||
const content = result.content.find((item) => item.type === "text");
|
||||
if (content?.type !== "text") throw new Error("missing text result");
|
||||
return content.text;
|
||||
};
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
if (
|
||||
typeof result.structuredContent !== "object" ||
|
||||
result.structuredContent === null
|
||||
)
|
||||
throw new Error("missing structured result");
|
||||
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
|
||||
};
|
||||
@@ -0,0 +1,195 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { composeBinarySessionFromProvider } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
evidenceBundleSchema,
|
||||
} from "../../../src/domain/evidenceBundle.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import type { AnalysisProvider } from "../../../src/application/AnalysisProvider.js";
|
||||
|
||||
const SNAPSHOT_PROFILE = createAnalysisProfile(
|
||||
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
|
||||
1,
|
||||
{ fixture: true },
|
||||
);
|
||||
|
||||
export interface SessionMcpHarness {
|
||||
readonly mcp: Client;
|
||||
readonly first: string;
|
||||
readonly second: string;
|
||||
readonly closed: string[];
|
||||
readonly resourceListChanges: () => number;
|
||||
readonly unknownResourceUpdates: () => number;
|
||||
}
|
||||
|
||||
export const createSessionMcpHarness = async (
|
||||
root: string,
|
||||
provider: (closed: string[]) => AnalysisProvider,
|
||||
resources: Array<{ close(): Promise<unknown> }>,
|
||||
): Promise<SessionMcpHarness> => {
|
||||
const first = join(root, "first.hop");
|
||||
const second = join(root, "second.hop");
|
||||
await Promise.all([writeFile(first, "one"), writeFile(second, "two")]);
|
||||
const closed: string[] = [];
|
||||
const session = composeBinarySessionFromProvider(provider(closed), {
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(ok({ profile: SNAPSHOT_PROFILE, compatibility: {} })),
|
||||
});
|
||||
const filePolicy = {
|
||||
roots: [root],
|
||||
maxBytes: 1024 * 1024,
|
||||
maxDepth: 68,
|
||||
maxStringLength: 1024,
|
||||
maxNodes: 10_000,
|
||||
};
|
||||
const server = createServer(session, session, {
|
||||
logger: silentLogger,
|
||||
evidenceFilePolicy: filePolicy,
|
||||
analysisSnapshotFilePolicy: filePolicy,
|
||||
});
|
||||
const mcp = new Client({ name: "session-test", version: "1.0.0" });
|
||||
let resourceChanges = 0;
|
||||
let unknownUpdates = 0;
|
||||
mcp.setNotificationHandler("notifications/resources/list_changed", () => {
|
||||
resourceChanges += 1;
|
||||
});
|
||||
mcp.setNotificationHandler("notifications/resources/updated", (notice) => {
|
||||
if (notice.params.uri.startsWith("rea://unknown/")) unknownUpdates += 1;
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(mcp, server);
|
||||
await server.connect(serverTransport);
|
||||
await mcp.connect(clientTransport);
|
||||
return {
|
||||
mcp,
|
||||
first,
|
||||
second,
|
||||
closed,
|
||||
resourceListChanges: () => resourceChanges,
|
||||
unknownResourceUpdates: () => unknownUpdates,
|
||||
};
|
||||
};
|
||||
|
||||
export const snapshotAndRecordUnknown = async (
|
||||
harness: SessionMcpHarness,
|
||||
root: string,
|
||||
): Promise<{
|
||||
recordedUnknown: { unknown_id: string; revision: number };
|
||||
changesBeforeMutation: number;
|
||||
}> => {
|
||||
const { mcp } = harness;
|
||||
const snapshotted = await mcp.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
const snapshotResult = z
|
||||
.object({ result: z.object({ bundle_uri: z.string() }) })
|
||||
.parse(structured(snapshotted)).result;
|
||||
const bundleResource = await mcp.readResource({
|
||||
uri: snapshotResult.bundle_uri,
|
||||
});
|
||||
const bundle = evidenceBundleSchema.parse(
|
||||
JSON.parse(
|
||||
z.object({ text: z.string() }).parse(bundleResource.contents[0]).text,
|
||||
),
|
||||
);
|
||||
expect(bundle.records).toHaveLength(1);
|
||||
const evidencePath = join(root, "evidence.json");
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: evidencePath },
|
||||
}),
|
||||
).result,
|
||||
).toMatchObject({ path: evidencePath, records: 1 });
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path: evidencePath },
|
||||
}),
|
||||
).result,
|
||||
).toEqual({ imported: 0, total: 1 });
|
||||
const externalEvidencePath = join(root, "external-evidence.json");
|
||||
await writeFile(
|
||||
externalEvidencePath,
|
||||
JSON.stringify(
|
||||
createEvidenceBundle([
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "external_observation", parameters: {}, result: true },
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path: externalEvidencePath },
|
||||
}),
|
||||
).result,
|
||||
).toEqual({ imported: 1, total: 2 });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(harness.resourceListChanges()).toBe(0);
|
||||
const changesBeforeMutation = harness.resourceListChanges();
|
||||
const recordedUnknown = z
|
||||
.object({
|
||||
result: z.object({ unknown_id: z.string(), revision: z.number() }),
|
||||
})
|
||||
.parse(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "record_unknown",
|
||||
arguments: {
|
||||
approved: true,
|
||||
question: "Does the alternate branch execute?",
|
||||
severity: "medium",
|
||||
domain: "control-flow",
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
},
|
||||
}),
|
||||
),
|
||||
).result;
|
||||
expect(recordedUnknown.revision).toBe(1);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(harness.resourceListChanges()).toBe(changesBeforeMutation);
|
||||
const listedUnknowns = await mcp.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: {},
|
||||
});
|
||||
expect(listedUnknowns.isError).not.toBe(true);
|
||||
expect(
|
||||
z
|
||||
.object({ result: z.object({ items: z.array(z.unknown()) }) })
|
||||
.parse(structured(listedUnknowns)).result.items,
|
||||
).toHaveLength(1);
|
||||
return { recordedUnknown, changesBeforeMutation };
|
||||
};
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
if (
|
||||
typeof result.structuredContent !== "object" ||
|
||||
result.structuredContent === null
|
||||
)
|
||||
throw new Error("missing structured result");
|
||||
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
describe("tool registration options", () => {
|
||||
it("reuses finalized advertised schemas", () => {
|
||||
const contract = TOOL_CONTRACTS[0];
|
||||
expect(contract).toBeDefined();
|
||||
if (contract === undefined) return;
|
||||
|
||||
const first = toolRegistrationOptions(contract);
|
||||
const second = toolRegistrationOptions(contract);
|
||||
expect(first.inputSchema["~standard"].jsonSchema.input()).toBe(
|
||||
second.inputSchema["~standard"].jsonSchema.output(),
|
||||
);
|
||||
expect(first.outputSchema["~standard"].jsonSchema.input()).toBe(
|
||||
second.outputSchema["~standard"].jsonSchema.output(),
|
||||
);
|
||||
});
|
||||
|
||||
it("gives fallback parameter guidance operational meaning", () => {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "analyze_function",
|
||||
);
|
||||
expect(contract).toBeDefined();
|
||||
if (contract === undefined) return;
|
||||
|
||||
const advertisedSchema =
|
||||
toolRegistrationOptions(contract).inputSchema[
|
||||
"~standard"
|
||||
].jsonSchema.input();
|
||||
const properties = Object.fromEntries(
|
||||
Object.entries(advertisedSchema.properties ?? {}),
|
||||
);
|
||||
expect(properties.include_assembly).toMatchObject({
|
||||
description: "Whether to include assembly in the result.",
|
||||
});
|
||||
expect(properties.max_instructions).toMatchObject({
|
||||
description: "Maximum permitted instructions for this operation.",
|
||||
});
|
||||
expect(properties.pseudocode_offset).toMatchObject({
|
||||
description: "Zero-based index of the first pseudocode to return.",
|
||||
});
|
||||
});
|
||||
|
||||
it("advertises validated contract examples on the MCP input schema", () => {
|
||||
for (const name of [
|
||||
"record_unknown",
|
||||
"run_replay_machine",
|
||||
"build_reconstruction_obligation_ledger",
|
||||
]) {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
(candidate) => candidate.name === name,
|
||||
);
|
||||
expect(contract).toBeDefined();
|
||||
if (contract === undefined) continue;
|
||||
|
||||
const schema =
|
||||
toolRegistrationOptions(contract).inputSchema[
|
||||
"~standard"
|
||||
].jsonSchema.input();
|
||||
expect(schema.examples).toEqual(
|
||||
contract.examples.map(({ input }) => input),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ToolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { HopperProcessError } from "../../../src/domain/errors.js";
|
||||
import { toCallToolResult } from "../../../src/server/toolResult.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemas.js";
|
||||
|
||||
const contract: ToolContract = {
|
||||
name: "provider_neutral_fixture",
|
||||
title: "Provider Neutral Fixture",
|
||||
description: "Fixture contract for provider-neutral output validation.",
|
||||
kind: "enhanced",
|
||||
inputSchema: z.object({}),
|
||||
outputSchema: z.object({ value: z.string() }),
|
||||
effects: {
|
||||
mutatesTarget: false,
|
||||
mutatesSession: false,
|
||||
writesFilesystem: false,
|
||||
launchesProcess: false,
|
||||
accessesNetwork: false,
|
||||
changesUiState: false,
|
||||
mayDiscardData: false,
|
||||
idempotent: true,
|
||||
},
|
||||
annotations: {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
examples: [{ title: "Example fixture request", input: {} }],
|
||||
};
|
||||
|
||||
describe("tool result projection", () => {
|
||||
it("exposes an actionable adapter code to MCP callers", () => {
|
||||
const result = toCallToolResult(err(new HopperProcessError(76)), contract);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
error: {
|
||||
code: "provider_unavailable",
|
||||
details: { failure_code: "unsupported_demo_dialog" },
|
||||
category: "execution_failure",
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("expected Hopper");
|
||||
});
|
||||
it("projects bounded private-display coordinates without raw stderr", () => {
|
||||
const result = toCallToolResult(
|
||||
err(
|
||||
new HopperProcessError(80, {
|
||||
schema_version: 1,
|
||||
component: "hopper_private_display",
|
||||
operation: "launch",
|
||||
status: "error",
|
||||
failure_code: "x11_socket_directory_unusable",
|
||||
reason: "socket_directory_read_only",
|
||||
socket_directory: "/tmp/.X11-unix",
|
||||
socket_directory_mode: "0777",
|
||||
mount_read_only: true,
|
||||
effective_socket_directory_mode: "1777",
|
||||
effective_mount_read_only: false,
|
||||
wsl: true,
|
||||
strategy: "user-mount-namespace",
|
||||
fallback_reason: null,
|
||||
xvfb_stderr_bytes: 512,
|
||||
xvfb_stderr_truncated: false,
|
||||
}),
|
||||
),
|
||||
contract,
|
||||
);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
error: {
|
||||
details: {
|
||||
failure_code: "x11_socket_directory_unusable",
|
||||
diagnostics: {
|
||||
socket_directory: "/tmp/.X11-unix",
|
||||
mount_read_only: true,
|
||||
wsl: true,
|
||||
strategy: "user-mount-namespace",
|
||||
xvfb_stderr_truncated: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("cookie");
|
||||
});
|
||||
it("classifies output contract failures without naming a provider", () => {
|
||||
const result = toCallToolResult(ok({ value: 42 }), contract);
|
||||
expect(result).toMatchObject({
|
||||
structuredContent: {
|
||||
error: {
|
||||
code: "unreadable_output",
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
retryable: false,
|
||||
remediation: {
|
||||
action:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
restart_required: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
isError: true,
|
||||
});
|
||||
expect(result.content[0]).toEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(result.structuredContent),
|
||||
});
|
||||
});
|
||||
|
||||
it("links successful evidence only when its session resource exists", () => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
operation: "fixture",
|
||||
parameters: {},
|
||||
result: { value: "observed" },
|
||||
limitations: [],
|
||||
},
|
||||
);
|
||||
const evidenceContract: ToolContract = {
|
||||
...contract,
|
||||
outputSchema: evidenceResultOf(z.object({ value: z.string() })),
|
||||
};
|
||||
|
||||
expect(
|
||||
toCallToolResult(ok(evidence), evidenceContract).content,
|
||||
).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ type: "resource_link" }),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
toCallToolResult(ok(evidence), evidenceContract, {
|
||||
evidenceResourcesAvailable: true,
|
||||
}).content,
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "resource_link",
|
||||
uri: `rea://evidence/${evidence.evidence_id}`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,424 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
containsProcess,
|
||||
getDescendants,
|
||||
maxTreeDepth,
|
||||
reconstructProcessTree,
|
||||
type ProcessTreeEvent,
|
||||
type ProcessEventType,
|
||||
type ProcessNode,
|
||||
type ProcessTreeReconstruction,
|
||||
} from "../../../src/domain/eventProcessTree.js";
|
||||
|
||||
describe("event-backed process tree reconstruction", () => {
|
||||
it("reconstructs a simple process tree", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 3,
|
||||
at_ms: 30,
|
||||
type: "exit",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.processes).toHaveLength(2);
|
||||
expect(result.events_consumed).toBe(4);
|
||||
expect(result.events_unmatched).toBe(0);
|
||||
expect(result.short_lived_descendants).toBe(2);
|
||||
});
|
||||
|
||||
it("detects short-lived descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: "/short",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 11,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.short_lived_descendants).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree transitions", () => {
|
||||
it("detects re-exec", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "re_exec",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/newroot",
|
||||
arguments: ["--new"],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_re_exec).toBe(true);
|
||||
const root = result.processes.find((p) => p.pid === 1)!;
|
||||
expect(root.is_re_exec).toBe(true);
|
||||
expect(root.executable).toBe("/newroot");
|
||||
});
|
||||
|
||||
it("detects reparenting", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "reparent",
|
||||
pid: 2,
|
||||
ppid: 0,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: 1,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_reparenting).toBe(true);
|
||||
const child = result.processes.find((p) => p.pid === 2)!;
|
||||
expect(child.is_reparented).toBe(true);
|
||||
expect(child.previous_ppid).toBe(1);
|
||||
expect(child.ppid).toBe(0);
|
||||
});
|
||||
|
||||
it("reports unmatched events for unknown exits", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "exit",
|
||||
pid: 999,
|
||||
ppid: null,
|
||||
process_name: null,
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 1,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.events_unmatched).toBe(1);
|
||||
expect(result.processes).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree queries", () => {
|
||||
it("gets descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child1",
|
||||
executable: "/c1",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "grandchild",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
const descendants = getDescendants(result.processes, 1);
|
||||
expect(descendants).toHaveLength(2);
|
||||
expect(descendants).toContain(2);
|
||||
expect(descendants).toContain(3);
|
||||
});
|
||||
|
||||
it("checks process containment", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(containsProcess(result.processes, 1)).toBe(true);
|
||||
expect(containsProcess(result.processes, 999)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree depth and types", () => {
|
||||
it("computes max tree depth", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/c",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "gc",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(maxTreeDepth(result.processes, 1)).toBe(2);
|
||||
});
|
||||
|
||||
it("uses exported types", () => {
|
||||
const node: ProcessNode = {
|
||||
pid: 1,
|
||||
ppid: null,
|
||||
process_name: "test",
|
||||
executable: "/test",
|
||||
arguments: [],
|
||||
children: [],
|
||||
spawn_time_ms: 0,
|
||||
exit_time_ms: null,
|
||||
exit_code: null,
|
||||
is_re_exec: false,
|
||||
is_reparented: false,
|
||||
previous_ppid: null,
|
||||
};
|
||||
expect(node.pid).toBe(1);
|
||||
const recon: ProcessTreeReconstruction = {
|
||||
root_pid: 1,
|
||||
processes: [node],
|
||||
events_consumed: 1,
|
||||
events_unmatched: 0,
|
||||
short_lived_descendants: 0,
|
||||
has_re_exec: false,
|
||||
has_reparenting: false,
|
||||
};
|
||||
expect(recon.root_pid).toBe(1);
|
||||
});
|
||||
|
||||
it("uses ProcessEventType", () => {
|
||||
const t: ProcessEventType = "spawn";
|
||||
expect(t).toBe("spawn");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,354 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { createElectronEvidence } from "../../../src/application/ElectronEvidence.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
|
||||
import { reconcileJavaScriptRuntime } from "../../../src/domain/javascriptRuntimeReconciliation.js";
|
||||
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`;
|
||||
const execute = promisify(execFile);
|
||||
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps byte-identical cross-layer candidates explicitly ambiguous", async () => {
|
||||
const application = await applicationFixture();
|
||||
const assets = await createTestTempDirectory("rea-runtime-assets-static-");
|
||||
const runtime = await createTestTempDirectory("rea-runtime-assets-live-");
|
||||
temporary.push(application, assets, runtime);
|
||||
await Promise.all([
|
||||
writeFile(join(assets, "app.js"), SOURCE),
|
||||
writeFile(join(runtime, "app.js"), SOURCE),
|
||||
writeFile(join(runtime, "index.html"), "<script></script>"),
|
||||
]);
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [
|
||||
{
|
||||
role: "application",
|
||||
analysis: await analyzeFixture(application),
|
||||
},
|
||||
{ role: "assets", analysis: await analyzeFixture(assets) },
|
||||
],
|
||||
runtime_observations: [
|
||||
electronRuntimeEvidence(runtime, SOURCE, { includeWorker: false }),
|
||||
],
|
||||
});
|
||||
const script = result.reconciliations.find(
|
||||
({ entity_kind: kind }) => kind === "script",
|
||||
);
|
||||
|
||||
expect(script).toMatchObject({
|
||||
status: "ambiguous",
|
||||
reason: "ambiguous-static-candidates",
|
||||
candidate_static_count: 2,
|
||||
});
|
||||
expect(script?.candidate_static_nodes).toHaveLength(2);
|
||||
expect(
|
||||
new Set(
|
||||
script?.candidate_static_nodes.map(
|
||||
({ static_layer_id: layerId }) => layerId,
|
||||
),
|
||||
).size,
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it("retains one target per capture and keeps load-state absence unknown when output is bounded", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const runtimeObservations = [
|
||||
electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
targetId: "target-one",
|
||||
}),
|
||||
electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
targetId: "target-two",
|
||||
}),
|
||||
];
|
||||
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: runtimeObservations,
|
||||
limits: {
|
||||
max_runtime_entities: 2,
|
||||
max_reconciliation_items: 2,
|
||||
max_static_load_states: 20_000,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.runtime_captures).toHaveLength(2);
|
||||
expect(
|
||||
new Set(result.runtime_captures.map(({ target_node_id: id }) => id)).size,
|
||||
).toBe(2);
|
||||
expect(result.summary).toMatchObject({
|
||||
runtime_targets: 2,
|
||||
runtime_frames: 0,
|
||||
runtime_scripts: 0,
|
||||
runtime_workers: 0,
|
||||
static_not_observed: 0,
|
||||
});
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
truncated: true,
|
||||
omitted_runtime_entities: 4,
|
||||
});
|
||||
expect(
|
||||
result.static_load_states.every(({ status }) => status === "unknown"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects runtime source bytes whose Evidence omits source-capture approval", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const staticEvidence = await analyzeFixture(fixture);
|
||||
const contradictoryRuntime = electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
sourceCaptureApproved: false,
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
reconcileJavaScriptRuntime({
|
||||
static_layers: [{ role: "application", analysis: staticEvidence }],
|
||||
runtime_observations: [contradictoryRuntime],
|
||||
}),
|
||||
).toThrow(/source-capture approval/u);
|
||||
});
|
||||
|
||||
it("keeps graph omission counts unknown when a runtime section is unavailable", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
temporary.push(fixture);
|
||||
const result = reconcileJavaScriptRuntime({
|
||||
static_layers: [
|
||||
{ role: "application", analysis: await analyzeFixture(fixture) },
|
||||
],
|
||||
runtime_observations: [
|
||||
electronRuntimeEvidence(fixture, SOURCE, {
|
||||
includeWorker: false,
|
||||
workersUnavailable: true,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
});
|
||||
expect(result.graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("runs the local verifier from operator-provided paths without emitting source", async () => {
|
||||
const fixture = await applicationFixture();
|
||||
const evidenceRoot = await createTestTempDirectory("rea-runtime-evidence-");
|
||||
const evidencePath = join(evidenceRoot, "runtime-evidence.json");
|
||||
temporary.push(fixture, evidenceRoot);
|
||||
await writeFile(
|
||||
evidencePath,
|
||||
JSON.stringify(electronRuntimeEvidence(fixture, SOURCE)),
|
||||
);
|
||||
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/verify-local-javascript-runtime.mjs",
|
||||
"--application",
|
||||
fixture,
|
||||
"--runtime-evidence",
|
||||
evidencePath,
|
||||
],
|
||||
{ cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 },
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
|
||||
expect(output).toMatchObject({
|
||||
verified: true,
|
||||
summary: { runtime_scripts: 1 },
|
||||
});
|
||||
expect(stdout).not.toContain(SOURCE.trim());
|
||||
}, 10_000);
|
||||
|
||||
const applicationFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-runtime-reconciliation-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "rea-runtime-reconciliation-fixture",
|
||||
version: "1.0.0",
|
||||
renderer: "index.html",
|
||||
}),
|
||||
),
|
||||
writeFile(join(root, "index.html"), "<script src='./app.js'></script>"),
|
||||
writeFile(join(root, "app.js"), SOURCE),
|
||||
writeFile(join(root, "worker.js"), "self.onmessage = () => undefined;\n"),
|
||||
]);
|
||||
return root;
|
||||
};
|
||||
|
||||
const analyzeFixture = async (root: string) => {
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication(authority, {
|
||||
input_path: root,
|
||||
approved: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
};
|
||||
|
||||
const electronRuntimeEvidence = (
|
||||
root: string,
|
||||
source: string,
|
||||
options: {
|
||||
readonly scriptFile?: string;
|
||||
readonly includeWorker?: boolean;
|
||||
readonly targetId?: string;
|
||||
readonly sourceCaptureApproved?: boolean;
|
||||
readonly workersUnavailable?: boolean;
|
||||
} = {},
|
||||
) => {
|
||||
const scriptFile = options.scriptFile ?? "app.js";
|
||||
const includeWorker = options.includeWorker ?? true;
|
||||
const targetId = options.targetId ?? "target-main";
|
||||
const sourceCaptureApproved = options.sourceCaptureApproved ?? true;
|
||||
const input = {
|
||||
cdp_endpoint: "http://127.0.0.1:9223",
|
||||
allowed_file_roots: [root],
|
||||
target_id: targetId,
|
||||
approved: true as const,
|
||||
observation_ms: 100,
|
||||
include_script_sources: sourceCaptureApproved,
|
||||
source_capture_approved: sourceCaptureApproved,
|
||||
limits: {
|
||||
max_frames: 200,
|
||||
max_dom_nodes: 2_000,
|
||||
max_scripts: 500,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_script_source_bytes: 1_048_576,
|
||||
max_total_script_source_bytes: 4_194_304,
|
||||
},
|
||||
};
|
||||
return createElectronEvidence(
|
||||
"inspect_electron_page",
|
||||
input,
|
||||
{
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
product: "Electron/fixture",
|
||||
protocol_version: "1.3",
|
||||
revision: "fixture",
|
||||
user_agent: "Electron fixture",
|
||||
js_version: "13",
|
||||
},
|
||||
target: {
|
||||
target_id: targetId,
|
||||
type: "page",
|
||||
title: "Fixture",
|
||||
file_path: join(root, "index.html"),
|
||||
attached: false,
|
||||
},
|
||||
capture_window: {
|
||||
started_at: "2026-07-15T00:00:00.000Z",
|
||||
ended_at: "2026-07-15T00:00:00.100Z",
|
||||
observation_ms: 100,
|
||||
},
|
||||
completeness: options.workersUnavailable
|
||||
? {
|
||||
...completeCapture(),
|
||||
status: "attach_limited" as const,
|
||||
conditions: ["attach_limited" as const],
|
||||
attach_limited_sections: ["workers" as const],
|
||||
unavailable_sections: ["workers" as const],
|
||||
}
|
||||
: completeCapture(),
|
||||
frames: [
|
||||
{
|
||||
frame_id: "frame-main",
|
||||
parent_frame_id: null,
|
||||
file_path: join(root, "index.html"),
|
||||
},
|
||||
],
|
||||
dom: { total_nodes: 0, nodes: [] },
|
||||
scripts: {
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
script_key: `electron_script_${"1".repeat(64)}`,
|
||||
frame_id: "frame-main",
|
||||
file_path: join(root, scriptFile),
|
||||
cdp_hash: "fixture",
|
||||
length: Buffer.byteLength(source),
|
||||
is_module: true,
|
||||
language: "JavaScript",
|
||||
source: {
|
||||
included: true as const,
|
||||
artifact: createWebTextArtifact(source, "text/javascript"),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
resources: [],
|
||||
workers: includeWorker
|
||||
? [
|
||||
{
|
||||
target_id: "worker-main",
|
||||
type: "worker",
|
||||
file_path: join(root, "worker.js"),
|
||||
attached: false,
|
||||
opener_target_id: targetId,
|
||||
parent_frame_id: "frame-main",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
limitations: ["Synthetic passive capture fixture."],
|
||||
},
|
||||
{
|
||||
id: "rea-cdp-electron",
|
||||
name: "REA Electron file-page CDP observation provider",
|
||||
version: "1",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const completeCapture = () => ({
|
||||
status: "complete_within_window" as const,
|
||||
conditions: ["complete_within_window" as const],
|
||||
policy_filtered_sections: [],
|
||||
attach_limited_sections: [],
|
||||
truncated_sections: [],
|
||||
unavailable_sections: [],
|
||||
excluded: [],
|
||||
dropped_events: {
|
||||
scripts: 0,
|
||||
network_requests: 0,
|
||||
console_events: 0,
|
||||
websocket_connections: 0,
|
||||
websocket_frames: 0,
|
||||
webmcp_tools: 0,
|
||||
timeline_events: 0,
|
||||
total: 0,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
digestProcessCommitment,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
const emptyCapture = (): ProcessCapture => {
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: readonly unknown[] = [];
|
||||
const replayPlan = {};
|
||||
return {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "test",
|
||||
provider_version: "3",
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
event_journal: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("classifies missing observations as unknown and one-sided evidence as added", () => {
|
||||
const base = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const added = compareProcessCaptures(base, {
|
||||
...base,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
columns: 3,
|
||||
rows: 1,
|
||||
cursor_x: 3,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["new"],
|
||||
serialized_state: "new",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(added.terminal).toBe("added");
|
||||
expect(added.status).toBe("changed");
|
||||
const unknown = compareProcessCaptures(
|
||||
{ ...base, residual_unknowns: [{ scope: "process", reason: "sampled" }] },
|
||||
base,
|
||||
);
|
||||
expect(unknown.process).toBe("unknown");
|
||||
expect(unknown.shim).toBe("unchanged");
|
||||
expect(unknown.status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("compares raw terminal chunks even when rendered states agree", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "bar" }],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }],
|
||||
});
|
||||
expect(comparison.terminal).toBe("changed");
|
||||
expect(comparison.first_divergence).toMatchObject({
|
||||
status: "found",
|
||||
dimension: "terminal",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps filesystem evidence unknown when stable snapshots match", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [
|
||||
{ scope: "filesystem" as const, reason: "watcher unavailable" },
|
||||
],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, capture);
|
||||
expect(comparison.filesystem).toBe("unknown");
|
||||
expect(comparison.status).toBe("unknown");
|
||||
|
||||
const complete = { ...capture, residual_unknowns: [] };
|
||||
const transient = compareProcessCaptures(complete, {
|
||||
...complete,
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "during_run",
|
||||
at_ms: 10,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(transient.filesystem).toBe("changed");
|
||||
expect(transient.status).toBe("changed");
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm, symlink } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenario,
|
||||
probeProcessCaptureCapability,
|
||||
ProcessCaptureError,
|
||||
} from "../../../src/application/ProcessHarness.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
type ProcessExecutionPolicy,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
const processFixture = fileURLToPath(
|
||||
new URL("../../fixtures/processFidelity.mjs", import.meta.url),
|
||||
);
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
it("does not follow or disclose symlink targets outside declared roots", async () => {
|
||||
const root = await createTestTempDirectory("rea-symlink-test-");
|
||||
await symlink("/etc/passwd", join(root, "escape"));
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: "/usr/bin/true",
|
||||
working_directory: root,
|
||||
filesystem_roots: [root],
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: ["/usr/bin"],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
const escaped = result.value.files_after.find((file) =>
|
||||
file.path.endsWith(":escape"),
|
||||
);
|
||||
expect(escaped?.symlink_target).toBe("<outside-declared-root>");
|
||||
expect(result.value.truncated).toBe(true);
|
||||
expect(JSON.stringify(result.value.files_after)).not.toContain(root);
|
||||
expect(JSON.stringify(result.value.files_after)).not.toContain(
|
||||
"/etc/passwd",
|
||||
);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not launch when policy denies capture", async () => {
|
||||
const scenario = parseProcessScenario({
|
||||
approved: true,
|
||||
executable: "/bin/sh",
|
||||
working_directory: "/tmp",
|
||||
});
|
||||
const result = await captureProcessScenario(scenario, {
|
||||
enabled: false,
|
||||
executableRoots: [],
|
||||
workingRoots: [],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected policy refusal");
|
||||
expect(result.error).toBeInstanceOf(ProcessCaptureError);
|
||||
});
|
||||
|
||||
it("distinguishes timeout from cancellation and cleans both runs", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const policy: ProcessExecutionPolicy = {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [dirname(processFixture)],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
};
|
||||
const timedOut = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "hang"],
|
||||
working_directory: dirname(processFixture),
|
||||
timeout_ms: 50,
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
policy,
|
||||
);
|
||||
expect(timedOut.ok).toBe(true);
|
||||
if (!timedOut.ok) throw timedOut.error;
|
||||
expect(timedOut.value.exit.reason).toBe("timeout");
|
||||
expect(timedOut.value.cleanup).toEqual({
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
});
|
||||
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), 50);
|
||||
const cancelled = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "hang"],
|
||||
working_directory: dirname(processFixture),
|
||||
timeout_ms: 5_000,
|
||||
idle_timeout_ms: 5_000,
|
||||
}),
|
||||
policy,
|
||||
controller.signal,
|
||||
);
|
||||
expect(cancelled.ok).toBe(false);
|
||||
if (cancelled.ok) throw new Error("expected cancellation");
|
||||
expect(cancelled.error.message).toContain("cancelled");
|
||||
});
|
||||
|
||||
it("captures source-owned interactive, resize, Unicode, and signal behavior", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "interactive"],
|
||||
working_directory: dirname(processFixture),
|
||||
events: [
|
||||
{ type: "input", at_ms: 100, data: "answer" },
|
||||
{ type: "resize", at_ms: 300, columns: 100, rows: 40 },
|
||||
{ type: "signal", at_ms: 700, signal: "SIGINT" },
|
||||
],
|
||||
normalization: { time_bucket_ms: 60_000 },
|
||||
timeout_ms: 2_000,
|
||||
idle_timeout_ms: 2_000,
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [dirname(processFixture)],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.ok).toBe(true);
|
||||
const output = result.value.frames.map(({ data }) => data).join("");
|
||||
expect(output).toContain("prompt>");
|
||||
expect(output).toContain("input:answer unicode:雪");
|
||||
expect(output).toContain("resize:100x40");
|
||||
expect(output).toContain("signal:SIGINT");
|
||||
expect(result.value.exit.code).toBe(0);
|
||||
});
|
||||
|
||||
it("dispatches scheduled events before a silent PTY produces output", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "silent-interactive"],
|
||||
working_directory: dirname(processFixture),
|
||||
events: [
|
||||
{ type: "resize", at_ms: 25, columns: 100, rows: 40 },
|
||||
{ type: "input", at_ms: 50, data: "answer" },
|
||||
],
|
||||
timeout_ms: 2_000,
|
||||
idle_timeout_ms: 2_000,
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: [
|
||||
join(dirname(process.execPath), "missing"),
|
||||
dirname(process.execPath),
|
||||
],
|
||||
workingRoots: [
|
||||
join(dirname(processFixture), "missing"),
|
||||
dirname(processFixture),
|
||||
],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.frames.map(({ data }) => data).join("")).toContain(
|
||||
"input:answer",
|
||||
);
|
||||
expect(result.value.interaction_events).toMatchObject([
|
||||
{ type: "resize", outcome: "dispatched" },
|
||||
{ type: "input", outcome: "dispatched" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("samples and cleans a source-owned child and grandchild process tree", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "tree"],
|
||||
working_directory: dirname(processFixture),
|
||||
timeout_ms: 2_000,
|
||||
idle_timeout_ms: 2_000,
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [dirname(processFixture)],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
const commands = result.value.process_samples.map(({ command }) => command);
|
||||
expect(commands.some((command) => command.includes("tree-child"))).toBe(true);
|
||||
expect(commands.some((command) => command.includes("forks.js"))).toBe(false);
|
||||
expect(commands.some((command) => command.includes("tree-grandchild"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(JSON.stringify(result.value.process_samples)).not.toContain(
|
||||
dirname(processFixture),
|
||||
);
|
||||
const { stdout } = await execFileAsync("ps", ["-axo", "command="]);
|
||||
expect(stdout).not.toContain(`${processFixture} tree-child`);
|
||||
expect(stdout).not.toContain(`${processFixture} tree-grandchild`);
|
||||
}, 20_000);
|
||||
@@ -0,0 +1,269 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenario,
|
||||
probeProcessCaptureCapability,
|
||||
} from "../../../src/application/ProcessHarness.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
validateProcessCapture,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
type EventSource = "process" | "filesystem" | "http" | "websocket" | "shim";
|
||||
|
||||
function eventTrigger(
|
||||
source: EventSource,
|
||||
exact: Record<string, unknown>,
|
||||
ignoreFields: readonly string[],
|
||||
) {
|
||||
return {
|
||||
kind: "event" as const,
|
||||
source,
|
||||
exact,
|
||||
ignore_fields: ignoreFields,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: true,
|
||||
cardinality: { min: 1, max: 1 },
|
||||
};
|
||||
}
|
||||
|
||||
function collectionTriggers() {
|
||||
const terminalTrigger = (literal: string) => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal,
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: false,
|
||||
});
|
||||
return [
|
||||
{
|
||||
kind: "any" as const,
|
||||
triggers: [
|
||||
terminalTrigger("Collecting"),
|
||||
terminalTrigger("unreachable-alternative"),
|
||||
],
|
||||
},
|
||||
eventTrigger(
|
||||
"process",
|
||||
{
|
||||
pid: 3,
|
||||
parent_pid: 1,
|
||||
command: "rea-reactive-worker",
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
},
|
||||
["at_ms"],
|
||||
),
|
||||
eventTrigger(
|
||||
"filesystem",
|
||||
{
|
||||
name: "ready_snapshot",
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
["at_ms"],
|
||||
),
|
||||
eventTrigger(
|
||||
"shim",
|
||||
{
|
||||
command: "codex",
|
||||
route_index: 0,
|
||||
arguments: ["probe"],
|
||||
working_directory: "<working-directory>",
|
||||
outcome: "matched",
|
||||
},
|
||||
["sequence", "at_ms"],
|
||||
),
|
||||
{
|
||||
kind: "sequence" as const,
|
||||
triggers: [
|
||||
eventTrigger(
|
||||
"http",
|
||||
{
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method: "GET",
|
||||
path: "/reactive",
|
||||
data: "",
|
||||
outcome: "matched",
|
||||
},
|
||||
["sequence", "at_ms"],
|
||||
),
|
||||
eventTrigger(
|
||||
"websocket",
|
||||
{
|
||||
protocol: "websocket",
|
||||
direction: "received",
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "reactive-client",
|
||||
outcome: "matched",
|
||||
},
|
||||
["sequence", "at_ms"],
|
||||
),
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function createMultiSourceScenario(root: string, script: string) {
|
||||
return parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [script, "codex"],
|
||||
working_directory: root,
|
||||
replay: {
|
||||
http: [{ method: "GET", path: "/reactive", status: 200, body: "ok" }],
|
||||
websocket_messages: ["reactive-server"],
|
||||
},
|
||||
command_shims: [
|
||||
{
|
||||
name: "codex",
|
||||
routes: [
|
||||
{
|
||||
arguments: ["probe"],
|
||||
outputs: [],
|
||||
termination: { type: "exit", code: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
reactive: {
|
||||
version: 1,
|
||||
initial_state: "ready",
|
||||
deadline_ms: 8_000,
|
||||
states: [
|
||||
{
|
||||
id: "ready",
|
||||
max_visits: 1,
|
||||
deadline_ms: 3_000,
|
||||
on: [
|
||||
{
|
||||
id: "checkpoint_ready",
|
||||
priority: 0,
|
||||
max_uses: 1,
|
||||
when: {
|
||||
kind: "terminal_text",
|
||||
view: "decoded",
|
||||
encoding: "utf8",
|
||||
literal: "Ready",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include",
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" },
|
||||
consume: true,
|
||||
},
|
||||
actions: [{ type: "checkpoint", name: "ready_snapshot" }],
|
||||
target: { kind: "goto", state: "collecting" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "collecting",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5_000,
|
||||
on: [
|
||||
{
|
||||
id: "finish_all_sources",
|
||||
priority: 0,
|
||||
max_uses: 1,
|
||||
when: { kind: "all", triggers: collectionTriggers() },
|
||||
actions: [],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// This is the single multi-source acceptance matrix for the process boundary.
|
||||
it("runs the committed multi-source reactive fixture deterministically", async () => {
|
||||
const root = await createTestTempDirectory("rea-reactive-e2e-");
|
||||
const script = fileURLToPath(
|
||||
new URL("../../fixtures/processReactiveScenario.mjs", import.meta.url),
|
||||
);
|
||||
const run = () =>
|
||||
captureProcessScenario(createMultiSourceScenario(root, script), {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const first = await run();
|
||||
const second = await run();
|
||||
if (!first.ok) throw first.error;
|
||||
if (!second.ok) throw second.error;
|
||||
expect(first.ok).toBe(true);
|
||||
expect(second.ok).toBe(true);
|
||||
const trace = (capture: ProcessCapture) =>
|
||||
capture.reactive_run?.transitions.map((transition) => ({
|
||||
transition_id: transition.transition_id,
|
||||
from: transition.state_before,
|
||||
to: transition.state_after,
|
||||
outcome: transition.outcome,
|
||||
trigger_collections: transition.trigger_event_ids.map(
|
||||
(id) => id.split(".")[1],
|
||||
),
|
||||
}));
|
||||
expect(
|
||||
first.value.reactive_run?.outcome,
|
||||
JSON.stringify({
|
||||
run: first.value.reactive_run,
|
||||
processes: first.value.process_samples,
|
||||
checkpoints: first.value.filesystem_checkpoints,
|
||||
shims: first.value.shim_events,
|
||||
protocols: first.value.protocol_events,
|
||||
}),
|
||||
).toBe("passed");
|
||||
expect(trace(first.value)).toEqual(trace(second.value));
|
||||
expect(trace(first.value)).toEqual([
|
||||
expect.objectContaining({ transition_id: "checkpoint_ready" }),
|
||||
expect.objectContaining({
|
||||
transition_id: "finish_all_sources",
|
||||
trigger_collections: expect.arrayContaining([
|
||||
"frames",
|
||||
"process_samples",
|
||||
"filesystem_checkpoints",
|
||||
"shim_events",
|
||||
"protocol_events",
|
||||
]),
|
||||
}),
|
||||
]);
|
||||
for (const outcome of ["action_rejected", "target_lost"] as const) {
|
||||
const failedActionCapture = {
|
||||
...first.value,
|
||||
reactive_run: {
|
||||
status: "finished" as const,
|
||||
outcome,
|
||||
active_state: "ready",
|
||||
transitions: [],
|
||||
controls: [],
|
||||
},
|
||||
};
|
||||
expect(
|
||||
validateProcessCapture(failedActionCapture).filter(({ path }) =>
|
||||
path.startsWith("reactive_run"),
|
||||
),
|
||||
).toEqual([]);
|
||||
}
|
||||
expect(first.value.truncated).toBe(false);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
@@ -0,0 +1,407 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { snapshotRoots } from "../../../src/application/FilesystemSnapshot.js";
|
||||
import {
|
||||
buildCaptureResult,
|
||||
prepareProcessCapture,
|
||||
type ProcessPreparationHost,
|
||||
} from "../../../src/application/ProcessCaptureLifecycle.js";
|
||||
import { ProcessCheckpoints } from "../../../src/application/ProcessCheckpoints.js";
|
||||
import { normalizeProcessSamples } from "../../../src/application/ProcessNormalization.js";
|
||||
import {
|
||||
isInitializedPtyRoot,
|
||||
readLinuxChildren,
|
||||
} from "../../../src/application/ProcessSampling.js";
|
||||
import { TerminalRenderer } from "../../../src/application/TerminalRenderer.js";
|
||||
import {
|
||||
authorizeProcessScenario,
|
||||
compareProcessCaptures,
|
||||
digestProcessCommitment,
|
||||
parseProcessCapture,
|
||||
parseProcessScenario,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
const base = {
|
||||
approved: true as const,
|
||||
executable: "/bin/sh",
|
||||
working_directory: "/tmp",
|
||||
};
|
||||
|
||||
const emptyCapture = (): ProcessCapture => {
|
||||
const normalization = {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
};
|
||||
const scenario = { executable_sha256: "0".repeat(64) };
|
||||
const comparisonContract = {};
|
||||
const shimPlan: readonly unknown[] = [];
|
||||
const replayPlan = {};
|
||||
return {
|
||||
schema_version: 4,
|
||||
manifest: {
|
||||
rea_version: "test",
|
||||
provider_version: "3",
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
pty_backend: "node-pty",
|
||||
started_at: "2026-01-01T00:00:00.000Z",
|
||||
completed_at: "2026-01-01T00:00:00.001Z",
|
||||
scenario,
|
||||
comparison_contract: comparisonContract,
|
||||
shim_plan: shimPlan,
|
||||
replay_plan: replayPlan,
|
||||
full_scenario_sha256: digestProcessCommitment(scenario),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: "0".repeat(64),
|
||||
normalization_sha256: digestProcessCommitment(normalization),
|
||||
shim_plan_sha256: digestProcessCommitment(shimPlan),
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
normalization,
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" },
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 50,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
event_journal: [],
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("returns detached terminal and filesystem checkpoint observations", async () => {
|
||||
const observed: string[] = [];
|
||||
const renderer = new TerminalRenderer({
|
||||
columns: 40,
|
||||
rows: 12,
|
||||
scrollback: 100,
|
||||
maxFrames: 10,
|
||||
maxBytes: 10_000,
|
||||
normalize: (value) => value,
|
||||
recordEvent: (collection, index) =>
|
||||
observed.push(`${collection}:${String(index)}`),
|
||||
});
|
||||
renderer.write("A", 20);
|
||||
renderer.resize(40, 12, 10);
|
||||
const frames = await renderer.frames();
|
||||
expect(frames.map(({ at_ms }) => at_ms)).toEqual([20, 10]);
|
||||
expect(observed).toEqual(["rendered_frames:0", "rendered_frames:1"]);
|
||||
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
|
||||
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
|
||||
await renderer.dispose();
|
||||
|
||||
const scenario = parseProcessScenario(base);
|
||||
const checkpoints = new ProcessCheckpoints(
|
||||
scenario,
|
||||
Date.now(),
|
||||
{ files: [], truncated: false },
|
||||
{ signal: undefined },
|
||||
);
|
||||
const first = await checkpoints.finish({ files: [], truncated: false });
|
||||
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
|
||||
const second = await checkpoints.finish({ files: [], truncated: false });
|
||||
expect(second[0]?.name).toBe("before");
|
||||
await checkpoints.dispose();
|
||||
});
|
||||
|
||||
it("preserves rendered observation order instead of timestamp sorting", () => {
|
||||
const capture = emptyCapture();
|
||||
const renderedFrames: ProcessCapture["rendered_frames"] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 20,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["first"],
|
||||
serialized_state: "first",
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["second"],
|
||||
serialized_state: "second",
|
||||
},
|
||||
];
|
||||
const result = buildCaptureResult({
|
||||
frames: [],
|
||||
reactiveRun: null,
|
||||
exit: { exitCode: 0, reason: "exited" },
|
||||
samples: [],
|
||||
replay: {
|
||||
httpUrl: "http://127.0.0.1",
|
||||
websocketUrl: "ws://127.0.0.1/ws",
|
||||
events: [],
|
||||
transitions: [],
|
||||
truncated: false,
|
||||
close: () => Promise.resolve(),
|
||||
},
|
||||
before: { files: [], truncated: false },
|
||||
after: { files: [], truncated: false },
|
||||
truncated: false,
|
||||
scenario: parseProcessScenario(base),
|
||||
rootPid: 1,
|
||||
samplingPartial: false,
|
||||
renderedFrames,
|
||||
interactions: [],
|
||||
checkpoints: capture.filesystem_checkpoints,
|
||||
shimEvents: [],
|
||||
settlement: capture.settlement,
|
||||
manifest: capture.manifest,
|
||||
eventJournal: [],
|
||||
});
|
||||
|
||||
expect(result.rendered_frames).toEqual(renderedFrames);
|
||||
});
|
||||
|
||||
it("cleans the temporary root when capture home creation fails", async () => {
|
||||
const cleaned: string[] = [];
|
||||
const host: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
|
||||
createHome: () => Promise.reject(new Error("mkdir failed")),
|
||||
cleanup: (path) => {
|
||||
cleaned.push(path);
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
prepareProcessCapture(
|
||||
parseProcessScenario(base),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
undefined,
|
||||
host,
|
||||
),
|
||||
).rejects.toThrow("mkdir failed");
|
||||
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
|
||||
});
|
||||
|
||||
it("normalizes every sampled process identifier in command text", () => {
|
||||
const samples = normalizeProcessSamples(
|
||||
[
|
||||
{
|
||||
at_ms: 0,
|
||||
pid: 101,
|
||||
parent_pid: 0,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "root 101",
|
||||
},
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 202,
|
||||
parent_pid: 101,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "child 202 peer=101 unrelated 1202",
|
||||
},
|
||||
],
|
||||
parseProcessScenario(base),
|
||||
101,
|
||||
);
|
||||
|
||||
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
|
||||
});
|
||||
|
||||
it("collects and deduplicates children from every Linux thread", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
expect(
|
||||
await readLinuxChildren(100, signal, {
|
||||
taskIds: () => Promise.resolve([100, 101, 102]),
|
||||
children: (_pid, taskId) =>
|
||||
Promise.resolve(
|
||||
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
|
||||
),
|
||||
}),
|
||||
).toEqual([201, 202, 203]);
|
||||
});
|
||||
|
||||
it("admits PTY samples only after stable session and token setup", () => {
|
||||
const initialized = {
|
||||
pid: 100,
|
||||
parent_pid: 10,
|
||||
process_group_id: 100,
|
||||
session_id: 100,
|
||||
startTime: "200",
|
||||
};
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, process_group_id: 10, session_id: 10 },
|
||||
observedRunId: undefined,
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, startTime: "201" },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, session_id: null },
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, session_id: null },
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps interaction and shim residual uncertainty in separate scopes", () => {
|
||||
const baseCapture = emptyCapture();
|
||||
const interaction = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [
|
||||
{ scope: "interaction", reason: "Interaction capture was partial." },
|
||||
],
|
||||
});
|
||||
const shim = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [{ scope: "shim", reason: "Shim capture was partial." }],
|
||||
});
|
||||
|
||||
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unknown",
|
||||
shim: "unchanged",
|
||||
});
|
||||
expect(compareProcessCaptures(shim, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unchanged",
|
||||
shim: "unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels filesystem snapshots before traversing declared roots", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
snapshotRoots(
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
filesystem_roots: ["/tmp"],
|
||||
}),
|
||||
controller.signal,
|
||||
),
|
||||
).rejects.toMatchObject({ name: "AbortError" });
|
||||
});
|
||||
|
||||
it("parses bounded scenarios and rejects unordered events", () => {
|
||||
expect(parseProcessScenario(base).timeout_ms).toBe(30_000);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [
|
||||
{ type: "input", at_ms: 2, data: "a" },
|
||||
{ type: "input", at_ms: 1, data: "b" },
|
||||
],
|
||||
}),
|
||||
).toThrow(/ordered/);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
environment: { HOME: "/unsafe" },
|
||||
}),
|
||||
).toThrow(/reserved/);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: 31_000, data: "late" }],
|
||||
}),
|
||||
).toThrow(/after the scenario timeout/);
|
||||
});
|
||||
|
||||
it("requires explicit operator approval for host network access", () => {
|
||||
expect(
|
||||
authorizeProcessScenario(parseProcessScenario(base), {
|
||||
enabled: true,
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: false,
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "host network access is not approved by operator policy",
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses paths and environment outside operator policy", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
...base,
|
||||
environment: { TOKEN: "secret" },
|
||||
});
|
||||
expect(
|
||||
authorizeProcessScenario(scenario, {
|
||||
enabled: true,
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "scenario requests an environment variable not allowed by policy",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,424 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
captureProcessScenario,
|
||||
probeProcessCaptureCapability,
|
||||
} from "../../../src/application/ProcessHarness.js";
|
||||
import {
|
||||
parseProcessScenario,
|
||||
validateProcessCapture,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
|
||||
function createInteractiveScenario(root: string, script: string) {
|
||||
return parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [script],
|
||||
working_directory: root,
|
||||
reactive: {
|
||||
version: 1,
|
||||
initial_state: "waiting",
|
||||
deadline_ms: 5_000,
|
||||
states: [
|
||||
{
|
||||
id: "waiting",
|
||||
max_visits: 1,
|
||||
deadline_ms: 2_000,
|
||||
on: [
|
||||
{
|
||||
id: "answer",
|
||||
priority: 0,
|
||||
max_uses: 1,
|
||||
when: {
|
||||
kind: "terminal_text",
|
||||
view: "decoded",
|
||||
encoding: "utf8",
|
||||
literal: "Ready",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include",
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" },
|
||||
consume: true,
|
||||
},
|
||||
actions: [
|
||||
{ type: "send_input", data: "accepted\n", sensitive: true },
|
||||
{ type: "close_stdin" },
|
||||
],
|
||||
target: { kind: "goto", state: "finishing" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "finishing",
|
||||
max_visits: 1,
|
||||
deadline_ms: 2_000,
|
||||
on: [
|
||||
{
|
||||
id: "complete",
|
||||
priority: 0,
|
||||
max_uses: 1,
|
||||
when: {
|
||||
kind: "terminal_text",
|
||||
view: "decoded",
|
||||
encoding: "utf8",
|
||||
literal: "Done",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include",
|
||||
occurrence: 1,
|
||||
since: { kind: "state_entry" },
|
||||
consume: true,
|
||||
},
|
||||
actions: [],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function assertCompletedCapture(capture: ProcessCapture): void {
|
||||
expect(capture.reactive_run).toMatchObject({
|
||||
status: "finished",
|
||||
outcome: "passed",
|
||||
active_state: "finishing",
|
||||
});
|
||||
expect(
|
||||
capture.reactive_run?.transitions.map(({ transition_id }) => transition_id),
|
||||
).toEqual(["answer", "complete"]);
|
||||
expect(capture.interaction_events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "input",
|
||||
data: "<redacted-input:9-bytes>",
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
);
|
||||
expect(capture.interaction_events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "stdin_close",
|
||||
data: "",
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
);
|
||||
expect(capture.frames.map(({ data }) => data).join("")).toContain("Done");
|
||||
expect(capture.manifest.comparison_contract).toHaveProperty("reactive");
|
||||
expect(JSON.stringify(capture.manifest.comparison_contract)).not.toContain(
|
||||
"accepted",
|
||||
);
|
||||
expect(JSON.stringify(capture.manifest.scenario)).not.toContain("accepted");
|
||||
}
|
||||
|
||||
function assertControlAndTransitionValidation(capture: ProcessCapture): void {
|
||||
const reactiveRun = capture.reactive_run;
|
||||
if (reactiveRun === null) throw new Error("reactive result missing");
|
||||
const lastOrder = capture.event_journal
|
||||
?.filter(({ collection }) =>
|
||||
[
|
||||
"frames",
|
||||
"interaction_events",
|
||||
"filesystem_checkpoints",
|
||||
"shim_events",
|
||||
].includes(collection),
|
||||
)
|
||||
.at(-1)?.capture_order;
|
||||
if (lastOrder === undefined)
|
||||
throw new Error("reactive observation order missing");
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...capture,
|
||||
reactive_run: {
|
||||
...reactiveRun,
|
||||
controls: [
|
||||
...reactiveRun.controls,
|
||||
{
|
||||
sequence: reactiveRun.controls.length,
|
||||
kind: "target_lost",
|
||||
after_capture_order: lastOrder,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: `reactive_run.controls[${String(reactiveRun.controls.length)}]`,
|
||||
message: "reactive control cannot follow a finished run",
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...capture,
|
||||
reactive_run: {
|
||||
...reactiveRun,
|
||||
transitions: reactiveRun.transitions.map((transition, index) =>
|
||||
index === 0
|
||||
? { ...transition, transition_id: "fabricated" }
|
||||
: transition,
|
||||
),
|
||||
},
|
||||
}),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: "reactive_run.transitions[0]",
|
||||
message:
|
||||
"reactive transition is not declared by its recorded source state",
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...capture,
|
||||
reactive_run: {
|
||||
status: "finished",
|
||||
outcome: "passed",
|
||||
active_state: "waiting",
|
||||
transitions: [],
|
||||
controls: [],
|
||||
},
|
||||
}),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: "reactive_run.outcome",
|
||||
message: "reactive outcome differs from deterministic journal replay",
|
||||
}),
|
||||
);
|
||||
const suffix = reactiveRun.transitions
|
||||
.slice(1)
|
||||
.map((transition, sequence) => ({
|
||||
...transition,
|
||||
sequence,
|
||||
}));
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...capture,
|
||||
reactive_run: { ...reactiveRun, transitions: suffix },
|
||||
}),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: "reactive_run.transitions[0].state_before",
|
||||
message:
|
||||
"reactive transition journal must start at the declared initial state",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function assertReplayValidation(capture: ProcessCapture): void {
|
||||
const reactiveRun = capture.reactive_run;
|
||||
if (reactiveRun === null) throw new Error("reactive result missing");
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...capture,
|
||||
reactive_run: {
|
||||
...reactiveRun,
|
||||
transitions: reactiveRun.transitions.map((transition, index) =>
|
||||
index === 0
|
||||
? { ...transition, trigger_event_ids: [], action_event_ids: [] }
|
||||
: transition,
|
||||
),
|
||||
},
|
||||
}),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: "reactive_run.transitions",
|
||||
message: expect.stringContaining(
|
||||
"reactive transition journal is not reproduced",
|
||||
),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: "reactive_run.transitions[0].action_event_ids",
|
||||
message: expect.stringContaining(
|
||||
"recorded action observations do not match proposed effects",
|
||||
),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...capture,
|
||||
reactive_run: { ...reactiveRun, status: "running", outcome: null },
|
||||
}),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
message: "completed capture requires a finished reactive outcome",
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...capture,
|
||||
reactive_run: {
|
||||
...reactiveRun,
|
||||
transitions: [
|
||||
reactiveRun.transitions[0]!,
|
||||
{ ...reactiveRun.transitions[0]!, sequence: 1 },
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: "reactive transition states must be contiguous",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
message:
|
||||
"reactive transition differs from deterministic journal replay",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
it("drives a process from terminal observations and retains the reactive transition journal", async () => {
|
||||
const root = await createTestTempDirectory("rea-reactive-harness-test-");
|
||||
const script = join(root, "reactive.mjs");
|
||||
await writeFile(
|
||||
script,
|
||||
[
|
||||
'import { createInterface } from "node:readline";',
|
||||
"const input = createInterface({ input: process.stdin, terminal: false });",
|
||||
'process.stdout.write("Ready\\n");',
|
||||
'input.once("line", () => { process.stdout.write("Done\\n"); input.close(); });',
|
||||
].join("\n"),
|
||||
);
|
||||
const scenario = createInteractiveScenario(root, script);
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(scenario, {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
assertCompletedCapture(result.value);
|
||||
assertControlAndTransitionValidation(result.value);
|
||||
assertReplayValidation(result.value);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("records target loss before post-exit settlement can win the deadline race", async () => {
|
||||
const root = await createTestTempDirectory("rea-reactive-target-loss-test-");
|
||||
const script = join(root, "exit.mjs");
|
||||
await writeFile(script, 'process.stdout.write("exiting\\n");\n');
|
||||
const scenario = parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [script],
|
||||
working_directory: root,
|
||||
settle_ms: 500,
|
||||
reactive: {
|
||||
version: 1,
|
||||
initial_state: "waiting",
|
||||
deadline_ms: 5_000,
|
||||
states: [
|
||||
{
|
||||
id: "waiting",
|
||||
max_visits: 1,
|
||||
// Leave process startup scheduling headroom; this test targets
|
||||
// post-exit settlement ordering, not a 300ms startup deadline.
|
||||
deadline_ms: 2_000,
|
||||
on: [
|
||||
{
|
||||
id: "unreachable",
|
||||
priority: 0,
|
||||
max_uses: 1,
|
||||
when: {
|
||||
kind: "terminal_text",
|
||||
view: "decoded",
|
||||
encoding: "utf8",
|
||||
literal: "never-produced",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include",
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" },
|
||||
consume: true,
|
||||
},
|
||||
actions: [],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
try {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(scenario, {
|
||||
enabled: true,
|
||||
executableRoots: [dirname(process.execPath)],
|
||||
workingRoots: [root],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.reactive_run).toMatchObject({
|
||||
status: "finished",
|
||||
outcome: "target_lost",
|
||||
active_state: "waiting",
|
||||
transitions: [],
|
||||
controls: [
|
||||
expect.objectContaining({
|
||||
kind: "target_lost",
|
||||
}),
|
||||
],
|
||||
});
|
||||
const frame = result.value.frames.at(-1);
|
||||
const journal = result.value.event_journal;
|
||||
const reactiveRun = result.value.reactive_run;
|
||||
if (frame === undefined || journal === undefined || reactiveRun === null)
|
||||
throw new Error("ordered reactive evidence missing");
|
||||
const laterCaptureOrder = journal.length;
|
||||
const withLaterMatch = {
|
||||
...result.value,
|
||||
frames: [
|
||||
...result.value.frames,
|
||||
{
|
||||
...frame,
|
||||
sequence: result.value.frames.length,
|
||||
at_ms: frame.at_ms + 1,
|
||||
data: "never-produced",
|
||||
},
|
||||
],
|
||||
event_journal: [
|
||||
...journal,
|
||||
{
|
||||
capture_order: laterCaptureOrder,
|
||||
collection: "frames" as const,
|
||||
index: result.value.frames.length,
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(
|
||||
validateProcessCapture(withLaterMatch).filter(({ path }) =>
|
||||
path.startsWith("reactive_run"),
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
validateProcessCapture({
|
||||
...withLaterMatch,
|
||||
reactive_run: {
|
||||
...reactiveRun,
|
||||
controls: reactiveRun.controls.map((control) => ({
|
||||
...control,
|
||||
after_capture_order: laterCaptureOrder,
|
||||
})),
|
||||
},
|
||||
}),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
path: "reactive_run.outcome",
|
||||
message: "reactive outcome differs from deterministic journal replay",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 10_000);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user