refactor(mcp): make analysis states unrepresentable (#468)

* refactor(config): parse capability settings into exact states

* refactor(runtime): encode replay and process outcomes exactly

* refactor: make analysis states unrepresentable

* refactor(mcp): register canonical schemas with SDK

* fix: preserve capability and catalog invariants

* fix(build): remove stale compiled modules

* fix(replay): update real verifier policy dependency

* fix(package): verify the complete MCP catalog

* fix(test): supply complete replay reload policy

* refactor(contracts): centralize output schema lookup

* refactor(mcp): delegate protocol boundaries to SDK

* fix(browser): approve real source capture

* fix(mcp): preserve catalog guidance
This commit is contained in:
morluto
2026-08-10 02:28:11 +08:00
committed by GitHub
parent 6901edc05d
commit b8a9da0c0f
271 changed files with 5970 additions and 5699 deletions
@@ -120,7 +120,8 @@ describe("Ghidra provider", () => {
});
expect(
ghidra.inspectTargetSupport({
...executableTarget("elf", "x86_64"),
path: "/tmp/fixture.asar",
sha256: "a".repeat(64),
kind: "archive",
format: "asar",
}),
@@ -129,14 +130,15 @@ describe("Ghidra provider", () => {
code: "target_kind_unsupported",
});
expect(
ghidra.inspectTargetSupport(executableTarget("javascript", "x86_64")),
ghidra.inspectTargetSupport({
path: "/tmp/fixture.js",
sha256: "a".repeat(64),
kind: "artifact",
format: "javascript",
}),
).toMatchObject({
status: "unsupported",
code: "target_format_unsupported",
});
expect(ghidra.inspectTargetSupport(executableTarget("elf"))).toMatchObject({
status: "unsupported",
code: "architecture_unsupported",
code: "target_kind_unsupported",
});
});
});
@@ -144,11 +146,7 @@ describe("Ghidra provider", () => {
describe("Ghidra platform support", () => {
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
const ghidra = provider({ ...installationHost(), platform: "win32" });
const nativeApplication: BinaryTarget = {
...executableTarget("pe", "x86_64"),
executableRole: "application",
managed: false,
};
const nativeApplication = peTarget("x86_64");
expect(ghidra.inspectTargetSupport(nativeApplication)).toMatchObject({
status: "supported",
@@ -208,16 +206,13 @@ describe("Ghidra platform support", () => {
code: "managed_target_unsupported",
});
expect(
ghidra.inspectTargetSupport({ ...nativeApplication, format: "elf" }),
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
).toMatchObject({
status: "unsupported",
code: "target_format_unsupported",
});
expect(
ghidra.inspectTargetSupport({
...nativeApplication,
architecture: "arm64",
}),
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
).toMatchObject({
status: "unsupported",
code: "architecture_unsupported",
@@ -470,14 +465,29 @@ const sessionInfo = () => ({
});
const executableTarget = (
format: BinaryTarget["format"],
architecture?: NonNullable<BinaryTarget["architecture"]>,
): BinaryTarget => ({
format: "mach-o" | "elf" | "pe",
architecture: NonNullable<BinaryTarget["architecture"]>,
): BinaryTarget =>
format === "pe"
? peTarget(architecture)
: {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
};
const peTarget = (
architecture: NonNullable<BinaryTarget["architecture"]>,
): Extract<BinaryTarget, { format: "pe" }> => ({
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
...(architecture === undefined
? {}
: { architecture, availableArchitectures: [architecture] }),
format: "pe",
architecture,
availableArchitectures: [architecture],
executableRole: "application",
managed: false,
});
@@ -27,8 +27,12 @@ describe("Hopper analysis profiles", () => {
[target("pe", "x86"), ["-l", "WinPE", "--intel-32"]],
[
{
...target("mach-o", "arm64"),
availableArchitectures: ["x86_64", "arm64"],
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format: "mach-o",
architecture: "arm64",
availableArchitectures: ["x86_64", "arm64"] as const,
} satisfies BinaryTarget,
["-l", "FAT", "--aarch64", "-l", "Mach-O"],
],
@@ -141,11 +145,23 @@ describe("Hopper analysis profiles", () => {
const target = (
format: "mach-o" | "elf" | "pe",
architecture: "x86" | "x86_64" | "arm" | "arm64",
): BinaryTarget => ({
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
});
): BinaryTarget =>
format === "pe"
? {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
executableRole: "application",
managed: false,
}
: {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
};
@@ -48,6 +48,7 @@ class FixtureLauncher implements BridgeLauncher {
ok({
process: child,
ownsProcessLifetime: true,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -78,9 +79,9 @@ class OwnedFixtureLauncher implements BridgeLauncher {
this.ownership = started.ownership;
return ok({
process: started.process,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
ownership: started.ownership,
shutdownByCleanup: true,
shutdownMode: "process-cleanup" as const,
cleanup: () => cleanupOwnedProcessGroup(started.ownership),
});
}
@@ -102,6 +103,29 @@ class UnconfirmedFixtureLauncher implements BridgeLauncher {
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: false,
shutdownMode: "bridge-request" as const,
}),
);
}
}
class UnconfirmedOwnedFixtureLauncher implements BridgeLauncher {
launch(session: BridgeSession) {
return Promise.resolve(
ok({
process: spawn(
process.execPath,
[
fixturePath,
session.socketPath,
session.token,
session.runId,
"unconfirmed",
],
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -183,6 +207,26 @@ describe("HopperClient cleanup", () => {
});
});
it("does not treat an owned launcher exit as bridge document shutdown", async () => {
const client = new HopperClient({
launcher: new UnconfirmedOwnedFixtureLauncher(),
startupTimeoutMs: 1_000,
});
clients.push(client);
expect((await client.start()).ok).toBe(true);
const closed = await client.closeWithOutcome();
expect(closed).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
cleanupIncomplete: true,
cleanupResources: ["hopper-document"],
},
});
});
it("kills only its owned Hopper group and emits sanitized shutdown coordinates", async () => {
const unrelated = spawn(
process.execPath,
@@ -42,7 +42,8 @@ class FixtureLauncher implements BridgeLauncher {
return Promise.resolve(
ok({
process: child,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -45,7 +45,8 @@ class FixtureLauncher implements BridgeLauncher {
return Promise.resolve(
ok({
process: child,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -42,7 +42,8 @@ class FixtureLauncher implements BridgeLauncher {
return Promise.resolve(
ok({
process: child,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -46,7 +46,8 @@ class FixtureLauncher implements BridgeLauncher {
return Promise.resolve(
ok({
process: child,
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -63,7 +64,8 @@ class SilentLauncher implements BridgeLauncher {
stdio: ["ignore", "ignore", "pipe"],
},
),
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -89,7 +91,8 @@ class ExitingLauncher implements BridgeLauncher {
process: spawn(process.execPath, ["-e", `process.exit(${this.code})`], {
stdio: ["ignore", "ignore", "pipe"],
}),
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -126,7 +129,8 @@ class DiagnosticExitingLauncher implements BridgeLauncher {
],
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: true,
ownsProcessLifetime: true as const,
shutdownMode: "bridge-request" as const,
}),
);
}
@@ -49,12 +49,11 @@ const processResult = (
value: HopperStartupDiagnostic,
overrides: Partial<LinuxPrivateDisplayProbeProcessResult> = {},
): LinuxPrivateDisplayProbeProcessResult => ({
outcome: "exited",
exitCode: value.status === "ready" ? 0 : failureExit(value.failure_code),
stderr: `${LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX}${JSON.stringify(value)}\n`,
stderrBytes: 0,
stderrTruncated: false,
timedOut: false,
cancelled: false,
cleanupIncomplete: false,
...overrides,
});
@@ -345,4 +345,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -135,4 +135,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -70,4 +70,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -146,8 +146,12 @@ describe("managed artifact failures", () => {
await client.close();
const nativeClient = new ManagedStaticProvider().createClient({
...parsed.value,
path: parsed.value.path,
sha256: parsed.value.sha256,
kind: "executable",
format: "elf",
architecture: "x86",
availableArchitectures: ["x86"],
});
await expect(
nativeClient.execute("inspect_managed_artifact", {}),
@@ -164,6 +168,8 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
const asManagedResult = (execution: AnalysisExecution) =>
@@ -168,4 +168,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -137,4 +137,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -151,4 +151,6 @@ const target = (bytes: Buffer): BinaryTarget => ({
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
@@ -300,6 +300,9 @@ const inspect = (
kind: "executable",
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
};
const result = inspectManagedMembersBytes(bytes, target, limits);
return {
@@ -151,11 +151,11 @@ const inventory = async (targetValue: BinaryTarget) => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -126,13 +126,13 @@ const inventory = async (targetValue: BinaryTarget) => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
const limits = () => ({ maxDepth: 20, maxPathBytes: 4_096 });
@@ -79,11 +79,11 @@ describe("artifact directory inventory", () => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -130,11 +130,11 @@ const inventory = async (targetValue: BinaryTarget) => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -106,11 +106,11 @@ describe("artifact pagination and slices", () => {
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { projectNativeApiInspection } from "../../../../src/application/NativeApiInspection.js";
import { functionDossierSchema } from "../../../../src/domain/hopperValues.js";
import { nativeApiBoundarySchema } from "../../../../src/domain/nativeApiBoundary.js";
import { ghidraFunctionDossier } from "../../../fixtures/ghidraFunction.js";
describe("native API inspection", () => {
@@ -59,4 +60,30 @@ describe("native API inspection", () => {
],
});
});
it("rejects boundary types placed in the wrong ABI role", () => {
const boundary = functionDossierSchema.parse(
ghidraFunctionDossier(),
).native_api;
if (boundary === null || boundary.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
expect(
nativeApiBoundarySchema.safeParse({
...boundary,
return_type: { ...boundary.return_type, role: "parameter" },
}).success,
).toBe(false);
expect(
nativeApiBoundarySchema.safeParse({
...boundary,
parameters: [
{
...boundary.return_type,
role: "return",
},
],
}).success,
).toBe(false);
});
});
@@ -7,6 +7,7 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { runControlledReplay } from "../../../../src/application/JavaScriptReplayService.js";
import type {
EnabledJavaScriptReplayPolicy,
JavaScriptReplayHost,
JavaScriptReplayPolicy,
JavaScriptReplayRunner,
@@ -19,8 +20,8 @@ import {
} from "../../../../src/domain/javascriptReplay.js";
const root = resolve("tests/fixtures/replay");
const policy: JavaScriptReplayPolicy = {
enabled: true,
const policy: EnabledJavaScriptReplayPolicy = {
status: "enabled",
roots: [root],
nodePath: process.execPath,
bubblewrapPath: process.execPath,
@@ -127,7 +128,7 @@ const input = (
entry_export: "default",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
approved: mode === "execute",
...(mode === "execute" ? { approved: true as const } : {}),
});
const completedRunner = (): JavaScriptReplayRunner => ({
@@ -153,6 +154,45 @@ const completedRunner = (): JavaScriptReplayRunner => ({
});
describe("controlled JavaScript replay planning", () => {
it("parses planning and execution as disjoint legal states", () => {
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
approved: false,
plan_digest: "0".repeat(64),
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
approved: true,
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
plan_digest: "0".repeat(64),
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("plan"),
approved: true,
}).success,
).toBe(false);
expect(
controlledReplayInputSchema.safeParse({
...input("execute"),
approved: true,
plan_digest: "0".repeat(64),
reproducer_export: {
path: "/tmp/reproducer",
approved: false,
},
}).success,
).toBe(false);
});
it("rejects relative paths and more than 128 combined cases", () => {
expect(
controlledReplayInputSchema.safeParse({
@@ -180,7 +220,7 @@ describe("controlled JavaScript replay planning", () => {
const readSource = vi.fn(host.readSource);
const result = await runControlledReplay(
{
policy,
policy: () => policy,
host: { ...host, probe, readSource },
runner: completedRunner(),
authority: authority(),
@@ -199,11 +239,21 @@ describe("controlled JavaScript replay planning", () => {
it("returns a deterministic plan without admitting application code", async () => {
const execute = vi.fn(completedRunner().execute);
const first = await runControlledReplay(
{ policy, host, runner: { execute }, authority: authority() },
{
policy: () => policy,
host,
runner: { execute },
authority: authority(),
},
input("plan"),
);
const second = await runControlledReplay(
{ policy, host, runner: { execute }, authority: authority() },
{
policy: () => policy,
host,
runner: { execute },
authority: authority(),
},
input("plan"),
);
expect(first).toEqual(second);
@@ -213,12 +263,26 @@ describe("controlled JavaScript replay planning", () => {
plan: { network: "none", filesystem: { host_writes: false } },
evidence: null,
});
if (!first.ok) throw first.error;
const output = controlledReplayOutputSchema.parse(first.value);
expect(
controlledReplayOutputSchema.safeParse({ ...output, plan: null }).success,
).toBe(false);
expect(
controlledReplayOutputSchema.safeParse({ ...output, phase: "execute" })
.success,
).toBe(false);
});
it("rejects a stale digest before worker admission", async () => {
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{ policy, host, runner: { execute }, authority: authority() },
{
policy: () => policy,
host,
runner: { execute },
authority: authority(),
},
{ ...input("execute"), plan_digest: "0".repeat(64) },
);
expect(result.ok).toBe(false);
@@ -227,10 +291,30 @@ describe("controlled JavaScript replay planning", () => {
});
});
describe("controlled JavaScript replay policy snapshots", () => {
it("uses one enabled policy snapshot for the complete planning operation", async () => {
let reads = 0;
const configuredPolicy = (): JavaScriptReplayPolicy => {
reads += 1;
return reads === 1 ? policy : { status: "disabled" };
};
const result = await runControlledReplay(
{
policy: configuredPolicy,
host,
runner: completedRunner(),
authority: authority(),
},
input("plan"),
);
expect([result.ok, reads]).toEqual([true, 1]);
});
});
describe("controlled JavaScript replay evidence and authorization", () => {
it("creates controlled-replay Evidence after an approved exact plan", async () => {
const dependencies = {
policy,
policy: () => policy,
host,
runner: completedRunner(),
authority: authority(),
@@ -272,6 +356,12 @@ describe("controlled JavaScript replay evidence and authorization", () => {
expect(output.evidence?.evidence_links).toEqual([
output.source_evidence[0]?.evidence_id,
]);
expect(
controlledReplayOutputSchema.safeParse({
...output,
source_evidence: [],
}).success,
).toBe(false);
});
it("cannot read or execute when replay is disabled", async () => {
@@ -279,7 +369,7 @@ describe("controlled JavaScript replay evidence and authorization", () => {
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{
policy: { ...policy, enabled: false },
policy: () => ({ status: "disabled" }),
host: { ...host, readSource },
runner: { execute },
authority: authority(),
@@ -293,7 +383,7 @@ describe("controlled JavaScript replay evidence and authorization", () => {
it("changes the commitment when selected module bytes change", async () => {
const dependencies = {
policy,
policy: () => policy,
host,
runner: completedRunner(),
authority: authority(),
@@ -333,7 +423,7 @@ describe("controlled JavaScript replay cancellation and export", () => {
}),
);
const dependencies = {
policy,
policy: () => policy,
host,
runner: { execute },
authority: authority(),
@@ -365,7 +455,7 @@ describe("controlled JavaScript replay cancellation and export", () => {
const execute = vi.fn(completedRunner().execute);
const result = await runControlledReplay(
{
policy,
policy: () => policy,
host: {
...host,
probe: async () => {
@@ -387,7 +477,7 @@ describe("controlled JavaScript replay cancellation and export", () => {
const directory = await createTestTempDirectory("rea-reproducer-test-");
const path = join(directory, "reproducer.json");
const dependencies = {
policy,
policy: () => policy,
host,
runner: completedRunner(),
authority: authority(directory),
@@ -66,6 +66,20 @@ const request = async (
});
describe("disposable JavaScript replay worker", () => {
it("rejects malformed runtime-hop requests before loading modules", async () => {
const result = await runWorker({
schemaVersion: 1,
left: { modules: "not-an-array", entryAlias: "entry", entryExport: "x" },
cases: [],
determinism: { clockIso: "2000-01-01T00:00:00.000Z", randomSeed: 7 },
limits: { resultDepth: 16, resultNodes: 10_000, exceptionBytes: 4096 },
});
expect(result.code).toBe(70);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("Invalid replay worker modules");
});
it("runs an ESM parser with projected plain data", async () => {
const result = await runWorker(
await request("parser.mjs", "esm", "default", ["# Title"]),
@@ -19,14 +19,14 @@ describe("replay worker protocol", () => {
parseReplayWorkerResponse(
{ schema_version: 1, left: [outcome] },
cases,
false,
"single",
),
).toMatchObject({ left: [outcome] });
expect(() =>
parseReplayWorkerResponse(
{ schema_version: 1, left: [{ ...outcome, case_id: "forged" }] },
cases,
false,
"single",
),
).toThrow("case identity changed");
expect(() =>
@@ -36,7 +36,7 @@ describe("replay worker protocol", () => {
left: [{ ...outcome, input_sha256: "2".repeat(64) }],
},
cases,
false,
"single",
),
).toThrow("case identity changed");
});
@@ -46,9 +46,9 @@ describe("replay worker protocol", () => {
parseReplayWorkerResponse(
{ schema_version: 1, left: [outcome] },
cases,
true,
"differential",
),
).toThrow("differential response is incomplete");
).toThrow();
expect(() =>
parseReplayWorkerResponse(
{
@@ -56,7 +56,7 @@ describe("replay worker protocol", () => {
left: [{ ...outcome, unexpected: true }],
},
cases,
false,
"single",
),
).toThrow();
expect(() =>
@@ -66,8 +66,8 @@ describe("replay worker protocol", () => {
left: [{ ...outcome, outcome: "exception", value: undefined }],
},
cases,
false,
"single",
),
).toThrow("Exception is missing");
).toThrow();
});
});