Merge remote-tracking branch 'origin/main' into feat/claude-code-plugin
# Conflicts: # docs/installation.md
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect } from "vitest";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import {
|
||||
aotFixtureImage,
|
||||
engineFixtureImage,
|
||||
REFERENCE_HASH,
|
||||
} from "../../src/flutter/FlutterBuild.fixture.js";
|
||||
import {
|
||||
createFlutterApk,
|
||||
createDuplicateFlutterApk,
|
||||
} from "../fixtures/flutterApk.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"CLI and stdio MCP retain Flutter identity, selected ABI and duplicate-member refusals",
|
||||
async ({ cli }) => {
|
||||
const image = aotFixtureImage();
|
||||
Buffer.from("Login\0").copy(image, 0x2300);
|
||||
const engine = engineFixtureImage({
|
||||
notes: Buffer.from(
|
||||
"040000000800000003000000474e55000123456789abcdef",
|
||||
"hex",
|
||||
),
|
||||
prefix: Buffer.from(
|
||||
"040000000800000003000000474e55001111111111111111",
|
||||
"hex",
|
||||
),
|
||||
labels: ["Android (test) clang version 9.0.8"],
|
||||
});
|
||||
const path = await createFlutterApk("selected target.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
|
||||
{
|
||||
path: "lib/arm64-v8a/libflutter.so",
|
||||
bytes: engine,
|
||||
},
|
||||
{ path: "lib/x86_64/libapp.so", bytes: image },
|
||||
{
|
||||
path: "lib/x86_64/libflutter.so",
|
||||
bytes: engine,
|
||||
},
|
||||
]);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [name, abi] of [
|
||||
["identify_flutter_build", undefined],
|
||||
["inspect_dart_aot", undefined],
|
||||
["inspect_dart_aot", "x86_64"],
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
name.replaceAll("_", "-"),
|
||||
path,
|
||||
"--json",
|
||||
...(abi === undefined ? [] : ["--abi", abi]),
|
||||
],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract(name).outputSchema.parse(result.json);
|
||||
const response = await call(name, {
|
||||
path,
|
||||
...(abi === undefined ? {} : { abi }),
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const mcp = parseEvidence(response.structuredContent);
|
||||
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
|
||||
expect(mcp.subject).toEqual(evidence.subject);
|
||||
expect(mcp.subject).toMatchObject({
|
||||
local_path: path,
|
||||
format: "apk",
|
||||
digest: { sha256: evidence.normalized_result.target.sha256 },
|
||||
});
|
||||
expect(mcp.evidence_id).toBe(evidence.evidence_id);
|
||||
if (name === "inspect_dart_aot") {
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
abi: abi ?? "arm64-v8a",
|
||||
libapp: {
|
||||
coverage: "complete",
|
||||
snapshot_hash: REFERENCE_HASH,
|
||||
sha256: createHash("sha256").update(image).digest("hex"),
|
||||
},
|
||||
string_pool: {
|
||||
coverage: "complete",
|
||||
class_like_tokens: expect.arrayContaining(["Login"]),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const identified = toolContract(
|
||||
"identify_flutter_build",
|
||||
).outputSchema.parse(result.json).normalized_result;
|
||||
expect(identified.coverage).toBe("complete");
|
||||
for (const abi of identified.abis) {
|
||||
expect(abi.libflutter).toMatchObject({
|
||||
build_id: "0123456789abcdef",
|
||||
build_id_candidates: ["0123456789abcdef"],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const duplicate = await createDuplicateFlutterApk();
|
||||
for (const name of [
|
||||
"identify_flutter_build",
|
||||
"inspect_dart_aot",
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [name.replaceAll("_", "-"), duplicate, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
const mcp = parseMcpToolError(await call(name, { path: duplicate }));
|
||||
expect(mcp.error).toEqual(result.json);
|
||||
expect(mcp.error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: [{ message: expect.stringContaining(duplicate) }] },
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"CLI and MCP retain unsupported snapshot kinds as partial evidence",
|
||||
async ({ cli }) => {
|
||||
const image = aotFixtureImage();
|
||||
for (const offset of [0x1000, 0x2000])
|
||||
image.writeBigUInt64LE(4n, offset + 12);
|
||||
const path = await createFlutterApk("unsupported-kind.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
|
||||
]);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-dart-aot", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_dart_aot").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_dart_aot", { path });
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(parseEvidence(response.structuredContent).normalized_result).toEqual(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
coverage: "partial",
|
||||
libapp: { coverage: "partial", snapshot_hash: REFERENCE_HASH },
|
||||
string_pool: { coverage: "complete" },
|
||||
});
|
||||
expect(
|
||||
evidence.normalized_result.libapp.sections
|
||||
.filter((section) => section.name.endsWith("Data"))
|
||||
.map((section) => section.kind),
|
||||
).toEqual([4, 4]);
|
||||
},
|
||||
);
|
||||
@@ -307,3 +307,36 @@ cliTest(
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"managed CLI reports a section table past EOF as invalid input",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-managed-cli-sections-");
|
||||
const path = join(root, "fixture.dll");
|
||||
const bytes = buildManagedPeFixture();
|
||||
const pe = bytes.readUInt32LE(0x3c);
|
||||
const sections = pe + 24 + bytes.readUInt16LE(pe + 20);
|
||||
bytes.writeUInt32LE(bytes.length + 0x1000, sections + 20);
|
||||
await writeFile(path, bytes);
|
||||
for (const command of [
|
||||
"inspect-managed-artifact",
|
||||
"inspect-managed-members",
|
||||
"inspect-managed-native-boundaries",
|
||||
]) {
|
||||
const result = await cli.run({ arguments: [command, path, "--json"] });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: expect.stringContaining("pe.section-data"),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -30,7 +30,7 @@ type CaptureOutcome =
|
||||
| { readonly kind: "partial"; readonly partial: unknown };
|
||||
|
||||
const captureScenario = (
|
||||
mode: "cooperative" | "ignoring" | "descendant",
|
||||
mode: "cooperative" | "ignoring" | "delayed-ignoring" | "descendant",
|
||||
root: string,
|
||||
additions: CaptureScenario = {},
|
||||
finalExitCode?: number,
|
||||
@@ -453,11 +453,13 @@ captureTest(
|
||||
"rea-finalization-cli-cancel-",
|
||||
);
|
||||
const cliScenarioPath = join(cliRoot, "scenario.json");
|
||||
// Match the other finalization cases' observation window. The old 300 ms
|
||||
// deadline could signal the fixture before it installed its handlers.
|
||||
await writeFile(
|
||||
cliScenarioPath,
|
||||
JSON.stringify(
|
||||
captureScenario("ignoring", cliRoot, {
|
||||
timeout_ms: 300,
|
||||
captureScenario("delayed-ignoring", cliRoot, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
),
|
||||
@@ -527,18 +529,36 @@ captureTest(
|
||||
const mcpRoot = await createTestTempDirectory(
|
||||
"rea-finalization-mcp-cancel-",
|
||||
);
|
||||
const { client } = await connectLocalToolsMcp();
|
||||
const { client, call: callTool } = await connectLocalToolsMcp();
|
||||
const controller = new AbortController();
|
||||
const call = client.callTool(
|
||||
{
|
||||
name: "capture_process_scenario",
|
||||
arguments: captureScenario("ignoring", mcpRoot, {
|
||||
timeout_ms: 300,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
let reportStarted: (() => void) | undefined;
|
||||
const captureStarted = new Promise<void>((resolve) => {
|
||||
reportStarted = resolve;
|
||||
});
|
||||
const call = callTool(
|
||||
"capture_process_scenario",
|
||||
captureScenario("delayed-ignoring", mcpRoot, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
{ signal: controller.signal, onprogress: () => reportStarted?.() },
|
||||
);
|
||||
// Observe rejection immediately: a failed readiness wait must not leave a
|
||||
// pending request to reject unhandled when the fixture closes its client.
|
||||
// The original promise remains available for the cancellation assertion.
|
||||
const observedCall = call.catch(() => undefined);
|
||||
onTestFinished(async () => {
|
||||
controller.abort();
|
||||
await observedCall;
|
||||
});
|
||||
// Start the fixture's readiness wait after the server begins this capture;
|
||||
// SDK schema preparation before dispatch is not target startup time.
|
||||
await Promise.race([
|
||||
captureStarted,
|
||||
call.then(() => {
|
||||
throw new Error("MCP capture completed before reporting startup");
|
||||
}),
|
||||
]);
|
||||
const mcpFixturePid = await waitForFinalization(mcpRoot);
|
||||
const mcpStarted = Date.now();
|
||||
controller.abort(new Error("cancel finalization acceptance fixture"));
|
||||
@@ -548,7 +568,7 @@ captureTest(
|
||||
).rejects.toThrow("cancel finalization acceptance fixture");
|
||||
await waitForProcessExit(mcpFixturePid);
|
||||
await expect(
|
||||
client.listTools(),
|
||||
client.listTools(undefined, { cacheMode: "refresh" }),
|
||||
"the server accepts a follow-up request after cancelling the capture",
|
||||
).resolves.toMatchObject({ tools: expect.any(Array) });
|
||||
expect(
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const cases = [
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "[]",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "null",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: '{"mcpServers":null,"keep":1}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: '{"mcpServers":"x","keep":1}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "pi",
|
||||
path: ".pi/agent/mcp.json",
|
||||
text: '{"mcpServers":[]}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "codex",
|
||||
path: ".codex/config.toml",
|
||||
text: 'mcp_servers = "x"\n',
|
||||
diagnostic: '"mcp_servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "opencode",
|
||||
path: ".config/opencode/opencode.json",
|
||||
text: '{"mcp":{"servers":null}}',
|
||||
diagnostic: '"mcp.servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "- item\n",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "mcp_servers: null\nkeep: 1\n",
|
||||
diagnostic: '"mcp_servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "not-json",
|
||||
diagnostic: "Configuration is not valid JSON",
|
||||
syntax: "JSON",
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "mcp_servers: [\n",
|
||||
diagnostic: "Configuration is not valid YAML",
|
||||
syntax: "YAML",
|
||||
},
|
||||
{
|
||||
client: "dsh",
|
||||
path: ".dsh/cordis.patch.yml",
|
||||
text: "- insert: [\n",
|
||||
diagnostic: "Configuration is not valid YAML",
|
||||
syntax: "YAML",
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const scenario of cases)
|
||||
cliTest(
|
||||
`setup and uninstall explain ${scenario.client} configuration ${scenario.text}`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory(
|
||||
"rea-client-config-diagnostic-",
|
||||
);
|
||||
const config = join(home, scenario.path);
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
await writeFile(config, scenario.text);
|
||||
const environment = {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
HERMES_HOME: join(home, ".hermes"),
|
||||
DSH_HOME: join(home, ".dsh"),
|
||||
};
|
||||
const setup = await cli.run({
|
||||
arguments: [
|
||||
"setup",
|
||||
"--client",
|
||||
scenario.client,
|
||||
"--skill=false",
|
||||
"--yes",
|
||||
"--json",
|
||||
],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(setup.exitCode).toBe(1);
|
||||
expect(setup.json).toMatchObject({
|
||||
status: "needs_human",
|
||||
plannedActions: [],
|
||||
appliedActions: [],
|
||||
});
|
||||
if ("syntax" in scenario) {
|
||||
expect(setup.json).toMatchObject({ remediation: expect.any(String) });
|
||||
if (scenario.syntax === "JSON")
|
||||
expect(setup.stdout).toContain("Invalid JSON/JSONC");
|
||||
} else {
|
||||
expect(setup.json).toMatchObject({
|
||||
remediation: expect.stringContaining(scenario.diagnostic),
|
||||
});
|
||||
expect(setup.stdout).not.toContain("invalid_type");
|
||||
}
|
||||
const uninstall = await cli.run({
|
||||
arguments: ["uninstall", "--json"],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(uninstall.exitCode).toBe(1);
|
||||
expect(uninstall.json).toMatchObject({
|
||||
status: "failed",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: scenario.client,
|
||||
status: "failed",
|
||||
detail: expect.stringContaining(scenario.diagnostic),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
if (!("syntax" in scenario))
|
||||
expect(uninstall.stdout).not.toContain("not valid JSON");
|
||||
expect(await readFile(config, "utf8")).toBe(scenario.text);
|
||||
expect(await readdir(dirname(config))).toEqual([
|
||||
scenario.path.split("/").at(-1),
|
||||
]);
|
||||
},
|
||||
);
|
||||
@@ -1,10 +1,10 @@
|
||||
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { mkdir, unlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
@@ -15,11 +15,56 @@ import {
|
||||
analysisViewCaptureEvidence,
|
||||
analysisViewObjectDenseCapture,
|
||||
} from "../../fixtures/analysisView.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js";
|
||||
|
||||
cliTest(
|
||||
"projects portable artifact inventory after the original ZIP is removed",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-inventory-view-cli-");
|
||||
const archive = join(root, "fixture.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("main.js", new TextReader("console.log('portable');\n"));
|
||||
await writeFile(archive, await writer.close());
|
||||
const inspected = await cli.run({
|
||||
arguments: ["inspect-artifact", archive, "--json"],
|
||||
});
|
||||
expect(inspected.exitCode).toBe(0);
|
||||
const parent = parseEvidence(inspected.json);
|
||||
await unlink(archive);
|
||||
const request = join(root, "view.json");
|
||||
await writeFile(
|
||||
request,
|
||||
JSON.stringify({
|
||||
source: { kind: "inline", evidence: parent },
|
||||
view: {
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: ["main.js"],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const projected = await cli.run({
|
||||
arguments: ["inspect-analysis-view", request, "--json"],
|
||||
});
|
||||
expect(projected.exitCode).toBe(0);
|
||||
expect(projected.json).toMatchObject({
|
||||
operation: "inspect_analysis_view",
|
||||
evidence_links: [parent.evidence_id],
|
||||
normalized_result: {
|
||||
parent_evidence_id: parent.evidence_id,
|
||||
kind: "inventory",
|
||||
source_complete: true,
|
||||
artifact: { path: archive, sha256: parent.subject?.digest.sha256 },
|
||||
items: [expect.objectContaining({ logical_path: "main.js" })],
|
||||
coverage: { total: 1, exhausted: true, next_offset: null },
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"admits portable captures before parsing and preserves capture caveats",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const level of ["loud", "INFO"])
|
||||
cliTest(
|
||||
`reports REA_LOG_LEVEL=${level} as invalid configuration`,
|
||||
async ({ cli }) => {
|
||||
for (const arguments_ of [["doctor", "--json"], ["--help"]]) {
|
||||
const result = await cli.run({
|
||||
arguments: arguments_,
|
||||
environment: { REA_LOG_LEVEL: level },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).toBe("");
|
||||
expect(result.stderr).toBe(
|
||||
'REA configuration is invalid: REA_LOG_LEVEL: Invalid option: expected one of "trace"|"debug"|"info"|"warn"|"error"|"fatal"|"silent".\n',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -25,7 +25,7 @@ describe("executable dispatcher", () => {
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli-runtime/cli.js",
|
||||
'export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
'export const cliConfigurationError = () => undefined; export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli-runtime/cliOutput.js",
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { serveCli } from "./cliServeHarness.js";
|
||||
|
||||
it.each(["identify-flutter-build", "inspect-dart-aot"])(
|
||||
"%s advertises a schema through the public CLI",
|
||||
async (command) => {
|
||||
const result = await serveCli([command, "--schema", "--json"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toBeTruthy();
|
||||
},
|
||||
);
|
||||
|
||||
it("reports an unreadable target with an input refusal", async () => {
|
||||
const result = await serveCli([
|
||||
"identify-flutter-build",
|
||||
"/nonexistent/app.apk",
|
||||
"--json",
|
||||
]);
|
||||
expect(result.stdout).toContain("invalid_request");
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
|
||||
|
||||
it("maps one-shot Frida CLI target, script, duration, and remote options", async () => {
|
||||
const calls: unknown[] = [];
|
||||
const provider: FridaInstrumentationPort = {
|
||||
async listDevices() {
|
||||
calls.push({ operation: "devices" });
|
||||
return { ok: true, value: { devices: [], cleanupError: null } };
|
||||
},
|
||||
async listProcesses() {
|
||||
return {
|
||||
ok: true,
|
||||
value: { deviceId: "local", processes: [], cleanupError: null },
|
||||
};
|
||||
},
|
||||
async startSession(input) {
|
||||
calls.push({ operation: "start", input });
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
deviceId: "remote",
|
||||
target: "fixture",
|
||||
pid: 71,
|
||||
mode: input.mode,
|
||||
state: "running",
|
||||
},
|
||||
};
|
||||
},
|
||||
async loadScript(sessionId, source) {
|
||||
calls.push({ operation: "load", sessionId, source });
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
scriptId: "00000000-0000-4000-8000-000000000002",
|
||||
sourceKind: source.sourceKind,
|
||||
sourcePath: source.sourceKind === "file" ? source.path : null,
|
||||
sourceSha256: "a".repeat(64),
|
||||
messages: [{ type: "send", payload: "observed" }],
|
||||
messagesTruncated: false,
|
||||
},
|
||||
};
|
||||
},
|
||||
async resumeSession(sessionId) {
|
||||
calls.push({ operation: "resume", sessionId });
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
async unloadScript() {
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
status(sessionId) {
|
||||
return {
|
||||
sessionId,
|
||||
deviceId: "remote",
|
||||
target: "fixture",
|
||||
pid: 71,
|
||||
mode: "attach",
|
||||
state: "running",
|
||||
targetResumeObserved: false,
|
||||
scripts: [],
|
||||
messages: [],
|
||||
messagesTruncated: false,
|
||||
};
|
||||
},
|
||||
async closeSession(sessionId) {
|
||||
calls.push({ operation: "close", sessionId });
|
||||
return { ok: true, value: { targetResumeObserved: false } };
|
||||
},
|
||||
async closeAll() {},
|
||||
};
|
||||
const cli = createCli({}, undefined, provider);
|
||||
let stdout = "";
|
||||
let exitCode = 0;
|
||||
await cli.serve(
|
||||
[
|
||||
"instrument-with-frida",
|
||||
"attach",
|
||||
"71",
|
||||
"--script",
|
||||
"send('hello')",
|
||||
"--remote-address",
|
||||
"127.0.0.1:27042",
|
||||
"--token",
|
||||
"synthetic-secret-token",
|
||||
"--keepalive-interval",
|
||||
"10",
|
||||
"--duration-ms",
|
||||
"0",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(exitCode).toBe(0);
|
||||
const result: unknown = JSON.parse(stdout);
|
||||
expect(JSON.stringify(result)).not.toContain("synthetic-secret-token");
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
operation: "start",
|
||||
input: {
|
||||
mode: "attach",
|
||||
pid: 71,
|
||||
remote: {
|
||||
address: "127.0.0.1:27042",
|
||||
token: "synthetic-secret-token",
|
||||
keepaliveInterval: 10,
|
||||
},
|
||||
source: { sourceKind: "inline", source: "send('hello')" },
|
||||
durationMs: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: "load",
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
source: { sourceKind: "inline", source: "send('hello')" },
|
||||
},
|
||||
{
|
||||
operation: "close",
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
},
|
||||
]);
|
||||
|
||||
stdout = "";
|
||||
exitCode = 0;
|
||||
await cli.serve(
|
||||
["list-frida-devices", "--token", "synthetic-secret-token", "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(stdout).not.toContain("synthetic-secret-token");
|
||||
});
|
||||
|
||||
it("awaits failed startup cleanup and retains the primary error if cleanup still fails", async () => {
|
||||
for (const cleanupFails of [false, true]) {
|
||||
const calls: string[] = [];
|
||||
const provider: FridaInstrumentationPort =
|
||||
new FridaInstrumentationManager();
|
||||
provider.startSession = async () => {
|
||||
calls.push("start");
|
||||
return {
|
||||
ok: false,
|
||||
error: new AnalysisCapabilityUnavailableError(
|
||||
"frida",
|
||||
"start_frida_session",
|
||||
"attach failed after spawn",
|
||||
{
|
||||
cleanup: {
|
||||
reason: "first resume failed",
|
||||
resources: ["paused spawn"],
|
||||
},
|
||||
},
|
||||
),
|
||||
};
|
||||
};
|
||||
provider.closeAll = async () => {
|
||||
calls.push("cleanup");
|
||||
if (cleanupFails) throw new Error("resume still failed");
|
||||
};
|
||||
let stdout = "";
|
||||
await createCli({}, undefined, provider).serve(
|
||||
[
|
||||
"instrument-with-frida",
|
||||
"spawn",
|
||||
"/tmp/fixture",
|
||||
"--script",
|
||||
"send('ready')",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
exit: () => {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(calls).toEqual(["start", "cleanup"]);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: cleanupFails ? "cleanup_incomplete" : "capability_unavailable",
|
||||
});
|
||||
expect(stdout).toContain("attach failed after spawn");
|
||||
if (cleanupFails) expect(stdout).toContain("primary_error");
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves observed devices when CLI provider cleanup fails", async () => {
|
||||
const provider: FridaInstrumentationPort = new FridaInstrumentationManager();
|
||||
const devices = [
|
||||
{ deviceId: "remote-device", name: "selected endpoint", type: "remote" },
|
||||
];
|
||||
provider.listDevices = async () => ({
|
||||
ok: true,
|
||||
value: { devices, cleanupError: null },
|
||||
});
|
||||
provider.closeAll = async () => {
|
||||
throw new Error("remote removal failed");
|
||||
};
|
||||
let stdout = "";
|
||||
await createCli({}, undefined, provider).serve(
|
||||
["list-frida-devices", "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: () => {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { diagnostics: { partial_observation: { devices } } },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
["attach", "abc", "--script", "send(1)"],
|
||||
"target",
|
||||
"attach mode needs a positive integer process ID.",
|
||||
],
|
||||
[
|
||||
["attach", "71"],
|
||||
"script",
|
||||
"Provide exactly one of --script or --script-file.",
|
||||
],
|
||||
])(
|
||||
"names the rejected instrument-with-frida argument for %j",
|
||||
async (argv, path, message) => {
|
||||
let starts = 0;
|
||||
const provider = {
|
||||
async startSession() {
|
||||
starts += 1;
|
||||
throw new Error("Frida must not start for invalid input");
|
||||
},
|
||||
} as unknown as FridaInstrumentationPort;
|
||||
const cli = createCli({}, undefined, provider);
|
||||
let stdout = "";
|
||||
await cli.serve(["instrument-with-frida", ...argv, "--json"], {
|
||||
env: {},
|
||||
exit: () => undefined,
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
});
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [{ path: [path], reason: "invalid_value", message }],
|
||||
},
|
||||
});
|
||||
expect(starts).toBe(0);
|
||||
},
|
||||
);
|
||||
@@ -30,3 +30,14 @@ it("validates decompile item input before contacting the engine", async () => {
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an invalid endpoint without breaking other commands", async () => {
|
||||
const environment = { REA_JEB_MCP_URL: "http://localhost:8425/mcp" };
|
||||
const jeb = await serveCli(["inspect-jeb-client", "--json"], environment);
|
||||
expect(JSON.parse(jeb.stdout)).toMatchObject({
|
||||
code: "configuration_invalid",
|
||||
details: { settings: [{ setting: "REA_JEB_MCP_URL" }] },
|
||||
});
|
||||
const capabilities = await serveCli(["capabilities", "--json"], environment);
|
||||
expect(capabilities.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { build } from "plist";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { deeplyNestedXmlPlist } from "../../fixtures/keyedArchiveXmlNesting.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const [name, xml] of [
|
||||
["dictionaries", deeplyNestedXmlPlist(3000)],
|
||||
[
|
||||
"quoted attributes",
|
||||
deeplyNestedXmlPlist(3000).replaceAll("<dict>", '<dict note="/>">'),
|
||||
],
|
||||
[
|
||||
"plist wrappers",
|
||||
"<plist>".repeat(3000) + "<string>x</string>" + "</plist>".repeat(3000),
|
||||
],
|
||||
] as const) {
|
||||
cliTest(
|
||||
`compiled CLI reports deeply nested XML ${name} as the decode limit`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-keyed-cli-depth-");
|
||||
const path = join(root, "Deep.plist");
|
||||
await writeFile(path, xml);
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-keyed-archive", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(1);
|
||||
expect(output.json).toMatchObject({
|
||||
code: "truncated",
|
||||
category: "truncated",
|
||||
details: {
|
||||
reason: "limit",
|
||||
truncated: true,
|
||||
detail:
|
||||
"Cannot decode selected Foundation keyed archive: Plist exceeds 128 nesting levels",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"compiled CLI decodes a shallow archive with opaque DOCTYPE markup",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-keyed-cli-doctype-");
|
||||
const path = join(root, "Shallow.plist");
|
||||
const archive = build({
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$objects: ["$null", "leaf"],
|
||||
$top: { root: { UID: 1 } },
|
||||
});
|
||||
await writeFile(
|
||||
path,
|
||||
archive.replace(
|
||||
/<!DOCTYPE[^>]*>/u,
|
||||
`<!DOCTYPE plist [<!ENTITY first "unused"><!ENTITY second "${"<dict>".repeat(130)}">]>`,
|
||||
),
|
||||
);
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-keyed-archive", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
expect(parseEvidence(output.json).normalized_result).toMatchObject({
|
||||
archive_format: "xml-plist",
|
||||
objects: expect.arrayContaining([
|
||||
expect.objectContaining({ value: "leaf" }),
|
||||
]),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,336 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
// A recording port checks the experimental producer/consumer representation.
|
||||
// Real provider verification remains in the separate native experiment receipts.
|
||||
const generate = `
|
||||
import {measureNativeEntry} from './experiments/analysis-efficiency/native-entry.mjs';
|
||||
const sha='0'.repeat(64);
|
||||
const duplicate=process.argv[1]==='duplicate';
|
||||
const stale=process.argv[1]==='stale-dos';
|
||||
const collision=process.argv[1];
|
||||
const dos=process.argv[1]==='dos'||stale||collision==='load-collision';
|
||||
const dossier={procedure:{address:'0x1000'},pseudocode:'return;',callers:[],callees:[]};
|
||||
class ToolFailure extends Error {}
|
||||
const build=async digit=>{
|
||||
const parent='ev_'+digit.repeat(63)+'0';
|
||||
let ordinal=0;
|
||||
const call=async(name,args)=>{
|
||||
if(stale)process.stdout.write(name+'\\n');
|
||||
if(name==='open_binary'||name==='close_binary')return {};
|
||||
if(name==='inspect_native_load_image')return {evidence_id:'ev_'+digit.repeat(63)+'6',normalized_result:{status:'verified',target_sha256:stale?'f'.repeat(64):sha,entry:{linear_address:'0x1000'}}};
|
||||
if(name==='resolve_containing_procedure')return {evidence_id:'ev_'+digit.repeat(63)+'7',normalized_result:{found:true}};
|
||||
if(name==='analyze_function')return {evidence_id:parent,subject:{digest:{sha256:sha}},normalized_result:dossier};
|
||||
const id='ev_'+digit.repeat(63)+(collision==='containing-collision'?7:collision==='load-collision'?6:duplicate?1:++ordinal);
|
||||
if(args.view.kind==='summary')return {evidence_id:id};
|
||||
const facet=args.view.facet;
|
||||
const item=facet==='pseudocode'?{text:dossier.pseudocode,unit:'utf16-code-units'}:dossier[facet];
|
||||
return {evidence_id:id,normalized_result:{parent_evidence_id:parent,artifact:{sha256:sha},item,coverage:{exhausted:true},limitations:[],unknowns:[]}};
|
||||
};
|
||||
return measureNativeEntry({seed:dos?undefined:'0x1000',values:{path:'/selected/input','native-question':'entry-views'},call,inputSha:sha,ToolFailure});
|
||||
};
|
||||
process.stdout.write(JSON.stringify([await build('1'),await build('2')]));
|
||||
`;
|
||||
|
||||
it.each([
|
||||
"observed",
|
||||
"missing",
|
||||
"errored",
|
||||
"wrong-target",
|
||||
"wrong-entry",
|
||||
"unreferenced",
|
||||
])(
|
||||
"binds the DOS model grade to its observed load image: %s",
|
||||
async (scenario) => {
|
||||
// Synthetic transcripts exercise grading; they are not real-provider or
|
||||
// resource measurements. Real DOS transcripts are replayed separately.
|
||||
const root = await createTestTempDirectory("rea-dos-grader-");
|
||||
const trial = join(root, "trial");
|
||||
const referenceDirectory = join(root, "reference");
|
||||
await mkdir(trial);
|
||||
await mkdir(referenceDirectory);
|
||||
const sha = "0".repeat(64);
|
||||
const imageId = "ev_" + "1".repeat(64);
|
||||
const procedureId = "ev_" + "2".repeat(64);
|
||||
const procedure = {
|
||||
address: "0x1000",
|
||||
name: "entry",
|
||||
classification: "observed",
|
||||
signature: null,
|
||||
locals: [],
|
||||
body: { ranges: [], total_bytes: 0 },
|
||||
};
|
||||
const loadImage = {
|
||||
status: "verified",
|
||||
target_sha256: sha,
|
||||
entry: { linear_address: "0x1000" },
|
||||
};
|
||||
const reference = {
|
||||
artifact_sha256: sha,
|
||||
entry_address: "0x1000",
|
||||
caller_count: 0,
|
||||
callee_count: 0,
|
||||
pseudocode_prefix: "return;",
|
||||
containing_procedure: { procedure },
|
||||
procedure,
|
||||
load_image: loadImage,
|
||||
};
|
||||
const answer = {
|
||||
...reference,
|
||||
load_image_status: "verified",
|
||||
evidence_ids: [
|
||||
procedureId,
|
||||
...(["missing", "errored", "unreferenced"].includes(scenario)
|
||||
? []
|
||||
: [imageId]),
|
||||
],
|
||||
};
|
||||
const event = (tool: string, status: string, value: unknown) => ({
|
||||
type: "item.completed",
|
||||
item: {
|
||||
type: "mcp_tool_call",
|
||||
tool,
|
||||
status,
|
||||
arguments: {},
|
||||
result: { structured_content: value },
|
||||
},
|
||||
});
|
||||
const events = [
|
||||
event("analyze_function", "completed", { evidence_id: procedureId }),
|
||||
];
|
||||
if (scenario !== "missing")
|
||||
events.push(
|
||||
event(
|
||||
"inspect_native_load_image",
|
||||
scenario === "errored" ? "failed" : "completed",
|
||||
scenario === "errored"
|
||||
? { error: { code: "unsupported_target" } }
|
||||
: {
|
||||
operation: "inspect_native_load_image",
|
||||
evidence_id: imageId,
|
||||
normalized_result: {
|
||||
...loadImage,
|
||||
target_sha256:
|
||||
scenario === "wrong-target" ? "f".repeat(64) : sha,
|
||||
entry: {
|
||||
linear_address:
|
||||
scenario === "wrong-entry" ? "0x2000" : "0x1000",
|
||||
},
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
const resourceLog = join(root, "resource.log");
|
||||
const output = join(root, "review.json");
|
||||
for (const [path, value] of [
|
||||
[
|
||||
join(trial, "summary.json"),
|
||||
{
|
||||
completed_mcp_calls: [
|
||||
{ tool: "close_binary", status: "completed", arguments: {} },
|
||||
],
|
||||
},
|
||||
],
|
||||
[join(trial, "trial-settings.json"), {}],
|
||||
[join(trial, "cleanup.json"), { profile_removed: true }],
|
||||
[join(trial, "answer.txt"), answer],
|
||||
[join(referenceDirectory, "answer.json"), reference],
|
||||
[
|
||||
resourceLog,
|
||||
{
|
||||
resource_scope: "synthetic-grader-fixture",
|
||||
abort: null,
|
||||
resource_counters_verified: true,
|
||||
resource_events_final: {
|
||||
"memory.events": { high: 0, max: 0, oom: 0, oom_kill: 0 },
|
||||
"pids.events": { max: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
] as const)
|
||||
await writeFile(path, JSON.stringify(value));
|
||||
await writeFile(
|
||||
join(trial, "events.jsonl"),
|
||||
events.map((value) => JSON.stringify(value)).join("\n"),
|
||||
);
|
||||
const command = execute("python3", [
|
||||
resolve("experiments/analysis-efficiency/review-model.py"),
|
||||
"--domain",
|
||||
"native",
|
||||
"--trial",
|
||||
trial,
|
||||
"--reference",
|
||||
referenceDirectory,
|
||||
"--resource-log",
|
||||
resourceLog,
|
||||
"--output",
|
||||
output,
|
||||
]);
|
||||
if (scenario === "observed") await command;
|
||||
else await expect(command).rejects.toMatchObject({ code: 1 });
|
||||
const report = JSON.parse(await readFile(output, "utf8"));
|
||||
expect(report.all_selected_checks_pass).toBe(scenario === "observed");
|
||||
if (["missing", "errored", "unreferenced"].includes(scenario))
|
||||
expect(report.checks.load_image_source_observed_and_referenced).toBe(
|
||||
false,
|
||||
);
|
||||
if (scenario === "wrong-target")
|
||||
expect(report.checks["load_image.target_sha256"]).toBe(false);
|
||||
if (scenario === "wrong-entry")
|
||||
expect(report.checks["load_image.source_entry"]).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains the DOS load-image source for its facts and derived entry seed", async () => {
|
||||
const { stdout } = await execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"dos",
|
||||
]);
|
||||
const [answer] = JSON.parse(stdout);
|
||||
expect(answer).toMatchObject({
|
||||
entry_address: "0x1000",
|
||||
load_image: { status: "verified", entry: { linear_address: "0x1000" } },
|
||||
evidence_ids: { native_load_image: "ev_" + "1".repeat(63) + "6" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a stale DOS load image before using its entry and closes the session", async () => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"stale-dos",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stdout: "open_binary\ninspect_native_load_image\nclose_binary\n",
|
||||
stderr: expect.stringContaining(
|
||||
"The DOS load image belongs to a different target",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["containing-collision", "load-collision"])(
|
||||
"rejects a retained view that reuses an earlier producer identity: %s",
|
||||
async (collision) => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
collision,
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stderr: expect.stringContaining(
|
||||
"Retained native view reused an Evidence identity",
|
||||
),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects a producer that reuses a view identity across facets", async () => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"duplicate",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stderr: expect.stringContaining(
|
||||
"Retained native view reused an Evidence identity",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["references", "item", "coverage", "limitations", "unknowns"])(
|
||||
"separates native references while comparing %s exactly",
|
||||
async (change) => {
|
||||
const { stdout: generated } = await execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
]);
|
||||
const [leftAnswer, rightAnswer] = JSON.parse(generated);
|
||||
if (change === "item")
|
||||
rightAnswer.retained_views[0].item.address = "0x1001";
|
||||
if (change === "coverage")
|
||||
rightAnswer.retained_views[0].coverage.exhausted = false;
|
||||
if (change === "limitations")
|
||||
rightAnswer.retained_views[0].limitations.push("partial");
|
||||
if (change === "unknowns")
|
||||
rightAnswer.retained_views[0].unknowns.push("unresolved");
|
||||
|
||||
const root = await createTestTempDirectory("rea-native-comparison-");
|
||||
const left = join(root, "left");
|
||||
const right = join(root, "right");
|
||||
const summary = {
|
||||
artifact: "sharex.exe",
|
||||
native_question: "entry-views",
|
||||
provider_search_path_sha256: "0".repeat(64),
|
||||
native_workflow_source_sha256: "1".repeat(64),
|
||||
calls: [],
|
||||
failure: null,
|
||||
};
|
||||
for (const [directory, answer] of [
|
||||
[left, leftAnswer],
|
||||
[right, rightAnswer],
|
||||
]) {
|
||||
await mkdir(directory);
|
||||
await writeFile(join(directory, "summary.json"), JSON.stringify(summary));
|
||||
await writeFile(join(directory, "answer.json"), JSON.stringify(answer));
|
||||
}
|
||||
const output = join(root, "comparison.json");
|
||||
const command = execute(process.execPath, [
|
||||
resolve("experiments/analysis-efficiency/compare.mjs"),
|
||||
"--left",
|
||||
left,
|
||||
"--right",
|
||||
right,
|
||||
"--output",
|
||||
output,
|
||||
]);
|
||||
if (change !== "references") {
|
||||
await expect(command).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining('"retained_views"'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const { stdout } = await command;
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
settings_match: true,
|
||||
facts_match: true,
|
||||
preserved_run_specific_values: [
|
||||
{
|
||||
side: "left",
|
||||
path: ["evidence_ids"],
|
||||
value: leftAnswer.evidence_ids,
|
||||
},
|
||||
{
|
||||
side: "right",
|
||||
path: ["evidence_ids"],
|
||||
value: rightAnswer.evidence_ids,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(leftAnswer.evidence_ids).not.toEqual(rightAnswer.evidence_ids);
|
||||
expect(leftAnswer.evidence_ids.retained_views[0]).toMatchObject({
|
||||
evidence_id: "ev_" + "1".repeat(64),
|
||||
parent_evidence_id: "ev_" + "1".repeat(63) + "0",
|
||||
});
|
||||
expect(leftAnswer.evidence_ids.native_summary).toBe(
|
||||
"ev_" + "1".repeat(63) + "5",
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
rename,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { dirname, join, matchesGlob } from "node:path";
|
||||
|
||||
import { afterAll, beforeAll, expect, it } from "vitest";
|
||||
import { parse } from "yaml";
|
||||
@@ -157,7 +157,7 @@ it("retains complete checks when implementation is renamed into documentation",
|
||||
const head = await commit(directory);
|
||||
expect(await classify(directory, base, head)).toMatchObject({
|
||||
code: true,
|
||||
package: true,
|
||||
runtime: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -268,6 +268,62 @@ it.each([
|
||||
{ code: false, evm: true, browser: false, package: false },
|
||||
],
|
||||
["unknown-input", { code: true, package: true, evm: true, browser: true }],
|
||||
[
|
||||
"src/application/Example.ts",
|
||||
{
|
||||
code: true,
|
||||
runtime: true,
|
||||
package: false,
|
||||
apple: false,
|
||||
evm: false,
|
||||
browser: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"bridge/ghidra/Example.java",
|
||||
{ code: true, runtime: true, package: false, apple: false },
|
||||
],
|
||||
[
|
||||
"src/native/AppleExample.ts",
|
||||
{ code: true, runtime: true, apple: true, package: false, evm: false },
|
||||
],
|
||||
[
|
||||
"scripts/verify/apple/example.mjs",
|
||||
{ code: true, apple: true, package: false, runtime: false },
|
||||
],
|
||||
[
|
||||
"src/windows/Example.ts",
|
||||
{ code: true, runtime: true, package: true, apple: false, evm: false },
|
||||
],
|
||||
["install.sh", { code: true, runtime: true, package: true, evm: false }],
|
||||
[
|
||||
".agents/skills/reverse-engineer-anything/SKILL.md",
|
||||
{ code: true, runtime: true, docs: true, package: false, evm: false },
|
||||
],
|
||||
[
|
||||
"scripts/verify-real-ghidra.mjs",
|
||||
{ code: true, runtime: false, package: false, apple: false, evm: false },
|
||||
],
|
||||
[
|
||||
"scripts/verify-claude-client.mjs",
|
||||
{ code: true, runtime: false, package: false, browser: false },
|
||||
],
|
||||
[
|
||||
"tests/boundary/process/darwinProcessRunTokenReader.test.ts",
|
||||
{ code: true, apple: true, package: false, runtime: false },
|
||||
],
|
||||
[
|
||||
"tests/boundary/cli/nativePlistCli.test.ts",
|
||||
{ code: true, apple: true, package: false, runtime: false },
|
||||
],
|
||||
[
|
||||
"tests/boundary/filesystem/windowsNpxRegistration.test.ts",
|
||||
{ code: true, package: true, runtime: true, apple: false },
|
||||
],
|
||||
[
|
||||
"src/process/ProcessOwnership.test.ts",
|
||||
{ code: true, package: true, apple: false, evm: false, browser: false },
|
||||
],
|
||||
])("selects the appropriate lanes for %s", async (path, expected) => {
|
||||
const { directory, base } = await fixture();
|
||||
const head = await change(directory, [path]);
|
||||
@@ -404,6 +460,14 @@ it.each([
|
||||
{ code: true, package: true, browser: true, evm: true },
|
||||
],
|
||||
["docs/.vitepress/config.ts", { code: false, docs: true, package: false }],
|
||||
["CHANGELOG.md", { code: false, docs: true, package: false }],
|
||||
["SECURITY.md", { code: false, docs: true, package: false }],
|
||||
[".github/pull_request_template.md", { code: false, docs: true }],
|
||||
[
|
||||
".github/ISSUE_TEMPLATE/bug.yml",
|
||||
{ code: false, docs: true, workflows: false },
|
||||
],
|
||||
["native/windows/README.md", { code: false, docs: true, package: false }],
|
||||
[
|
||||
"src/contracts/evm/tools.ts",
|
||||
{ code: true, docs: true, evm: true, package: false },
|
||||
@@ -462,6 +526,43 @@ it("fails without emitting a plan when package metadata is malformed", async ()
|
||||
expect(await readFile(join(directory, "scope-output"), "utf8")).toBe("");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"verify:keyed-archive",
|
||||
"npm run build:cached && node scripts/verify/apple/keyed-archive.mjs",
|
||||
{ apple: true, package: false, evm: false, browser: false },
|
||||
],
|
||||
[
|
||||
"verify:inspector",
|
||||
"npm run build:cached && node scripts/verify/inspector/runtime-observation.mjs",
|
||||
{ package: true, apple: false, evm: false, browser: false },
|
||||
],
|
||||
[
|
||||
"verify:windows-native",
|
||||
"node scripts/verify-windows-native.mjs",
|
||||
{ package: true, apple: false, evm: false, browser: false },
|
||||
],
|
||||
])(
|
||||
"routes the %s script to its glob-owned lane",
|
||||
async (script, command, expected) => {
|
||||
const { directory } = await fixture();
|
||||
const base = await change(
|
||||
directory,
|
||||
["package.json"],
|
||||
JSON.stringify({ scripts: { [script]: command } }),
|
||||
);
|
||||
const head = await change(
|
||||
directory,
|
||||
["package.json"],
|
||||
JSON.stringify({ scripts: { [script]: `${command} --verbose` } }),
|
||||
);
|
||||
expect(await classify(directory, base, head)).toMatchObject({
|
||||
code: true,
|
||||
...expected,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("retains a broad fallback when a provider script adds shared shell work", async () => {
|
||||
const { directory } = await fixture();
|
||||
const before = {
|
||||
@@ -538,3 +639,119 @@ it.each(["compile:termux", "build:termux", "build:termux:run"])(
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const INTEL_HOST = {
|
||||
os: "macos-15-intel",
|
||||
platform: "darwin",
|
||||
architecture: "x64",
|
||||
};
|
||||
|
||||
it("keeps macOS x64 package verification for ci:full and non-PR events", async () => {
|
||||
const { directory, base } = await fixture();
|
||||
const head = await change(directory, ["src/windows/Example.ts"]);
|
||||
const matrix = z.object({ include: z.array(z.unknown()) });
|
||||
const hosts = async (event: string, full: boolean) =>
|
||||
matrix.parse((await classify(directory, base, head, event, full)).matrix)
|
||||
.include;
|
||||
const pullRequest = await hosts("pull_request", false);
|
||||
expect(pullRequest).toHaveLength(3);
|
||||
expect(pullRequest).not.toContainEqual(INTEL_HOST);
|
||||
expect(await hosts("pull_request", true)).toContainEqual(INTEL_HOST);
|
||||
for (const event of ["push", "schedule", "workflow_dispatch"])
|
||||
expect(await hosts(event, false)).toContainEqual(INTEL_HOST);
|
||||
});
|
||||
|
||||
const workflowFile = async (name: string): Promise<unknown> =>
|
||||
parse(
|
||||
await readFile(
|
||||
new URL(`../../../.github/workflows/${name}`, import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
|
||||
const scopesSchema = z.object({
|
||||
SCOPES: z.record(z.string(), z.array(z.string())),
|
||||
MANUAL_VERIFIERS: z.array(z.string()),
|
||||
});
|
||||
|
||||
const loadScopes = async () =>
|
||||
scopesSchema.parse(
|
||||
await import(
|
||||
new URL("../../../scripts/ci/scopes.mjs", import.meta.url).href
|
||||
),
|
||||
);
|
||||
|
||||
const stepRuns = z.object({
|
||||
on: z.unknown(),
|
||||
jobs: z.record(
|
||||
z.string(),
|
||||
z.object({
|
||||
steps: z.array(z.object({ run: z.string().optional() })).optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
it("owns every explicit native-host test path with the lane that runs it", async () => {
|
||||
const { SCOPES } = await loadScopes();
|
||||
const ci = stepRuns.parse(await workflowFile("ci.yml"));
|
||||
const listed = (job: string) =>
|
||||
(ci.jobs[job]?.steps ?? [])
|
||||
.flatMap((step) => step.run?.split(/\s+/) ?? [])
|
||||
.filter((token) => token.endsWith(".test.ts"));
|
||||
const unowned = (job: string, scope: string) =>
|
||||
listed(job).filter(
|
||||
(path) =>
|
||||
!(SCOPES[scope] ?? []).some((pattern) => matchesGlob(path, pattern)),
|
||||
);
|
||||
expect(listed("apple-artifacts").length).toBeGreaterThan(0);
|
||||
expect(listed("windows-curated").length).toBeGreaterThan(0);
|
||||
expect(unowned("apple-artifacts", "apple")).toEqual([]);
|
||||
expect(unowned("windows-curated", "package")).toEqual([]);
|
||||
});
|
||||
|
||||
it("never runs a manual-only verifier from an automatic workflow", async () => {
|
||||
const { MANUAL_VERIFIERS } = await loadScopes();
|
||||
const scripts = z
|
||||
.object({ scripts: z.record(z.string(), z.string()) })
|
||||
.parse(
|
||||
JSON.parse(
|
||||
await readFile(
|
||||
new URL("../../../package.json", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
).scripts;
|
||||
const directory = new URL("../../../.github/workflows/", import.meta.url);
|
||||
const commands: string[] = [];
|
||||
for (const name of await readdir(directory)) {
|
||||
const workflow = stepRuns.parse(await workflowFile(name));
|
||||
const triggers = JSON.stringify(workflow.on);
|
||||
if (
|
||||
name !== "ci.yml" &&
|
||||
!triggers.includes("workflow_call") &&
|
||||
!triggers.includes("pull_request")
|
||||
)
|
||||
continue;
|
||||
for (const job of Object.values(workflow.jobs))
|
||||
for (const step of job.steps ?? []) if (step.run) commands.push(step.run);
|
||||
}
|
||||
const files = new Set<string>();
|
||||
const seen = new Set<string>();
|
||||
while (commands.length) {
|
||||
const command = commands.pop() ?? "";
|
||||
for (const [, file] of command.matchAll(/\b(scripts\/[\w./-]+\.mjs)\b/g))
|
||||
if (file) files.add(file);
|
||||
for (const [, script] of command.matchAll(/npm run ([\w:.-]+)/g)) {
|
||||
if (!script || seen.has(script)) continue;
|
||||
seen.add(script);
|
||||
const body = scripts[script];
|
||||
if (body) commands.push(body);
|
||||
}
|
||||
}
|
||||
expect(files.size).toBeGreaterThan(0);
|
||||
expect(
|
||||
[...files].filter((file) =>
|
||||
MANUAL_VERIFIERS.some((pattern) => matchesGlob(file, pattern)),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
import { parse } from "yaml";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseTestDurations } from "../../ciTestSequencer.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const script = new URL("../../../scripts/ci/test-report.mjs", import.meta.url);
|
||||
const stepsSchema = z.array(
|
||||
z.object({
|
||||
name: z.string().optional(),
|
||||
run: z.string().optional(),
|
||||
uses: z.string().optional(),
|
||||
if: z.string().optional(),
|
||||
env: z.record(z.string(), z.string()).optional(),
|
||||
with: z.record(z.string(), z.unknown()).optional(),
|
||||
}),
|
||||
);
|
||||
const workflow = async () =>
|
||||
z
|
||||
.object({
|
||||
jobs: z.object({
|
||||
test: z.object({ steps: stepsSchema }),
|
||||
build: z.object({ steps: stepsSchema }),
|
||||
docs: z.object({ steps: stepsSchema }),
|
||||
static: z.object({ steps: stepsSchema }),
|
||||
}),
|
||||
})
|
||||
.parse(
|
||||
parse(
|
||||
await readFile(
|
||||
new URL("../../../.github/workflows/ci.yml", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
).jobs;
|
||||
|
||||
it("collects failed-shard diagnostics before enforcing the shard result", async () => {
|
||||
const steps = (await workflow()).test!.steps;
|
||||
const merge = steps.findIndex((step) => step.run?.includes("test:ci:merge"));
|
||||
const upload = steps.findIndex((step) => step.with?.name === "test-results");
|
||||
const gate = steps.findIndex(
|
||||
(step) => step.env?.SHARD_RESULT && step.run?.includes("test "),
|
||||
);
|
||||
expect(merge).toBeGreaterThan(0);
|
||||
expect(upload).toBeGreaterThan(merge);
|
||||
expect(gate).toBeGreaterThan(upload);
|
||||
expect(steps[merge]?.if).not.toContain("needs.test-shard.result");
|
||||
const command = steps[gate]?.run;
|
||||
if (command === undefined) throw new Error("Missing shard result gate");
|
||||
for (const result of ["failure", "cancelled", "skipped", ""]) {
|
||||
await expect(
|
||||
execute("bash", ["-c", command], {
|
||||
env: { ...process.env, CODE_REQUIRED: "true", SHARD_RESULT: result },
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 1 });
|
||||
}
|
||||
await expect(
|
||||
execute("bash", ["-c", command], {
|
||||
env: { ...process.env, CODE_REQUIRED: "false", SHARD_RESULT: "skipped" },
|
||||
}),
|
||||
).resolves.toMatchObject({ stderr: "" });
|
||||
});
|
||||
|
||||
it("keeps diagnosis available after merge failure and publishes only complete successful history", async () => {
|
||||
const steps = (await workflow()).test!.steps;
|
||||
const diagnosis = steps.find((step) => step.with?.name === "test-results");
|
||||
expect(diagnosis?.if).toContain("!cancelled()");
|
||||
expect(diagnosis?.if).not.toContain("success()");
|
||||
const history = steps.find((step) => step.with?.name === "test-timings");
|
||||
expect(history?.if).toContain("success()");
|
||||
expect(history?.if).toContain("needs.test-shard.result == 'success'");
|
||||
expect(history?.with?.path).toBe(".cache/ci-test-history/test-results.json");
|
||||
const download = (await workflow()).build!.steps.find(
|
||||
(step) => step.name === "Download previous timing report",
|
||||
);
|
||||
expect(download?.with?.name).toBe(history?.with?.name);
|
||||
});
|
||||
|
||||
it("runs the existing onboarding and Python producer guards from their selected CI owners", async () => {
|
||||
const jobs = await workflow();
|
||||
const scripts = z
|
||||
.object({ scripts: z.record(z.string(), z.string()) })
|
||||
.parse(
|
||||
JSON.parse(
|
||||
await readFile(
|
||||
new URL("../../../package.json", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
).scripts;
|
||||
expect(
|
||||
jobs.docs.steps.some((step) => step.run === "npm run docs:check"),
|
||||
).toBe(true);
|
||||
expect(scripts["docs:check"]).toContain(
|
||||
"tests/conformance/readmeConsistency.test.ts",
|
||||
);
|
||||
const producer = jobs.static.steps.find(
|
||||
(step) => step.run === "npm run test:python",
|
||||
);
|
||||
expect(producer?.if).toBe("needs.changes.outputs.code == 'true'");
|
||||
expect(scripts["test:python"]).toContain(
|
||||
"bridge/native/test_rea_lldb_tracer.py",
|
||||
);
|
||||
});
|
||||
|
||||
it("exports portable timing history and removes it on a failed, partial, or invalid rerun", async () => {
|
||||
const root = await createTestTempDirectory("rea-ci-report-");
|
||||
const summary = join(root, "summary.md");
|
||||
const history = join(root, ".cache/ci-test-history/test-results.json");
|
||||
const report = {
|
||||
success: true,
|
||||
numFailedTests: 0,
|
||||
testResults: [
|
||||
{
|
||||
name: join(root, "tests/slow.test.ts"),
|
||||
startTime: 10,
|
||||
endTime: 110,
|
||||
assertionResults: [{ large: "not timing data" }],
|
||||
},
|
||||
{ name: join(root, "tests/fast.test.ts"), startTime: 20, endTime: 30 },
|
||||
],
|
||||
};
|
||||
const run = async (value: unknown, shards = "success", merge = "success") => {
|
||||
await writeFile(join(root, "test-results.json"), JSON.stringify(value));
|
||||
await writeFile(summary, "");
|
||||
return execute(process.execPath, [fileURLToPath(script)], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_STEP_SUMMARY: summary,
|
||||
SHARD_RESULT: shards,
|
||||
MERGE_RESULT: merge,
|
||||
},
|
||||
});
|
||||
};
|
||||
await run(report);
|
||||
const contents = await readFile(history, "utf8");
|
||||
expect(contents).not.toContain("assertionResults");
|
||||
expect(contents).not.toContain(root);
|
||||
expect(
|
||||
parseTestDurations(contents, resolve(root, "different-checkout")),
|
||||
).toEqual(
|
||||
new Map([
|
||||
["tests/slow.test.ts", 100],
|
||||
["tests/fast.test.ts", 10],
|
||||
]),
|
||||
);
|
||||
for (const [value, shards, merge] of [
|
||||
[{ ...report, success: false, numFailedTests: 1 }, "failure", "failure"],
|
||||
[report, "cancelled", "success"],
|
||||
[report, "success", "failure"],
|
||||
] as const) {
|
||||
await run(report);
|
||||
await run(value, shards, merge);
|
||||
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await readFile(summary, "utf8")).toContain("diagnostic only");
|
||||
}
|
||||
await run(report);
|
||||
await expect(
|
||||
run({
|
||||
...report,
|
||||
testResults: [{ name: "../outside.test.ts", startTime: 1, endTime: 3 }],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 1 });
|
||||
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import {
|
||||
chmod,
|
||||
copyFile,
|
||||
lstat,
|
||||
mkdir,
|
||||
@@ -21,6 +22,7 @@ import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
|
||||
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { readConfigurationFile } from "../../../src/application/ClientConfigurationFiles.js";
|
||||
import {
|
||||
detectClients,
|
||||
systemSetupHost,
|
||||
@@ -63,10 +65,13 @@ describe("client configuration filesystem lifecycle", () => {
|
||||
"commandcode",
|
||||
"qwen_code",
|
||||
"vscode",
|
||||
"trae",
|
||||
"grok_build",
|
||||
"omp",
|
||||
"pi",
|
||||
"hermes",
|
||||
"qoder",
|
||||
"zcode",
|
||||
"dsh",
|
||||
"grok_bot",
|
||||
]);
|
||||
@@ -1526,6 +1531,68 @@ describe("client configuration filesystem removal", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("removes emptied skill directories and keeps ones with user files", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-skill-dirs-");
|
||||
roots.push(home);
|
||||
const shared = join(home, ".agents/skills/reverse-engineer-anything");
|
||||
const claude = join(home, ".claude/skills/reverse-engineer-anything");
|
||||
for (const root of [shared, claude]) {
|
||||
await mkdir(join(root, "references"), { recursive: true });
|
||||
await writeFile(join(root, "SKILL.md"), ownedSkillManifest);
|
||||
await writeFile(
|
||||
join(root, "references/evidence-workflows.md"),
|
||||
"managed",
|
||||
);
|
||||
}
|
||||
await writeFile(join(claude, "notes.md"), "user");
|
||||
|
||||
const result = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, undefined, {
|
||||
HOME: home,
|
||||
CLAUDE_CONFIG_DIR: join(home, ".claude"),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("complete");
|
||||
await expect(lstat(shared)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(lstat(join(claude, "references"))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
expect(await readFile(join(claude, "notes.md"), "utf8")).toBe("user");
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"reports an emptied skill directory that cannot be removed",
|
||||
async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-skill-perm-");
|
||||
roots.push(home);
|
||||
const parent = join(home, ".agents/skills");
|
||||
const root = join(parent, "reverse-engineer-anything");
|
||||
await mkdir(join(root, "references"), { recursive: true });
|
||||
await writeFile(join(root, "SKILL.md"), ownedSkillManifest);
|
||||
await chmod(parent, 0o555);
|
||||
try {
|
||||
const result = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, undefined, { HOME: home }),
|
||||
);
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "skill",
|
||||
status: "failed",
|
||||
detail: expect.stringContaining(
|
||||
`Managed skill directory could not be removed: ${root}.`,
|
||||
),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await chmod(parent, 0o755);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("removes an owned entry through a symlink without replacing it", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-symlink-");
|
||||
roots.push(home);
|
||||
@@ -1593,6 +1660,37 @@ describe("uninstall configuration preflight", () => {
|
||||
expect(await readFile(config, "utf8")).toBe("not-json");
|
||||
});
|
||||
|
||||
it.each([
|
||||
['{"mcpServers":null,"keep":1}', '"mcpServers" must be an object'],
|
||||
["[]", "The configuration root must be an object"],
|
||||
['{"mcpServers":"x"}', '"mcpServers" must be an object'],
|
||||
])(
|
||||
"names the structural problem in valid JSON %s",
|
||||
async (content, problem) => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-shape-");
|
||||
roots.push(home);
|
||||
const config = join(home, ".cursor/mcp.json");
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
await writeFile(config, content);
|
||||
expect(await readConfigurationFile(config, "json")).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "malformed",
|
||||
detail: `Configuration ${config} is malformed: ${problem}`,
|
||||
},
|
||||
});
|
||||
const result = await runUninstall(false, systemUninstallHost(home));
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual({
|
||||
name: "cursor",
|
||||
status: "failed",
|
||||
detail: `Configuration was not changed: ${problem}. Repair it, then rerun uninstall.`,
|
||||
});
|
||||
expect(await readFile(config, "utf8")).toBe(content);
|
||||
await expect(readFile(`${config}.rea.backup`, "utf8")).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it("stops before any removal when one client configuration is malformed", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-stop-");
|
||||
roots.push(home);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,9 +6,15 @@ import { parse as parseYaml } from "yaml";
|
||||
|
||||
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
|
||||
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import {
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { supportedClients } from "../../../src/application/SupportedClients.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import {
|
||||
runUninstall,
|
||||
systemUninstallHost,
|
||||
} from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
|
||||
|
||||
@@ -90,18 +96,75 @@ describe("Hermes configuration paths", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hermes YAML registration", () => {
|
||||
const hermesClient = async () => {
|
||||
const home = await createTestTempDirectory("rea-hermes-");
|
||||
const client = supportedClients(home, process.platform, {}).find(
|
||||
({ name }) => name === "hermes",
|
||||
);
|
||||
if (client?.markerPath === undefined)
|
||||
throw new Error("missing Hermes client");
|
||||
await mkdir(client.markerPath, { recursive: true });
|
||||
return { home, client };
|
||||
};
|
||||
const hermesClient = async () => {
|
||||
const home = await createTestTempDirectory("rea-hermes-");
|
||||
const client = supportedClients(home, process.platform, {}).find(
|
||||
({ name }) => name === "hermes",
|
||||
);
|
||||
if (client?.markerPath === undefined)
|
||||
throw new Error("missing Hermes client");
|
||||
await mkdir(client.markerPath, { recursive: true });
|
||||
return { home, client };
|
||||
};
|
||||
|
||||
describe("Hermes YAML shape diagnostics", () => {
|
||||
it.each(
|
||||
[
|
||||
"!!set {rea: null}",
|
||||
"!!omap [{rea: {command: rea, args: [mcp]}}]",
|
||||
"!!timestamp 2001-12-15",
|
||||
"!!binary cmVh",
|
||||
].flatMap((value) => [
|
||||
{
|
||||
original: `${value}\n`,
|
||||
problem: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
original: `mcp_servers: ${value}\n`,
|
||||
problem: '"mcp_servers" must be an object',
|
||||
},
|
||||
]),
|
||||
)(
|
||||
"blocks setup and uninstall before changes for tagged non-record YAML: $original",
|
||||
async ({ original, problem }) => {
|
||||
const { home, client } = await hermesClient();
|
||||
const cursor = join(home, ".cursor", "mcp.json");
|
||||
const cursorOriginal =
|
||||
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}';
|
||||
await mkdir(join(home, ".cursor"));
|
||||
await writeFile(cursor, cursorOriginal);
|
||||
await writeFile(client.configPath, original);
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, command),
|
||||
).toMatchObject({
|
||||
status: "invalid",
|
||||
remediation: `Configuration ${client.configPath} is malformed: ${problem}`,
|
||||
});
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
const result = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, undefined, {}),
|
||||
);
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual({
|
||||
name: "hermes",
|
||||
status: "failed",
|
||||
detail: `Configuration was not changed: ${problem}. Repair it, then rerun uninstall.`,
|
||||
});
|
||||
expect(await readFile(client.configPath, "utf8")).toBe(original);
|
||||
expect(await readFile(cursor, "utf8")).toBe(cursorOriginal);
|
||||
await expect(
|
||||
readFile(`${client.configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
await expect(readFile(`${cursor}.rea.backup`, "utf8")).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Hermes YAML registration", () => {
|
||||
it("writes mcp_servers, preserves comments, reads back, and uninstalls", async () => {
|
||||
const { home, client } = await hermesClient();
|
||||
await writeFile(
|
||||
|
||||
@@ -334,13 +334,18 @@ describe("native macOS installer", { timeout: 20_000 }, () => {
|
||||
});
|
||||
|
||||
describe("installer semantic version parsing", { timeout: 20_000 }, () => {
|
||||
it.each(["1.2.3-01"])(
|
||||
it.each([
|
||||
"1.2.3-01",
|
||||
"1.2.3-$(printf unexpected)",
|
||||
'1.2.3-"; printf unexpected; #',
|
||||
])(
|
||||
"rejects malformed semantic versions before invoking npm: %s",
|
||||
async (version) => {
|
||||
const fixture = await createFixture();
|
||||
await expect(
|
||||
runInstaller(fixture, ["--version", version, "--dry-run"]),
|
||||
).rejects.toMatchObject({
|
||||
stdout: "",
|
||||
stderr:
|
||||
"REA installation failed: version must be an exact semantic version.\n",
|
||||
});
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { inspectBundleKeyedArchive } from "../../../src/artifacts/apple/KeyedArchiveReader.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { deeplyNestedXmlPlist } from "../../fixtures/keyedArchiveXmlNesting.js";
|
||||
|
||||
it.each([129, 3000])(
|
||||
"reports XML nesting of %i levels as the keyed archive decode limit",
|
||||
async (depth) => {
|
||||
const root = await createTestTempDirectory("rea-keyed-depth-");
|
||||
await writeFile(join(root, "Deep.plist"), deeplyNestedXmlPlist(depth));
|
||||
const rejected = await inspectBundleKeyedArchive({
|
||||
bundlePath: root,
|
||||
targetSha256: "a".repeat(64),
|
||||
parameters: { path: "Deep.plist" },
|
||||
platform: "linux",
|
||||
}).catch((cause: unknown) => cause);
|
||||
// Recursive decoding exhausts the call stack before the projection limit
|
||||
// can report it, so the limit diagnostic must come from the preflight.
|
||||
expect(rejected).toMatchObject({
|
||||
reason: "limit",
|
||||
message:
|
||||
"Cannot decode selected Foundation keyed archive: Plist exceeds 128 nesting levels",
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -9,6 +9,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { SUPPORTED_CLIENT_DEFINITIONS } from "../../../src/application/SupportedClients.js";
|
||||
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import { FRIDA_PROVIDER_IDENTITY } from "../../../src/frida/FridaInstrumentationManager.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
HOPPER_OPERATIONS,
|
||||
@@ -78,6 +79,14 @@ describe("canonical product catalog", () => {
|
||||
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
|
||||
?.capabilities,
|
||||
).toEqual([...GHIDRA_OPERATIONS].sort());
|
||||
expect(
|
||||
catalog.providers.find(({ id }) => id === FRIDA_PROVIDER_IDENTITY.id)
|
||||
?.capabilities,
|
||||
).toEqual(
|
||||
TOOL_CONTRACTS.filter(({ name }) => name.includes("frida"))
|
||||
.map(({ name }) => name)
|
||||
.sort(),
|
||||
);
|
||||
expect(
|
||||
JSON.parse(await readFile("docs/public/product-catalog.json", "utf8")),
|
||||
).toEqual(catalog);
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { 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 { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { skillDestinations } from "../../../src/application/SetupSkill.js";
|
||||
import { supportedClients } from "../../../src/application/SupportedClients.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
|
||||
|
||||
/**
|
||||
* The registration command setup writes on the host running the tests. Windows
|
||||
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
|
||||
*/
|
||||
const command = npxRegistrationCommand(process.platform);
|
||||
|
||||
beforeEach(clearClientLocationEnvironment);
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
const qoderPath = (
|
||||
home: string,
|
||||
platform: NodeJS.Platform = "linux",
|
||||
env: Parameters<typeof supportedClients>[2] = {},
|
||||
) => supportedClients(home, platform, env).find(({ name }) => name === "qoder");
|
||||
|
||||
describe("Qoder configuration paths", () => {
|
||||
it("resolves the user settings file and marker directory", () => {
|
||||
expect(qoderPath("/home/a")).toEqual({
|
||||
name: "qoder",
|
||||
displayName: "Qoder",
|
||||
configPath: join("/home/a", ".qoder", "settings.json"),
|
||||
markerPath: join("/home/a", ".qoder"),
|
||||
format: "json",
|
||||
});
|
||||
expect(qoderPath("/Users/a", "darwin")?.configPath).toBe(
|
||||
join("/Users/a", ".qoder", "settings.json"),
|
||||
);
|
||||
expect(qoderPath("C:\\Users\\a", "win32")?.configPath).toBe(
|
||||
join("C:\\Users\\a", ".qoder", "settings.json"),
|
||||
);
|
||||
});
|
||||
|
||||
it("honors the QODER_CONFIG_DIR override", () => {
|
||||
expect(
|
||||
qoderPath("/home/a", "linux", { QODER_CONFIG_DIR: "/opt/qoder" })
|
||||
?.configPath,
|
||||
).toBe(join("/opt/qoder", "settings.json"));
|
||||
expect(
|
||||
qoderPath("/home/a", "linux", { QODER_CONFIG_DIR: "" })?.configPath,
|
||||
).toBe(join("/home/a", ".qoder", "settings.json"));
|
||||
});
|
||||
|
||||
it("resolves the personal skills directory beside the config root", () => {
|
||||
expect(
|
||||
skillDestinations("/home/a", ["qoder"]).map(({ path }) => path),
|
||||
).toEqual([
|
||||
join("/home/a", ".qoder", "skills", "reverse-engineer-anything"),
|
||||
]);
|
||||
expect(
|
||||
skillDestinations("/home/a", ["qoder"], {
|
||||
QODER_CONFIG_DIR: "/opt/qoder",
|
||||
}).map(({ path }) => path),
|
||||
).toEqual([join("/opt/qoder", "skills", "reverse-engineer-anything")]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Qoder JSON registration", () => {
|
||||
const qoderClient = async () => {
|
||||
const home = await createTestTempDirectory("rea-qoder-");
|
||||
const client = qoderPath(home, process.platform);
|
||||
if (client?.markerPath === undefined)
|
||||
throw new Error("missing Qoder client");
|
||||
await mkdir(client.markerPath, { recursive: true });
|
||||
return { home, client };
|
||||
};
|
||||
|
||||
it("upserts rea into mcpServers while preserving unrelated settings", async () => {
|
||||
const { home, client } = await qoderClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`{
|
||||
"mcpServers": {
|
||||
"other": { "command": "other-server" }
|
||||
},
|
||||
"model": { "name": "qoder-model" }
|
||||
}`,
|
||||
);
|
||||
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
|
||||
expect(parsed.model).toEqual({ name: "qoder-model" });
|
||||
expect(parsed.mcpServers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "unchanged",
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await readClientRegistrationStatuses(home, undefined, {
|
||||
platform: process.platform,
|
||||
environment: {},
|
||||
})
|
||||
).find(({ client }) => client === "qoder"),
|
||||
).toMatchObject({ state: "aligned", command });
|
||||
});
|
||||
|
||||
it("creates the mcpServers table in an existing settings file without servers", async () => {
|
||||
const { client } = await qoderClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
JSON.stringify({ general: { vimMode: false } }, null, 2),
|
||||
);
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.general).toEqual({ vimMode: false });
|
||||
expect(parsed.mcpServers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
});
|
||||
|
||||
it("registers into an empty settings file", async () => {
|
||||
const { client } = await qoderClient();
|
||||
await writeFile(client.configPath, "");
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcpServers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
});
|
||||
|
||||
it("removes only the rea entry on uninstall", async () => {
|
||||
const { home, client } = await qoderClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
JSON.stringify(
|
||||
{ mcpServers: { other: { command: "other-server" } } },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
await configureClientConfiguration(client, {}, command);
|
||||
|
||||
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
|
||||
"removed",
|
||||
);
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
|
||||
expect(parsed.mcpServers.rea).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,66 @@ beforeEach(async () => {
|
||||
|
||||
afterEach(() => openMock.mockReset());
|
||||
|
||||
describe("ZCode fallback cleanup ownership", () => {
|
||||
it.each(["preflight", "configure"])(
|
||||
"retains a failed ZCode fallback close during %s until host cleanup",
|
||||
async (operation) => {
|
||||
const home = await createTestTempDirectory("rea-zcode-fallback-close-");
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
||||
{ HOME: home },
|
||||
);
|
||||
const client = (await host.supportedClients()).find(
|
||||
({ name }) => name === "zcode",
|
||||
);
|
||||
if (client?.zcodeFallbackPath === undefined)
|
||||
throw new Error("ZCode fallback path missing");
|
||||
const fallback = client.zcodeFallbackPath;
|
||||
await mkdir(dirname(fallback), { recursive: true });
|
||||
const original = '{"mcpServers":{"other":{"command":"other"}}}\n';
|
||||
await writeFile(fallback, original);
|
||||
const closeAttempts: object[] = [];
|
||||
let allowClose = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== fallback) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!allowClose) throw new Error("held fallback handle");
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
try {
|
||||
const action =
|
||||
operation === "preflight"
|
||||
? host.inspectClientConfiguration?.(client, {}, ["rea", "mcp"])
|
||||
: host.configureClient(client, {}, ["rea", "mcp"]);
|
||||
if (action === undefined) throw new Error("setup preflight missing");
|
||||
await expect(action).rejects.toMatchObject({
|
||||
_tag: "ConfigurationError",
|
||||
cause: expect.any(RegularFileCleanupFailure),
|
||||
cleanup: { resources: [fallback] },
|
||||
});
|
||||
expect(closeAttempts).toHaveLength(2);
|
||||
expect(closeAttempts[0]).toBe(closeAttempts[1]);
|
||||
expect(await readFile(fallback, "utf8")).toBe(original);
|
||||
await expect(readFile(client.configPath)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
allowClose = true;
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
await host.close?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("setup client configuration cleanup ownership", () => {
|
||||
it("stops client configuration and retries the same alignment handle from host close", async () => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-close-");
|
||||
|
||||
@@ -5,7 +5,11 @@ import { describe, expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { resolveClientConfigTransactionPath } from "../../../src/application/ClientConfigPath.js";
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { readConfigurationFile } from "../../../src/application/ClientConfigurationFiles.js";
|
||||
import {
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
|
||||
const pinnedPackage = PRODUCT_IDENTITY.registrationPackageSpecifier;
|
||||
@@ -330,3 +334,87 @@ describe("JSON client configuration migration and provider paths", () => {
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("JSON client configuration shape diagnostics", () => {
|
||||
it.each([
|
||||
{
|
||||
format: "json" as const,
|
||||
original:
|
||||
'{"__proto__":{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}}',
|
||||
serversKey: "mcpServers",
|
||||
},
|
||||
{
|
||||
format: "opencode" as const,
|
||||
original:
|
||||
'{"mcp":{"__proto__":{"servers":{"rea":{"type":"local","command":["rea","mcp"]}}}}}',
|
||||
serversKey: "mcp",
|
||||
},
|
||||
])(
|
||||
"registers an own server instead of trusting inherited $format settings",
|
||||
async ({ format, original, serversKey }) => {
|
||||
const directory = await createTestTempDirectory("rea-setup-prototype-");
|
||||
const configPath = join(directory, "mcp.json");
|
||||
const client = {
|
||||
name: format === "json" ? "cursor" : "opencode",
|
||||
configPath,
|
||||
format,
|
||||
};
|
||||
await writeFile(configPath, original);
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toMatchObject({ status: "update" });
|
||||
expect(
|
||||
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toMatchObject({ status: "configured" });
|
||||
const document = JSON.parse(await readFile(configPath, "utf8"));
|
||||
expect(Object.hasOwn(document, serversKey)).toBe(true);
|
||||
expect(Object.hasOwn(document[serversKey], "rea")).toBe(true);
|
||||
expect(document[serversKey].rea.command).toEqual(
|
||||
format === "json" ? "rea" : ["rea", "mcp"],
|
||||
);
|
||||
const originalDocument = JSON.parse(original);
|
||||
expect(
|
||||
format === "json" ? document.__proto__ : document[serversKey].__proto__,
|
||||
).toEqual(
|
||||
format === "json"
|
||||
? originalDocument.__proto__
|
||||
: originalDocument[serversKey].__proto__,
|
||||
);
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toMatchObject({ status: "already_current" });
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['{"mcpServers":null,"keep":1}', '"mcpServers" must be an object'],
|
||||
["[]", "The configuration root must be an object"],
|
||||
['{"mcpServers":"x"}', '"mcpServers" must be an object'],
|
||||
] as const)(
|
||||
"names structural shape problems in setup remediation: %s",
|
||||
async (original, problem) => {
|
||||
const directory = await createTestTempDirectory("rea-setup-shape-");
|
||||
const configPath = join(directory, "mcp.json");
|
||||
const client = {
|
||||
name: "cursor",
|
||||
configPath,
|
||||
format: "json" as const,
|
||||
};
|
||||
await writeFile(configPath, original);
|
||||
const read = await readConfigurationFile(configPath, "json");
|
||||
expect(read.ok).toBe(false);
|
||||
if (read.ok) throw new Error("expected malformed configuration");
|
||||
expect(read.error.detail).toBe(
|
||||
`Configuration ${configPath} is malformed: ${problem}`,
|
||||
);
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toEqual({
|
||||
status: "invalid",
|
||||
remediation: `Configuration ${configPath} is malformed: ${problem}`,
|
||||
});
|
||||
expect(await readFile(configPath, "utf8")).toBe(original);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { workflowGit } from "../../support/workflowGit.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
it.skipIf(process.platform === "android")(
|
||||
"reruns test validation after repository or external input changes while reusing preparation",
|
||||
async () => {
|
||||
const config = z
|
||||
.object({
|
||||
tasks: z.record(z.string(), z.record(z.string(), z.unknown())),
|
||||
})
|
||||
.parse(
|
||||
JSON.parse(
|
||||
await readFile(
|
||||
new URL("../../../turbo.json", import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
const testTask = config.tasks["test:run"];
|
||||
const dependencies = z.array(z.string()).parse(testTask?.dependsOn);
|
||||
const root = await createTestTempDirectory("rea-test-cache-");
|
||||
const external = await createTestTempDirectory("rea-test-dependency-");
|
||||
const dependency = join(external, "provider.json");
|
||||
const scripts: Record<string, string> = { "test:run": "node check.mjs" };
|
||||
const tasks: Record<string, unknown> = { "test:run": testTask };
|
||||
for (const [index, task] of dependencies.entries()) {
|
||||
scripts[task] = `node prepare.mjs ${index}`;
|
||||
tasks[task] = {
|
||||
inputs: ["artifact-input.txt"],
|
||||
outputs: [`prepared-${index}.txt`],
|
||||
};
|
||||
}
|
||||
await writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "rea-cache-fixture",
|
||||
version: "1.0.0",
|
||||
private: true,
|
||||
type: "module",
|
||||
packageManager: "npm@11.16.0",
|
||||
scripts,
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "package-lock.json"),
|
||||
JSON.stringify({
|
||||
name: "rea-cache-fixture",
|
||||
version: "1.0.0",
|
||||
lockfileVersion: 3,
|
||||
packages: { "": { name: "rea-cache-fixture", version: "1.0.0" } },
|
||||
}),
|
||||
);
|
||||
await writeFile(join(root, "turbo.json"), JSON.stringify({ tasks }));
|
||||
await writeFile(
|
||||
join(root, "artifact-input.txt"),
|
||||
"unchanged preparation input",
|
||||
);
|
||||
await writeFile(join(root, "README_zh.md"), "aligned");
|
||||
await writeFile(dependency, "healthy");
|
||||
await writeFile(
|
||||
join(root, "prepare.mjs"),
|
||||
'import { appendFileSync } from "node:fs"; appendFileSync(`prepared-${process.argv[2]}.txt`, "prepared\\n");',
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "check.mjs"),
|
||||
`import { readFileSync } from "node:fs"; if(readFileSync("README_zh.md","utf8") !== "aligned" || readFileSync(${JSON.stringify(dependency)},"utf8") !== "healthy") throw new Error("current input is invalid");`,
|
||||
);
|
||||
await workflowGit(root, ["init", "--initial-branch=main"]);
|
||||
await workflowGit(root, ["add", "."]);
|
||||
await workflowGit(root, ["commit", "-m", "test: seed cache fixture"]);
|
||||
const run = () =>
|
||||
execute(
|
||||
process.execPath,
|
||||
[
|
||||
join(process.cwd(), "node_modules/turbo/bin/turbo"),
|
||||
"run",
|
||||
"test:run",
|
||||
"--output-logs=errors-only",
|
||||
],
|
||||
{ cwd: root, env: { ...process.env, TURBO_DAEMON: "false" } },
|
||||
);
|
||||
await run();
|
||||
await writeFile(join(root, "README_zh.md"), "wrong command");
|
||||
await expect(run()).rejects.toMatchObject({ code: 1 });
|
||||
await writeFile(join(root, "README_zh.md"), "aligned");
|
||||
await run();
|
||||
await writeFile(dependency, "faulty");
|
||||
await expect(run()).rejects.toMatchObject({ code: 1 });
|
||||
await expect(run()).rejects.toMatchObject({ code: 1 });
|
||||
await writeFile(dependency, "healthy");
|
||||
await run();
|
||||
for (const index of dependencies.keys()) {
|
||||
expect(await readFile(join(root, `prepared-${index}.txt`), "utf8")).toBe(
|
||||
"prepared\n",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,173 @@
|
||||
import { 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 { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { skillDestinations } from "../../../src/application/SetupSkill.js";
|
||||
import { supportedClients } from "../../../src/application/SupportedClients.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
|
||||
|
||||
/**
|
||||
* The registration command setup writes on the host running the tests. Windows
|
||||
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
|
||||
*/
|
||||
const command = npxRegistrationCommand(process.platform);
|
||||
|
||||
beforeEach(clearClientLocationEnvironment);
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
const traePath = (
|
||||
home: string,
|
||||
platform: NodeJS.Platform = "linux",
|
||||
env: Parameters<typeof supportedClients>[2] = {},
|
||||
) => supportedClients(home, platform, env).find(({ name }) => name === "trae");
|
||||
|
||||
describe("Trae configuration paths", () => {
|
||||
it("resolves the VS Code-style user directory per platform", () => {
|
||||
expect(traePath("/home/a", "linux", {})?.configPath).toBe(
|
||||
join("/home/a", ".config", "Trae", "User", "mcp.json"),
|
||||
);
|
||||
expect(
|
||||
traePath("/home/a", "linux", { XDG_CONFIG_HOME: "/xdg" })?.configPath,
|
||||
).toBe(join("/xdg", "Trae", "User", "mcp.json"));
|
||||
expect(traePath("/Users/a", "darwin")?.configPath).toBe(
|
||||
join(
|
||||
"/Users/a",
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Trae",
|
||||
"User",
|
||||
"mcp.json",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
traePath("C:\\Users\\a", "win32", {
|
||||
APPDATA: "C:\\Users\\a\\AppData\\Roaming",
|
||||
})?.configPath,
|
||||
).toBe(join("C:\\Users\\a\\AppData\\Roaming", "Trae", "User", "mcp.json"));
|
||||
expect(
|
||||
traePath("C:\\Users\\a", "win32", {
|
||||
APPDATA: "C:\\Users\\a\\AppData\\Roaming",
|
||||
})?.markerPath,
|
||||
).toBe(join("C:\\Users\\a\\AppData\\Roaming", "Trae", "User"));
|
||||
});
|
||||
|
||||
it("resolves the registration format as the plain mcpServers JSON dialect", () => {
|
||||
expect(traePath("/home/a")?.format).toBe("json");
|
||||
});
|
||||
|
||||
it("resolves the personal skills directory under the home root", () => {
|
||||
expect(
|
||||
skillDestinations("/home/a", ["trae"]).map(({ path }) => path),
|
||||
).toEqual([
|
||||
join("/home/a", ".trae", "skills", "reverse-engineer-anything"),
|
||||
]);
|
||||
expect(
|
||||
skillDestinations("C:\\Users\\a", ["trae"], {}, "win32").map(
|
||||
({ path }) => path,
|
||||
),
|
||||
).toEqual([
|
||||
join("C:\\Users\\a", ".trae", "skills", "reverse-engineer-anything"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Trae JSON registration", () => {
|
||||
const traeClient = async () => {
|
||||
const home = await createTestTempDirectory("rea-trae-");
|
||||
const client = traePath(home, process.platform);
|
||||
if (client?.markerPath === undefined)
|
||||
throw new Error("missing Trae client");
|
||||
await mkdir(client.markerPath, { recursive: true });
|
||||
return { home, client };
|
||||
};
|
||||
|
||||
it("upserts rea into mcpServers while preserving unrelated settings", async () => {
|
||||
const { home, client } = await traeClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`{
|
||||
"mcpServers": {
|
||||
"other": { "command": "other-server" }
|
||||
}
|
||||
}`,
|
||||
);
|
||||
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
|
||||
expect(parsed.mcpServers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "unchanged",
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await readClientRegistrationStatuses(home, undefined, {
|
||||
platform: process.platform,
|
||||
environment: {},
|
||||
})
|
||||
).find(({ client }) => client === "trae"),
|
||||
).toMatchObject({ state: "aligned", command });
|
||||
});
|
||||
|
||||
it("creates the mcpServers table in an existing mcp.json without servers", async () => {
|
||||
const { client } = await traeClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
JSON.stringify({ unrelated: { setting: true } }, null, 2),
|
||||
);
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.unrelated).toEqual({ setting: true });
|
||||
expect(parsed.mcpServers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
});
|
||||
|
||||
it("registers into an empty mcp.json", async () => {
|
||||
const { client } = await traeClient();
|
||||
await writeFile(client.configPath, "");
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcpServers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
});
|
||||
|
||||
it("removes only the rea entry on uninstall", async () => {
|
||||
const { home, client } = await traeClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
JSON.stringify(
|
||||
{ mcpServers: { other: { command: "other-server" } } },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
await configureClientConfiguration(client, {}, command);
|
||||
|
||||
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
|
||||
"removed",
|
||||
);
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
|
||||
expect(parsed.mcpServers.rea).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,401 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
|
||||
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
|
||||
import {
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { skillDestinations } from "../../../src/application/SetupSkill.js";
|
||||
import { supportedClients } from "../../../src/application/SupportedClients.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
|
||||
|
||||
/**
|
||||
* The registration command setup writes on the host running the tests. Windows
|
||||
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
|
||||
*/
|
||||
const command = npxRegistrationCommand(process.platform);
|
||||
|
||||
beforeEach(clearClientLocationEnvironment);
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
const zcodePath = (
|
||||
home: string,
|
||||
platform: NodeJS.Platform = "linux",
|
||||
env: Parameters<typeof supportedClients>[2] = {},
|
||||
) => supportedClients(home, platform, env).find(({ name }) => name === "zcode");
|
||||
|
||||
describe("ZCode configuration paths", () => {
|
||||
it("resolves the user config file and marker directory", () => {
|
||||
expect(zcodePath("/home/a")).toEqual({
|
||||
name: "zcode",
|
||||
displayName: "ZCode",
|
||||
configPath: join("/home/a", ".zcode", "cli", "config.json"),
|
||||
markerPath: join("/home/a", ".zcode", "cli"),
|
||||
format: "zcode",
|
||||
zcodeFallbackPath: join("/home/a", ".agents", "mcp.json"),
|
||||
});
|
||||
expect(zcodePath("/Users/a", "darwin")?.configPath).toBe(
|
||||
join("/Users/a", ".zcode", "cli", "config.json"),
|
||||
);
|
||||
expect(zcodePath("C:\\Users\\a", "win32")?.configPath).toBe(
|
||||
join("C:\\Users\\a", ".zcode", "cli", "config.json"),
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves the personal skills directory beside the config root", () => {
|
||||
expect(
|
||||
skillDestinations("/home/a", ["zcode"]).map(({ path }) => path),
|
||||
).toEqual([
|
||||
join("/home/a", ".zcode", "skills", "reverse-engineer-anything"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const zcodeClient = async () => {
|
||||
const home = await createTestTempDirectory("rea-zcode-");
|
||||
const client = zcodePath(home, process.platform);
|
||||
if (client?.markerPath === undefined) throw new Error("missing ZCode client");
|
||||
await mkdir(client.markerPath, { recursive: true });
|
||||
return { home, client };
|
||||
};
|
||||
|
||||
describe("ZCode JSON registration", () => {
|
||||
it("upserts rea into mcp.servers while preserving unrelated settings", async () => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
`{
|
||||
"mcp": {
|
||||
"rea": { "unrelated": true },
|
||||
"servers": {
|
||||
"other": { "command": "other-server" }
|
||||
}
|
||||
}
|
||||
}`,
|
||||
);
|
||||
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcp.rea).toEqual({ unrelated: true });
|
||||
expect(parsed.mcp.servers.other).toEqual({ command: "other-server" });
|
||||
expect(parsed.mcp.servers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "unchanged",
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await readClientRegistrationStatuses(home, undefined, {
|
||||
platform: process.platform,
|
||||
environment: {},
|
||||
})
|
||||
).find(({ client }) => client === "zcode"),
|
||||
).toMatchObject({ state: "aligned", command });
|
||||
});
|
||||
|
||||
it("creates the mcp.servers table in an existing config without servers", async () => {
|
||||
const { client } = await zcodeClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
JSON.stringify({ ui: { theme: "dark" } }, null, 2),
|
||||
);
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.ui).toEqual({ theme: "dark" });
|
||||
expect(parsed.mcp.servers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
});
|
||||
|
||||
it("registers into an empty config file", async () => {
|
||||
const { client } = await zcodeClient();
|
||||
await writeFile(client.configPath, "");
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcp.servers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
});
|
||||
|
||||
it("removes only the rea entry on uninstall", async () => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
JSON.stringify(
|
||||
{ mcp: { servers: { other: { command: "other-server" } } } },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
await configureClientConfiguration(client, {}, command);
|
||||
|
||||
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
|
||||
"removed",
|
||||
);
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcp.servers.other).toEqual({ command: "other-server" });
|
||||
expect(parsed.mcp.servers.rea).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
const fallbackPath = (home: string) => join(home, ".agents", "mcp.json");
|
||||
|
||||
describe("ZCode .agents fallback preservation", () => {
|
||||
it.each([undefined, '{"ui":{"theme":"dark"}}\n', '{"mcp":{"servers":{}}}\n'])(
|
||||
"migrates fallback servers with native config %s",
|
||||
async (original) => {
|
||||
const { home, client } = await zcodeClient();
|
||||
if (original !== undefined) await writeFile(client.configPath, original);
|
||||
await mkdir(join(home, ".agents"), { recursive: true });
|
||||
await writeFile(
|
||||
fallbackPath(home),
|
||||
JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
other: { command: "other-server", env: { TOKEN: "x" } },
|
||||
rea: {
|
||||
command: "old-rea",
|
||||
args: ["mcp"],
|
||||
env: {
|
||||
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
|
||||
GHIDRA_INSTALL_DIR: "/caller/ghidra",
|
||||
CALLER_CHOICE: "keep-me",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcp.servers.other).toEqual({
|
||||
command: "other-server",
|
||||
env: { TOKEN: "x" },
|
||||
});
|
||||
expect(parsed.mcp.servers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
env: {
|
||||
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
|
||||
GHIDRA_INSTALL_DIR: "/caller/ghidra",
|
||||
CALLER_CHOICE: "keep-me",
|
||||
},
|
||||
});
|
||||
if (original !== undefined) {
|
||||
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
|
||||
original,
|
||||
);
|
||||
if (JSON.parse(original).ui !== undefined)
|
||||
expect(parsed.ui).toEqual({ theme: "dark" });
|
||||
}
|
||||
// The fallback file stays in place; ZCode ignores it from now on.
|
||||
expect(
|
||||
JSON.parse(await readFile(fallbackPath(home), "utf8")).mcpServers.other,
|
||||
).toEqual({ command: "other-server", env: { TOKEN: "x" } });
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "unchanged",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves an existing native table alone instead of merging the fallback", async () => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await mkdir(join(home, ".agents"), { recursive: true });
|
||||
await writeFile(
|
||||
fallbackPath(home),
|
||||
JSON.stringify(
|
||||
{ mcpServers: { shared: { command: "fallback-server" } } },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
JSON.stringify(
|
||||
{ mcp: { servers: { existing: { command: "existing-server" } } } },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
|
||||
expect(parsed.mcp.servers.existing).toEqual({
|
||||
command: "existing-server",
|
||||
});
|
||||
expect(parsed.mcp.servers.rea).toEqual({
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
});
|
||||
expect(parsed.mcp.servers.shared).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ZCode fallback admission", () => {
|
||||
it.each([{ PORT: 123 }, { REA_MCP_INPUT_SCHEMA_PROFILE: "unknown" }])(
|
||||
"refuses malformed fallback REA environment %j before native writes",
|
||||
async (env) => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await mkdir(join(home, ".agents"), { recursive: true });
|
||||
const original = JSON.stringify({
|
||||
mcpServers: { rea: { command: "old-rea", env } },
|
||||
});
|
||||
await writeFile(fallbackPath(home), original);
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, command),
|
||||
).toMatchObject({
|
||||
status: "invalid",
|
||||
remediation: expect.stringContaining(
|
||||
Object.keys(env)[0] ?? "environment",
|
||||
),
|
||||
});
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
await expect(readFile(client.configPath)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
expect(await readFile(fallbackPath(home), "utf8")).toBe(original);
|
||||
},
|
||||
);
|
||||
|
||||
it("fails closed when the fallback configuration is malformed", async () => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await mkdir(join(home, ".agents"), { recursive: true });
|
||||
await writeFile(fallbackPath(home), "{ not json");
|
||||
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
await expect(readFile(client.configPath, "utf8")).rejects.toThrow();
|
||||
expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
|
||||
{ status: "invalid" },
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed when the fallback path is not a regular file", async () => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await mkdir(fallbackPath(home), { recursive: true });
|
||||
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
await expect(readFile(client.configPath, "utf8")).rejects.toThrow();
|
||||
expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
|
||||
{ status: "invalid" },
|
||||
);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects a FIFO fallback without blocking on it",
|
||||
async () => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await mkdir(join(home, ".agents"), { recursive: true });
|
||||
await promisify(execFile)("mkfifo", [fallbackPath(home)]);
|
||||
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
await expect(readFile(client.configPath, "utf8")).rejects.toThrow();
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, command),
|
||||
).toMatchObject({ status: "invalid" });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("ZCode disabled registrations", () => {
|
||||
it("reports enable: false as stale and repairs it on setup", async () => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await writeFile(
|
||||
client.configPath,
|
||||
JSON.stringify(
|
||||
{
|
||||
mcp: {
|
||||
servers: {
|
||||
rea: {
|
||||
command: command[0],
|
||||
args: command.slice(1),
|
||||
enable: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
const statusFor = async () =>
|
||||
(
|
||||
await readClientRegistrationStatuses(home, undefined, {
|
||||
platform: process.platform,
|
||||
environment: {},
|
||||
})
|
||||
).find(({ client }) => client === "zcode");
|
||||
expect(await statusFor()).toMatchObject({ state: "stale" });
|
||||
|
||||
expect(
|
||||
(await configureClientConfiguration(client, {}, command)).status,
|
||||
).toBe("configured");
|
||||
expect(await statusFor()).toMatchObject({ state: "aligned", command });
|
||||
});
|
||||
});
|
||||
|
||||
describe("ZCode strict native JSON", () => {
|
||||
it.each(['{ // comment\n "mcp": {}}', '{"mcp":{},}', "\uFEFF{}"])(
|
||||
"rejects unreadable native syntax without modifying %s",
|
||||
async (original) => {
|
||||
const { home, client } = await zcodeClient();
|
||||
await writeFile(client.configPath, original);
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, command),
|
||||
).toMatchObject({ status: "invalid" });
|
||||
expect(await configureClientConfiguration(client, {}, command)).toEqual({
|
||||
status: "failed",
|
||||
reason: "readback",
|
||||
});
|
||||
expect(await readFile(client.configPath, "utf8")).toBe(original);
|
||||
await expect(
|
||||
readFile(`${client.configPath}.rea.backup`),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(
|
||||
(
|
||||
await readClientRegistrationStatuses(home, undefined, {
|
||||
platform: process.platform,
|
||||
environment: {},
|
||||
})
|
||||
).find(({ client }) => client === "zcode"),
|
||||
).toMatchObject({ state: "invalid" });
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { readFile, unlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
@@ -12,8 +13,81 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
createEvidence,
|
||||
parseEvidence,
|
||||
type Evidence,
|
||||
} from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
artifactInspectionResultSchema,
|
||||
createArtifactInspection,
|
||||
} from "../../../src/domain/artifactInspection.js";
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
type ArtifactInventoryResult,
|
||||
} from "../../../src/domain/artifactGraph.js";
|
||||
import {
|
||||
analysisViewResultSchema,
|
||||
type AnalysisViewResult,
|
||||
} from "../../../src/domain/analysisView/analysisView.js";
|
||||
|
||||
it("inspects a standalone keyed archive through MCP with original object identities", async () => {
|
||||
const assertInventorySubjectValidation = async (
|
||||
client: Client,
|
||||
source: Evidence,
|
||||
): Promise<void> => {
|
||||
const result =
|
||||
source.operation === "inspect_artifact"
|
||||
? artifactInspectionResultSchema.parse(source.normalized_result)
|
||||
.substeps[0]?.evidence.normalized_result
|
||||
: source.normalized_result;
|
||||
const inventory = artifactInventoryResultSchema.parse(result);
|
||||
if (source.subject === null)
|
||||
throw new Error("Fixture requires a known subject");
|
||||
for (const target of [
|
||||
undefined,
|
||||
{
|
||||
path: source.subject.local_path,
|
||||
sha256: inventory.manifest.root_sha256,
|
||||
format: "file" as const,
|
||||
},
|
||||
{
|
||||
path: source.subject.local_path,
|
||||
sha256: "f".repeat(64),
|
||||
format: inventory.manifest.root_format,
|
||||
},
|
||||
]) {
|
||||
const inconsistent = createEvidence(target, source.provider, {
|
||||
operation: source.operation,
|
||||
parameters: source.parameters,
|
||||
result: source.normalized_result,
|
||||
});
|
||||
for (const view of [
|
||||
{ kind: "summary" },
|
||||
{ kind: "inventory", collection: "nodes", offset: 0, limit: 1 },
|
||||
]) {
|
||||
const reply = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: { source: { kind: "inline", evidence: inconsistent }, view },
|
||||
});
|
||||
expect(parseMcpToolError(reply)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["source"],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining("subject does not match"),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
it("preserves keyed archive identities and rejects inconsistent inventory carrier subjects", async () => {
|
||||
const directory = await createTestTempDirectory("rea-keyed-mcp-");
|
||||
const path = join(directory, "archive.plist");
|
||||
await writeFile(
|
||||
@@ -99,6 +173,19 @@ it("inspects a standalone keyed archive through MCP with original object identit
|
||||
},
|
||||
},
|
||||
});
|
||||
const inspected = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
const parent = parseEvidence(inspected.structuredContent);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
parent.normalized_result,
|
||||
);
|
||||
const inventory = inspection.substeps[0]?.evidence;
|
||||
if (inventory === undefined) throw new Error("Missing inventory Evidence");
|
||||
await assertInventorySubjectValidation(client, inventory);
|
||||
await assertInventorySubjectValidation(client, parent);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
@@ -106,7 +193,201 @@ it("inspects a standalone keyed archive through MCP with original object identit
|
||||
}
|
||||
});
|
||||
|
||||
it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", async () => {
|
||||
const createInventoryViewReader = async (client: Client, parent: Evidence) => {
|
||||
const advertised = (await client.listTools()).tools.find(
|
||||
(tool) => tool.name === "inspect_analysis_view",
|
||||
);
|
||||
if (advertised?.outputSchema === undefined)
|
||||
throw new Error("Missing advertised view schemas");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const inputSchema: Record<string, unknown> = advertised.inputSchema;
|
||||
const outputSchema: Record<string, unknown> = advertised.outputSchema;
|
||||
const validateInput = ajv.compile(inputSchema);
|
||||
const validateOutput = ajv.compile(outputSchema);
|
||||
expect(
|
||||
validateInput({
|
||||
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
||||
view: { kind: "inventory", collection: "nodes", logical_paths: [] },
|
||||
}),
|
||||
).toBe(false);
|
||||
const readView = async (
|
||||
view: Record<string, unknown>,
|
||||
source = {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: parent.evidence_id,
|
||||
},
|
||||
) => {
|
||||
const arguments_ = { source, view };
|
||||
expect(
|
||||
validateInput(arguments_),
|
||||
JSON.stringify(validateInput.errors),
|
||||
).toBe(true);
|
||||
const reply = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: arguments_,
|
||||
});
|
||||
if (reply.isError)
|
||||
throw new Error(JSON.stringify(parseMcpToolError(reply)));
|
||||
expect(
|
||||
validateOutput(reply.structuredContent),
|
||||
JSON.stringify(validateOutput.errors),
|
||||
).toBe(true);
|
||||
const evidence = parseEvidence(reply.structuredContent);
|
||||
return {
|
||||
evidence,
|
||||
result: analysisViewResultSchema.parse(evidence.normalized_result),
|
||||
};
|
||||
};
|
||||
return readView;
|
||||
};
|
||||
|
||||
const assertHistoricalInventory = async (
|
||||
client: Client,
|
||||
input: {
|
||||
archive: string;
|
||||
parent: Evidence;
|
||||
inventoryEvidence: Evidence;
|
||||
graph: ArtifactInventoryResult;
|
||||
},
|
||||
) => {
|
||||
const { archive, parent, inventoryEvidence, graph } = input;
|
||||
// Historical records may omit a later inventory field. Input parsing must
|
||||
// not insert defaults inside that authenticated child Evidence.
|
||||
const { integrity_contradictions: _contradictions, ...legacyInventory } =
|
||||
graph;
|
||||
const legacyTarget = {
|
||||
path: archive,
|
||||
sha256: graph.manifest.root_sha256,
|
||||
format: "zip" as const,
|
||||
};
|
||||
const legacySource = createEvidence(
|
||||
legacyTarget,
|
||||
inventoryEvidence.provider,
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: legacyInventory,
|
||||
},
|
||||
);
|
||||
const legacyInspection = createArtifactInspection(legacySource);
|
||||
expect(legacyInspection.substeps[0]?.evidence).toEqual(legacySource);
|
||||
expect(
|
||||
legacyInspection.substeps[0]?.evidence.normalized_result,
|
||||
).not.toHaveProperty("integrity_contradictions");
|
||||
const legacyParent = createEvidence(legacyTarget, parent.provider, {
|
||||
operation: "inspect_artifact",
|
||||
parameters: {},
|
||||
result: legacyInspection,
|
||||
});
|
||||
const legacyReply = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: { kind: "inline", evidence: legacyParent },
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
});
|
||||
expect(
|
||||
legacyReply.isError,
|
||||
JSON.stringify(legacyReply.structuredContent),
|
||||
).not.toBe(true);
|
||||
expect(
|
||||
parseEvidence(legacyReply.structuredContent).normalized_result,
|
||||
).toMatchObject({
|
||||
parent_evidence_id: legacyParent.evidence_id,
|
||||
summary: {
|
||||
source_complete: true,
|
||||
inventory_evidence_ids: [legacySource.evidence_id],
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const assertPortableRoundtrip = async (
|
||||
client: Client,
|
||||
directory: string,
|
||||
parent: Evidence,
|
||||
originalView: AnalysisViewResult,
|
||||
) => {
|
||||
const saved = join(directory, "evidence.json");
|
||||
const exported = await client.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: saved },
|
||||
});
|
||||
if (exported.isError)
|
||||
throw new Error(JSON.stringify(parseMcpToolError(exported)));
|
||||
const closed = await client.callTool({
|
||||
name: "close_binary",
|
||||
arguments: {},
|
||||
});
|
||||
if (closed.isError)
|
||||
throw new Error(JSON.stringify(parseMcpToolError(closed)));
|
||||
const missing = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
});
|
||||
expect(parseMcpToolError(missing)).toMatchObject({
|
||||
error: { details: { reason: "missing" } },
|
||||
});
|
||||
const imported = await client.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path: saved },
|
||||
});
|
||||
if (imported.isError)
|
||||
throw new Error(JSON.stringify(parseMcpToolError(imported)));
|
||||
const restored = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
});
|
||||
if (restored.isError)
|
||||
throw new Error(JSON.stringify(parseMcpToolError(restored)));
|
||||
expect(parseEvidence(restored.structuredContent).normalized_result).toEqual(
|
||||
originalView,
|
||||
);
|
||||
};
|
||||
|
||||
const assertSummaryDelivery = async (
|
||||
client: Client,
|
||||
session: ReturnType<typeof createTestBinarySession>,
|
||||
complete: Evidence,
|
||||
) => {
|
||||
expect(complete.parameters).not.toHaveProperty("detail");
|
||||
const reply = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: { detail: "summary" },
|
||||
});
|
||||
expect(reply.isError, JSON.stringify(reply.structuredContent)).not.toBe(true);
|
||||
const projected = parseEvidence(reply.structuredContent);
|
||||
const view = analysisViewResultSchema.parse(projected.normalized_result);
|
||||
expect(projected.operation).toBe("inspect_analysis_view");
|
||||
expect(view.kind).toBe("summary");
|
||||
const retained = session.evidenceById(view.parent_evidence_id);
|
||||
if (retained === undefined) throw new Error("Missing complete inspection");
|
||||
expect(retained.operation).toBe("inspect_artifact");
|
||||
expect(retained.parameters).toMatchObject({ detail: "summary" });
|
||||
expect(retained.normalized_result).toEqual(complete.normalized_result);
|
||||
expect(retained.evidence_id).not.toBe(projected.evidence_id);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
retained.normalized_result,
|
||||
);
|
||||
expect(
|
||||
session.evidenceById(inspection.substeps[0]?.evidence_id ?? ""),
|
||||
).toEqual(inspection.substeps[0]?.evidence);
|
||||
const explicit = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: { detail: "complete" },
|
||||
});
|
||||
expect(explicit.isError).not.toBe(true);
|
||||
expect(parseEvidence(explicit.structuredContent).normalized_result).toEqual(
|
||||
complete.normalized_result,
|
||||
);
|
||||
};
|
||||
|
||||
it("keeps complete ZIP output and reads retained inventory views after the source is removed", async () => {
|
||||
const directory = await createTestTempDirectory("rea-artifact-inline-");
|
||||
const archive = join(directory, "many.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
@@ -138,27 +419,154 @@ it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", as
|
||||
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const inspection = z
|
||||
.object({
|
||||
substeps: z.array(
|
||||
z.object({
|
||||
evidence: z.object({
|
||||
normalized_result: z.object({
|
||||
occurrences: z.array(z.object({ logical_path: z.string() })),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.parse(
|
||||
z
|
||||
.object({ normalized_result: z.unknown() })
|
||||
.parse(result.structuredContent).normalized_result,
|
||||
);
|
||||
const parent = parseEvidence(result.structuredContent);
|
||||
await assertSummaryDelivery(client, session, parent);
|
||||
const parsedInspection = artifactInspectionResultSchema.parse(
|
||||
parent.normalized_result,
|
||||
);
|
||||
const inventoryEvidence = parsedInspection.substeps[0]?.evidence;
|
||||
if (inventoryEvidence === undefined)
|
||||
throw new Error("Missing inventory Evidence");
|
||||
const graph = artifactInventoryResultSchema.parse(
|
||||
inventoryEvidence.normalized_result,
|
||||
);
|
||||
expect(graph.occurrences).toHaveLength(fileCount + 1);
|
||||
// Follow-ups must use retained source facts, not reopen this archive.
|
||||
await unlink(archive);
|
||||
const readView = await createInventoryViewReader(client, parent);
|
||||
const summary = await readView({ kind: "summary" });
|
||||
expect(summary.result).toMatchObject({
|
||||
kind: "summary",
|
||||
parent_evidence_id: parent.evidence_id,
|
||||
artifact: { path: archive, sha256: graph.manifest.root_sha256 },
|
||||
summary: {
|
||||
manifest: graph.manifest,
|
||||
source_complete: true,
|
||||
available_counts: { occurrences: fileCount + 1 },
|
||||
observed_entry_kind_counts: { file: fileCount + 1 },
|
||||
inventory_evidence_ids: [inventoryEvidence.evidence_id],
|
||||
},
|
||||
});
|
||||
expect(summary.evidence.evidence_links).toEqual([parent.evidence_id]);
|
||||
const paths = ["files/0.txt", "files/519.txt", "missing.txt"];
|
||||
const selected = await readView({
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: paths,
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
});
|
||||
expect(selected.result).toMatchObject({
|
||||
kind: "inventory",
|
||||
source_complete: true,
|
||||
items: graph.occurrences
|
||||
.filter((row) => paths.includes(row.logical_path))
|
||||
.slice(0, 1),
|
||||
coverage: { examined: 1, total: 2, next_offset: 1, exhausted: false },
|
||||
});
|
||||
const next = await readView({
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: paths,
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
});
|
||||
expect(next.result).toMatchObject({
|
||||
coverage: { examined: 1, next_offset: null, exhausted: true },
|
||||
});
|
||||
const none = await readView({
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: [],
|
||||
});
|
||||
expect(none.result).toMatchObject({
|
||||
items: [],
|
||||
coverage: { total: 0, exhausted: true },
|
||||
});
|
||||
|
||||
const partial = createEvidence(
|
||||
{ path: archive, sha256: graph.manifest.root_sha256, format: "zip" },
|
||||
inventoryEvidence.provider,
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: { ...graph, occurrences: graph.occurrences.slice(0, 1) },
|
||||
},
|
||||
);
|
||||
const partialReply = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: { kind: "inline", evidence: partial },
|
||||
view: {
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: ["missing.txt"],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(
|
||||
inspection.substeps[0]?.evidence.normalized_result.occurrences,
|
||||
).toHaveLength(fileCount + 1);
|
||||
parseEvidence(partialReply.structuredContent).normalized_result,
|
||||
).toMatchObject({
|
||||
source_complete: false,
|
||||
items: [],
|
||||
unknowns: expect.arrayContaining([
|
||||
expect.stringContaining("Missing matches do not establish absence"),
|
||||
]),
|
||||
});
|
||||
|
||||
await assertHistoricalInventory(client, {
|
||||
archive,
|
||||
parent,
|
||||
inventoryEvidence,
|
||||
graph,
|
||||
});
|
||||
await assertPortableRoundtrip(client, directory, parent, summary.result);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses summary delivery without a retained Evidence owner and preserves complete delivery", async () => {
|
||||
const directory = await createTestTempDirectory("rea-inventory-fixed-");
|
||||
const archive = join(directory, "fixture.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("main.js", new TextReader("console.log('fixed');\n"));
|
||||
await writeFile(archive, await writer.close());
|
||||
const session = createTestBinarySession(new ArtifactProvider(process.env));
|
||||
const opened = await session.open(archive);
|
||||
if (!opened.ok) throw opened.error;
|
||||
const server = createServer({ kind: "fixed", analysis: session });
|
||||
const client = new Client({ name: "artifact-fixed-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const summary = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: { detail: "summary" },
|
||||
});
|
||||
expect(parseMcpToolError(summary)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("does not retain Evidence"),
|
||||
},
|
||||
});
|
||||
const complete = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(complete.isError).not.toBe(true);
|
||||
expect(
|
||||
parseEvidence(complete.structuredContent).normalized_result,
|
||||
).toMatchObject({
|
||||
substeps: [expect.objectContaining({ operation: "inventory_artifact" })],
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import type { FlutterBuildAnalysisPort } from "../../../src/application/flutter/FlutterBuildAnalysisPort.js";
|
||||
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
|
||||
import { assertAdvertisedMcpContracts } from "./mcpContractHarness.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";
|
||||
|
||||
const identity = {
|
||||
id: "flutter",
|
||||
name: "Flutter build identification",
|
||||
version: null,
|
||||
};
|
||||
|
||||
const SNAPSHOT_HASH = "65817c30a78bb44c3dc3771876b6010a";
|
||||
|
||||
/** One shared target identity for both fake operation results. */
|
||||
const target = {
|
||||
path: "/targets/gallery.apk",
|
||||
bytes: 117817550,
|
||||
sha256: "a".repeat(64),
|
||||
};
|
||||
|
||||
const inspectExecution = () =>
|
||||
createAnalysisExecution(
|
||||
{
|
||||
target,
|
||||
abi: "arm64-v8a",
|
||||
libapp: {
|
||||
coverage: "complete",
|
||||
bytes: 24691632,
|
||||
sha256: "b".repeat(64),
|
||||
snapshot_hash: SNAPSHOT_HASH,
|
||||
snapshot_hash_candidates: [SNAPSHOT_HASH],
|
||||
snapshot_hash_sources: 2,
|
||||
sections: [
|
||||
{
|
||||
name: "_kDartVmSnapshotData",
|
||||
offset: 4096,
|
||||
size: 52,
|
||||
magic_valid: true,
|
||||
kind: 3,
|
||||
header_length: 48,
|
||||
},
|
||||
{
|
||||
name: "_kDartIsolateSnapshotData",
|
||||
offset: 8192,
|
||||
size: 1536,
|
||||
magic_valid: true,
|
||||
kind: 3,
|
||||
header_length: 48,
|
||||
},
|
||||
],
|
||||
},
|
||||
string_pool: {
|
||||
coverage: "complete",
|
||||
package_uris: [
|
||||
"package:adaptive_breakpoints/src/adaptive_breakpoints.dart",
|
||||
],
|
||||
package_uri_count_at_least: 1,
|
||||
dart_uris: ["dart:_http"],
|
||||
dart_uri_count_at_least: 1,
|
||||
class_like_tokens: ["AdaptiveBreakpoint"],
|
||||
class_like_token_count_at_least: 1,
|
||||
printable_run_count: 4,
|
||||
},
|
||||
coverage: "complete",
|
||||
},
|
||||
identity,
|
||||
);
|
||||
|
||||
const identifyExecution = () =>
|
||||
createAnalysisExecution(
|
||||
{
|
||||
target,
|
||||
flutter_detected: true,
|
||||
abis: [
|
||||
{
|
||||
abi: "arm64-v8a",
|
||||
libapp: {
|
||||
present: true,
|
||||
bytes: 24691632,
|
||||
sha256: "b".repeat(64),
|
||||
elf_header_valid: true,
|
||||
snapshot_hash_sources: 2,
|
||||
snapshot_hash_candidates: [SNAPSHOT_HASH],
|
||||
snapshot_hash: SNAPSHOT_HASH,
|
||||
},
|
||||
libflutter: {
|
||||
present: true,
|
||||
bytes: 9073432,
|
||||
sha256: "c".repeat(64),
|
||||
build_id: "e8d907ef7c175ec4313f47111019adc9588c5f61",
|
||||
build_id_candidates: ["e8d907ef7c175ec4313f47111019adc9588c5f61"],
|
||||
dart_version: null,
|
||||
dart_version_capped: false,
|
||||
toolchain_lines: ["Android (5900059) clang version 9.0.8"],
|
||||
toolchain_capped: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
coverage: "complete",
|
||||
},
|
||||
identity,
|
||||
);
|
||||
|
||||
/** A recording-free provider answering both Flutter operations inline. */
|
||||
const fakeProvider = (): FlutterBuildAnalysisPort => ({
|
||||
async inspectAvailability() {
|
||||
return { status: "available", code: null, reason: null, diagnostics: {} };
|
||||
},
|
||||
async close() {},
|
||||
async execute(request) {
|
||||
return ok(
|
||||
request.operation === "inspect_dart_aot"
|
||||
? inspectExecution()
|
||||
: identifyExecution(),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
it("advertises an exact valid Flutter schema and records inline evidence through MCP", async () => {
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("deep provider must not start");
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ flutterAnalysis: fakeProvider() },
|
||||
);
|
||||
onTestFinished(() => server.close());
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
const client = new Client({ name: "flutter-boundary", version: "0.0.0" });
|
||||
onTestFinished(() => client.close());
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const { tools } = await client.listTools();
|
||||
assertAdvertisedMcpContracts(
|
||||
["identify_flutter_build", "inspect_dart_aot"],
|
||||
tools,
|
||||
);
|
||||
|
||||
const identified = await client.callTool({
|
||||
name: "identify_flutter_build",
|
||||
arguments: { path: "/targets/gallery.apk" },
|
||||
});
|
||||
expect(identified.isError).not.toBe(true);
|
||||
const text = (identified.content as { readonly text?: string }[])
|
||||
.map((part) => part.text ?? "")
|
||||
.join("");
|
||||
const evidence = parseEvidence(JSON.parse(text));
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
flutter_detected: true,
|
||||
abis: [
|
||||
{
|
||||
abi: "arm64-v8a",
|
||||
libapp: { snapshot_hash: SNAPSHOT_HASH },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const inspected = await client.callTool({
|
||||
name: "inspect_dart_aot",
|
||||
arguments: { path: "/targets/gallery.apk", abi: "arm64-v8a" },
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
const inspectedText = (inspected.content as { readonly text?: string }[])
|
||||
.map((part) => part.text ?? "")
|
||||
.join("");
|
||||
const inspectedEvidence = parseEvidence(JSON.parse(inspectedText));
|
||||
expect(inspectedEvidence.normalized_result).toMatchObject({
|
||||
abi: "arm64-v8a",
|
||||
libapp: {
|
||||
snapshot_hash: SNAPSHOT_HASH,
|
||||
snapshot_hash_candidates: [SNAPSHOT_HASH],
|
||||
snapshot_hash_sources: 2,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,415 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import type { AnySchema } from "ajv";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
|
||||
const createFridaTestProvider = (
|
||||
overrides: Partial<FridaInstrumentationPort> = {},
|
||||
): FridaInstrumentationPort => ({
|
||||
async listDevices() {
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
devices: [
|
||||
{ deviceId: "remote-device", name: "target", type: "remote" },
|
||||
],
|
||||
cleanupError: null,
|
||||
},
|
||||
};
|
||||
},
|
||||
async listProcesses() {
|
||||
return {
|
||||
ok: true,
|
||||
value: { deviceId: "remote-device", processes: [], cleanupError: null },
|
||||
};
|
||||
},
|
||||
async startSession(input) {
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
deviceId: "remote-device",
|
||||
target: String(input.mode),
|
||||
pid: 10,
|
||||
mode: input.mode,
|
||||
state: input.mode === "spawn" ? "paused" : "running",
|
||||
},
|
||||
};
|
||||
},
|
||||
async loadScript() {
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
scriptId: "00000000-0000-4000-8000-000000000002",
|
||||
sourceKind: "inline",
|
||||
sourcePath: null,
|
||||
sourceSha256: "a".repeat(64),
|
||||
messages: [],
|
||||
messagesTruncated: false,
|
||||
},
|
||||
};
|
||||
},
|
||||
async resumeSession() {
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
async unloadScript() {
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
status(sessionId) {
|
||||
return {
|
||||
sessionId,
|
||||
deviceId: "remote-device",
|
||||
target: "fixture",
|
||||
pid: 10,
|
||||
mode: "attach",
|
||||
state: "running",
|
||||
targetResumeObserved: false,
|
||||
scripts: [],
|
||||
messages: [],
|
||||
messagesTruncated: false,
|
||||
};
|
||||
},
|
||||
async closeSession() {
|
||||
return { ok: true, value: { targetResumeObserved: false } };
|
||||
},
|
||||
async closeAll() {},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const expectFridaToolsAvailable = async (client: Client) => {
|
||||
const inventory = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
const parsedInventory = toolContract("binary_session").outputSchema.safeParse(
|
||||
inventory.structuredContent,
|
||||
);
|
||||
if (!parsedInventory.success)
|
||||
throw new Error("Invalid binary session output");
|
||||
const toolAvailability = expandToolAvailability(
|
||||
parsedInventory.data.result.tool_availability,
|
||||
);
|
||||
expect(toolAvailability).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "list_frida_devices",
|
||||
available: true,
|
||||
reason: "available",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "instrument_with_frida",
|
||||
available: true,
|
||||
reason: "available",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
it("advertises Frida MCP schemas and keeps remote credentials out of results", async () => {
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Binary provider must not start");
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{
|
||||
fridaInstrumentation: createFridaTestProvider(),
|
||||
},
|
||||
);
|
||||
const client = new Client({ name: "frida-contract", version: "1" });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const tools = (await client.listTools()).tools;
|
||||
const advertised = tools.find((tool) => tool.name === "list_frida_devices");
|
||||
if (
|
||||
advertised?.inputSchema === undefined ||
|
||||
advertised.outputSchema === undefined
|
||||
)
|
||||
throw new Error("Missing advertised Frida 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 response = await client.callTool({
|
||||
name: "list_frida_devices",
|
||||
arguments: {
|
||||
remote: { address: "127.0.0.1:27042", token: "synthetic-secret-token" },
|
||||
},
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(JSON.stringify(response.structuredContent)).not.toContain(
|
||||
"synthetic-secret-token",
|
||||
);
|
||||
expect(ajv.validate(outputSchema, response.structuredContent)).toBe(true);
|
||||
expect(toolContract("start_frida_session").effects.mutatesTarget).toBe(true);
|
||||
|
||||
const processes = await client.callTool({
|
||||
name: "list_frida_processes",
|
||||
arguments: { device_id: "remote-device" },
|
||||
});
|
||||
expect(processes.isError).not.toBe(true);
|
||||
|
||||
const started = await client.callTool({
|
||||
name: "start_frida_session",
|
||||
arguments: {
|
||||
mode: "attach",
|
||||
pid: 10,
|
||||
remote: { address: "127.0.0.1:27042", token: "synthetic-secret-token" },
|
||||
},
|
||||
});
|
||||
expect(started.isError).not.toBe(true);
|
||||
expect(JSON.stringify(started.structuredContent)).not.toContain(
|
||||
"synthetic-secret-token",
|
||||
);
|
||||
const loaded = await client.callTool({
|
||||
name: "load_frida_script",
|
||||
arguments: {
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
source_kind: "inline",
|
||||
source: "send('loaded');",
|
||||
},
|
||||
});
|
||||
expect(loaded.isError).not.toBe(true);
|
||||
expect(JSON.stringify(loaded.structuredContent)).not.toContain(
|
||||
"synthetic-secret-token",
|
||||
);
|
||||
const loadedValue = loaded.structuredContent;
|
||||
if (
|
||||
loadedValue === undefined ||
|
||||
typeof loadedValue !== "object" ||
|
||||
loadedValue === null ||
|
||||
!("evidence_id" in loadedValue) ||
|
||||
typeof loadedValue.evidence_id !== "string"
|
||||
)
|
||||
throw new Error("Expected inline Frida Evidence");
|
||||
const retainedEvidence = session.evidenceById(loadedValue.evidence_id);
|
||||
expect(JSON.stringify(retainedEvidence)).not.toContain(
|
||||
"synthetic-secret-token",
|
||||
);
|
||||
|
||||
for (const [name, args] of [
|
||||
[
|
||||
"resume_frida_session",
|
||||
{ session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
],
|
||||
[
|
||||
"unload_frida_script",
|
||||
{
|
||||
session_id: "00000000-0000-4000-8000-000000000001",
|
||||
script_id: "00000000-0000-4000-8000-000000000002",
|
||||
},
|
||||
],
|
||||
[
|
||||
"frida_session_status",
|
||||
{ session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
],
|
||||
[
|
||||
"close_frida_session",
|
||||
{ session_id: "00000000-0000-4000-8000-000000000001" },
|
||||
],
|
||||
] as const) {
|
||||
const result = await client.callTool({ name, arguments: args });
|
||||
expect(
|
||||
result.isError,
|
||||
`${name}: ${JSON.stringify(result.structuredContent)}`,
|
||||
).not.toBe(true);
|
||||
}
|
||||
|
||||
const invalidAddress = await client.callTool({
|
||||
name: "list_frida_devices",
|
||||
arguments: {
|
||||
remote: { address: "tcp://127.0.0.1:27042?token=synthetic-secret-token" },
|
||||
},
|
||||
});
|
||||
expect(invalidAddress.isError).toBe(true);
|
||||
|
||||
const oneShot = await client.callTool({
|
||||
name: "instrument_with_frida",
|
||||
arguments: {
|
||||
mode: "attach",
|
||||
pid: 10,
|
||||
source_kind: "inline",
|
||||
source: "send('one-shot');",
|
||||
duration_ms: 0,
|
||||
},
|
||||
});
|
||||
expect(oneShot.isError).not.toBe(true);
|
||||
const oneShotContract = tools.find(
|
||||
(tool) => tool.name === "instrument_with_frida",
|
||||
);
|
||||
if (oneShotContract?.outputSchema === undefined)
|
||||
throw new Error("Missing one-shot Frida output schema");
|
||||
const validateOneShot = ajv.compile(
|
||||
oneShotContract.outputSchema as AnySchema,
|
||||
);
|
||||
expect(validateOneShot(oneShot.structuredContent)).toBe(true);
|
||||
|
||||
await expectFridaToolsAvailable(client);
|
||||
});
|
||||
|
||||
it("reports Frida tools as unavailable after the optional binding fails to load", async () => {
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Binary provider must not start");
|
||||
});
|
||||
const provider = new FridaInstrumentationManager({
|
||||
deviceManagerLoader: async () => {
|
||||
throw new Error("Cannot find package 'frida'");
|
||||
},
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ fridaInstrumentation: provider },
|
||||
);
|
||||
const client = new Client({ name: "frida-optional-binding", version: "1" });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const missing = await client.callTool({
|
||||
name: "list_frida_devices",
|
||||
arguments: {},
|
||||
});
|
||||
expect(missing.isError).toBe(true);
|
||||
|
||||
const inventory = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
const parsedInventory = toolContract("binary_session").outputSchema.safeParse(
|
||||
inventory.structuredContent,
|
||||
);
|
||||
if (!parsedInventory.success)
|
||||
throw new Error("Invalid binary session output");
|
||||
expect(
|
||||
expandToolAvailability(parsedInventory.data.result.tool_availability),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "list_frida_devices",
|
||||
available: false,
|
||||
reason: "provider_unavailable",
|
||||
remediation: expect.stringContaining("Cannot find package 'frida'"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("retains cancellation Evidence after the MCP client stops waiting", async () => {
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Binary provider must not start");
|
||||
});
|
||||
let finishLoad: (() => void) | undefined;
|
||||
const loadGate = new Promise<void>((resolve) => {
|
||||
finishLoad = resolve;
|
||||
});
|
||||
let markLoadStarted: (() => void) | undefined;
|
||||
const loadStarted = new Promise<void>((resolve) => {
|
||||
markLoadStarted = resolve;
|
||||
});
|
||||
let markSessionClosed: (() => void) | undefined;
|
||||
const sessionClosed = new Promise<void>((resolve) => {
|
||||
markSessionClosed = resolve;
|
||||
});
|
||||
const provider = createFridaTestProvider({
|
||||
async loadScript() {
|
||||
markLoadStarted?.();
|
||||
await loadGate;
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
scriptId: "00000000-0000-4000-8000-000000000002",
|
||||
sourceKind: "inline",
|
||||
sourcePath: null,
|
||||
sourceSha256: "a".repeat(64),
|
||||
messages: [{ type: "send", payload: "cancel-observed" }],
|
||||
messagesTruncated: false,
|
||||
},
|
||||
};
|
||||
},
|
||||
status(sessionId) {
|
||||
return {
|
||||
sessionId,
|
||||
deviceId: "remote-device",
|
||||
target: "fixture",
|
||||
pid: 10,
|
||||
mode: "attach",
|
||||
state: "running",
|
||||
targetResumeObserved: false,
|
||||
scripts: [],
|
||||
messages: [{ type: "send", payload: "cancel-observed" }],
|
||||
messagesTruncated: false,
|
||||
};
|
||||
},
|
||||
async closeSession() {
|
||||
markSessionClosed?.();
|
||||
return { ok: true, value: { targetResumeObserved: false } };
|
||||
},
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ fridaInstrumentation: provider },
|
||||
);
|
||||
const client = new Client({ name: "frida-cancellation", version: "1" });
|
||||
const controller = new AbortController();
|
||||
onTestFinished(async () => {
|
||||
finishLoad?.();
|
||||
controller.abort();
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const call = client.callTool(
|
||||
{
|
||||
name: "instrument_with_frida",
|
||||
arguments: {
|
||||
mode: "attach",
|
||||
pid: 10,
|
||||
source_kind: "inline",
|
||||
source: "send('cancel-observed');",
|
||||
duration_ms: 1_000,
|
||||
},
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
await loadStarted;
|
||||
controller.abort(new Error("cancel Frida observation"));
|
||||
finishLoad?.();
|
||||
await expect(call).rejects.toThrow("cancel Frida observation");
|
||||
await sessionClosed;
|
||||
await client.ping();
|
||||
|
||||
const bundle = await client.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(JSON.stringify(bundle.structuredContent)).toContain("cancel-observed");
|
||||
expect(JSON.stringify(bundle.structuredContent)).toContain(
|
||||
"instrument_with_frida",
|
||||
);
|
||||
});
|
||||
@@ -141,3 +141,45 @@ it("preserves JEB provider failure reasons through the MCP boundary", async () =
|
||||
expect(text).toContain("ECONNREFUSED");
|
||||
expect(text).toContain("REA_JEB_MCP_URL");
|
||||
});
|
||||
|
||||
it("keeps the MCP server usable when REA_JEB_MCP_URL is invalid", async () => {
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("deep provider must not start");
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ environment: { REA_JEB_MCP_URL: "http://localhost:8425/mcp" } },
|
||||
);
|
||||
const client = new Client({ name: "jeb-invalid-endpoint", version: "1" });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
expect((await client.listTools()).tools.length).toBeGreaterThan(0);
|
||||
const failed = await client.callTool({
|
||||
name: "inspect_jeb_client",
|
||||
arguments: {},
|
||||
});
|
||||
expect(failed.isError).toBe(true);
|
||||
const text = (failed.content ?? [])
|
||||
.map((block) => (block.type === "text" ? block.text : ""))
|
||||
.join("");
|
||||
expect(JSON.parse(text)).toMatchObject({
|
||||
error: {
|
||||
code: "configuration_invalid",
|
||||
details: {
|
||||
settings: [
|
||||
{
|
||||
setting: "REA_JEB_MCP_URL",
|
||||
constraint: expect.stringContaining("loopback"),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -281,7 +281,7 @@ describe("target-free MCP workflow", () => {
|
||||
);
|
||||
expect(
|
||||
beforeTools.find(({ name }) => name === "inspect_artifact")?.description,
|
||||
).toContain("Returns the complete content-addressed artifact graph");
|
||||
).toMatch(/\breturns the complete content-addressed artifact graph\b/iu);
|
||||
expect(beforeNames).toContain("open_binary");
|
||||
expect(beforeNames).toContain("binary_session");
|
||||
expect(beforeNames).toContain("current_document");
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import type { Client } from "@modelcontextprotocol/client";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { readFile, realpath, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { WasmArtifactService } from "../../../src/application/wasm/WasmArtifactService.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { wasmArtifactSummaryViewResultSchema } from "../../../src/domain/analysisView/analysisView.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
@@ -30,6 +34,63 @@ const wasmToolSchemas = async (client: Client) => {
|
||||
return { name: advertised.name, ajv, inputSchema, outputSchema };
|
||||
};
|
||||
|
||||
const assertFirstSummaryDelivery = async (
|
||||
harness: Awaited<ReturnType<typeof createApplicationMcpHarness>>,
|
||||
value: ReturnType<typeof wasmArtifactFixture>,
|
||||
inspect: WasmArtifactService["provider"]["inspect"],
|
||||
) => {
|
||||
const {
|
||||
ajv: wasmAjv,
|
||||
inputSchema,
|
||||
outputSchema,
|
||||
} = await wasmToolSchemas(harness.client);
|
||||
const summaryInput = { path: value.artifact.path, detail: "summary" };
|
||||
expect(wasmAjv.validate(inputSchema, summaryInput)).toBe(true);
|
||||
expect(
|
||||
wasmAjv.validate(inputSchema, { ...summaryInput, detail: "brief" }),
|
||||
).toBe(false);
|
||||
const directSummary = await harness.client.callTool({
|
||||
name: "inspect_wasm_artifact",
|
||||
arguments: summaryInput,
|
||||
});
|
||||
expect(directSummary.isError).not.toBe(true);
|
||||
expect(
|
||||
wasmAjv.validate(outputSchema, directSummary.structuredContent),
|
||||
JSON.stringify(wasmAjv.errors),
|
||||
).toBe(true);
|
||||
const summaryEvidence = parseEvidence(directSummary.structuredContent);
|
||||
const summary = wasmArtifactSummaryViewResultSchema.parse(
|
||||
summaryEvidence.normalized_result,
|
||||
);
|
||||
expect(summaryEvidence.confidence).toBe("derived");
|
||||
expect(summaryEvidence.evidence_links).toEqual([summary.parent_evidence_id]);
|
||||
expect(summary.summary.wat).toMatchObject({
|
||||
sha256: value.wat.sha256,
|
||||
code_units: value.wat.text.length,
|
||||
});
|
||||
expect(summary.summary.wat).not.toHaveProperty("text");
|
||||
const retained = harness.session.evidenceById(summary.parent_evidence_id);
|
||||
if (retained === undefined) throw new Error("Summary lost original Evidence");
|
||||
expect(retained.normalized_result).toEqual(value);
|
||||
expect(retained.parameters).toEqual({
|
||||
path: value.artifact.path,
|
||||
glue_paths: [],
|
||||
candidate_paths: [],
|
||||
});
|
||||
expect(inspect).toHaveBeenCalledTimes(1);
|
||||
expect(inspect).toHaveBeenLastCalledWith(
|
||||
retained.parameters,
|
||||
expect.objectContaining({ signal: expect.any(AbortSignal) }),
|
||||
);
|
||||
expect(
|
||||
wasmAjv.validate(outputSchema, {
|
||||
...summaryEvidence,
|
||||
normalized_result: { ...summary, parent_operation: "inventory_artifact" },
|
||||
}),
|
||||
).toBe(false);
|
||||
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(
|
||||
@@ -81,6 +142,16 @@ it("directs rejected native WASM opening to the advertised static tool while pre
|
||||
},
|
||||
},
|
||||
});
|
||||
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(
|
||||
@@ -141,3 +212,288 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
|
||||
await harness.close();
|
||||
expect(close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reads an oversized completed WASM result through its reported retained reference", async () => {
|
||||
const text = "(module)\n" + ";;😀\n" + " ".repeat(6 * 1024 * 1024);
|
||||
const value = {
|
||||
...wasmArtifactFixture(),
|
||||
imports: ['(import "env" "memory.with punctuation" (memory 1))'],
|
||||
exports: ['(export "first" (func 0))', '(export "second" (func 1))'],
|
||||
wat: {
|
||||
text,
|
||||
sha256: createHash("sha256").update(text, "utf8").digest("hex"),
|
||||
representation: "decoded-wat" as const,
|
||||
},
|
||||
};
|
||||
const inspect = vi.fn(() =>
|
||||
Promise.resolve(ok(wasmArtifactExecution(value))),
|
||||
);
|
||||
const service = new WasmArtifactService({
|
||||
close: () => Promise.resolve(),
|
||||
inspect,
|
||||
});
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { wasmArtifact: service },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const { summary, retained } = await assertFirstSummaryDelivery(
|
||||
harness,
|
||||
value,
|
||||
inspect,
|
||||
);
|
||||
const reply = await harness.client.callTool({
|
||||
name: "inspect_wasm_artifact",
|
||||
arguments: { path: value.artifact.path },
|
||||
});
|
||||
const reference = z
|
||||
.object({
|
||||
details: z.object({
|
||||
reported_limits: z.object({
|
||||
evidence_reference: z.object({
|
||||
kind: z.literal("retained-evidence"),
|
||||
evidence_id: z.string(),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(parseMcpToolError(reply).error).details
|
||||
.reported_limits.evidence_reference;
|
||||
expect(reference.evidence_id).toBe(summary.parent_evidence_id);
|
||||
const explicitComplete = await harness.client.callTool({
|
||||
name: "inspect_wasm_artifact",
|
||||
arguments: { path: value.artifact.path, detail: "complete" },
|
||||
});
|
||||
expect(parseMcpToolError(explicitComplete)).toMatchObject({
|
||||
error: {
|
||||
code: "resource_constraint",
|
||||
details: { reported_limits: { evidence_reference: reference } },
|
||||
},
|
||||
});
|
||||
const catalog = await harness.client.listTools();
|
||||
const advertised = catalog.tools.find(
|
||||
(tool) => tool.name === "inspect_analysis_view",
|
||||
);
|
||||
if (advertised?.outputSchema === undefined)
|
||||
throw new Error("Missing WASM view schemas");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const input: Record<string, unknown> = advertised.inputSchema;
|
||||
const output: Record<string, unknown> = advertised.outputSchema;
|
||||
for (const [view, expected] of [
|
||||
[
|
||||
{ kind: "summary" },
|
||||
{
|
||||
summary: {
|
||||
validation: "valid",
|
||||
available_counts: { imports: 1, exports: 2 },
|
||||
runtime_execution: "not-performed",
|
||||
network_fetch: "not-performed",
|
||||
wat: { sha256: value.wat.sha256, code_units: text.length },
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{ kind: "wasm", facet: "exports", offset: 1, limit: 1 },
|
||||
{
|
||||
item: [value.exports[1]],
|
||||
coverage: { total: 2, next_offset: null, exhausted: true },
|
||||
},
|
||||
],
|
||||
[{ kind: "wasm", facet: "imports" }, { item: value.imports }],
|
||||
[
|
||||
{ kind: "wasm", facet: "wat", offset: 0, limit: 16 },
|
||||
{
|
||||
item: { text: text.slice(0, 16), unit: "utf16-code-units" },
|
||||
coverage: { total: text.length, next_offset: 16, exhausted: false },
|
||||
},
|
||||
],
|
||||
] as const) {
|
||||
const args = { source: reference, view };
|
||||
expect(ajv.validate(input, args), JSON.stringify(ajv.errors)).toBe(true);
|
||||
const selected = await harness.client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: args,
|
||||
});
|
||||
expect(
|
||||
selected.isError,
|
||||
JSON.stringify(selected.structuredContent),
|
||||
).not.toBe(true);
|
||||
expect(
|
||||
ajv.validate(output, selected.structuredContent),
|
||||
JSON.stringify(ajv.errors),
|
||||
).toBe(true);
|
||||
const evidence = parseEvidence(selected.structuredContent);
|
||||
expect(evidence.confidence).toBe("derived");
|
||||
expect(evidence.evidence_links).toEqual([reference.evidence_id]);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
parent_evidence_id: reference.evidence_id,
|
||||
...expected,
|
||||
});
|
||||
}
|
||||
const original = harness.session.evidenceById(reference.evidence_id);
|
||||
expect(original?.normalized_result).toEqual(value);
|
||||
expect(original).toEqual(retained);
|
||||
expect(inspect).toHaveBeenCalledTimes(3);
|
||||
await harness.client.ping();
|
||||
});
|
||||
|
||||
it("rejects inconsistent decoded-WAT digests in portable Evidence without a provider run", async () => {
|
||||
const value = wasmArtifactFixture();
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { environment: {} },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const inconsistent = createEvidence(
|
||||
{
|
||||
path: value.artifact.path,
|
||||
sha256: value.artifact.sha256,
|
||||
format: "file",
|
||||
},
|
||||
{ id: "historical-wabt", name: "Historical WABT", version: "1" },
|
||||
{
|
||||
operation: "inspect_wasm_artifact",
|
||||
parameters: {},
|
||||
result: { ...value, wat: { ...value.wat, sha256: "f".repeat(64) } },
|
||||
},
|
||||
);
|
||||
const invalid = await harness.client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source: { kind: "inline", evidence: inconsistent },
|
||||
view: { kind: "summary" },
|
||||
},
|
||||
});
|
||||
expect(parseMcpToolError(invalid)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: ["source", "normalized_result", "wat", "sha256"],
|
||||
reason: "invalid_value",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
await harness.client.ping();
|
||||
});
|
||||
|
||||
it("rejects absent or inconsistent WASM source identity before deriving portable views", async () => {
|
||||
const value = wasmArtifactFixture();
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: { environment: {} },
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
for (const target of [
|
||||
undefined,
|
||||
{
|
||||
path: `${value.artifact.path}.other`,
|
||||
sha256: value.artifact.sha256,
|
||||
format: "file" as const,
|
||||
},
|
||||
{
|
||||
path: value.artifact.path,
|
||||
sha256: "f".repeat(64),
|
||||
format: "file" as const,
|
||||
},
|
||||
]) {
|
||||
const source = createEvidence(
|
||||
target,
|
||||
{ id: "historical-wabt", name: "Historical WABT", version: "1" },
|
||||
{ operation: "inspect_wasm_artifact", parameters: {}, result: value },
|
||||
);
|
||||
for (const view of [
|
||||
{ kind: "summary" },
|
||||
{ kind: "wasm", facet: "exports", offset: 0, limit: 1 },
|
||||
]) {
|
||||
const reply = await harness.client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: { source: { kind: "inline", evidence: source }, view },
|
||||
});
|
||||
expect(parseMcpToolError(reply)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [{ path: ["source", "subject"], reason: "invalid_value" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
await harness.client.ping();
|
||||
});
|
||||
|
||||
it("requires retention for WASM summary delivery while keeping fixed-server complete delivery", async () => {
|
||||
const value = wasmArtifactFixture();
|
||||
const service = new WasmArtifactService({
|
||||
close: () => Promise.resolve(),
|
||||
inspect: () => Promise.resolve(ok(wasmArtifactExecution(value))),
|
||||
});
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("No deep provider");
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "fixed", analysis: session },
|
||||
{ wasmArtifact: service },
|
||||
);
|
||||
const client = new Client({ name: "wasm-fixed-delivery", version: "1" });
|
||||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(b);
|
||||
await client.connect(a);
|
||||
const summary = await client.callTool({
|
||||
name: "inspect_wasm_artifact",
|
||||
arguments: { path: value.artifact.path, detail: "summary" },
|
||||
});
|
||||
expect(parseMcpToolError(summary)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("does not retain Evidence"),
|
||||
},
|
||||
});
|
||||
const complete = await client.callTool({
|
||||
name: "inspect_wasm_artifact",
|
||||
arguments: { path: value.artifact.path },
|
||||
});
|
||||
expect(complete.isError).not.toBe(true);
|
||||
expect(parseEvidence(complete.structuredContent).normalized_result).toEqual(
|
||||
value,
|
||||
);
|
||||
await client.ping();
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("retries cleanup of the injected WASM module after server shutdown fails", async () => {
|
||||
const close = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error("retained WASM workspace"))
|
||||
.mockResolvedValue(undefined);
|
||||
const service = new WasmArtifactService({
|
||||
close,
|
||||
inspect: () => Promise.resolve(ok(wasmArtifactExecution())),
|
||||
});
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("No deep provider");
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ wasmArtifact: service },
|
||||
);
|
||||
const client = new Client({ name: "wasm-cleanup-retry", version: "1" });
|
||||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(b);
|
||||
await client.connect(a);
|
||||
await expect(server.close()).rejects.toThrow("REA session cleanup failed");
|
||||
await server.close();
|
||||
expect(close).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import type { BrowserScenarioCapturePort } from "../../../src/application/BrowserScenarioCapturePort.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { startMcpTransport } from "../../../src/main/transport.js";
|
||||
import type { RuntimeDependencies } from "../../../src/main/types.js";
|
||||
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
|
||||
it("keeps the shared browser scenario provider open when the SDK discards its discovery probe", async () => {
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Unexpected deep provider");
|
||||
});
|
||||
const close = vi.fn(async () => undefined);
|
||||
const browserScenarioCapture: BrowserScenarioCapturePort = {
|
||||
identity: () => ({
|
||||
id: "fake-browser",
|
||||
name: "Fake browser",
|
||||
version: "1",
|
||||
}),
|
||||
captureScenario: async () => {
|
||||
throw new Error("Unexpected scenario capture");
|
||||
},
|
||||
close,
|
||||
};
|
||||
const factories: Parameters<RuntimeDependencies["serve"]>[0][] = [];
|
||||
const runtime: RuntimeDependencies = {
|
||||
env: {},
|
||||
serve: (factory) => {
|
||||
factories.push(factory);
|
||||
return { close: async () => undefined };
|
||||
},
|
||||
writeStderr: () => undefined,
|
||||
setExitCode: () => undefined,
|
||||
registerShutdown: () => () => undefined,
|
||||
};
|
||||
const transport = await startMcpTransport(runtime, session, {
|
||||
logger: silentLogger,
|
||||
serverLogger: silentLogger,
|
||||
environment: runtime.env,
|
||||
delivery: new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
|
||||
loadOptionalProviders: async () => ({ browserScenarioCapture }),
|
||||
});
|
||||
if (!transport.ok) throw new Error("Transport failed");
|
||||
const factory = factories[0];
|
||||
if (factory === undefined) throw new Error("Missing SDK server factory");
|
||||
try {
|
||||
const probe = await factory({ era: "modern" });
|
||||
await probe.close();
|
||||
const replacement = await factory({ era: "legacy" });
|
||||
await replacement.close();
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
|
||||
await transport.closeOptionalProviders();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await transport.closeAndroid();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
@@ -70,4 +70,5 @@ const universalTarget = (path: string): BinaryTarget => ({
|
||||
format: "mach-o-universal",
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["arm64"],
|
||||
universalSlice: { offset: 0, size: 32 },
|
||||
});
|
||||
|
||||
@@ -18,7 +18,7 @@ the read-only Ghidra inventory contracts without committing a binary.
|
||||
`scripts/create-ghidra-windows-fixture.mjs` separately emits a deterministic,
|
||||
ignored native x86-64 PE application for the controlled Windows Ghidra P0 lane.
|
||||
The generator and fixed SHA-256 are versioned; the `.exe` is never committed or
|
||||
executed. `npm run verify:ghidra:windows` uses it to prove all 19 operations,
|
||||
executed. `npm run verify:ghidra:windows` uses it to verify the admitted read-only operation inventory,
|
||||
digest linkage, transport, and cleanup on the self-hosted real-Ghidra runner.
|
||||
|
||||
The C fixture fixes a known call chain and strings. The version pair fixes an
|
||||
|
||||
Vendored
+1
@@ -34,6 +34,7 @@ export const CLIENT_LOCATION_ENVIRONMENT = [
|
||||
"PI_CODING_AGENT_DIR",
|
||||
"PI_CONFIG_DIR",
|
||||
"PI_PROFILE",
|
||||
"QODER_CONFIG_DIR",
|
||||
"QWEN_HOME",
|
||||
"SAND_DATA_ROOT",
|
||||
"XDG_CONFIG_HOME",
|
||||
|
||||
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { aotFixtureImage } from "../../src/flutter/FlutterBuild.fixture.js";
|
||||
import { createTestTempDirectory } from "./temporaryDirectory.js";
|
||||
|
||||
/** Materialize real ZIP members with test-scoped exact-path cleanup. */
|
||||
export const createFlutterApk = async (
|
||||
name: string,
|
||||
files: ReadonlyArray<{ readonly path: string; readonly bytes: Buffer }>,
|
||||
): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-flutter-");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter(), {
|
||||
useWebWorkers: false,
|
||||
});
|
||||
for (const file of files)
|
||||
await writer.add(file.path, new Uint8ArrayReader(file.bytes));
|
||||
const path = join(root, name);
|
||||
await writeFile(path, await writer.close());
|
||||
return path;
|
||||
};
|
||||
|
||||
/** ZIP permits repeated names; the writer refuses them, so rewrite both records. */
|
||||
export const createDuplicateFlutterApk = async (): Promise<string> => {
|
||||
const path = await createFlutterApk("duplicates.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: aotFixtureImage() },
|
||||
{ path: "lib/arm64-v8a/libxxx.so", bytes: Buffer.alloc(64) },
|
||||
]);
|
||||
const bytes = await readFile(path);
|
||||
const from = Buffer.from("lib/arm64-v8a/libxxx.so");
|
||||
for (
|
||||
let at = bytes.indexOf(from);
|
||||
at >= 0;
|
||||
at = bytes.indexOf(from, at + from.length)
|
||||
)
|
||||
bytes.write("lib/arm64-v8a/libapp.so", at);
|
||||
await writeFile(path, bytes);
|
||||
return path;
|
||||
};
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/** A well-formed XML plist of N nested dictionaries, each with one key. */
|
||||
export const deeplyNestedXmlPlist = (depth: number): string =>
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n' +
|
||||
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n' +
|
||||
'<plist version="1.0">\n' +
|
||||
"<dict><key>k</key>".repeat(depth) +
|
||||
"<string>x</string>" +
|
||||
"</dict>".repeat(depth) +
|
||||
"\n</plist>\n";
|
||||
Vendored
+13
-3
@@ -1,4 +1,7 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import {
|
||||
Client,
|
||||
type CallToolRequestOptions,
|
||||
} from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import type { ValidateFunction } from "ajv";
|
||||
@@ -69,12 +72,19 @@ export async function connectLocalToolsMcp() {
|
||||
validatedSchemas.add(serialized);
|
||||
}
|
||||
const definitions = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
const call = async (name: string, arguments_: Record<string, unknown>) => {
|
||||
const call = async (
|
||||
name: string,
|
||||
arguments_: Record<string, unknown>,
|
||||
options?: Pick<CallToolRequestOptions, "signal" | "onprogress">,
|
||||
) => {
|
||||
const definition = definitions.get(name);
|
||||
if (definition !== undefined) compileValidator(definition.inputSchema);
|
||||
const response = await client.callTool(
|
||||
{ name, arguments: arguments_ },
|
||||
definition === undefined ? undefined : { toolDefinition: definition },
|
||||
{
|
||||
...options,
|
||||
...(definition === undefined ? {} : { toolDefinition: definition }),
|
||||
},
|
||||
);
|
||||
if (
|
||||
response.structuredContent !== undefined &&
|
||||
|
||||
+7
-1
@@ -1,6 +1,7 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
// Writes a periodic report, then behaves by mode:
|
||||
@@ -8,11 +9,16 @@ import { fileURLToPath } from "node:url";
|
||||
// and exits cleanly.
|
||||
// - "ignoring": stays alive and swallows SIGTERM and SIGINT, so only SIGKILL
|
||||
// ends the process.
|
||||
// - "delayed-ignoring": installs those handlers after a slow startup.
|
||||
// - "exits": exits on its own at once.
|
||||
// - "descendant": cooperates while leaving a SIGTERM-ignoring child for owned cleanup.
|
||||
// An optional third argument is the exit code a cooperative finalizer uses.
|
||||
const [mode, directory, finalExitCode = "0"] = process.argv.slice(2);
|
||||
|
||||
// Make the cancellation case exercise startup beyond its old 300 ms capture
|
||||
// window deterministically, rather than relying on a busy CI runner.
|
||||
if (mode === "delayed-ignoring") await delay(500);
|
||||
|
||||
writeFileSync(join(directory, "pid.txt"), String(process.pid));
|
||||
writeFileSync(
|
||||
join(directory, "periodic.json"),
|
||||
@@ -31,7 +37,7 @@ if (mode === "descendant") {
|
||||
);
|
||||
}
|
||||
|
||||
if (mode === "ignoring") {
|
||||
if (mode === "ignoring" || mode === "delayed-ignoring") {
|
||||
process.on("SIGTERM", () => {
|
||||
writeFileSync(join(directory, "sigterm-received"), "received");
|
||||
});
|
||||
|
||||
Vendored
+16
-11
@@ -1,7 +1,10 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
|
||||
import type { WasmArtifact } from "../../../src/domain/wasm/wasmArtifact.js";
|
||||
/** Source-owned transport seam; upstream binaries are verified in a separate lane. */
|
||||
export const wasmArtifactFixture = (path = "/artifacts/module.wasm") => ({
|
||||
export const wasmArtifactFixture = (
|
||||
path = "/artifacts/module.wasm",
|
||||
): WasmArtifact => ({
|
||||
artifact: { path, sha256: "a".repeat(64), bytes: 8 },
|
||||
validation: "valid" as const,
|
||||
sections: [],
|
||||
@@ -18,16 +21,18 @@ export const wasmArtifactFixture = (path = "/artifacts/module.wasm") => ({
|
||||
source: "https://github.com/WebAssembly/wabt" as const,
|
||||
release: "1.0.42" as const,
|
||||
source_commit: "ff0ef7e0009402740c805a9744c09b05be063e48" as const,
|
||||
commands: ["wasm-validate", "wasm-objdump", "wasm2wat"].map((tool) => ({
|
||||
tool,
|
||||
path: `/tools/${tool}`,
|
||||
sha256: "b".repeat(64),
|
||||
version_banner: "1.0.42\n",
|
||||
arguments:
|
||||
tool === "wasm-objdump"
|
||||
? ["-h", "-x", "module.wasm"]
|
||||
: ["--enable-all", "module.wasm"],
|
||||
})),
|
||||
commands: (["wasm-validate", "wasm-objdump", "wasm2wat"] as const).map(
|
||||
(tool) => ({
|
||||
tool,
|
||||
path: `/tools/${tool}`,
|
||||
sha256: "b".repeat(64),
|
||||
version_banner: "1.0.42\n",
|
||||
arguments:
|
||||
tool === "wasm-objdump"
|
||||
? ["-h", "-x", "module.wasm"]
|
||||
: ["--enable-all", "module.wasm"],
|
||||
}),
|
||||
),
|
||||
timeout_ms: 30_000,
|
||||
output_budget_bytes: 32 * 1024 * 1024,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user