fix!: repair boundary contracts across CLI and MCP (#597)

* fix(comparisons)!: preserve unknowns across partial observations

Share absence and digest semantics, keep unobserved managed bodies unknown, and match unique managed type/name/signatures before structural fallback.

BREAKING CHANGE: Managed comparison metadata adds exact-signature matching and its count, and name_matching now reports exact-signature-fallback.

* fix(javascript): preserve projected result binding semantics

Share syntax-aware property reads and assigned-result resolution. Retain destructuring paths and downgrade downstream whole-result relationships instead of resolving nested or wrapped calls as aliases.

* fix(native)!: admit complete parser values and preserve typed failures

Decode Mach headers by named columns, validate complete slice keys and lipo alignment, and preserve codesign runtime flags and tagged parser errors. Rename the Ghidra test dossier fixture and connect fake-backed suites to real verification lanes.

BREAKING CHANGE: Native load-command results no longer contain the unused, always-null file_offset field.

* fix(process): preserve host identity and actionable boundary failures

Thread selected platform and environment through process and Doctor seams, stamp observed producer identity in Evidence, and retain PTY, filesystem, lease and lazy-provider failure causes. Drain cancelled lazy loads and omit exited descendants from verified lineage.

* fix(browser): preserve cleanup and document-transition evidence

Make V8 and Playwright teardown cancellation-aware, expose primary failures alongside incomplete cleanup, share frame-tree and navigation rules, and clear stale WebMCP registrations without pruning unrelated child frames.

* fix(adapters): align managed targets and typed CLI outcomes

Inspect managed PE/CLI targets independently of native provider selection, reuse successful managed selections, and keep evidence bound to the actual inspected target. Classify canonical CLI error envelopes and exhaustive setup/update/uninstall outcomes, audit registered CLI coverage, and assert platform-specific runtime results.

* docs: refresh boundary contracts and shipped roadmap behavior
This commit is contained in:
morluto
2026-10-06 00:50:38 +08:00
committed by GitHub
parent f3e6582e9e
commit 9c25dc4ed2
134 changed files with 3547 additions and 812 deletions
+61 -16
View File
@@ -7,6 +7,8 @@ import { z } from "zod";
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
const mainPath = fileURLToPath(
new URL("../../../dist/main.js", import.meta.url),
@@ -56,7 +58,9 @@ const completeStderrRecords = (stderr: string): unknown[] =>
.map((line): unknown => JSON.parse(line));
describe("production stdio runtime", () => {
it("starts the built entrypoint, lists the catalog, calls one, and shuts down", async () => {
// The `test:acceptance` lane runs the real entrypoint on the current host;
// these cases state each supported host's result in the test name and body.
const callCurrentDocument = async () => {
const transport = new StdioClientTransport({
command: process.execPath,
args: [mainPath],
@@ -75,31 +79,72 @@ describe("production stdio runtime", () => {
});
const client = new Client({ name: "runtime-smoke", version: "1.0.0" });
let result: Awaited<ReturnType<Client["callTool"]>>;
try {
await client.connect(transport);
await expectAvailableToolInventory(client);
const result = await client.callTool({
result = await client.callTool({
name: "current_document",
arguments: {},
});
expect(result.isError === true).toBe(process.platform === "linux");
} finally {
await client.close();
await transport.close();
}
const records = completeStderrRecords(stderr);
expect(records).toContainEqual(
expect.objectContaining({
application: "rea",
mode: "mcp",
layer: "server",
tool: "current_document",
status: process.platform === "linux" ? "error" : "ok",
}),
);
expect(stderr).not.toContain("HOPPER_LOADER_ARGS_JSON");
expect(stderr).not.toContain(fixturePath);
}, 15_000);
return { result, stderr, records: completeStderrRecords(stderr) };
};
it.runIf(process.platform === "linux")(
"reports the Linux current-document failure through MCP and structured logs",
async () => {
const { result, stderr, records } = await callCurrentDocument();
expect(result.isError).toBe(true);
expect(result.content).toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "text", text: expect.any(String) }),
]),
);
expect(records).toContainEqual(
expect.objectContaining({
application: "rea",
mode: "mcp",
layer: "server",
tool: "current_document",
status: "error",
}),
);
expect(stderr).not.toContain("HOPPER_LOADER_ARGS_JSON");
expect(stderr).not.toContain(fixturePath);
},
15_000,
);
it.runIf(process.platform === "darwin")(
"returns the selected document on macOS through MCP and structured logs",
async () => {
const { result, stderr, records } = await callCurrentDocument();
expect(result.isError).not.toBe(true);
const observation = evidenceResultOf(z.literal("fixture")).parse(
result.structuredContent,
);
const evidence = parseEvidence(observation.evidence);
expect(evidence.operation).toBe("current_document");
expect(evidence.provider.id).toBe("hopper");
expect(evidence.normalized_result).toBe(observation.result);
expect(records).toContainEqual(
expect.objectContaining({
application: "rea",
mode: "mcp",
layer: "server",
tool: "current_document",
status: "ok",
}),
);
expect(stderr).not.toContain("HOPPER_LOADER_ARGS_JSON");
expect(stderr).not.toContain(fixturePath);
},
15_000,
);
it("starts with a database-kind initial target without a fatal record", async () => {
const transport = new StdioClientTransport({
@@ -120,6 +120,91 @@ describeBrowser("CdpBrowserProvider: document script 1", () => {
});
});
describeBrowser("CdpBrowserProvider: transient WebMCP frames", () => {
it("drops stale child tools and reports partial coverage when a blank commit remains", async () => {
const browser = await startFakeCdpBrowser({
webMcpTools: true,
webMcpChildTransientBlank: 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",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
expect(result.value.tools.items.map(({ name }) => name)).not.toContain(
"child_tool",
);
expect(result.value.completeness.attach_limited_sections).toContain(
"webmcp_tools",
);
expect(
result.value.completeness.excluded.find(
({ section }) => section === "webmcp_tools",
)?.count,
).toBe(1);
});
it("accepts fresh child registrations after a stable frame commit", async () => {
const browser = await startFakeCdpBrowser({
webMcpTools: true,
webMcpChildRecoversAfterTransient: true,
webMcpChildTransientBlank: 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",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
expect(result.value.tools.items).toContainEqual(
expect.objectContaining({ name: "child_tool" }),
);
expect(result.value.completeness.attach_limited_sections).not.toContain(
"webmcp_tools",
);
});
it("drops registrations from a child document when that frame commits a replacement", async () => {
const browser = await startFakeCdpBrowser({
webMcpTools: true,
webMcpChildNavigatesAllowed: 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",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
expect(result.value.tools.items.map(({ name }) => name)).not.toContain(
"child_tool",
);
expect(
result.value.completeness.excluded.find(
({ section }) => section === "webmcp_tools",
)?.count,
).toBe(1);
});
});
describeBrowser("CdpBrowserProvider: document script 2", () => {
it("discovers untrusted WebMCP declarations without registering or invoking them", async () => {
const browser = await startFakeCdpBrowser({ webMcpTools: true });
@@ -0,0 +1,52 @@
import { expect, it } from "vitest";
import { CdpCaptureCompleteness } from "../../../src/browser/CdpCaptureCompleteness.js";
import {
captureFrames,
captureResources,
} from "../../../src/browser/CdpCaptureDocuments.js";
it("reports malformed child frame entries instead of silently completing inventory", () => {
const completeness = new CdpCaptureCompleteness();
const captured = captureFrames(
{
frameTree: {
frame: {
id: "main",
url: "https://example.test/",
},
childFrames: [
null,
{ frame: { id: "child", url: "https://example.test/child" } },
],
},
},
new Set(["https://example.test"]),
undefined,
completeness,
);
expect(captured.items.map(({ frame_id }) => frame_id)).toEqual([
"main",
"child",
]);
expect(completeness.snapshot().unavailable_sections).toContain("frames");
});
it("reports missing top-level frame trees for frame and resource inventories", () => {
const completeness = new CdpCaptureCompleteness();
expect(
captureFrames(
{},
new Set(["https://example.test"]),
undefined,
completeness,
).items,
).toEqual([]);
expect(
captureResources({}, new Set(["https://example.test"]), completeness).items,
).toEqual([]);
expect(completeness.snapshot().unavailable_sections).toEqual(
expect.arrayContaining(["frames", "resources"]),
);
});
+1 -1
View File
@@ -20,7 +20,7 @@ import {
ghidraFunctionDossier,
ghidraFunctionIdentity,
ghidraReferenceEdge,
} from "../../../src/domain/hopperValues.fixture.js";
} from "../../../src/domain/ghidraValues.fixture.js";
const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
+123 -12
View File
@@ -11,12 +11,92 @@ 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 type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
import { SessionProviderRouter } from "../../../src/application/SessionProviderRouter.js";
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managedWorkflowExamples.js";
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js";
it("runs every managed static inspection independently of an active native target", async () => {
const directory = await createTestTempDirectory(
"rea-managed-independent-mcp-",
);
const path = join(directory, "fixture.dll");
await writeFile(path, buildManagedPeFixture());
const session = composeBinarySession(
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]),
);
const server = createServer(
session,
sessionWithUnrelatedNativeTarget(session),
{
availabilityPolicy: () => ({
processCaptureEnabled: false,
investigationInputRoots: 0,
browserObservationEnabled: false,
electronObservationEnabled: false,
}),
},
);
const client = new Client({
name: "managed-independent-mcp",
version: "1.0.0",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const artifact = structured(
await client.callTool({
name: "inspect_managed_artifact",
arguments: { path },
}),
);
expect(artifact).toMatchObject({
evidence: {
operation: "inspect_managed_artifact",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
},
});
const invalidSelection = await client.callTool({
name: "inspect_managed_artifact",
arguments: { path: join(directory, "missing.dll") },
});
expect(invalidSelection.isError).toBe(true);
const members = structured(
await client.callTool({ name: "inspect_managed_members", arguments: {} }),
);
expect(members).toMatchObject({
evidence: {
operation: "inspect_managed_members",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
},
});
const boundaries = structured(
await client.callTool({
name: "inspect_managed_native_boundaries",
arguments: { path },
}),
);
expect(boundaries).toMatchObject({
evidence: {
operation: "inspect_managed_native_boundaries",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
},
});
} finally {
await Promise.all([client.close(), server.close()]);
await session.close();
}
}, 30_000);
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");
@@ -28,14 +108,18 @@ it("opens a managed PE and executes the managed static provider through MCP", as
new ManagedStaticProvider(),
]),
);
const server = createServer(session, session, {
availabilityPolicy: () => ({
processCaptureEnabled: false,
investigationInputRoots: 0,
browserObservationEnabled: false,
electronObservationEnabled: false,
}),
});
const server = createServer(
session,
sessionWithUnrelatedNativeTarget(session),
{
availabilityPolicy: () => ({
processCaptureEnabled: false,
investigationInputRoots: 0,
browserObservationEnabled: false,
electronObservationEnabled: false,
}),
},
);
const client = new Client({ name: "managed-mcp-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
@@ -124,11 +208,16 @@ const inspectManagedStaticWorkflow = async (
references: [expect.objectContaining({ name: "System.Runtime" })],
},
});
expect(inlineEvidence(inspected)).toMatchObject({
operation: "inspect_managed_artifact",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
});
const members = inlineEvidence(
structured(
await client.callTool({
name: "inspect_managed_members",
arguments: {},
arguments: { path },
}),
),
);
@@ -150,7 +239,7 @@ const inspectManagedStaticWorkflow = async (
const boundaries = structured(
await client.callTool({
name: "inspect_managed_native_boundaries",
arguments: {},
arguments: { path },
}),
);
expect(boundaries).toMatchObject({
@@ -163,6 +252,28 @@ const inspectManagedStaticWorkflow = async (
return members;
};
const sessionWithUnrelatedNativeTarget = (
session: BinarySession,
): BinarySession => {
const nativeTarget: BinaryTarget = {
kind: "executable",
format: "pe",
path: "C:\\Windows\\System32\\notepad.exe",
sha256: "a".repeat(64),
architecture: "x86_64",
availableArchitectures: ["x86_64"],
executableRole: "application",
managed: false,
};
return new Proxy(session, {
get(target, property, receiver) {
if (property === "activeTarget") return () => nativeTarget;
const value: unknown = Reflect.get(target, property, receiver);
return typeof value === "function" ? value.bind(target) : value;
},
});
};
const methodFrom = (members: Record<string, unknown>) =>
z
.array(
@@ -210,8 +321,8 @@ const verifyManagedComparisonAndReconstruction = async (
provider: { id: "rea-dotnet-workflows" },
confidence: "inferred",
normalized_result: {
algorithm: { name_matching: "not-used" },
matching: { exact_il_signature: 1 },
algorithm: { name_matching: "exact-signature-fallback" },
matching: { exact_il_signature: 1, exact_signature: 0 },
},
});
const method = methodFrom(members);
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import {
processCaptureProbeFailureReason,
processCaptureOwnershipUnavailableReason,
probeProcessCaptureCapability,
} from "../../../src/application/ProcessCaptureCapability.js";
describe("process capture capability diagnostics", () => {
it("distinguishes missing native modules from runtime ABI mismatches", () => {
expect(
processCaptureProbeFailureReason(
Object.assign(
new Error("Cannot find package '@lydell/node-pty-win32-x64'"),
{
code: "ERR_MODULE_NOT_FOUND",
},
),
),
).toContain("optional dependencies enabled");
expect(
processCaptureProbeFailureReason(
Object.assign(
new Error("compiled against a different Node.js version"),
{
code: "ERR_DLOPEN_FAILED",
},
),
),
).toContain("incompatible with this Node.js runtime");
});
it("returns the actual cause from the real probe boundary", async () => {
const capability = await probeProcessCaptureCapability({
platform: "darwin",
loadPty: async () => {
throw Object.assign(new Error("optional binary was not installed"), {
code: "ERR_MODULE_NOT_FOUND",
});
},
});
expect(capability).toEqual({
available: false,
backend: "node-pty",
reason: expect.stringContaining("optional binary was not installed"),
});
});
it("preserves the actual diagnostic for a genuine probe failure", () => {
expect(
processCaptureProbeFailureReason(new Error("spawn EACCES")),
).toContain("spawn EACCES");
});
it("keeps the ownership limitation separate from native PTY support", () => {
expect(processCaptureOwnershipUnavailableReason("win32")).toContain(
"process-tree ownership",
);
});
});
@@ -0,0 +1,35 @@
import { expect, it } from "vitest";
import { parseProcessScenario } from "../../../src/domain/processScenario.js";
import {
createRunManifest,
observeSettlement,
} from "../../../src/application/ProcessCaptureLifecycle.js";
it("uses one selected host identity for manifest and settlement", async () => {
const scenario = parseProcessScenario({
executable: process.execPath,
working_directory: process.cwd(),
events: [],
});
const selectedHost = {
platform: "win32" as const,
architecture: "arm64" as const,
};
const manifest = await createRunManifest(
scenario,
new Date(0),
new Date(1),
selectedHost,
);
const settlement = await observeSettlement(
"run",
[],
0,
() => undefined,
selectedHost.platform,
);
expect(manifest).toMatchObject(selectedHost);
expect(settlement).toEqual({ state: "unverifiable", elapsed_ms: 0 });
});
@@ -346,6 +346,32 @@ describe("provider process output and cleanup primitives", () => {
});
});
describe("provider process host injection", () => {
it("uses injected host platform and environment when spawning", async () => {
const spawned = await spawnOwnedProviderProcess({
command: process.execPath,
arguments: ["-e", "process.stdout.write(process.env.REA_HOST_TEST)"],
runId: "injected-host-run",
platform: "win32",
hostEnvironment: { PATH: process.env.PATH, REA_HOST_TEST: "host-value" },
env: { REA_HOST_TEST: "spawn-override" },
});
try {
const supervisor = new ProviderProcessSupervisor({
process: spawned.process,
ownsProcessLifetime: true,
});
expect(await supervisor.waitForExit(2_000)).toBe(true);
expect(supervisor.snapshot().stdout.text).toBe("spawn-override");
} finally {
if (spawned.process.exitCode === null)
await new Promise<void>((resolve) =>
spawned.process.once("close", () => resolve()),
);
}
});
});
describe("provider process spawning primitives", () => {
it("spawns an owned process group with exact identity coordinates", async () => {
const runId = "provider-process-run";
@@ -79,6 +79,10 @@ describe("artifact Mach-O slices", () => {
byteOffset: 8,
declaredSize: 8,
});
for (const adapterKey of ["0x8:8", "1e3:8", " 8 :8"])
await expect(
reader.open({ ...secondEntry, adapterKey }),
).rejects.toMatchObject({ reason: "integrity" });
const chunks: Buffer[] = [];
const stream = await reader.open(secondEntry);
for await (const chunk of stream) chunks.push(Buffer.from(chunk));
@@ -52,3 +52,37 @@ it("keeps multi-word field names such as time stamp intact", async () => {
expect(load.commands.some((command) => "time" in command.fields)).toBe(false);
expect(stamped[0]?.fields["time stamp"]).toMatch(/^2 Thu Jan/);
});
it("decodes Mach header fields by their column names", () => {
const reordered = parseOtoolLoadCommands(
[
"Mach header",
" flags filetype magic cputype",
" NOUNDEFS 2 0xfeedfacf 16777228",
"Load command 0",
" cmd LC_UUID",
" uuid 01234567-89ab-cdef-0123-456789abcdef",
].join("\n"),
);
expect(reordered.fileType).toBe("2");
expect(reordered.flags).toEqual(["NOUNDEFS"]);
const reorderedMultiwordFlags = parseOtoolLoadCommands(
[
"Mach header",
" filetype magic flags ncmds sizeofcmds",
" 2 0xfeedfacf NOUNDEFS DYLDLINK 4 512",
].join("\n"),
);
expect(reorderedMultiwordFlags.fileType).toBe("2");
expect(reorderedMultiwordFlags.flags).toEqual(["DYLDLINK", "NOUNDEFS"]);
const missing = parseOtoolLoadCommands(
"Mach header\n magic cputype flags\n 0xfeedfacf 1 NOUNDEFS\n",
);
expect(missing.fileType).toBeNull();
expect(missing.flags).toEqual(["NOUNDEFS"]);
const incomplete = parseOtoolLoadCommands(
"Mach header\n filetype magic flags ncmds sizeofcmds\n 2 0xfeedfacf NOUNDEFS\n",
);
expect(incomplete.fileType).toBeNull();
expect(incomplete.flags).toEqual([]);
});
@@ -13,6 +13,7 @@ import {
} from "../../../../src/native/CommandRunner.js";
import { err, ok } from "../../../../src/domain/result.js";
import { parseLipoArchitectures } from "../../../../src/native/parsers/lipo.js";
import { parseCodeSignature } from "../../../../src/native/parsers/codesign.js";
import {
NativeFixtureRunner as FixtureRunner,
@@ -238,6 +239,41 @@ describe("native macOS provider inspection", () => {
});
});
describe("native dispatch metadata error results", () => {
it("preserves tagged cancellation and integrity failures", async () => {
directory = await createTestTempDirectory("rea-dispatch-errors-");
const targetPath = join(directory, "fixture.macho");
await writeFile(targetPath, "bound target bytes");
const client = new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
).createClient(machoTarget(targetPath));
const controller = new AbortController();
const cancelled = client.execute(
"inspect_native_dispatch_metadata",
{},
{ signal: controller.signal },
);
controller.abort();
const cancellationResult = await cancelled;
expect(!cancellationResult.ok && cancellationResult.error._tag).toBe(
"AnalysisCancelledError",
);
const mismatchedClient = new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
).createClient({ ...machoTarget(targetPath), sha256: "f".repeat(64) });
const integrityResult = await mismatchedClient.execute(
"inspect_native_dispatch_metadata",
{},
);
expect(!integrityResult.ok && integrityResult.error._tag).toBe(
"EvidenceIntegrityError",
);
});
});
describe("native macOS provider failures and parsing", () => {
it("classifies unavailable, malformed, command failure, and cancellation", async () => {
const unavailable = new NativeMacOSProvider(
@@ -319,6 +355,41 @@ describe("native macOS provider failures and parsing", () => {
{ name: "arm64", file_offset: null, size: null, alignment: 16384 },
]);
});
it("requires the full alignment field to use a recognized spelling", () => {
const output = [
"architecture arm64",
" offset 0",
" size 16",
" align 2^14 (16384)",
].join("\n");
expect(
parseLipoArchitectures(output.replace("(16384)", "(8192)"))[0]?.alignment,
).toBeNull();
expect(
parseLipoArchitectures(output.replace("2^14 (16384)", "2^14"))[0]
?.alignment,
).toBe(16384);
});
it("reads hardened runtime only from CodeDirectory flags", () => {
expect(
parseCodeSignature("Diagnostic: runtime policy unavailable", false)
.hardened_runtime,
).toBeNull();
expect(
parseCodeSignature(
"CodeDirectory v=20500 flags=0x10000(runtime) hashes=10+7",
false,
).hardened_runtime,
).toBe(true);
expect(
parseCodeSignature(
"CodeDirectory v=20500 flags=0x2(adhoc,hard) runtime=1",
false,
).hardened_runtime,
).toBe(false);
});
});
class FailingRunner implements NativeCommandRunner {
+39 -1
View File
@@ -90,7 +90,8 @@ const emitWebMcpEvents = (
},
]
: []),
...(options.webMcpChildLeavesScope === true
...(options.webMcpChildLeavesScope === true ||
options.webMcpChildTransientBlank === true
? [
{
name: "child_tool",
@@ -119,6 +120,43 @@ const emitWebMcpEvents = (
],
});
}
if (options.webMcpChildTransientBlank === true)
event(socket, "Page.frameNavigated", command.sessionId, {
frame: {
id: "frame-child",
parentId: "frame-main",
loaderId: "loader-transient",
url: "about:blank",
},
});
if (options.webMcpChildRecoversAfterTransient === true) {
event(socket, "Page.frameNavigated", command.sessionId, {
frame: {
id: "frame-child",
parentId: "frame-main",
loaderId: "loader-child-recovered",
url: `http://127.0.0.1:${String(port)}/child-recovered`,
},
});
event(socket, "WebMCP.toolsAdded", command.sessionId, {
tools: [
{
name: "child_tool",
description: "Replayed from the current child document",
frameId: "frame-child",
},
],
});
}
if (options.webMcpChildNavigatesAllowed === true)
event(socket, "Page.frameNavigated", command.sessionId, {
frame: {
id: "frame-child",
parentId: "frame-main",
loaderId: "loader-child-replacement",
url: `http://127.0.0.1:${String(port)}/child-replacement`,
},
});
}
};
+3
View File
@@ -63,6 +63,9 @@ export interface FakeOptions {
readonly webMcpFrameCount?: number;
readonly webMcpSchemaPropertyCount?: number;
readonly webMcpChildLeavesScope?: boolean;
readonly webMcpChildTransientBlank?: boolean;
readonly webMcpChildRecoversAfterTransient?: boolean;
readonly webMcpChildNavigatesAllowed?: boolean;
readonly electronFileUrl?: string;
readonly duplicateElectronInventory?: boolean;
readonly electronInventoryCount?: number;
+30 -5
View File
@@ -2,6 +2,15 @@ import { afterEach, describe, expect, it } from "vitest";
import { logCliCommand } from "../../src/cliLogging.js";
import { silentLogger } from "../../src/logger.js";
import {
ArtifactOperationError,
projectAnalysisError,
} from "../../src/domain/errors.js";
import { isSetupFailure, runSetup } from "../../src/application/Setup.js";
import {
FakeSetupHost,
options as setupOptions,
} from "../../src/application/Setup.fixture.js";
const originalExitCode = process.exitCode;
@@ -21,9 +30,20 @@ describe("CLI operation status", () => {
});
it("keeps unapproved setup applications unsuccessful", async () => {
const host = new FakeSetupHost();
host.availableClients = [{ name: "cursor", configPath: "/cursor.json" }];
const result = await runSetup(
{ ...setupOptions(false), clientIds: ["cursor"] },
host,
);
expect(result.status).toBe("needs_confirmation");
expect(isSetupFailure(result)).toBe(true);
process.exitCode = undefined;
await logCliCommand(silentLogger, "setup", () =>
Promise.resolve({ status: "needs_confirmation" }),
await logCliCommand(
silentLogger,
"setup",
() => Promise.resolve(result),
isSetupFailure,
);
expect(process.exitCode).toBe(1);
});
@@ -31,9 +51,14 @@ describe("CLI operation status", () => {
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" },
...projectAnalysisError(
new ArtifactOperationError("inspect_artifact", "integrity", {
logicalPath: "main.js",
declaredSha256: "a".repeat(64),
calculatedSha256: "b".repeat(64),
unpacked: false,
}),
),
};
await expect(