chore: merge current main into PR #2791

This commit is contained in:
morluto
2026-10-13 23:57:24 +08:00
177 changed files with 7940 additions and 1054 deletions
@@ -4,6 +4,40 @@ import {
recordedCrashFixtureBytes,
} from "../../fixtures/binaryDiagnostics/recordedCrash.js";
import { validateRecordedCrashStructure } from "../../../src/native/pwntools/RecordedCrashStructureBindings.js";
import { RECORDED_LINUX_CORE_PROFILES } from "../../../src/domain/native/recordedCrash.js";
it.each(["x86_64-little-endian", "aarch64-little-endian"] as const)(
"admits a %s core whose header carries that profile's e_machine",
(architecture) => {
const report = recordedCrashFixture(undefined, architecture);
expect(() =>
validateRecordedCrashStructure(
report,
recordedCrashFixtureBytes(report),
report.decoder_diagnostics,
),
).not.toThrow();
},
);
it.each([
["x86_64-little-endian", "aarch64-little-endian"],
["aarch64-little-endian", "x86_64-little-endian"],
] as const)(
"rejects a %s report whose header carries the other profile's e_machine",
(reported, embedded) => {
const report = recordedCrashFixture(undefined, reported);
const snapshot = recordedCrashFixtureBytes(report);
snapshot.writeUInt16LE(RECORDED_LINUX_CORE_PROFILES[embedded].machine, 18);
expect(() =>
validateRecordedCrashStructure(
report,
snapshot,
report.decoder_diagnostics,
),
).toThrow(/Reported core structure differs/);
},
);
it.each([
[6, 0],
@@ -1,5 +1,8 @@
import type { AnalysisError } from "../../../src/domain/analysisErrorBase.js";
import type { RecordedCrash } from "../../../src/domain/native/recordedCrash.js";
import type {
RecordedCrash,
RecordedCrashArchitecture,
} from "../../../src/domain/native/recordedCrash.js";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
@@ -48,6 +51,7 @@ it
.runIf(host)
.each([
"success",
"success-aarch64",
"wrong-register",
"wrong-register-source",
"missing-thread",
@@ -77,9 +81,13 @@ it
] as const)(
"validates recorded source bytes and cleanup: %s",
async (scenario) => {
const architecture = scenario.endsWith("aarch64")
? "aarch64-little-endian"
: "x86_64-little-endian";
const { path, value, bytes } = await fixture(
true,
scenario === "wrong-owner-display",
architecture,
);
if (scenario.startsWith("wrong-ei-version-"))
bytes[6] = Number(scenario.at(-1));
@@ -123,8 +131,9 @@ it
path,
include_debugger_context: false,
});
if (scenario === "success") {
if (scenario === "success" || scenario === "success-aarch64") {
if (!result.ok) throw result.error;
expect(result.value.architecture).toBe(architecture);
expect(result.value.threads).toEqual(value.threads);
expect(result.value.diagnostics.stdout).toBe("recorded warning");
} else
@@ -340,13 +349,17 @@ const expectOptionalContextFailure = (
});
};
const fixture = async (includeSignal = false, opaqueOwner = false) => {
const fixture = async (
includeSignal = false,
opaqueOwner = false,
architecture: RecordedCrashArchitecture = "x86_64-little-endian",
) => {
const workspace = await createTestWorkspace("rea-recorded-core-seam-");
onTestFinished(() => removeTestWorkspace(workspace.root));
const path = join(workspace.root, "recorded.core");
const value = includeSignal
? recordedCrashSignalFixture(path)
: recordedCrashFixture(path);
? recordedCrashSignalFixture(path, architecture)
: recordedCrashFixture(path, architecture);
if (opaqueOwner) {
value.notes = value.notes.map((note) =>
note.index === 0
@@ -0,0 +1,92 @@
import { expect, it } from "vitest";
import { Cli } from "incur";
import pino from "pino";
import type { ApktoolResourceAnalysisPort } from "../../../src/application/apktool/ApktoolResourceAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { registerApktoolCommands } from "../../../src/cli/apktoolCommands.js";
import { presentOmittableDefaults } from "../../../src/cli/omittableDefaults.js";
import type { ApktoolRequest } from "../../../src/domain/apktool/apktoolResourceAnalysis.js";
import { ok } from "../../../src/domain/result.js";
const invoke = async (argv: readonly string[]) => {
const requests: ApktoolRequest[] = [];
const provider: ApktoolResourceAnalysisPort = {
async inspectAvailability() {
throw new Error("unexpected provider probe");
},
async close() {},
async execute(request) {
requests.push(request);
return ok(
createAnalysisExecution(
{ strings: [] },
{ id: "apktool", name: "Apktool", version: null },
),
);
},
};
const cli = Cli.create("rea", { sync: false });
registerApktoolCommands(cli, pino({ level: "silent" }), {}, provider);
presentOmittableDefaults(cli);
let stdout = "";
let exitCode = 0;
await cli.serve([...argv], {
env: {},
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
});
return { exitCode, stdout, requests };
};
/**
* Locales the apktool input owner admits. The owner's own rejection message
* advertises `b+zh+Hans+CN`, so the CLI cannot be narrower than this list
* without refusing a caller-selected locale the decoding lane supports.
*/
const OWNER_ADMITTED_LOCALES = [
"de",
"pt-BR",
"pt-rBR",
"zh-rCN",
"en-419",
"b+zh+Hans+CN",
] as const;
it("forwards every locale the apktool input owner admits", async () => {
for (const locale of OWNER_ADMITTED_LOCALES) {
const result = await invoke([
"decode-android-resources",
"/targets/app.apk",
"--locale",
locale,
"--json",
]);
expect(result.exitCode, `exit code for locale ${locale}`).toBe(0);
expect(result.requests, `request for locale ${locale}`).toEqual([
{
operation: "decode_android_resources",
input: { path: "/targets/app.apk", include_strings: true, locale },
},
]);
}
});
it("still refuses a locale the apktool input owner refuses", async () => {
const result = await invoke([
"decode-android-resources",
"/targets/app.apk",
"--locale",
"not a locale",
"--json",
]);
expect(result.exitCode).not.toBe(0);
expect(result.requests).toEqual([]);
});
+36 -57
View File
@@ -188,8 +188,12 @@ it("closes the service and retains an unexpected producer rejection", async () =
});
});
it("rejects an oversized selector budget before the CLI invokes its service", async () => {
const cli = Cli.create("capture-selector-test", { sync: false });
/** Serve one inspection request whose service must never be reached. */
const rejectBeforeService = async (
name: string,
args: string[],
): Promise<string> => {
const cli = Cli.create(name, { sync: false });
let called = false;
registerCaptureCommands(
cli,
@@ -207,66 +211,41 @@ it("rejects an oversized selector budget before the CLI invokes its service", as
},
);
let stdout = "";
await cli.serve(
[
"inspect-packet-capture",
"recording.pcap",
"--fields",
"x".repeat(8192),
"--display_filter",
"界".repeat(8192),
"--format",
"json",
],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
await cli.serve(args, {
stdout: (text) => {
stdout += text;
},
);
exit: () => {},
});
expect(called).toBe(false);
return stdout;
};
it("rejects an oversized selector budget before the CLI invokes its service", async () => {
const stdout = await rejectBeforeService("capture-selector-test", [
"inspect-packet-capture",
"recording.pcap",
"--fields",
"x".repeat(8192),
"--display_filter",
"界".repeat(8192),
"--format",
"json",
]);
expect(stdout).toContain("32 KiB");
});
it("rejects conflicting output options before the CLI invokes its service", async () => {
const cli = Cli.create("capture-window-test", { sync: false });
let called = false;
registerCaptureCommands(
cli,
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
called = true;
throw new Error("Must not inspect");
},
close: async () => {},
},
);
let stdout = "";
await cli.serve(
[
"inspect-packet-capture",
"recording.pcap",
"--fields",
"ip.addr",
"--all_matches",
"--match_limit",
"20",
"--format",
"json",
],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(called).toBe(false);
const stdout = await rejectBeforeService("capture-window-test", [
"inspect-packet-capture",
"recording.pcap",
"--fields",
"ip.addr",
"--all_matches",
"--match_limit",
"20",
"--format",
"json",
]);
expect(stdout).toContain("mutually exclusive");
});
@@ -287,9 +287,12 @@ cliTest("uninstall names each retained skill directory", async ({ cli }) => {
};
const skill = report.items?.find(({ name }) => name === "skill");
expect(skill?.status).toBe("retained");
for (const directory of [shared, claude]) {
for (const [client, directory] of [
["shared", shared],
["claude_code", claude],
]) {
expect(skill?.detail).toContain(
`${directory}: retained (Skill manifest is not REA-owned.)`,
`${client} (${directory}): retained (Skill manifest is not REA-owned.)`,
);
expect(await readFile(join(directory, "SKILL.md"), "utf8")).toBe(
"---\nname: unrelated\n---\n",
@@ -0,0 +1,130 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { buffer } from "node:stream/consumers";
import { setImmediate } from "node:timers/promises";
import { expect, it } from "vitest";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import { readAsarListing } from "../../../src/artifacts/AsarListing.js";
import {
asarHeaderBytes,
nestedAsarHeader,
} from "../../fixtures/asarHeader.js";
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const archiveWith = async (bytes: Buffer) => {
const root = await createTestTempDirectory("rea-asar-listing-");
const path = join(root, "app.asar");
await writeFile(path, bytes);
return path;
};
it("interrupts expanded listing admission between traversal batches", async () => {
const controller = new AbortController();
const header = {
files: Object.fromEntries(
Array.from({ length: 4000 }, (_, index) => [
`f${index}`,
{ size: 0, offset: "0" },
]),
),
};
const listing = readAsarListing(header, controller.signal);
await setImmediate();
controller.abort();
await expect(listing).rejects.toMatchObject({ reason: "cancelled" });
});
it("rejects path expansion before publishing any inventory, preserving the input", async () => {
const bytes = nestedAsarHeader(64, "d".repeat(256), 4000);
expect(bytes.length).toBeLessThan(150_000);
const path = await archiveWith(bytes);
await expect(inventoryArtifact(path)).rejects.toMatchObject({
reason: "limit",
message: "ASAR expanded listing exceeds its 64 MiB representation budget",
});
expect(await readFile(path)).toEqual(bytes);
});
it("reads deeply nested packed metadata without recursive listing or member lookup", async () => {
const path = await archiveWith(nestedAsarHeader(3500, "d", 1));
const reader = new AsarArtifactReader(path);
try {
let count = 0;
for await (const entry of reader.entries()) {
count++;
if (entry.kind === "file") {
expect(entry.path).toBe(`${"d/".repeat(3500)}f0`);
expect(await buffer(await reader.open(entry))).toEqual(Buffer.alloc(0));
}
}
expect(count).toBe(3501);
} finally {
await reader.close();
}
});
it.each(["..", ".", "", "a/../b", "a/b", "a\0b"])(
"rejects raw ASAR component %j before host normalization can alias another entry",
async (component) => {
const json = JSON.stringify({
files: { [component]: { size: 0, offset: "0" } },
});
await expect(
inventoryArtifact(await archiveWith(asarHeaderBytes(json))),
).rejects.toMatchObject({ reason: "path" });
},
);
it("orders raw names portably and retains prototype-named entries and links", async () => {
const path = await archiveWith(
asarHeaderBytes(
'{"files":{"a0":{"size":0,"offset":"0"},"__proto__":{"size":0,"offset":"0"},"a":{"files":{"b":{"link":"a0"}}},"😀":{"size":0,"offset":"0"},"\uE000":{"size":0,"offset":"0"}}}',
),
);
const reader = new AsarArtifactReader(path);
try {
const entries = [];
for await (const entry of reader.entries())
entries.push([entry.path, entry.kind]);
expect(entries).toEqual([
["__proto__", "file"],
["a", "directory"],
["a/b", "symlink"],
["a0", "file"],
["\uE000", "file"],
["😀", "file"],
]);
} finally {
await reader.close();
}
});
it("preserves POSIX literal backslashes and rejects Windows component separators", async () => {
const path = await archiveWith(
asarHeaderBytes(
JSON.stringify({ files: { "a\\b": { size: 0, offset: "0" } } }),
),
);
const reader = new AsarArtifactReader(path);
try {
const list = async () => {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
return entries;
};
if (process.platform === "win32") {
await expect(list()).rejects.toMatchObject({ reason: "path" });
} else {
const entries = await list();
expect(entries).toHaveLength(1);
expect(entries[0]?.path).toBe("a\\b");
expect(await buffer(await reader.open(entries[0]!))).toEqual(
Buffer.alloc(0),
);
}
} finally {
await reader.close();
}
});
@@ -64,6 +64,7 @@ describe("client configuration filesystem lifecycle", () => {
"copilot_cli",
"commandcode",
"qwen_code",
"kimi",
"vscode",
"trae",
"grok_build",
@@ -1895,14 +1896,11 @@ describe("client configuration filesystem failure reporting", () => {
remove: () => Promise.reject(new Error("SECRET removal failure")),
}),
);
expect(result.items).toContainEqual(
expect.objectContaining({
name: "skill",
status: "failed",
detail: expect.stringContaining(
`Managed file could not be removed: ${join(skillRoot, "SKILL.md")}`,
),
}),
const skillItem = result.items.find(({ name }) => name === "skill");
expect(skillItem?.status).toBe("failed");
expect(skillItem?.detail).toContain(`shared (${skillRoot}): failed (`);
expect(skillItem?.detail).toContain(
`Managed file could not be removed: ${join(skillRoot, "SKILL.md")}`,
);
expect(JSON.stringify(result)).not.toContain("SECRET");
expect(await readFile(join(skillRoot, "SKILL.md"), "utf8")).toBe(
@@ -1944,6 +1942,42 @@ describe("client configuration filesystem failure reporting", () => {
});
});
describe("skill root client identifier labels", () => {
it("labels each retained or removed skill root by its client identifier", async () => {
const home = await createTestTempDirectory("rea-uninstall-skill-labels-");
roots.push(home);
const customClaudeDirectory = join(home, "claude-config");
const sharedRoot = join(home, ".agents/skills/reverse-engineer-anything");
const claudeRoot = join(
customClaudeDirectory,
"skills/reverse-engineer-anything",
);
await mkdir(sharedRoot, { recursive: true });
await mkdir(claudeRoot, { recursive: true });
await writeFile(
join(sharedRoot, "SKILL.md"),
"---\nname: another-skill\n---\n# Not REA-owned\n",
);
await writeFile(join(claudeRoot, "SKILL.md"), ownedSkillManifest);
const skillItem = await systemUninstallHost(home, testFileSystem, {
CLAUDE_CONFIG_DIR: customClaudeDirectory,
}).removeSkill();
expect(skillItem.name).toBe("skill");
expect(skillItem.detail).toContain(`shared (${sharedRoot}): retained (`);
expect(skillItem.detail).toContain(
`claude_code (${claudeRoot}): removed (`,
);
await expect(
readFile(join(claudeRoot, "SKILL.md"), "utf8"),
).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(join(sharedRoot, "SKILL.md"), "utf8")).toContain(
"another-skill",
);
});
});
const testFileSystem: UninstallFileSystem = {
readText: (path) => readFile(path, "utf8"),
copy: (source, destination) =>
@@ -2195,3 +2195,135 @@ describe("DeepSeek Harness caller node metadata", () => {
},
);
});
describe("DeepSeek Harness uninstall of a shared operation", () => {
it("keeps a group patch's own fields and comment when its only row was REA's", async () => {
const { home, client } = await harnessClient();
const entry = canonicalEntry();
await writeFile(
client.configPath,
`- insert:
- id: user-a
name: plugin-a
# caller group patch
- id: tools
config:
sandbox: strict
insert:
- id: rea-mcp
name: "${entry.name}"
config:
serverName: rea
transport: stdio
command: ${entry.config.command}
args: ${JSON.stringify(entry.config.args)}
`,
);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const text = await readFile(client.configPath, "utf8");
expect(parseYaml(text)).toEqual([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
{ id: "tools", config: { sandbox: "strict" } },
]);
expect(text).toContain("# caller group patch");
});
it("keeps an operation's own fields when setup removes a second REA row from it", async () => {
// Setup refuses a REA row in a group patch, so the setup path meets the
// keep rule only on an operation without a selector.
const { home, client } = await harnessClient();
const entry = canonicalEntry();
const row = (launcher: string) => ` - id: rea-mcp
name: "${entry.name}"
config:
serverName: rea
transport: stdio
command: ${launcher}
args: [mcp]
`;
await writeFile(
client.configPath,
`- insert:
${row("first-launcher")}# caller operation
- disabled: false
insert:
${row("second-launcher")}`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text).toContain("# caller operation");
expect(loadedInserts(text)).toHaveLength(1);
expect((parseYaml(text) as unknown[]).at(-1)).toEqual({ disabled: false });
expect(await dshStatus(home)).toMatchObject({ state: "aligned" });
});
it("drops an emptied operation that targets REA's own row", async () => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
stringifyYaml([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
{
id: "rea-mcp",
config: { serverName: "rea" },
insert: [canonicalEntry()],
},
]),
);
const host = systemUninstallHost(home);
expect((await host.removeClient(client)).status).toBe("removed");
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
]);
});
it.each([
{ selector: { id: "tools" } },
{ selector: { name: "tools" } },
{ selector: { id: "tools", name: "tools" } },
])(
"drops an emptied operation left with only its target selector $selector",
async ({ selector }) => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
stringifyYaml([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
{ ...selector, insert: [canonicalEntry()] },
]),
);
expect(
(await systemUninstallHost(home).removeClient(client)).status,
).toBe("removed");
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
]);
},
);
it("still drops an insert-only operation that REA's row emptied", async () => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
stringifyYaml([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
{ insert: [canonicalEntry()] },
]),
);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
]);
});
});
+16 -21
View File
@@ -209,13 +209,7 @@ describe("installer TTY fallback", { timeout: 20_000 }, () => {
cwd: process.cwd(),
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"),
...installerEnvironment(fixture),
TERM: "xterm-256color",
},
name: "xterm-256color",
@@ -581,6 +575,19 @@ const executable = async (path: string, source: string): Promise<void> => {
await chmod(path, 0o755);
};
/** Fixture-owned installer environment shared by the exec, pipe and PTY runs. */
const installerEnvironment = (
fixture: InstallerFixture,
): Record<string, string> => ({
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"),
});
const runInstaller = async (
fixture: InstallerFixture,
args: readonly string[] = [],
@@ -590,13 +597,7 @@ const runInstaller = async (
execFileAsync("/bin/bash", [script, ...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"),
...installerEnvironment(fixture),
...overrides,
},
});
@@ -618,13 +619,7 @@ const runPipedInstaller = async (
new Promise((resolve, reject) => {
const child = spawn("/bin/bash", ["-s", "--", ...args], {
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"),
...installerEnvironment(fixture),
...overrides,
},
stdio: ["pipe", "pipe", "pipe"],
@@ -405,12 +405,16 @@ describe("keyed archive hierarchy coverage", () => {
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
const archive = join(resources, "Foundation.nib");
await compile("/usr/bin/xcrun", [
"swift",
"tests/conformance/native/keyed-archive-hierarchy.swift",
archive,
"40",
]);
await compile(
"/usr/bin/xcrun",
[
"swift",
"tests/conformance/native/keyed-archive-hierarchy.swift",
archive,
"40",
],
{ timeout: 90_000 },
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
@@ -431,6 +435,7 @@ describe("keyed archive hierarchy coverage", () => {
),
).toHaveLength(41);
},
120_000,
);
});
@@ -0,0 +1,384 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { setupRegistrationCommand } from "../../../src/application/SetupHost.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import {
clientSkillDirectories,
supportedClients,
} from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { MCP_STARTUP_POLICY } from "../../../src/mcpStartupPolicy.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
clearClientLocationEnvironment,
NPX_REGISTRATION_COMMAND,
} from "../../fixtures/clientEnvironment.js";
const command = NPX_REGISTRATION_COMMAND;
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const kimiPath = (
home: string,
platform: NodeJS.Platform,
env: Parameters<typeof supportedClients>[2] = {},
) => supportedClients(home, platform, env).find(({ name }) => name === "kimi");
const exists = async (path: string): Promise<boolean> => {
try {
await access(path);
return true;
} catch {
return false;
}
};
const expectedRegistration = (launcher: readonly string[]) => ({
command: launcher[0],
args: launcher.slice(1),
startupTimeoutMs: MCP_STARTUP_POLICY.kimiStartupTimeoutMs,
toolTimeoutMs: MCP_STARTUP_POLICY.kimiToolTimeoutMs,
});
describe("Kimi Code configuration paths and skills", () => {
it.each([
[undefined, join("/home/a/.kimi-code")],
["", join("/home/a/.kimi-code")],
[join("/tmp", "isolated-kimi"), join("/tmp", "isolated-kimi")],
])("resolves KIMI_CODE_HOME for %j", (override, directory) => {
const client = kimiPath(
"/home/a",
"linux",
override === undefined ? {} : { KIMI_CODE_HOME: override },
);
expect(client).toEqual({
name: "kimi",
displayName: "Kimi Code",
configPath: join(directory, "mcp.json"),
markerPath: directory,
format: "kimi",
});
});
it("uses the existing shared skill destination without a separate skill root", () => {
expect(clientSkillDirectories("/home/a", ["kimi"])).toEqual([
{ client: "shared", directory: "/home/a/.agents/skills" },
]);
});
});
describe("Kimi Code registration lifecycle", () => {
const kimiClient = async () => {
const home = await createTestTempDirectory("rea-kimi-");
const client = kimiPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Kimi Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("preserves the caller's enabledTools selection during refresh", async () => {
const { client } = await kimiClient();
const enabledTools = ["binary_session", "analyze_javascript_application"];
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: { command: "old-rea", args: ["mcp"], enabledTools },
},
}),
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(
JSON.parse(await readFile(client.configPath, "utf8")).mcpServers.rea,
).toEqual({
...expectedRegistration(command),
enabledTools,
});
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("unchanged");
});
it("registers without type, preserves unrelated settings, backs up, and is idempotent", async () => {
const { home, client } = await kimiClient();
const original = `{
"customSetting": { "enabled": true },
"mcpServers": {
"other": { "command": "other-server", "startupTimeoutMs": 5000 }
}
}
`;
await writeFile(client.configPath, original);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "configured",
backupPath: `${client.configPath}.rea.backup`,
});
const text = await readFile(client.configPath, "utf8");
expect(JSON.parse(text)).toEqual({
customSetting: { enabled: true },
mcpServers: {
other: { command: "other-server", startupTimeoutMs: 5000 },
rea: expectedRegistration(command),
},
});
expect(text).not.toContain('"type"');
expect(text).not.toContain('"transport"');
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
original,
);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(await readFile(client.configPath, "utf8")).toBe(text);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command });
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(JSON.parse(await readFile(client.configPath, "utf8"))).toEqual({
customSetting: { enabled: true },
mcpServers: {
other: { command: "other-server", startupTimeoutMs: 5000 },
},
});
});
});
describe("Kimi Code package launchers", () => {
const kimiClient = async () => {
const home = await createTestTempDirectory("rea-kimi-launcher-");
const client = kimiPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Kimi Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client } as const;
};
it.each([
["npx", "linux"],
["bunx", "linux"],
["npx", "win32"],
["bunx", "win32"],
] as const)(
"keeps the %s launcher aligned on %s",
async (runner, platform) => {
const { home, client } = await kimiClient();
const launcher = setupRegistrationCommand(platform, runner);
expect(
(await configureClientConfiguration(client, {}, launcher)).status,
).toBe("configured");
expect(
JSON.parse(await readFile(client.configPath, "utf8")).mcpServers.rea,
).toEqual(expectedRegistration(launcher));
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform,
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command: launcher });
expect(await configureClientConfiguration(client, {}, launcher)).toEqual({
status: "unchanged",
});
},
);
});
describe("Kimi Code transport validation", () => {
const kimiClient = async () => {
const home = await createTestTempDirectory("rea-kimi-validation-");
const client = kimiPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Kimi Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("creates a registration in a zero-byte file and accepts whitespace-only files", async () => {
const { home, client } = await kimiClient();
for (const original of ["", " \n\t"]) {
await writeFile(client.configPath, original);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(
JSON.parse(await readFile(client.configPath, "utf8")).mcpServers.rea,
).toEqual(expectedRegistration(command));
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(await systemUninstallHost(home).removeClient(client)).status,
).toBe("removed");
}
});
it.each([
'{"mcpServers": {',
'{/* comment */ "mcpServers": {}}',
'{"mcpServers": {},}',
'\uFEFF{"mcpServers": {}}',
])("rejects invalid strict JSON %j without writes", async (original) => {
const { client } = await kimiClient();
await writeFile(client.configPath, original);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "failed",
reason: "readback",
});
expect(await readFile(client.configPath, "utf8")).toBe(original);
expect(await exists(`${client.configPath}.rea.backup`)).toBe(false);
});
it("accepts explicit stdio transport without causing repeated rewrites", async () => {
const { home, client } = await kimiClient();
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
transport: "stdio",
...expectedRegistration(command),
},
},
}),
);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command });
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command });
});
it.each(["sse"])(
"rejects explicit transport %j instead of silently accepting another protocol",
async (transport) => {
const { home, client } = await kimiClient();
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
transport,
...expectedRegistration(command),
},
},
}),
);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "invalid", command: [] });
},
);
});
describe("Kimi Code timeout validation", () => {
const kimiClient = async () => {
const home = await createTestTempDirectory("rea-kimi-timeout-");
const client = kimiPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Kimi Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client } as const;
};
it.each([
["startupTimeoutMs", 1],
["toolTimeoutMs", 1],
["startupTimeoutMs", undefined],
["toolTimeoutMs", undefined],
] as const)("reports stale when %s is %j", async (field, value) => {
const { home, client } = await kimiClient();
const registration = {
...expectedRegistration(command),
[field]: value,
};
await writeFile(
client.configPath,
JSON.stringify({ mcpServers: { rea: registration } }),
);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "stale" });
});
it("uses a direct installed REA command without requiring a package runner", async () => {
const { home, client } = await kimiClient();
const entry = join(home, "scripts", "rea.mjs");
const launcher = [process.execPath, entry, "mcp"];
expect(
(await configureClientConfiguration(client, {}, launcher)).status,
).toBe("configured");
expect(
(
await readClientRegistrationStatuses(home, entry, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command: launcher });
});
it("leaves a foreign rea-key registration out of aligned state", async () => {
const { home, client } = await kimiClient();
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
...expectedRegistration(command),
command: "another-package",
args: ["mcp"],
},
},
}),
);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "stale" });
});
});
@@ -54,6 +54,42 @@ const holdReadHandle = (path: string, reason: string) => {
};
};
/** Linux setup host with its VS Code client configuration directory prepared. */
const preparedVsCodeSetupHost = async (prefix: string) => {
const home = await createTestTempDirectory(prefix);
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home, XDG_CONFIG_HOME: join(home, "xdg") },
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
return { home, host, client };
};
/** Release the held read handle and show host cleanup reuses it as a third attempt. */
const expectCloseReclaimsHandle = async (
host: { close?: () => Promise<string | undefined> },
closeAttempts: readonly object[],
release: () => void,
) => {
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
};
/** Give up on the assertion path: release the handle and let cleanup close it. */
const cleanupHeldHandle = async (
host: { close?: () => Promise<string | undefined> },
release: () => void,
) => {
release();
await host.close?.();
};
it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fails", async () => {
const home = await createTestTempDirectory("rea-uninstall-utf8-close-");
const path = join(home, "client.json");
@@ -77,13 +113,9 @@ it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fa
});
expect(await readFile(path)).toEqual(original);
expect(closeAttempts).toHaveLength(2);
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
release();
await host.close?.();
await cleanupHeldHandle(host, release);
}
});
@@ -126,13 +158,9 @@ describe("ZCode fallback cleanup ownership", () => {
await expect(readFile(client.configPath)).rejects.toMatchObject({
code: "ENOENT",
});
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
release();
await host.close?.();
await cleanupHeldHandle(host, release);
}
},
);
@@ -145,20 +173,9 @@ describe("setup client configuration cleanup ownership", () => {
] as const)(
"stops configuration and retains the %s read owner until host close",
async (encoding, original) => {
const home = await createTestTempDirectory("rea-setup-config-close-");
const environment = {
HOME: home,
XDG_CONFIG_HOME: join(home, "xdg"),
};
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
environment,
const { host, client } = await preparedVsCodeSetupHost(
"rea-setup-config-close-",
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(client.configPath, original);
const { closeAttempts, release } = holdReadHandle(
@@ -210,32 +227,17 @@ describe("setup client configuration cleanup ownership", () => {
expect(closeAttempts[0]).toBe(closeAttempts[1]);
expect(await readFile(client.configPath)).toEqual(original);
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
release();
await host.close?.();
await cleanupHeldHandle(host, release);
}
},
);
it("waits for an admitted configuration read and rejects later admissions", async () => {
const home = await createTestTempDirectory("rea-setup-config-inflight-");
const environment = {
HOME: home,
XDG_CONFIG_HOME: join(home, "xdg"),
};
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
environment,
const { host, client } = await preparedVsCodeSetupHost(
"rea-setup-config-inflight-",
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(client.configPath, '{"servers": {}}\n');
let beginRead!: () => void;
@@ -70,7 +70,7 @@ const failFirstCloses = (path: string) => {
describe("skill regular-file cleanup ownership", () => {
it("retains a failed setup skill read until setup host disposal", async () => {
const home = await createTestTempDirectory("rea-setup-skill-close-");
const [destination] = skillDestinations(home, []);
const [destination] = skillDestinations(home, [], {}, "linux");
if (destination === undefined) throw new Error("Shared skill root missing");
const manifest = join(destination.path, "SKILL.md");
await mkdir(dirname(manifest), { recursive: true });
@@ -1,4 +1,4 @@
import { chmod, realpath, writeFile } from "node:fs/promises";
import { chmod, readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { systemDoctorHost } from "../../../src/application/Doctor.js";
@@ -78,7 +78,7 @@ describe("executable format refusal diagnostics", () => {
});
describe("target route diagnostics", () => {
it.each(["module.wasm", "module.bin", "misleading.js"])(
it.each(["module.wasm", "module.bin", "misleading.js", "misleading.hop"])(
"identifies a WASM v1 header in %s without suggesting native provider installation",
async (name) => {
const directory = await createTestTempDirectory("rea-wasm-target-");
@@ -346,3 +346,68 @@ describe("raw-binary load rejection diagnostics", () => {
});
});
});
describe("caller-selected and inferred target interpretation", () => {
it.each(["archive.hop", "archive.HOP"])(
"preserves inferred database routing for ZIP content named %s",
async (name) => {
const directory = await createTestTempDirectory("rea-zip-database-");
const bytes = Buffer.alloc(22);
bytes.writeUInt32LE(0x06054b50, 0);
const zipPath = join(directory, "archive.zip");
const databasePath = join(directory, name);
await writeFile(zipPath, bytes);
await writeFile(databasePath, bytes);
expect(await parseBinaryTarget(zipPath)).toMatchObject({
ok: true,
value: { kind: "archive", format: "zip" },
});
expect(await parseBinaryTarget(databasePath)).toMatchObject({
ok: true,
value: { kind: "database", format: "analysis-database" },
});
expect(await readFile(databasePath)).toEqual(bytes);
},
);
it("preserves explicit DOS COM interpretation for bytes with a WASM header", async () => {
const directory = await createTestTempDirectory("rea-wasm-explicit-com-");
const path = join(directory, "module.hop");
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
expect(
await parseBinaryTarget(path, { formatHint: "dos-com" }),
).toMatchObject({
ok: true,
value: { kind: "executable", format: "dos-com", architecture: "x86" },
});
});
it.each(["module.wasm", "misleading.hop"])(
"preserves explicitly selected database routing for %s",
async (name) => {
const directory = await createTestTempDirectory(
"rea-wasm-explicit-database-",
);
const path = join(directory, name);
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
expect(
await parseBinaryTarget(path, { targetKind: "database" }),
).toMatchObject({
ok: true,
value: { kind: "database", format: "analysis-database" },
});
},
);
it.each(["ordinary.hop", "ordinary.HOP"])(
"retains automatic database routing for non-WASM %s",
async (name) => {
const directory = await createTestTempDirectory("rea-ordinary-database-");
const path = join(directory, name);
await writeFile(path, "existing database content");
expect(await parseBinaryTarget(path)).toMatchObject({
ok: true,
value: { kind: "database", format: "analysis-database" },
});
},
);
});
+4 -9
View File
@@ -1,3 +1,4 @@
import { advertisedMcpToolSchemas } from "../../fixtures/advertisedMcpTool.js";
import { API_SURFACE_EXAMPLE } from "../../../src/contracts/analysisViewApiSurfaceExample.js";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
@@ -212,16 +213,10 @@ it("advertises exact schemas and projects one layout section from retained Evide
inspect: () => Promise.resolve(ok(layout)),
});
const { client, session } = await connect(service);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_analysis_view",
const { ajv, inputSchema, outputSchema } = await advertisedMcpToolSchemas(
client,
"inspect_analysis_view",
);
if (advertised?.outputSchema === undefined)
throw new Error("inspect_analysis_view must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(inputSchema, {
source: { kind: "inline", evidence: analysisViewLayoutEvidence() },
@@ -0,0 +1,60 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import { nestedAsarHeader } from "../../fixtures/asarHeader.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("reports expanded ASAR admission failure through MCP and permits a valid retry", async () => {
const root = await createTestTempDirectory("rea-asar-listing-mcp-");
const path = join(root, "app.asar");
const bytes = nestedAsarHeader(64, "d".repeat(256), 4000);
await writeFile(path, bytes);
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer({ kind: "session", session });
const client = new Client({ name: "asar-listing-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
expect(
(await client.callTool({ name: "open_binary", arguments: { path } }))
.isError,
).not.toBe(true);
const result = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "truncated",
category: "truncated",
},
});
expect(result.structuredContent).toBeUndefined();
expect(await readFile(path)).toEqual(bytes);
const valid = join(root, "valid.asar");
await writeFile(valid, nestedAsarHeader(1, "lib", 1));
expect(
(
await client.callTool({
name: "open_binary",
arguments: { path: valid },
})
).isError,
).not.toBe(true);
expect(
(await client.callTool({ name: "inspect_artifact", arguments: {} }))
.isError,
).not.toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
+15 -23
View File
@@ -1,9 +1,11 @@
import {
advertisedMcpToolSchemas,
assertRecordedMcpEvidence,
} from "../../fixtures/advertisedMcpTool.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { BinaryLayoutService } from "../../../src/application/binaryDiagnostics/BinaryLayoutService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
@@ -43,16 +45,11 @@ it("advertises exact valid schemas and records inline layout without a binary ta
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_binary_layout",
const schemas = await advertisedMcpToolSchemas(
client,
"inspect_binary_layout",
);
if (advertised?.outputSchema === undefined)
throw new Error("layout must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const { ajv, inputSchema } = schemas;
expect(ajv.validate(inputSchema, { path: value.artifact.path })).toBe(true);
expect(
ajv.validate(inputSchema, {
@@ -64,19 +61,14 @@ it("advertises exact valid schemas and records inline layout without a binary ta
name: "inspect_binary_layout",
arguments: { path: value.artifact.path },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_binary_layout").outputSchema.parse(
response.structuredContent,
const evidence = assertRecordedMcpEvidence(
response,
"inspect_binary_layout",
schemas,
session,
value,
"observed",
);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const viewed = await client.callTool({
name: "inspect_analysis_view",
arguments: {
@@ -49,6 +49,9 @@ const observeAgain = (
result,
confidence: source.confidence,
authority: source.authority,
...(source.relationship_coverage === null
? {}
: { relationshipCoverage: source.relationship_coverage }),
},
);
+15 -21
View File
@@ -1,3 +1,7 @@
import {
advertisedMcpToolSchemas,
assertRecordedMcpEvidence,
} from "../../fixtures/advertisedMcpTool.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createHash } from "node:crypto";
import { Ajv2020 } from "ajv/dist/2020.js";
@@ -66,16 +70,11 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_evm_interface",
const schemas = await advertisedMcpToolSchemas(
client,
"inspect_evm_interface",
);
if (advertised?.outputSchema === undefined)
throw new Error("EVM interface inspection must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const { ajv, inputSchema } = schemas;
expect(
ajv.validate(inputSchema, { path: value.artifact.path, encoding: "hex" }),
).toBe(true);
@@ -99,19 +98,14 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
name: "inspect_evm_interface",
arguments: { path: value.artifact.path, encoding: "hex" },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_evm_interface").outputSchema.parse(
response.structuredContent,
assertRecordedMcpEvidence(
response,
"inspect_evm_interface",
schemas,
session,
value,
"inferred",
);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("inferred");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
await client.callTool({
+270 -2
View File
@@ -5,9 +5,277 @@ import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { nativeAotPeFixture } from "../../fixtures/nativeaotPe.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
import { err, ok } from "../../../src/domain/result.js";
import { ghidraFunctionIdentity } from "../../../src/domain/ghidraValues.fixture.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
import {
connectGhidraMcp,
ghidraInstallationHost,
sessionEvidence,
} from "./ghidraMcpHarness.js";
import { spawn } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { GhidraClient } from "../../../src/ghidra/GhidraClient.js";
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { silentLogger } from "../../../src/logger.js";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { createServer } from "../../../src/server/createServer.js";
import { waitForExit } from "../../support/process/processFixture.js";
import { GhidraSessionError } from "../../../src/ghidra/GhidraSessionError.js";
it("retains byte-search coverage and rejects malformed pages before creating Evidence", async () => {
const page = {
matches: [
{
address: "0x401000",
segment: ".text",
file_offset: null,
procedure: null,
},
],
searched: {
blocks: [
{ segment: ".text", start: "0x401000", end: "0x40100f", bytes: 16 },
],
bytes: 16,
skipped_uninitialized: [
{ segment: ".bss", start: "0x402000", end: "0x40200f", bytes: 16 },
],
skipped_not_loaded: [
{ segment: ".symtab", start: "0x0", end: "0x17f", bytes: 384 },
],
},
complete: false,
next_cursor: "continuation",
};
let output = jsonValueSchema.parse(page);
const harness = await connectGhidraMcp("byte-search-projection", () =>
Promise.resolve(ok(output)),
);
try {
const first = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "48 ??", limit: 1 },
});
expect(first.isError).not.toBe(true);
expect(
sessionEvidence(harness.session, first.structuredContent)
.normalized_result,
).toEqual(page);
output = jsonValueSchema.parse({
...page,
matches: [],
complete: true,
next_cursor: null,
});
const last = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "48 ??", cursor: "continuation" },
});
expect(last.isError).not.toBe(true);
expect(
sessionEvidence(harness.session, last.structuredContent)
.normalized_result,
).toEqual(output);
output = jsonValueSchema.parse({ ...page, complete: true });
const malformed = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "49 ??" },
});
expect(parseMcpToolError(malformed)).toMatchObject({
error: { code: "unreadable_output" },
});
for (const block of [
{ segment: ".text", start: "0x1000", end: "0x1009", bytes: 1 },
{ segment: ".text", start: "0x1009", end: "0x1000", bytes: 1 },
{ segment: ".text", start: "overlay:0x1000", end: "0x1000", bytes: 1 },
{ segment: ".text", start: "invalid", end: "0x1000", bytes: 1 },
]) {
output = jsonValueSchema.parse({
...page,
searched: { ...page.searched, blocks: [block], bytes: block.bytes },
});
const invalidCoverage = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "48 ??" },
});
expect(parseMcpToolError(invalidCoverage)).toMatchObject({
error: { code: "unreadable_output" },
});
expect(invalidCoverage.structuredContent).toBeUndefined();
}
const calls = harness.calls.length;
for (const args of [{ pattern: "??" }, { pattern: "48", mask: "ffff" }]) {
const invalid = await harness.mcp.callTool({
name: "search_bytes",
arguments: args,
});
expect(invalid.isError).toBe(true);
expect(JSON.stringify(invalid.content)).toContain(
"Input validation error",
);
}
expect(harness.calls).toHaveLength(calls);
} finally {
await harness.close();
}
});
it("projects cancelled byte searches as typed failures without successful partial Evidence", async () => {
const harness = await connectGhidraMcp("byte-search-cancelled", () =>
Promise.resolve(
err(new GhidraSessionError("cancelled", "Search cancelled")),
),
);
try {
const reply = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "48 8b" },
});
expect(reply.isError).toBe(true);
expect(parseMcpToolError(reply)).toMatchObject({
error: { code: "cancelled" },
});
expect(reply.structuredContent).toBeUndefined();
} finally {
await harness.close();
}
});
it("searches bytes through MCP and the socket bridge with pagination and skipped coverage", async () => {
const config = parseConfig({ GHIDRA_INSTALL_DIR: "/fixture/ghidra" });
if (!config.ok) throw config.error;
const provider = new GhidraProvider(
config.value,
silentLogger,
{},
ghidraInstallationHost(),
(options) =>
new GhidraClient({
...options,
platform: process.platform,
startupTimeoutMs: 5000,
launcher: {
launch: async (launch) => {
const projectRoot = join(launch.runtimeRoot, "project");
await mkdir(projectRoot);
const child = spawn(
process.execPath,
[
fileURLToPath(
new URL("../../fixtures/fakeGhidra.mjs", import.meta.url),
),
],
{
stdio: ["ignore", "pipe", "pipe"],
env: {
...process.env,
REA_GHIDRA_FIXTURE_CONFIG: JSON.stringify({
endpointPath: launch.endpointPath,
token: launch.token,
runId: launch.runId,
providerVersion: launch.providerVersion,
profileDigest: launch.profileDigest,
targetSha256: launch.targetSha256,
transport: launch.transport,
}),
},
},
);
return ok({
process: child,
ownsProcessLifetime: true as const,
projectRoot,
ghidraLogPath: join(launch.runtimeRoot, "ghidra.log"),
scriptLogPath: join(launch.runtimeRoot, "script.log"),
cleanup: async () => {
const signaled =
child.exitCode === null && child.signalCode === null;
if (signaled) child.kill("SIGTERM");
return (await waitForExit(child, 2000))
? { cleaned: true as const, signaled }
: { cleaned: false as const, reason: "Fixture did not exit" };
},
});
},
},
}),
);
const session = composeBinarySession(
new AnalysisProviderRegistry([provider]),
);
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const client = new Client({ name: "byte-search", 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: process.execPath },
});
expect(opened.isError).not.toBe(true);
const first = await client.callTool({
name: "search_bytes",
arguments: { pattern: "48 8b ?? ?? 89", limit: 1 },
});
expect(first.isError, JSON.stringify(first)).not.toBe(true);
const firstEvidence = sessionEvidence(session, first.structuredContent);
expect(firstEvidence.normalized_result).toMatchObject({
matches: [
{
address: "0x1000",
segment: ".text",
file_offset: 0,
procedure: { name: "fixture_main" },
},
],
searched: {
bytes: 10,
skipped_uninitialized: [{ segment: ".bss", bytes: 16 }],
},
complete: false,
next_cursor: "fixture-second-page",
});
const second = await client.callTool({
name: "search_bytes",
arguments: {
pattern: "48 8b ?? ?? 89",
limit: 1,
cursor: "fixture-second-page",
},
});
expect(second.isError).not.toBe(true);
expect(
sessionEvidence(session, second.structuredContent).normalized_result,
).toMatchObject({
matches: [{ address: "0x1005", file_offset: 5 }],
complete: true,
next_cursor: null,
});
const invalid = await client.callTool({
name: "search_bytes",
arguments: { pattern: "??" },
});
expect(invalid.isError).toBe(true);
expect(JSON.stringify(invalid.content)).toContain(
"Pattern must constrain at least one bit",
);
} finally {
await client.close();
await server.close();
const closed = await session.close();
if (!closed.ok) throw closed.error;
}
});
it("retains missing PDB coverage in empty PE name-search Evidence and snapshot replay", async () => {
const root = await createTestTempDirectory("rea-pdb-evidence-");
+2 -2
View File
@@ -54,7 +54,7 @@ export const connectGhidraMcp = async (
config.value,
silentLogger,
{},
installationHost(),
ghidraInstallationHost(),
factory,
);
const session = composeBinarySession(
@@ -100,7 +100,7 @@ export const sessionEvidence = (session: BinarySession, value: unknown) => {
return evidence;
};
const installationHost = (): GhidraInstallationHost => ({
export const ghidraInstallationHost = (): GhidraInstallationHost => ({
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
+23 -1
View File
@@ -43,7 +43,23 @@ describe("official operation arguments", () => {
const execute: AnalysisOperationPort["execute"] = (name, parameters) => {
calls.push({ name, parameters });
return Promise.resolve(
observed(name === "search_strings" ? [] : "int main() {}"),
observed(
name === "search_bytes"
? {
matches: [],
searched: {
blocks: [],
bytes: 0,
skipped_uninitialized: [],
skipped_not_loaded: [],
},
complete: true,
next_cursor: null,
}
: name === "search_strings"
? []
: "int main() {}",
),
);
};
const createSession = () =>
@@ -59,6 +75,7 @@ describe("official operation arguments", () => {
const client = await connect({ execute });
for (const [name, mcpParameters, cliParameters] of [
["procedure_pseudo_code", { procedure: "main" }, { procedure: "main" }],
["search_bytes", { pattern: "48 ??" }, { pattern: "48 ??", limit: 100 }],
[
"search_strings",
{ pattern: "entry" },
@@ -93,6 +110,11 @@ describe("official operation arguments", () => {
["list_procedures", { document: null }],
["procedure_pseudo_code", { procedure: "main", document: 3 }],
["search_strings", { pattern: "entry", case_sensitive: null }],
["search_bytes", { pattern: "??" }],
["search_bytes", { pattern: "48 8B", mask: "ff" }],
["search_bytes", { pattern: "4?" }],
["search_bytes", { pattern: "48", limit: 1001 }],
["search_bytes", { pattern: "48", cursor: null }],
] as const) {
const result = await client.callTool({ name, arguments: parameters });
expect(result.isError).toBe(true);
+67
View File
@@ -10,6 +10,12 @@ 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";
import { HopperProvider } from "../../../src/hopper/HopperProvider.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { silentLogger } from "../../../src/logger.js";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { createBinarySessionTargets } from "../../fixtures/binarySession.js";
interface Invocation {
readonly name: string;
@@ -18,6 +24,67 @@ interface Invocation {
const resources: Array<{ close(): Promise<void> }> = [];
it("returns typed Hopper byte-search unavailability without launching the provider", async () => {
const [target] = await createBinarySessionTargets();
const config = parseConfig({ HOPPER_LAUNCHER_PATH: process.execPath });
if (!config.ok) throw config.error;
const provider = new HopperProvider(config.value, silentLogger, {}, "linux");
const session = composeBinarySession(
new AnalysisProviderRegistry([provider]),
);
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const client = new Client({
name: "hopper-byte-search-unavailable",
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: target },
});
expect(opened.isError).not.toBe(true);
const result = await client.callTool({
name: "search_bytes",
arguments: { pattern: "48 8b" },
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: { provider_id: "hopper", operation: "search_bytes" },
},
});
} finally {
await client.close();
await server.close();
const closed = await session.close();
if (!closed.ok) throw closed.error;
}
});
it("advertises strict masked-byte arguments and bounded pages", () => {
const contract = OFFICIAL_TOOL_CONTRACTS.find(
({ name }) => name === "search_bytes",
);
expect(
contract?.inputSchema.parse({ pattern: "48 8B ?? ?? 89" }),
).toMatchObject({ limit: 100 });
expect(
contract?.inputSchema.safeParse({ pattern: "48", ignored: true }).success,
).toBe(false);
expect(
contract?.inputSchema.safeParse({ pattern: "48", mask: "f0", limit: 1000 })
.success,
).toBe(true);
});
describe("read_bytes contract", () => {
it("accepts lengths above the former arbitrary ceiling and rejects zero", () => {
const contract = OFFICIAL_TOOL_CONTRACTS.find(
@@ -257,3 +257,72 @@ it("keeps the untrusted target-content marker on an oversized error's replacemen
await Promise.all([client.close(), server.close()]);
}
});
// The delivered error wire omits only the private structured carrier; its
// `isError` flag and any provenance marker count against the result budget.
const deliveredErrorBytes = (nameBytes: number, targetContent: boolean) => {
const { structuredContent: _carrier, ...wire } = failureWithName(
nameBytes,
targetContent,
);
return Buffer.byteLength(JSON.stringify(wire));
};
it.each([false, true])(
"applies the result budget to the complete delivered error (target content: %s)",
async (targetContent) => {
const fittingName =
delivery.resultBudgetBytes - deliveredErrorBytes(0, targetContent);
expect(deliveredErrorBytes(fittingName, targetContent)).toBe(
delivery.resultBudgetBytes,
);
const server = new EvidenceMcpServer(
{ name: "error-budget-test", version: "1" },
{ capabilities: {} },
undefined,
delivery,
);
server.registerTool(
"fitting_failure",
{ inputSchema: z.object({}) },
async () => failureWithName(fittingName, targetContent),
);
server.registerTool(
"one_byte_over_failure",
{ inputSchema: z.object({}) },
async () => failureWithName(fittingName + 1, targetContent),
);
const client = new Client({ name: "error-budget-client", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const fitting = await client.callTool({
name: "fitting_failure",
arguments: {},
});
expect(fitting.isError).toBe(true);
expect(parseMcpToolError(fitting)).toEqual(
failureWithName(fittingName, targetContent).structuredContent,
);
const over = await client.callTool({
name: "one_byte_over_failure",
arguments: {},
});
expect(over.isError).toBe(true);
expect(over.structuredContent).toBeUndefined();
expect(parseMcpToolError(over)).toMatchObject({
error: {
code: "resource_constraint",
details: {
reported_limits: { original_error_code: "invalid_request" },
},
},
});
} finally {
await Promise.all([client.close(), server.close()]);
}
},
20000,
);
@@ -0,0 +1,184 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { z } from "zod";
import { createServer } from "../../../src/server/createServer.js";
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { err, ok } from "../../../src/domain/result.js";
import {
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
const bundleResult = (reply: CallToolResult) =>
z.object({ result: evidenceBundleSchema }).parse(reply.structuredContent)
.result;
const successfulTool = async (
client: Client,
name: string,
arguments_: Record<string, unknown> = {},
): Promise<CallToolResult> => {
const reply = await client.callTool({ name, arguments: arguments_ });
expect(reply.isError, `${name}: ${JSON.stringify(reply.content)}`).not.toBe(
true,
);
return reply;
};
const recordUnknownHistory = async (client: Client): Promise<void> => {
const fields = {
severity: "medium",
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
};
const unknown = await successfulTool(client, "record_unknown", {
...fields,
question: "Which source revision produced this target?",
domain: "provenance",
});
const recorded = z
.object({ result: z.object({ unknown_id: z.string() }) })
.parse(unknown.structuredContent).result;
await successfulTool(client, "update_unknown", {
...fields,
unknown_id: recorded.unknown_id,
expected_revision: 1,
status: "investigating",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
resolution: null,
});
};
it.each(["switch", "restart"] as const)(
"preserves investigation records through failed target %s and cleanup retries",
async (transition) => {
const root = await createTestTempDirectory("rea-mcp-switch-evidence-");
const first = join(root, "first.hop");
const second = join(root, "second.hop");
await writeFile(first, "first source-owned target");
await writeFile(second, "second source-owned target");
const application = join(root, "application");
await mkdir(application);
await writeFile(
join(application, "index.js"),
'export const label = "retained";',
);
const nextTarget = transition === "switch" ? second : first;
const calls: string[] = [];
const base = createCacheProvider(calls);
let cleanupAllowed = true;
let created = 0;
const failure = new ProviderCleanupError(
"fixture",
[join(root, "runtime")],
{
reason: "fixture cleanup temporarily unavailable",
},
);
const session = createTestBinarySession({
...base,
createClient: (target, profile, context) => {
created += 1;
return {
...base.createClient(target, profile, context),
operationHealthSnapshot: () => ({
state: cleanupAllowed ? "idle" : "exited",
stage: "analysis",
retryAction: cleanupAllowed ? null : "restart_provider",
exitCode: cleanupAllowed ? null : 1,
requests: [],
}),
close: () =>
Promise.resolve(cleanupAllowed ? ok(null) : err(failure)),
};
},
});
const server = createServer(
{ kind: "session", session },
{ environment: {} },
);
const client = new Client({
name: "switch-evidence-recovery",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const call = (name: string, arguments_: Record<string, unknown> = {}) =>
successfulTool(client, name, arguments_);
const query = { address: "0x1000", document: "fixture" };
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await call("open_binary", { path: first });
// The cached primitive must be discarded when the provider is retired,
// independently of the investigation's Evidence and Unknown history.
await call("address_name", query);
const analyzed = await call("analyze_javascript_application", {
input_path: application,
format: "directory",
max_heap_mb: 128,
});
const applicationId = z
.object({ evidence_id: z.string() })
.parse(analyzed.structuredContent).evidence_id;
await recordUnknownHistory(client);
const before = bundleResult(await call("get_evidence_bundle"));
expect(before.records).toHaveLength(4);
expect(before.unknowns).toHaveLength(2);
cleanupAllowed = false;
for (let attempt = 0; attempt < 2; attempt += 1) {
const replacement = await client.callTool({
name: "open_binary",
arguments: { path: nextTarget },
});
expect(parseMcpToolError(replacement)).toMatchObject({
error: { code: "cleanup_incomplete" },
});
expect(session.activeTarget()).toBeUndefined();
expect(created).toBe(1);
expect(bundleResult(await call("get_evidence_bundle"))).toEqual(before);
}
const exportedPath = join(root, "retained.json");
await call("export_evidence_bundle", { path: exportedPath });
expect(
evidenceBundleSchema.parse(
JSON.parse(await readFile(exportedPath, "utf8")),
),
).toEqual(before);
cleanupAllowed = true;
await call("open_binary", { path: nextTarget });
expect(bundleResult(await call("get_evidence_bundle"))).toEqual(before);
await call("address_name", query);
expect(
calls.filter((operation) => operation === "address_name"),
).toHaveLength(2);
expect(created).toBe(2);
await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: applicationId },
view: { kind: "page", collection: "modules", offset: 0, limit: 10 },
});
await call("close_binary");
const closed = bundleResult(await call("get_evidence_bundle"));
expect(closed.records).toEqual([]);
expect(closed.unknowns).toEqual([]);
} finally {
cleanupAllowed = true;
await client.close();
await server.close();
await session.close();
}
},
);
@@ -217,6 +217,46 @@ function resolveReference(schema: unknown, reference: string): unknown {
return value;
}
function localReferenceExpansions(schema: Record<string, unknown>): number {
// Clients that render SDK declarations from the advertised input expand
// schema-local references against a shared per-input budget; Pi 1.1.0
// code-mode allows 32 and renders every later reference as `unknown`.
// Count conservatively: every resolvable, non-cyclic reference occurrence
// reached while walking the input, never the definitions themselves.
let count = 0;
const visit = (node: unknown, active: ReadonlySet<string>): void => {
if (Array.isArray(node)) {
node.forEach((child) => visit(child, active));
return;
}
if (!isRecord(node)) return;
if (typeof node.$ref === "string" && !active.has(node.$ref)) {
const target = resolveReference(schema, node.$ref);
if (target !== undefined) {
count += 1;
visit(target, new Set([...active, node.$ref]));
return;
}
}
for (const [key, value] of Object.entries(node)) {
if (
[
"$defs",
"definitions",
"examples",
"default",
"const",
"enum",
].includes(key)
)
continue;
visit(value, active);
}
};
visit(schema, new Set());
return count;
}
function recursiveReferences(tools: readonly ToolSchemas[]): string[] {
return tools.flatMap((tool) =>
(["inputSchema", "outputSchema"] as const).flatMap((kind) => {
@@ -674,6 +714,14 @@ it("ships nonrecursive input and output schemas in the generated catalog", () =>
expect(recursiveReferences(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
});
it("keeps advertised input references within the client expansion budget", () => {
for (const tool of GENERATED_MCP_TOOL_CATALOG)
expect(
localReferenceExpansions(tool.inputSchema),
`${tool.name} exhausts the shared reference-expansion budget`,
).toBeLessThanOrEqual(32);
});
it("rejects unresolved output-schema references even for uncalled tools", () => {
const errors = schemaErrors([
{
+97 -95
View File
@@ -1,5 +1,9 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import {
advertisedMcpToolSchemas,
assertRecordedMcpEvidence,
} from "../../fixtures/advertisedMcpTool.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished, vi } from "vitest";
import { readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -20,20 +24,6 @@ import {
wasmArtifactExecution,
} from "../../fixtures/wasm/artifact.js";
const wasmToolSchemas = async (client: Client) => {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_wasm_artifact",
);
if (advertised?.outputSchema === undefined)
throw new Error("WASM recovery must name an advertised static tool");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
return { name: advertised.name, ajv, inputSchema, outputSchema };
};
const assertFirstSummaryDelivery = async (
harness: Awaited<ReturnType<typeof createApplicationMcpHarness>>,
value: ReturnType<typeof wasmArtifactFixture>,
@@ -43,7 +33,7 @@ const assertFirstSummaryDelivery = async (
ajv: wasmAjv,
inputSchema,
outputSchema,
} = await wasmToolSchemas(harness.client);
} = await advertisedMcpToolSchemas(harness.client, "inspect_wasm_artifact");
const summaryInput = { path: value.artifact.path, detail: "summary" };
expect(wasmAjv.validate(inputSchema, summaryInput)).toBe(true);
expect(
@@ -91,73 +81,86 @@ const assertFirstSummaryDelivery = async (
return { summary, retained };
};
it("directs rejected native WASM opening to the advertised static tool while preserving missing-WABT diagnostics", async () => {
const directory = await createTestTempDirectory("rea-wasm-recovery-");
const path = join(
await realpath(directory),
process.platform === "win32" ? "module space.bin" : 'module "quoted".bin',
);
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
const createClient = vi.fn(() => {
throw new Error("native provider must not start for WASM");
});
const session = createTestBinarySession(createClient);
const harness = await createApplicationMcpHarness({
session,
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const { client } = harness;
const { name, ajv, inputSchema } = await wasmToolSchemas(client);
const input = { path };
expect(
toolContract("inspect_wasm_artifact").inputSchema.safeParse(input).success,
).toBe(true);
const opening = await client.callTool({
name: "open_binary",
arguments: input,
});
expect(opening.isError).toBe(true);
const failure = parseMcpToolError(opening);
expect(failure).toMatchObject({
error: {
code: "target_unavailable",
category: "unsupported_target",
details: { constraint: "wasm_requires_static_inspection" },
},
});
expect(failure.error.remediation.action).toContain(JSON.stringify({ path }));
expect(ajv.validate(inputSchema, input)).toBe(true);
const inspection = await client.callTool({
name,
arguments: input,
});
expect(inspection.isError).toBe(true);
expect(parseMcpToolError(inspection)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: "inspect_wasm_artifact",
reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY"),
it.each(["bin", "hop"])(
"directs rejected native WASM opening (%s suffix) to the advertised static tool while preserving missing-WABT diagnostics",
async (extension) => {
const directory = await createTestTempDirectory("rea-wasm-recovery-");
const path = join(
await realpath(directory),
process.platform === "win32"
? `module space.${extension}`
: `module "quoted".${extension}`,
);
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
const createClient = vi.fn(() => {
throw new Error("native provider must not start for WASM");
});
const session = createTestBinarySession(createClient);
const harness = await createApplicationMcpHarness({
session,
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const { client } = harness;
const { name, ajv, inputSchema } = await advertisedMcpToolSchemas(
client,
"inspect_wasm_artifact",
);
const input = { path };
const opening = await client.callTool({
name: "open_binary",
arguments: input,
});
expect(opening.isError).toBe(true);
const failure = parseMcpToolError(opening);
expect(failure).toMatchObject({
error: {
code: "target_unavailable",
category: "unsupported_target",
details: { constraint: "wasm_requires_static_inspection" },
},
},
});
const summary = await client.callTool({
name,
arguments: { ...input, detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
details: { reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY") },
},
});
await client.ping();
expect(createClient).not.toHaveBeenCalled();
expect(await readFile(path)).toEqual(
Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]),
);
});
});
const [, recoveryName, serializedInput] =
failure.error.remediation.action.match(
/call (\w+) with (\{.*\}) or run/,
) ?? [];
expect(recoveryName).toBe(name);
const recoveryInput = z
.object({ path: z.literal(path) })
.strict()
.parse(JSON.parse(serializedInput ?? "null"));
expect(ajv.validate(inputSchema, recoveryInput)).toBe(true);
const inspection = await client.callTool({
name: recoveryName ?? "",
arguments: recoveryInput,
});
expect(inspection.isError).toBe(true);
expect(parseMcpToolError(inspection)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: "inspect_wasm_artifact",
reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY"),
},
},
});
const summary = await client.callTool({
name,
arguments: { ...input, detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
details: { reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY") },
},
});
await client.ping();
expect(createClient).not.toHaveBeenCalled();
expect(await readFile(path)).toEqual(
Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]),
);
},
);
it("advertises exact valid schemas and records inline WASM interface evidence without a binary target", async () => {
const value = wasmArtifactFixture();
@@ -175,7 +178,11 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
});
onTestFinished(harness.close);
const { client } = harness;
const { ajv, inputSchema, outputSchema } = await wasmToolSchemas(client);
const schemas = await advertisedMcpToolSchemas(
client,
"inspect_wasm_artifact",
);
const { ajv, inputSchema } = schemas;
expect(ajv.validate(inputSchema, { path: value.artifact.path })).toBe(true);
expect(
ajv.validate(inputSchema, {
@@ -188,19 +195,14 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_wasm_artifact").outputSchema.parse(
response.structuredContent,
assertRecordedMcpEvidence(
response,
"inspect_wasm_artifact",
schemas,
session,
value,
"observed",
);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
await client.callTool({
@@ -229,6 +229,62 @@ it("normalizes legacy version-minimum commands into build metadata", () => {
]);
});
it("names numeric build-version platforms and tools", () => {
const load = parseOtoolLoadCommands(
withOtoolMachHeader(
[
"Load command 0",
" cmd LC_BUILD_VERSION",
" cmdsize 48",
" platform 1",
" minos 11.0",
" sdk 26.5",
" ntools 2",
" tool 3",
" version 1267.0",
" tool 1029",
" version 1.0",
"Load command 1",
" cmd LC_BUILD_VERSION",
" cmdsize 24",
" platform 99",
" minos 1.0",
" sdk 1.0",
" ntools 0",
"Load command 2",
" cmd LC_BUILD_VERSION",
" cmdsize 32",
" platform MACCATALYST",
" minos 14.0",
" sdk 14.2",
" ntools 1",
" tool SWIFT",
" version 5.9",
"",
].join("\n"),
),
);
expect(load.builds).toEqual([
{
platform: "MACOS",
minimum_os: "11.0",
sdk: "26.5",
tools: [
{ name: "LD", version: "1267.0" },
{ name: "1029", version: "1.0" },
],
},
{ platform: "99", minimum_os: "1.0", sdk: "1.0", tools: [] },
{
platform: "MACCATALYST",
minimum_os: "14.0",
sdk: "14.2",
tools: [{ name: "SWIFT", version: "5.9" }],
},
]);
expect(load.commands[0]?.fields.platform).toBe(1);
});
it("does not classify LC_LOAD_DYLINKER as a dylib dependency", async () => {
const load = parseOtoolLoadCommands(
await nativeFixture("native-macho-header/otool-header-load.txt"),
@@ -273,3 +329,78 @@ it("limits thread-state entrypoints instead of reporting none silently", async (
"Thread-state entrypoints (LC_UNIXTHREAD/LC_THREAD) are retained as raw load commands; file offsets are not derived.",
);
});
it.each([
["1", "MACOS"],
["2", "IOS"],
["3", "TVOS"],
["4", "WATCHOS"],
["5", "BRIDGEOS"],
["6", "MACCATALYST"],
["7", "IOSSIMULATOR"],
["8", "TVOSSIMULATOR"],
["9", "WATCHOSSIMULATOR"],
["10", "DRIVERKIT"],
["11", "VISIONOS"],
["12", "VISIONOSSIMULATOR"],
["13", "FIRMWARE"],
["14", "SEPOS"],
["15", "MACOS_EXCLAVECORE"],
["16", "MACOS_EXCLAVEKIT"],
["17", "IOS_EXCLAVECORE"],
["18", "IOS_EXCLAVEKIT"],
["19", "TVOS_EXCLAVECORE"],
["20", "TVOS_EXCLAVEKIT"],
["21", "WATCHOS_EXCLAVECORE"],
["22", "WATCHOS_EXCLAVEKIT"],
["23", "VISIONOS_EXCLAVECORE"],
["24", "VISIONOS_EXCLAVEKIT"],
] as const)("names build platform %s as %s", (code, name) => {
const load = parseOtoolLoadCommands(
withOtoolMachHeader(
[
"Load command 0",
"cmd LC_BUILD_VERSION",
"cmdsize 24",
`platform ${code}`,
"minos 1.0",
"sdk 1.0",
"ntools 0",
"",
].join("\n"),
),
);
expect(load.builds[0]?.platform).toBe(name);
});
it.each([
["1", "CLANG"],
["2", "SWIFT"],
["3", "LD"],
["4", "LLD"],
["1024", "METAL"],
["1025", "AIRLLD"],
["1026", "AIRNT"],
["1027", "AIRNT_PLUGIN"],
["1028", "AIRPACK"],
["1031", "GPUARCHIVER"],
["1032", "METAL_FRAMEWORK"],
] as const)("names build tool %s as %s", (code, name) => {
const load = parseOtoolLoadCommands(
withOtoolMachHeader(
[
"Load command 0",
"cmd LC_BUILD_VERSION",
"cmdsize 32",
"platform 1",
"minos 1.0",
"sdk 1.0",
"ntools 1",
`tool ${code}`,
"version 1.0",
"",
].join("\n"),
),
);
expect(load.builds[0]?.tools).toEqual([{ name, version: "1.0" }]);
});