Merge origin/main for artifact admission and evidence fixes

This commit is contained in:
64579525
2026-10-13 14:32:52 +08:00
188 changed files with 8882 additions and 937 deletions
+159 -84
View File
@@ -1,100 +1,175 @@
import { execFile } from "node:child_process";
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { promisify } from "node:util";
import {
copyFile,
mkdir,
readFile,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const runner = resolve("scripts/run-development-tests.mjs");
describe("development test runner", () => {
it("rejects nonexistent explicit paths instead of returning a zero-test success", async () => {
await expect(
execute(process.execPath, [
runner,
"focused",
"src/missing.test.ts",
"--dry-run",
]),
).rejects.toMatchObject({ code: 1 });
const run = (root: string, command: string, arguments_: readonly string[]) =>
execFileOutput(command, arguments_, {
cwd: root,
stopSignal: "SIGTERM",
timeout: 30_000,
maxBuffer: 1024 * 1024,
});
it("reports actionable remediation when the comparison base is unavailable", async () => {
await expect(
execute(process.execPath, [
runner,
"changed",
"--base",
"missing-test-base",
"--dry-run",
const git = (root: string, ...arguments_: string[]) =>
run(root, "git", arguments_);
const commit = (root: string, message: string) =>
git(
root,
"-c",
"user.name=REA fixture",
"-c",
"user.email=fixture@example.test",
"-c",
"commit.gpgSign=false",
"commit",
"--quiet",
"-m",
message,
);
const fixture = async () => {
const root = await createTestTempDirectory("rea-development-tests-");
await mkdir(join(root, "scripts", "lib"), { recursive: true });
await mkdir(join(root, "src"));
for (const path of [
"scripts/run-development-tests.mjs",
"scripts/lib/development-tests.mjs",
])
await copyFile(join(process.cwd(), path), join(root, path));
await symlink(
join(process.cwd(), "node_modules"),
join(root, "node_modules"),
process.platform === "win32" ? "junction" : undefined,
);
await writeFile(join(root, "package.json"), '{"type":"module"}\n');
await writeFile(join(root, ".gitignore"), "node_modules\nselected.txt\n");
await writeFile(
join(root, "vitest.config.mjs"),
'export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };\n',
);
await writeFile(join(root, "src/value.ts"), "export const value = 1;\n");
await writeFile(
join(root, "src/value.test.ts"),
'import { expect, it } from "vitest"; import { writeFileSync } from "node:fs"; import { value } from "./value.js"; it("checks the selected source", () => { expect(value).toBe(1); writeFileSync("selected.txt", String(value)); });\n',
);
await git(root, "init", "--quiet", "-b", "main");
await git(root, "add", ".");
await commit(root, "fixture");
return root;
};
const testCommand = (root: string, ...arguments_: string[]) =>
run(root, process.execPath, [
"scripts/run-development-tests.mjs",
...arguments_,
]);
describe("development test runner public CLI", () => {
it("runs an explicitly selected source test on a clean tree without build artifacts", async () => {
const root = await fixture();
const { stdout: status } = await git(root, "status", "--porcelain");
expect(status).toBe("");
await testCommand(root, "local", "src/value.test.ts");
expect(await readFile(join(root, "selected.txt"), "utf8")).toBe("1");
});
it("plans an exact local test without building", async () => {
const root = await fixture();
const { stdout } = await testCommand(
root,
"local",
"src/value.test.ts",
"--dry-run",
);
expect(JSON.parse(stdout)).toMatchObject({
needsBuild: false,
artifactTasks: [],
vitestArguments: expect.arrayContaining([
"run",
"--project",
"domain",
"--project",
"services",
"--project",
"adapters",
"--project",
"composition",
"--project",
"conformance",
"--project",
"evaluation",
"src/value.test.ts",
]),
});
});
it("uses committed dependency changes to select source tests and reports failures", async () => {
const root = await fixture();
const { stdout: base } = await git(root, "rev-parse", "HEAD");
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
await git(root, "add", "src/value.ts");
await commit(root, "change dependency");
await expect(
testCommand(root, "changed", "--base", base.trim()),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("src/value.test.ts"),
stderr: expect.stringContaining("expected 2 to be 1"),
});
});
it("runs changed and focused tests from a committed branch regression", async () => {
const root = await fixture();
const { stdout: baseline } = await git(root, "rev-parse", "HEAD");
await git(root, "update-ref", "refs/remotes/origin/main", baseline.trim());
await git(root, "switch", "--quiet", "-c", "regression");
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
await writeFile(
join(root, "src/value.test.ts"),
'import { expect, it } from "vitest"; import { value } from "./value.js"; it("checks current source", () => expect(value).toBe(2));\n',
);
await git(root, "add", "src");
await commit(root, "regression fix");
expect((await git(root, "status", "--porcelain")).stdout).toBe("");
const changed = await testCommand(root, "changed");
expect(changed.stdout).toContain("1 passed");
const focused = await testCommand(root, "focused", "src/value.test.ts");
expect(focused.stdout).toContain("1 passed");
}, 60_000);
it("reports a missing comparison base and rejects missing or compiled-boundary paths", async () => {
const root = await fixture();
await expect(
testCommand(root, "changed", "--base", "missing-test-base", "--dry-run"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining(
"Fetch origin/main or pass --base REVISION",
),
});
});
it("runs a committed branch regression through real Git and Vitest without dist", async () => {
const root = await createTestTempDirectory("rea-development-tests-");
await mkdir(join(root, "src"));
await symlink(
resolve("node_modules"),
join(root, "node_modules"),
"junction",
);
await writeFile(
join(root, "package.json"),
JSON.stringify({ type: "module" }),
);
await writeFile(join(root, ".gitignore"), "node_modules\n");
await writeFile(
join(root, "vitest.config.ts"),
`export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };`,
);
await writeFile(join(root, "src/value.ts"), "export const value = 1;\n");
await writeFile(
join(root, "src/value.test.ts"),
`import { it, expect } from "vitest"; import { value } from "./value"; it("checks current source", () => expect(value).toBe(1));\n`,
);
const git = (arguments_: string[]) =>
execute("git", arguments_, { cwd: root });
await git(["init", "-b", "main"]);
await git(["add", ".gitignore", "package.json", "vitest.config.ts", "src"]);
const commit = [
"-c",
"user.name=REA fixture",
"-c",
"user.email=fixture@example.test",
"commit",
"-m",
"fixture",
];
await git(commit);
const { stdout: baseline } = await git(["rev-parse", "HEAD"]);
await git(["update-ref", "refs/remotes/origin/main", baseline.trim()]);
await git(["switch", "-c", "regression"]);
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
await writeFile(
join(root, "src/value.test.ts"),
`import { it, expect } from "vitest"; import { value } from "./value"; it("checks current source", () => expect(value).toBe(2));\n`,
);
await git(["add", "src"]);
await git(commit);
expect((await git(["status", "--porcelain"])).stdout).toBe("");
const { stdout } = await execute(process.execPath, [runner, "changed"], {
cwd: root,
await expect(
testCommand(root, "focused", "src/missing.test.ts"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("ENOENT"),
});
expect(stdout).toContain("1 passed");
const explicit = await execute(
process.execPath,
[runner, "focused", "src/value.test.ts"],
{ cwd: root },
);
expect(explicit.stdout).toContain("1 passed");
}, 30_000);
await expect(
testCommand(root, "local", "tests/acceptance/runtime.test.ts"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("Use test:focused"),
});
});
});
+37
View File
@@ -0,0 +1,37 @@
import { expect, it } from "vitest";
import { expectConfigurationRefusal, serveCli } from "./cliServeHarness.js";
it.each(["inspect-pcap-client", "inspect-pcap-capture"])(
"%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.each([
["inspect-pcap-client"],
["inspect-pcap-capture", "/nonexistent/capture.pcap"],
])("%s names the missing Wireshark tool to configure", async (...argv) => {
const result = await serveCli([...argv, "--json"], {
REA_TSHARK_COMMAND: "/nonexistent/tshark",
REA_CAPINFOS_COMMAND: "/nonexistent/capinfos",
});
expectConfigurationRefusal(
result,
"Cannot run selected tool /nonexistent/tshark",
);
expectConfigurationRefusal(result, "through absolute REA_TSHARK_COMMAND");
});
it("names a relative tool selection as configuration to fix", async () => {
const result = await serveCli(["inspect-pcap-client", "--json"], {
REA_TSHARK_COMMAND: "tshark",
});
expectConfigurationRefusal(
result,
"REA_TSHARK_COMMAND must be an absolute path to the tshark binary",
);
});
@@ -1,110 +0,0 @@
import {
copyFile,
mkdir,
readFile,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const run = (root: string, command: string, arguments_: readonly string[]) =>
execFileOutput(command, arguments_, {
cwd: root,
stopSignal: "SIGTERM",
timeout: 20_000,
});
const commit = (root: string, message: string) =>
run(root, "git", [
"-c",
"user.name=REA fixture",
"-c",
"user.email=fixture@example.invalid",
"-c",
"commit.gpgSign=false",
"commit",
"--quiet",
"-m",
message,
]);
const fixture = async () => {
const root = await createTestTempDirectory("rea-development-tests-");
await mkdir(join(root, "scripts", "lib"), { recursive: true });
await mkdir(join(root, "src"));
for (const path of [
"scripts/run-development-tests.mjs",
"scripts/lib/development-tests.mjs",
])
await copyFile(join(process.cwd(), path), join(root, path));
await symlink(
join(process.cwd(), "node_modules"),
join(root, "node_modules"),
process.platform === "win32" ? "junction" : undefined,
);
await writeFile(join(root, "package.json"), '{"type":"module"}\n');
await writeFile(join(root, ".gitignore"), "node_modules\nselected.txt\n");
await writeFile(
join(root, "vitest.config.mjs"),
'export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };\n',
);
await writeFile(join(root, "src", "value.ts"), "export const value = 1;\n");
await writeFile(
join(root, "src", "value.test.ts"),
'import { expect, it } from "vitest"; import { writeFileSync } from "node:fs"; import { value } from "./value.js"; it("checks the selected source", () => { expect(value).toBe(1); writeFileSync("selected.txt", String(value)); });\n',
);
await run(root, "git", ["init", "--quiet"]);
await run(root, "git", ["add", "."]);
await commit(root, "fixture");
return root;
};
const testCommand = (root: string, ...arguments_: string[]) =>
run(root, process.execPath, [
"scripts/run-development-tests.mjs",
...arguments_,
]);
it("executes an explicitly selected source test on a clean tree without build artifacts", async () => {
const root = await fixture();
const { stdout: status } = await run(root, "git", ["status", "--porcelain"]);
expect(status).toBe("");
await testCommand(root, "local", "src/value.test.ts");
expect(await readFile(join(root, "selected.txt"), "utf8")).toBe("1");
});
it("uses committed dependency changes since the requested Git base to select source tests", async () => {
const root = await fixture();
const { stdout: base } = await run(root, "git", ["rev-parse", "HEAD"]);
await writeFile(join(root, "src", "value.ts"), "export const value = 2;\n");
await run(root, "git", ["add", "src/value.ts"]);
await commit(root, "change dependency");
await expect(
testCommand(root, "changed", "--base", base.trim()),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("src/value.test.ts"),
stderr: expect.stringContaining("expected 2 to be 1"),
});
});
it("rejects a compiled boundary in the source-only command and a missing exact test", async () => {
const root = await fixture();
await expect(
testCommand(root, "local", "tests/acceptance/runtime.test.ts"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("Use test:focused"),
});
await expect(
testCommand(root, "local", "src/missing.test.ts"),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("ENOENT"),
});
});
@@ -52,7 +52,7 @@ const target = {
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.3\n",
readText: () => "application.version=12.1.3\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.12",
@@ -11,6 +11,7 @@ import {
import { join } from "node:path";
import { promisify } from "node:util";
import { spawn as spawnPty } from "@lydell/node-pty";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -185,6 +186,69 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
});
});
describe("installer TTY fallback", { timeout: 20_000 }, () => {
it("skips automatic setup when stderr is redirected", async () => {
const fixture = await createFixture();
const script = join(process.cwd(), "install.sh");
const wrapper = `
const { spawnSync } = require("node:child_process");
const { openSync, closeSync } = require("node:fs");
const stderr = openSync(process.argv[2], "w");
const child = spawnSync("/bin/bash", [process.argv[1], ...process.argv.slice(3)], {
stdio: ["inherit", "inherit", stderr],
env: process.env,
});
closeSync(stderr);
process.exit(child.status ?? 1);
`;
let output = "";
const terminal = spawnPty(
process.execPath,
["-e", wrapper, script, fixture.installerStderrLog, "--version", "0.3.0"],
{
cwd: process.cwd(),
env: {
...process.env,
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
TERM: "xterm-256color",
},
name: "xterm-256color",
cols: 120,
rows: 40,
},
);
let timedOut = false;
const exitCode = await new Promise<number>((resolve, reject) => {
const timeout = setTimeout(() => {
timedOut = true;
terminal.kill();
}, 10_000);
terminal.onData((data) => {
output += data;
});
terminal.onExit(({ exitCode: code }) => {
clearTimeout(timeout);
if (timedOut)
reject(new Error(`Installer PTY timed out after output: ${output}`));
else resolve(code);
});
});
expect(exitCode).toBe(0);
expect(output).toContain(
`Run ${join(fixture.home, ".local/bin/rea")} setup to configure Hopper and agents.`,
);
expect(await readFile(fixture.reaLog, "utf8")).toBe("--version\n");
expect(await readFile(fixture.installerStderrLog, "utf8")).toBe("");
});
});
describe("truncated installer download", { timeout: 20_000 }, () => {
it("runs nothing from a download truncated after the npm install line", async () => {
const fixture = await createFixture();
@@ -433,6 +497,7 @@ interface InstallerFixture {
readonly temporary: string;
readonly npmLog: string;
readonly reaLog: string;
readonly installerStderrLog: string;
}
const getProcessOutput = (
@@ -456,6 +521,7 @@ const createFixture = async (): Promise<InstallerFixture> => {
const temporary = join(root, "tmp");
const npmLog = join(root, "npm.log");
const reaLog = join(root, "rea.log");
const installerStderrLog = join(root, "installer.stderr.log");
await Promise.all([mkdir(home), mkdir(bin), mkdir(temporary)]);
await Promise.all([
executable(
@@ -507,7 +573,7 @@ exit 0
symlink(`/usr/bin/${command}`, join(bin, command)),
),
]);
return { home, bin, temporary, npmLog, reaLog };
return { home, bin, temporary, npmLog, reaLog, installerStderrLog };
};
const executable = async (path: string, source: string): Promise<void> => {
@@ -6,7 +6,7 @@ import { analyzeJavaScriptApplication } from "../../support/javascriptApplicatio
import { parseApplicationGraphEvidence } from "../../../src/application/javascript/JavaScriptApplicationEvidenceGraph.js";
import { findApplicationFeatureSeeds } from "../../../src/domain/javascript/javascriptFeatureSeed.js";
import { compareSourceToBundle } from "../../../src/domain/javascript/sourceToBundleComparison.js";
import { resolveSourceMapSource } from "../../../src/javascript/sourceMaps/DecodedSourceMap.js";
import { resolveJavaScriptSourceMapUrl } from "../../../src/domain/javascript/javascriptSourceMapPaths.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
@@ -180,7 +180,7 @@ it.each([
decoy: decoyPath = "src/a.js",
}) => {
if (sourceRoot !== undefined) {
const resolved = resolveSourceMapSource(
const resolved = resolveJavaScriptSourceMapUrl(
source,
sourceRoot,
`https://example.test/${mapPath}`,
@@ -39,6 +39,8 @@ import {
} from "../../fixtures/analysisView.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { BINARY_LAYOUT_TEST_PROVIDER } from "../../fixtures/binaryDiagnostics/layout.js";
import { wasmArtifactFixture } from "../../fixtures/wasm/artifact.js";
import { evmInterfaceFixture } from "../../fixtures/evm/interface.js";
const connect = async (
binaryLayout?: BinaryLayoutService,
@@ -310,6 +312,65 @@ it("reports a tampered inline Evidence ID at its full MCP source path", async ()
});
});
it("rejects self-contained WASM and EVM Evidence views when the subject format differs", async () => {
const { client } = await connect();
const wasm = wasmArtifactFixture();
const evm = evmInterfaceFixture();
const cases = [
{
evidence: createEvidence(
{
path: wasm.artifact.path,
format: "elf",
sha256: wasm.artifact.sha256,
},
{ id: "fixture-wabt", name: "WABT", version: "1" },
{
operation: "inspect_wasm_artifact",
parameters: { path: wasm.artifact.path },
result: wasm,
},
),
},
{
evidence: createEvidence(
{
path: evm.artifact.path,
format: "elf",
sha256: evm.artifact.sha256,
},
{ id: "fixture-evm", name: "EVMole", version: "1" },
{
operation: "inspect_evm_interface",
parameters: { path: evm.artifact.path, encoding: "hex" },
result: evm,
},
),
},
] as const;
for (const { evidence } of cases) {
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
expect.objectContaining({
path: ["source", "subject"],
reason: "invalid_value",
}),
],
},
});
}
});
it("admits portable captures before SDK Evidence parsing and preserves capture caveats", async () => {
const { client } = await connect();
const dense = analysisViewCaptureEvidence(analysisViewObjectDenseCapture());
@@ -2,6 +2,7 @@ import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import type { Client } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { AnySchema } from "ajv";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import {
@@ -10,12 +11,143 @@ import {
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "../../../src/domain/javascript/javascriptApplicationGraph.js";
import { createJavaScriptSemanticGraph } from "../../../src/domain/javascript/javascriptSemanticGraph.js";
import {
artifactEvidence,
sourceMapReference,
} from "../../../src/domain/javascript/javascriptApplicationGraph.fixture.js";
import {
createApplicationMcpHarness,
type ApplicationMcpHarness,
} from "../../fixtures/applicationMcpHarness.js";
import { createHistoricalSourceGraph } from "../../../src/domain/referenceSourceGraph.js";
async function runUnicodeSourceMapComparison(
harness: ApplicationMcpHarness,
): Promise<void> {
const baseApplication = SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.application;
const subject = baseApplication.subject;
if (subject === null) throw new Error("Application Evidence has no subject");
const baseResult = javascriptApplicationAnalysisResultSchema.parse(
baseApplication.normalized_result,
);
const baseGraph = baseResult.graph;
const decomposedSource = "cafe\u0301.ts";
const unicodeSourceNode = createJavaScriptApplicationNode({
kind: "source-module",
identity: {
strategy: "source-map-original",
source_root: "../src/",
stability: "source-map-exact",
source_map_sha256: "1".repeat(64),
original_source: decomposedSource,
source_sha256: "3".repeat(64),
},
observations: [
{
label: "decomposed source-map spelling",
source_map_reference: sourceMapReference(
decomposedSource,
"../src/",
"dist/main.js.map",
),
properties: { content_available: true, content_sha256: "3".repeat(64) },
evidence: artifactEvidence("1".repeat(64), "dist/main.js.map"),
},
],
});
const applicationGraph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: [...baseGraph.root_node_ids, unicodeSourceNode.node_id],
nodes: [...baseGraph.nodes, unicodeSourceNode],
edges: baseGraph.edges,
coverage: baseGraph.coverage,
limitations: baseGraph.limitations,
});
const semantic = baseResult.semantic_graph;
const { graph_id: _semanticGraphId, ...semanticInput } = semantic;
const semanticGraph = createJavaScriptSemanticGraph({
...semanticInput,
application_graph_id: applicationGraph.graph_id,
});
const unicodeApplication = createEvidence(
{
path: baseResult.input_path,
sha256: subject.digest.sha256,
format: subject.format,
},
baseApplication.provider,
{
predicateType: baseApplication.predicate_type,
operation: baseApplication.operation,
parameters: baseApplication.parameters,
result: {
...baseResult,
graph: applicationGraph,
semantic_graph: semanticGraph,
},
confidence: baseApplication.confidence,
authority: baseApplication.authority,
limitations: baseApplication.limitations,
evidenceLinks: baseApplication.evidence_links,
},
);
const historicalUnicodePath = "src/caf\u00e9.ts";
const unicodeReference = createHistoricalSourceGraph({
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
root_sha256: undefined,
entries: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.entries.map(
(entry) =>
entry.path === "src/main.ts"
? { ...entry, path: historicalUnicodePath }
: entry,
),
});
const reply = await harness.client.callTool({
name: "compare_source_to_bundle",
arguments: { reference: unicodeReference, application: unicodeApplication },
});
expect(reply.isError).not.toBe(true);
expect(reply.structuredContent).toMatchObject({
normalized_result: {
items: [
{
source_path: historicalUnicodePath,
status: "unknown",
current_node_ids: [],
candidates: [
expect.objectContaining({
confidence: "low",
signals: expect.arrayContaining([
expect.objectContaining({
kind: "unicode-equivalent-path",
source_value: historicalUnicodePath,
current_values: ["src/cafe\u0301.ts"],
}),
]),
}),
],
},
],
},
});
const advertised = (await harness.client.listTools()).tools.find(
({ name }) => name === "compare_source_to_bundle",
);
if (advertised?.outputSchema === undefined)
throw new Error("Comparison tool output schema is missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const outputSchema = advertised.outputSchema as AnySchema;
expect(ajv.validateSchema(outputSchema)).toBe(true);
const validateOutput = ajv.compile(outputSchema);
expect(validateOutput(reply.structuredContent)).toBe(true);
}
async function runInlineWorkflowScenarios(
harness: ApplicationMcpHarness,
): Promise<void> {
@@ -92,6 +224,8 @@ async function runInlineWorkflowScenarios(
},
});
await runUnicodeSourceMapComparison(harness);
const referenceWithExclusion = createHistoricalSourceGraph({
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
root_sha256: undefined,
@@ -1,10 +1,20 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ANALYSIS_SNAPSHOT_TARGET } from "../../../src/domain/analysisSnapshot.fixture.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
import { createServer } from "../../../src/server/createServer.js";
it("returns the complete session Evidence bundle in the tool result", async () => {
@@ -44,3 +54,251 @@ it("returns the complete session Evidence bundle in the tool result", async () =
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
it("rejects bundle field stripping at MCP import without changing retained evidence", async () => {
const root = await createTestTempDirectory("rea-evidence-bundle-mcp-");
const sourceSession = createBundleSourceSession();
const targetSession = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
const source = await connectEvidenceMcp("bundle-source", sourceSession);
const target = await connectEvidenceMcp("bundle-target", targetSession);
const { client: sourceClient } = source;
const { client: targetClient } = target;
const bundlePath = join(root, "exported.json");
const targetExportPath = join(root, "round-trip.json");
try {
const { sourceJson, records, evidenceIndex } = await exportFixtureBundle(
sourceClient,
bundlePath,
);
const initial = structured(
await targetClient.callTool({
name: "get_evidence_bundle",
arguments: {},
}),
).result;
for (const [label, path] of unsupportedBundleFields(evidenceIndex)) {
const candidate = structuredClone(sourceJson);
setPath(candidate, path, "unsupported-metadata");
const malformedPath = join(root, `${label.replaceAll(" ", "-")}.json`);
await writeFile(malformedPath, JSON.stringify(candidate));
const rejected = await targetClient.callTool({
name: "import_evidence_bundle",
arguments: { path: malformedPath },
});
expect(parseMcpToolError(rejected), label).toMatchObject({
error: { code: "evidence_integrity_mismatch" },
});
expect(
structured(
await targetClient.callTool({
name: "get_evidence_bundle",
arguments: {},
}),
).result,
label,
).toEqual(initial);
}
const imported = await targetClient.callTool({
name: "import_evidence_bundle",
arguments: { path: bundlePath },
});
if (imported.isError === true)
throw new Error(JSON.stringify(parseMcpToolError(imported)));
await targetClient.callTool({
name: "export_evidence_bundle",
arguments: { path: targetExportPath },
});
expect(JSON.parse(await readFile(targetExportPath, "utf8"))).toEqual(
sourceJson,
);
const observedRecord = records[evidenceIndex]!;
expect(observedRecord.parameters).toEqual({ caller: { note: "preserve" } });
expect(observedRecord.normalized_result).toEqual({
producer: { extension: "preserve" },
});
expect(object(observedRecord.analysis_profile).parameters).toEqual({
loader: { mode: "full" },
});
} finally {
await Promise.allSettled([
sourceClient.close(),
source.server.close(),
sourceSession.close(),
targetClient.close(),
target.server.close(),
targetSession.close(),
]);
}
});
const createBundleSourceSession = () => {
const provider = { id: "fixture", name: "Fixture", version: "1" };
const evidence = createEvidence(ANALYSIS_SNAPSHOT_TARGET, provider, {
operation: "observe",
parameters: { caller: { note: "preserve" } },
result: { producer: { extension: "preserve" } },
analysisProfile: createAnalysisProfile(provider, {
loader: { mode: "full" },
}),
environment: {
id: "fixture-linux",
platform: "linux",
architecture: "x86_64",
isolation: "process",
},
locations: [{ kind: "address", address: "0x1000" }],
});
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
expect(session.recordEvidence(evidence).ok).toBe(true);
for (const extra of [
createEvidence(ANALYSIS_SNAPSHOT_TARGET, provider, {
operation: "controlled_replay",
parameters: {},
result: { completed: true },
authority: "controlled-replay",
}),
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
confidence: "observed",
authority: "controlled-replay",
}),
])
expect(session.recordEvidence(extra).ok).toBe(true);
return session;
};
const exportFixtureBundle = async (
client: Client,
path: string,
): Promise<{
readonly sourceJson: unknown;
readonly records: Record<string, unknown>[];
readonly evidenceIndex: number;
}> => {
const unknown = await client.callTool({
name: "record_unknown",
arguments: {
question: "Does this remain unknown?",
severity: "medium",
domain: "bundle-format",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [{ operation: "observe", rationale: "Inspect it." }],
relationships: [],
},
});
expect(unknown.isError).not.toBe(true);
const exported = await client.callTool({
name: "export_evidence_bundle",
arguments: { path },
});
expect(exported.isError).not.toBe(true);
const sourceJson = JSON.parse(await readFile(path, "utf8")) as unknown;
const records = array(object(sourceJson).records).map(object);
const evidenceIndex = records.findIndex(
(record) => record.operation === "observe",
);
expect(evidenceIndex).toBeGreaterThanOrEqual(0);
return { sourceJson, records, evidenceIndex };
};
const unsupportedBundleFields = (
evidenceIndex: number,
): readonly [string, readonly (string | number)[]][] => [
["bundle envelope", ["schema_version"]],
["record provider", ["records", evidenceIndex, "provider", "future_field"]],
["provider manifest", ["providers", 0, "future_field"]],
["record subject", ["records", evidenceIndex, "subject", "future_field"]],
[
"subject digest",
["records", evidenceIndex, "subject", "digest", "future_field"],
],
["artifact manifest", ["artifacts", 0, "future_field"]],
[
"record environment",
["records", evidenceIndex, "environment", "future_field"],
],
["environment manifest", ["environments", 0, "future_field"]],
[
"source location",
["records", evidenceIndex, "locations", 0, "future_field"],
],
["scenario manifest", ["scenarios", 0, "future_field"]],
["capture manifest", ["captures", 0, "future_field"]],
[
"analysis profile",
["records", evidenceIndex, "analysis_profile", "future_field"],
],
[
"profile provider",
["records", evidenceIndex, "analysis_profile", "provider", "future_field"],
],
["unknown revision", ["unknowns", 0, "future_field"]],
["unknown probe", ["unknowns", 0, "recommended_probes", 0, "future_field"]],
];
const connectEvidenceMcp = async (
name: string,
session: ReturnType<typeof createTestBinarySession>,
) => {
const server = createServer({ kind: "session", session });
const client = new Client({ name, version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return { client, server };
};
const object = (value: unknown): Record<string, unknown> => {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new Error("Expected object in exported Evidence bundle");
return value as Record<string, unknown>;
};
const array = (value: unknown): unknown[] => {
if (!Array.isArray(value))
throw new Error("Expected array in Evidence bundle");
return value;
};
const setPath = (
root: unknown,
path: readonly (string | number)[],
value: unknown,
): void => {
const [last, ...parents] = [...path].reverse();
if (last === undefined) throw new Error("Expected a nonempty bundle path");
const target = parents
.reverse()
.reduce<unknown>(
(current, segment) =>
typeof segment === "number"
? array(current)[segment]
: object(current)[segment],
root,
);
object(target)[String(last)] = value;
};
const structured = (result: Awaited<ReturnType<Client["callTool"]>>) => {
if (result.isError === true) throw parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("Missing structured MCP result");
return result.structuredContent as Record<string, unknown>;
};
@@ -107,6 +107,30 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
).toBe(true);
});
it("rejects an EVM provider response with a non-file subject before recording Evidence", async () => {
const value = evmInterfaceFixture();
const execution = evmInterfaceExecution(value);
const malformed = {
...execution,
subject: { ...execution.subject, format: "elf" },
} as unknown as typeof execution;
const harness = await createApplicationMcpHarness({
serverOptions: {
evmInterface: new EvmInterfaceService({
inspect: () => Promise.resolve(ok(malformed)),
}),
},
});
onTestFinished(harness.close);
const before = harness.session.exportEvidenceBundle().records.length;
const response = await harness.client.callTool({
name: "inspect_evm_interface",
arguments: { path: value.artifact.path, encoding: "hex" },
});
expect(parseMcpToolError(response).error.code).toBe("unreadable_output");
expect(harness.session.exportEvidenceBundle().records).toHaveLength(before);
});
it.each(["unavailable", "incompatible-output"])(
"preserves a healthy WASM peer and explicit EVM failure: %s",
async (scenario) => {
+1 -1
View File
@@ -95,7 +95,7 @@ export const sessionEvidence = (session: BinarySession, value: unknown) => {
const installationHost = (): GhidraInstallationHost => ({
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
+1 -1
View File
@@ -99,7 +99,7 @@ class FixtureLauncher implements GhidraLauncher {
const installationHost: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
+118
View File
@@ -0,0 +1,118 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import type { PcapAnalysisPort } from "../../../src/application/pcap/PcapAnalysisPort.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: "pcap", name: "Packet capture analysis", version: null };
const clientIdentity = {
tshark_command: "/usr/bin/tshark",
tshark_source: "path",
tshark_version: "TShark (Wireshark) 4.6.6",
capinfos_command: "/usr/bin/capinfos",
capinfos_source: "path",
capinfos_version: "Capinfos (Wireshark) 4.6.6",
};
it("advertises exact valid pcap schemas and records inline evidence through MCP", async () => {
const provider: PcapAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute(request) {
if (request.operation === "inspect_pcap_client")
return ok(
createAnalysisExecution({ client: clientIdentity }, identity),
);
return ok(
createAnalysisExecution(
{
client: clientIdentity,
target: {
path: "/captures/session.pcap",
bytes: 23279,
sha256: "a".repeat(64),
},
file_type: "Wireshark/tcpdump/... - pcap",
encapsulation: "Linux cooked-mode capture v2",
packet_count: 50,
capture_start: "2026-10-11 14:13:40.608505",
capture_end: "2026-10-11 14:13:40.981978",
capture_duration_seconds: 0.373473,
snapshot_length: 262144,
endpoints: [
{ address: "192.168.1.100", port: null, packet_count: 30 },
{ address: "8.8.8.8", port: 53, packet_count: 5 },
],
endpoint_count: 2,
dns_queries: [
{
query: "example.com",
response_addresses: ["93.184.216.34"],
response_address_count: 1,
},
],
dns_query_count: 1,
tls_sni_values: ["example.com"],
tls_sni_count: 1,
protocol_distribution: [
{ protocol: "ip:tcp:tls", packet_count: 25 },
{ protocol: "ip:udp:dns", packet_count: 5 },
],
protocol_count: 2,
http_request_uris: ["http://example.com/api"],
http_request_uri_count: 1,
http_uri_redaction_count: 0,
unattributed_dns_addresses: [],
unattributed_dns_address_count: 0,
unattributed_dns_packet_count: 0,
coverage: "complete",
},
identity,
),
);
},
};
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ pcapAnalysis: provider },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "pcap-boundary", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const { tools } = await client.listTools();
assertAdvertisedMcpContracts(
["inspect_pcap_client", "inspect_pcap_capture"],
tools,
);
const inspected = await client.callTool({
name: "inspect_pcap_capture",
arguments: { path: "/captures/session.pcap" },
});
expect(inspected.isError).not.toBe(true);
const text = (inspected.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
const evidence = parseEvidence(JSON.parse(text));
expect(evidence.normalized_result).toMatchObject({
packet_count: 50,
tls_sni_values: ["example.com"],
coverage: "complete",
});
});
@@ -252,6 +252,56 @@ it("reports CLI trace specification issues like the MCP trace_spec input", async
});
});
it("rejects a deep trace cycle as an input error through CLI and MCP", async () => {
const events = Array.from({ length: 6000 }, (_, index) => ({
id: `e${String(index)}`,
source: "lifecycle",
exact: { marker: index },
}));
const trace = {
events,
language: {
kind: "partial_order",
happens_before: events.map((event, index) => ({
before: event.id,
after: events[(index + 1) % events.length]!.id,
})),
not_before: events.map((event, index) => ({
event: event.id,
anchor: events[(index + 1) % events.length]!.id,
})),
unordered_groups: [{ events: events.map(({ id }) => id) }],
},
};
const issue = {
path: ["trace_spec", "language"],
message: "happens-before graph must be acyclic",
};
const capture = captureEvidence("left");
const root = await createTestTempDirectory("rea-process-trace-cycle-");
const capturePath = join(root, "capture.json");
const specPath = join(root, "spec.json");
await writeFile(capturePath, JSON.stringify(capture));
await writeFile(specPath, JSON.stringify(trace));
expect(
await compareProcessEvidenceFiles(capturePath, capturePath, specPath),
).toMatchObject({
code: "invalid_request",
details: { issues: [issue] },
});
const client = await connect();
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left: capture, right: capture, trace_spec: trace },
});
expect(response.isError).toBe(true);
expect(response.content).toEqual([
{ type: "text", text: expect.stringContaining(issue.message) },
]);
await client.ping();
});
it("names the side and constraint when Evidence is not a usable capture", async () => {
const client = await connect();
const capture = captureEvidence("right");
@@ -3,7 +3,10 @@ import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { completeReconstructionCoverageData } from "../../../src/domain/reconstructionCoverage.fixture.js";
import {
completeReconstructionCoverageData,
reconstructionCoverageEvidenceId,
} from "../../../src/domain/reconstructionCoverage.fixture.js";
import { createReconstructionCoverageData } from "../../../src/domain/reconstructionCoverage.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createServer } from "../../../src/server/createServer.js";
@@ -36,6 +39,42 @@ describe("reconstruction coverage MCP", () => {
boundary_id: boundaryId,
summary: { reasons: 0 },
});
const coverage = currentFixtureCoverage(boundaryId);
const latest = coverage.verifier_results[0];
if (latest === undefined)
throw new Error("Expected fixture verifier result");
const ambiguous = await client.callTool({
name: "evaluate_reconstruction_coverage",
arguments: {
coverage: createReconstructionCoverageData({
...coverage,
verifier_results: [
latest,
{
...latest,
status: "fail",
evidence_ids: [reconstructionCoverageEvidenceId("1")],
},
],
}),
boundary_id: boundaryId,
},
});
expect(ambiguous.isError).not.toBe(true);
expect(ambiguous.structuredContent).toMatchObject({
status: "unknown",
boundary_id: boundaryId,
reasons: [
expect.objectContaining({
code: "verifier-result-ambiguous",
subject_id: "claim.cli.help",
}),
],
evidence_ids: expect.arrayContaining([
reconstructionCoverageEvidenceId("3"),
reconstructionCoverageEvidenceId("1"),
]),
});
const unknown = await client.callTool({
name: "evaluate_reconstruction_coverage",
arguments: {
+7 -8
View File
@@ -281,7 +281,7 @@ it("pages filtered unknown heads through the public MCP contract", async () => {
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
}
const defaultPage = structured(
@@ -372,12 +372,11 @@ it("pages filtered unknown heads through the public MCP contract", async () => {
.result as typeof defaultPage;
expect(first).toMatchObject({ total: 3, offset: 0, next_offset: 2 });
expect(first.items).toHaveLength(2);
const second = structured(
await client.callTool({
...request,
arguments: { ...request.arguments, offset: first.next_offset ?? 0 },
}),
).result as typeof defaultPage;
const secondResponse = await client.callTool({
...request,
arguments: { ...request.arguments, offset: first.next_offset ?? 0 },
});
const second = structured(secondResponse).result as typeof defaultPage;
expect(second).toMatchObject({ total: 3, offset: 2, next_offset: null });
expect(second.items).toHaveLength(1);
expect(
@@ -389,7 +388,7 @@ it("pages filtered unknown heads through the public MCP contract", async () => {
);
expect(
toolContract("list_unknowns").outputSchema.safeParse(
(await client.callTool(request)).structuredContent,
secondResponse.structuredContent,
).success,
).toBe(true);
@@ -213,6 +213,31 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
expect(close).toHaveBeenCalled();
});
it("rejects a WASM provider response with a non-file subject before recording Evidence", async () => {
const value = wasmArtifactFixture();
const execution = wasmArtifactExecution(value);
const malformed = {
...execution,
subject: { ...execution.subject, format: "elf" },
} as unknown as typeof execution;
const harness = await createApplicationMcpHarness({
serverOptions: {
wasmArtifact: new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () => Promise.resolve(ok(malformed)),
}),
},
});
onTestFinished(harness.close);
const before = harness.session.exportEvidenceBundle().records.length;
const response = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
expect(parseMcpToolError(response).error.code).toBe("unreadable_output");
expect(harness.session.exportEvidenceBundle().records).toHaveLength(before);
});
it("reads an oversized completed WASM result through its reported retained reference", async () => {
const text = "(module)\n" + ";;😀\n" + " ".repeat(6 * 1024 * 1024);
const value = {
+53
View File
@@ -0,0 +1,53 @@
import { setTimeout as delay } from "node:timers/promises";
import { expect, it, onTestFinished, vi } from "vitest";
import { runPcapCommand } from "../../../src/pcap/PcapCommand.js";
import * as ownership from "../../../src/process/ProcessOwnershipObservation.js";
it("does not spend the tool execution deadline preparing native ownership", async () => {
const original = ownership.prepareProcessOwnershipInspection;
let entered!: () => void;
let release!: () => void;
const preparing = new Promise<void>((resolve) => {
entered = resolve;
});
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let first = true;
const prepare = vi
.spyOn(ownership, "prepareProcessOwnershipInspection")
.mockImplementation(async (signal) => {
await original(signal);
if (first) {
first = false;
entered();
await gate;
}
});
onTestFinished(() => {
prepare.mockRestore();
release();
});
const pending = runPcapCommand({
operation: "inspect_pcap_client",
command: process.execPath,
arguments: ["--version"],
limits: { timeoutMs: 1000, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
retain: (owner) => {
onTestFinished(async () => {
expect((await owner.stop()).status).not.toBe("incomplete");
});
},
}).then(
(value) => ({ ok: true as const, value }),
(error: unknown) => ({ ok: false as const, error }),
);
await preparing;
await delay(1100);
release();
const result = await pending;
if (!result.ok) throw result.error;
expect(result.value.stdout.trim()).toBe(process.version);
});
+533
View File
@@ -0,0 +1,533 @@
import { createHash } from "node:crypto";
import { watch } from "node:fs";
import { chmod, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, onTestFinished, test, vi } from "vitest";
import { PcapProvider } from "../../../src/pcap/PcapProvider.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import {
pcapResultSchemas,
type PcapRequest,
} from "../../../src/domain/pcap/pcapAnalysis.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { holdFirstFileRead } from "../../support/holdFirstFileRead.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
const it = test.skipIf(process.platform !== "linux");
const CAPINFOS_OUTPUT = [
"File name: /work/capture.pcap",
"File type: Wireshark/tcpdump/... - pcap",
"File encapsulation: Ethernet",
"Packet size limit: file hdr: 262144 bytes",
"Number of packets: 3",
"Capture duration: 0.123 seconds",
].join("\n");
const TSHARK_JSON = JSON.stringify([
{
_source: {
layers: {
"frame.number": ["1"],
"frame.protocols": ["eth:ethertype:ip:udp:dns"],
"ip.src": ["192.168.1.100"],
"ip.dst": ["8.8.8.8"],
"dns.qry.name": ["api.example.com"],
"dns.flags.response": ["1"],
"dns.a": ["93.184.216.34"],
},
},
},
{
_source: {
layers: {
"frame.number": ["2"],
"frame.protocols": ["eth:ethertype:ip:tcp:tls"],
"ip.src": ["192.168.1.100"],
"ip.dst": ["93.184.216.34"],
"tls.handshake.extensions_server_name": ["api.example.com"],
},
},
},
{
_source: {
layers: {
"frame.number": ["3"],
"frame.protocols": ["eth:ethertype:ip:tcp:http"],
"ip.src": ["192.168.1.100"],
"ip.dst": ["93.184.216.34"],
"http.request.full_uri": ["http://api.example.com/v1/data"],
},
},
},
]);
const writeStubTools = async (
root: string,
options: { readonly failCapinfos?: boolean } = {},
): Promise<{ tshark: string; capinfos: string }> => {
const tshark = join(root, "tshark");
const capinfos = join(root, "capinfos");
await writeFile(
tshark,
`#!/bin/sh
if [ "$1" = "--version" ]; then printf 'TShark (Wireshark) 4.6.6-stub\\n'; exit 0; fi
[ "$1" = "-n" ] && [ "$2" = "-r" ] && [ "$4" = "-T" ] && [ "$5" = "json" ] || exit 2
printf '%s' '${TSHARK_JSON.replace(/'/gu, "'\\''")}'
exit 0
`,
{ mode: 0o755 },
);
await writeFile(
capinfos,
`#!/bin/sh
if [ "$1" = "--version" ]; then printf 'Capinfos (Wireshark) 4.6.6-stub\\n'; exit 0; fi
[ "$1" = "-M" ] && [ "$2" = "--" ] && [ "$#" = "3" ] || exit 2
if [ "${String(options.failCapinfos === true)}" = "true" ]; then
printf 'capinfos: The file is not a capture file' >&2; exit 1
fi
printf '%s\\n' '${CAPINFOS_OUTPUT.replace(/'/gu, "'\\''")}'
exit 0
`,
{ mode: 0o755 },
);
await chmod(tshark, 0o755);
await chmod(capinfos, 0o755);
return { tshark, capinfos };
};
const providerWith = async (options: { failCapinfos?: boolean } = {}) => {
const root = await createTestTempDirectory("rea-pcap-");
const { tshark, capinfos } = await writeStubTools(root, options);
const provider = new PcapProvider({
environment: { REA_TSHARK_COMMAND: tshark, REA_CAPINFOS_COMMAND: capinfos },
});
onTestFinished(() => provider.close());
return {
provider,
root,
};
};
const evidenceResult = async (
provider: PcapProvider,
request: PcapRequest,
): Promise<Record<string, unknown>> => {
const result = await provider.execute(request);
if (!result.ok) throw new Error(result.error.message);
return pcapResultSchemas[request.operation].parse(result.value.result);
};
const captureFixture = async (root: string): Promise<string> => {
const path = join(root, "capture.pcap");
await writeFile(path, Buffer.from("pcap-fixture-bytes"));
return path;
};
it("inspects both tools without reading a capture", async () => {
const { provider } = await providerWith();
const result = await evidenceResult(provider, {
operation: "inspect_pcap_client",
input: {},
});
expect(result.client).toMatchObject({
tshark_source: "environment",
tshark_version: "TShark (Wireshark) 4.6.6-stub",
capinfos_source: "environment",
capinfos_version: "Capinfos (Wireshark) 4.6.6-stub",
});
});
it("inspects a capture with endpoints, DNS, TLS SNI, and HTTP", async () => {
const { provider, root } = await providerWith();
const path = await captureFixture(root);
const result = await evidenceResult(provider, {
operation: "inspect_pcap_capture",
input: { path },
});
expect(result.target).toMatchObject({
path,
bytes: 18,
sha256: createHash("sha256").update("pcap-fixture-bytes").digest("hex"),
});
expect(result.file_type).toBe("Wireshark/tcpdump/... - pcap");
expect(result.packet_count).toBe(3);
expect(result.endpoints).toEqual(
expect.arrayContaining([
{ address: "192.168.1.100", port: null, packet_count: 3 },
{ address: "8.8.8.8", port: null, packet_count: 1 },
]),
);
expect(result.dns_queries).toEqual([
{
query: "api.example.com",
response_addresses: ["93.184.216.34"],
response_address_count: 1,
},
]);
expect(result.tls_sni_values).toEqual(["api.example.com"]);
expect(result.http_request_uris).toEqual(["http://api.example.com/v1/data"]);
expect(result.coverage).toBe("complete");
});
it("reports a non-capture file as unsupported", async () => {
const { provider, root } = await providerWith({ failCapinfos: true });
const failPath = join(root, "fail.pcap");
await writeFile(failPath, "not a capture file");
const result = await provider.execute({
operation: "inspect_pcap_capture",
input: { path: failPath },
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "unsupported_target",
});
});
it("reports a missing tshark binary as a capability gap", async () => {
const provider = new PcapProvider({
environment: { REA_TSHARK_COMMAND: "/nonexistent/tshark" },
});
expect(await provider.inspectAvailability()).toMatchObject({
status: "unavailable",
code: "executable_missing",
});
});
it("rejects a capture that is not a readable file", async () => {
const { provider } = await providerWith();
const result = await provider.execute({
operation: "inspect_pcap_capture",
input: { path: "/nonexistent/capture.pcap" },
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
});
});
it("cancels before spawning anything", async () => {
const { provider, root } = await providerWith();
await writeFile(join(root, "spawned"), "");
const controller = new AbortController();
controller.abort();
const result = await provider.execute(
{
operation: "inspect_pcap_capture",
input: { path: "/some/capture.pcap" },
},
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
});
});
it("reports relative configuration and missing capinfos as capability gaps", async () => {
const root = await createTestTempDirectory("rea-pcap-config-");
const { tshark } = await writeStubTools(root);
for (const environment of [
{ REA_TSHARK_COMMAND: "relative/tshark" },
{
REA_TSHARK_COMMAND: tshark,
REA_CAPINFOS_COMMAND: join(root, "missing-capinfos"),
},
]) {
const provider = new PcapProvider({ environment });
onTestFinished(() => provider.close());
expect((await provider.inspectAvailability()).status).toBe("unavailable");
const result = await provider.execute({
operation: "inspect_pcap_client",
input: {},
});
if (result.ok) throw new Error("expected unavailable tools");
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("capability_unavailable");
expect(projected.message).toContain(
"Supply Wireshark 4.x tshark and capinfos",
);
}
});
it("names the prlimit selection when the Linux limiter is unusable", async () => {
const root = await createTestTempDirectory("rea-pcap-prlimit-");
const tools = await writeStubTools(root);
const provider = new PcapProvider({
environment: {
REA_TSHARK_COMMAND: tools.tshark,
REA_CAPINFOS_COMMAND: tools.capinfos,
REA_TSHARK_PRLIMIT_COMMAND: "relative/prlimit",
},
});
onTestFinished(() => provider.close());
const result = await provider.execute({
operation: "inspect_pcap_capture",
input: { path: "/not-opened/capture.pcap" },
});
if (result.ok) throw new Error("expected an unusable limiter");
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("capability_unavailable");
expect(projected.message).toContain(
"(REA_TSHARK_PRLIMIT_COMMAND must be absolute.) Check that REA_TSHARK_PRLIMIT_COMMAND",
);
});
const nodeTool = async (
root: string,
name: string,
body: string,
): Promise<string> => {
const path = join(root, name);
await writeFile(
path,
`#!/usr/bin/env -S ${process.execPath} --jitless --max-old-space-size=64\nconst fs = require('node:fs'); const crypto = require('node:crypto');\n${body}\n`,
{ mode: 0o755 },
);
return path;
};
const versionProbe =
"if (process.argv[2] === '--version') { console.log((process.argv[1].includes('capinfos') ? 'Capinfos' : 'TShark') + ' (Wireshark) 4.6.6-test'); process.exit(0); }";
it("refuses observations whose owned snapshot changed during dissection", async () => {
const root = await createTestTempDirectory("rea-pcap-mutated-");
const { capinfos } = await writeStubTools(root);
const path = await captureFixture(root);
const before = await readFile(path);
const tshark = await nodeTool(
root,
"tshark.cjs",
`${versionProbe}
const selected = process.argv[process.argv.indexOf('-r') + 1];
fs.chmodSync(selected, 0o600); fs.writeFileSync(selected, 'changed private snapshot');
console.log(${JSON.stringify(TSHARK_JSON)});`,
);
const provider = new PcapProvider({
environment: { REA_TSHARK_COMMAND: tshark, REA_CAPINFOS_COMMAND: capinfos },
});
onTestFinished(() => provider.close());
const result = await provider.execute({
operation: "inspect_pcap_capture",
input: { path },
});
expect(result.ok).toBe(false);
if (!result.ok)
expect(projectAnalysisError(result.error)).toMatchObject({
code: "artifact_changed",
});
expect(await readFile(path)).toEqual(before);
});
it("binds both tools to the snapshot when the original capture changes", async () => {
const root = await createTestTempDirectory("rea-pcap-identity-");
const path = join(root, "caller capture.pcap");
await writeFile(path, "192.0.2.1");
const capinfos = await nodeTool(
root,
"capinfos.cjs",
`${versionProbe}
const selected = process.argv.at(-1); const bytes = fs.readFileSync(selected);
console.log('File type: pcap\\nFile encapsulation: Raw IP\\nNumber of packets: 1\\nSHA256: ' + crypto.createHash('sha256').update(bytes).digest('hex'));
fs.writeFileSync(${JSON.stringify(path)}, '192.0.2.2');`,
);
const tshark = await nodeTool(
root,
"tshark.cjs",
`${versionProbe}
const selected = process.argv[process.argv.indexOf('-r') + 1];
console.log(JSON.stringify([{_source:{layers:{'frame.number':['1'],'frame.protocols':['ip'],'ip.src':[fs.readFileSync(selected,'utf8')]}}}]));`,
);
const provider = new PcapProvider({
environment: { REA_TSHARK_COMMAND: tshark, REA_CAPINFOS_COMMAND: capinfos },
});
onTestFinished(() => provider.close());
const result = await provider.execute({
operation: "inspect_pcap_capture",
input: { path },
});
if (!result.ok) throw result.error;
const value = pcapResultSchemas.inspect_pcap_capture.parse(
result.value.result,
);
expect(value.target.sha256).toBe(
createHash("sha256").update("192.0.2.1").digest("hex"),
);
expect(value.endpoints).toEqual([
{ address: "192.0.2.1", port: null, packet_count: 1 },
]);
expect(await readFile(path, "utf8")).toBe("192.0.2.2");
});
it.each(["probe", "capinfos", "tshark"] as const)(
"preserves in-flight %s cancellation and cleans up",
async (phase) => {
const root = await createTestTempDirectory("rea-pcap-cancel-");
const marker = join(root, "ready");
const slow = await nodeTool(
root,
`slow-${phase}.cjs`,
`${phase !== "probe" ? versionProbe : ""}
fs.writeFileSync(${JSON.stringify(marker)}, 'ready'); setInterval(() => {}, 1000);`,
);
const { capinfos, tshark } = await writeStubTools(root);
const path = await captureFixture(root);
const provider = new PcapProvider({
environment: {
REA_TSHARK_COMMAND: phase === "capinfos" ? tshark : slow,
REA_CAPINFOS_COMMAND: phase === "capinfos" ? slow : capinfos,
},
});
onTestFinished(() => provider.close());
const controller = new AbortController();
let watcher: ReturnType<typeof watch> | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
const ready = new Promise<void>((resolve, reject) => {
watcher = watch(root, (_event, name) => {
if (name === "ready") resolve();
});
timer = setTimeout(() => {
controller.abort();
reject(new Error("tool did not start"));
}, 5000);
});
try {
const pending = provider.execute(
{ operation: "inspect_pcap_capture", input: { path } },
{ signal: controller.signal },
);
await ready;
controller.abort(new Error("caller cancellation"));
const result = await pending;
if (result.ok) throw new Error("expected cancellation");
expect(projectAnalysisError(result.error).code).toBe("cancelled");
await provider.close();
} finally {
watcher?.close();
clearTimeout(timer);
}
},
);
it.each(["change", "cancel"] as const)(
"preserves %s during snapshot acquisition",
async (action) => {
const { provider, root } = await providerWith();
const path = await captureFixture(root);
const controller = new AbortController();
const held = await holdFirstFileRead(path);
onTestFinished(() => {
vi.restoreAllMocks();
});
const pending = provider.execute(
{ operation: "inspect_pcap_capture", input: { path } },
{ signal: controller.signal },
);
try {
await held.firstRead;
if (action === "cancel") controller.abort();
else await writeFile(path, "changed source bytes");
} finally {
held.release();
}
const result = await pending;
if (result.ok) throw new Error("expected interrupted acquisition");
expect(result.error._tag).toBe(
action === "cancel"
? "AnalysisCancelledError"
: "AnalysisArtifactChangedError",
);
},
);
it("admits one capture and drains it before close releases resources", async () => {
const { provider, root } = await providerWith();
const path = await captureFixture(root);
const held = await holdFirstFileRead(path);
onTestFinished(() => {
vi.restoreAllMocks();
});
const pending = provider.execute({
operation: "inspect_pcap_capture",
input: { path },
});
let closing: Promise<void> | undefined;
try {
await held.firstRead;
const concurrent = await provider.execute({
operation: "inspect_pcap_capture",
input: { path },
});
expect(concurrent.ok).toBe(false);
if (!concurrent.ok)
expect(projectAnalysisError(concurrent.error)).toMatchObject({
code: "resource_constraint",
details: { resource: "capacity" },
});
let closed = false;
closing = provider.close().then(() => {
closed = true;
});
await Promise.resolve();
expect(closed).toBe(false);
} finally {
held.release();
}
expect((await pending).ok).toBe(true);
await closing;
const afterClose = await provider.execute({
operation: "inspect_pcap_capture",
input: { path },
});
expect(afterClose.ok).toBe(false);
});
it.each([false, true])(
"retains failed snapshot cleanup after an analysis failure=%s",
async (failCapinfos) => {
const { provider, root } = await providerWith({ failCapinfos });
const path = await captureFixture(root);
let retained: PrivateRuntimeRoot | undefined;
const spy = vi
.spyOn(PrivateRuntimeRoot.prototype, "close")
.mockImplementation(function (this: PrivateRuntimeRoot) {
retained = this;
return Promise.reject(new Error("controlled cleanup failure"));
});
const result = await provider.execute({
operation: "inspect_pcap_capture",
input: { path },
});
try {
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Cleanup failure cannot return success");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cleanup_incomplete",
});
if (failCapinfos)
expect(projectAnalysisError(result.error)).toMatchObject({
details: {
diagnostics: { primary_error: { code: "unsupported_target" } },
},
});
else
expect(result.error.partialObservation).toMatchObject({
operation: "inspect_pcap_capture",
normalized_result: { packet_count: 3 },
});
expect(retained).toBeDefined();
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
} finally {
spy.mockRestore();
}
await provider.close();
await expect(
readFile(join(retained!.path, "capture.pcap")),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -0,0 +1,153 @@
/**
* Cross-platform pcap provider tests.
*
* POSIX hosts run the #!/bin/sh fixtures;
* Windows runs the .cmd stubs from tests/fixtures/pcap/. Both validate
* the same provider contract surface: tool probing, capture inspection,
* refusal paths, and cancellation before spawn.
*/
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { PcapProvider } from "../../../src/pcap/PcapProvider.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import type { PcapRequest } from "../../../src/domain/pcap/pcapAnalysis.js";
const isWindows = process.platform === "win32";
const hasNativeBound = process.platform === "linux" || isWindows;
const stubDir = join(import.meta.dirname, "../../fixtures/pcap");
const tsharkStub = isWindows
? join(stubDir, "tshark-stub.cmd")
: join(stubDir, "tshark-stub.sh");
const capinfosStub = isWindows
? join(stubDir, "capinfos-stub.cmd")
: join(stubDir, "capinfos-stub.sh");
const providerOver = (): PcapProvider => {
const provider = new PcapProvider({
environment: {
REA_TSHARK_COMMAND: tsharkStub,
REA_CAPINFOS_COMMAND: capinfosStub,
},
});
onTestFinished(() => provider.close());
return provider;
};
const evidenceResult = async (
provider: PcapProvider,
request: PcapRequest,
): Promise<Record<string, unknown>> => {
const result = await provider.execute(request);
if (!result.ok) throw new Error(result.error.message);
return result.value.result as Record<string, unknown>;
};
it("inspects both tools through cross-platform stubs", async () => {
const result = await evidenceResult(providerOver(), {
operation: "inspect_pcap_client",
input: {},
});
expect(result.client).toMatchObject({
tshark_source: "environment",
tshark_version: expect.stringContaining("4.6.6") as unknown,
capinfos_source: "environment",
capinfos_version: expect.stringContaining("4.6.6") as unknown,
});
});
it.runIf(hasNativeBound)(
"inspects a capture with metadata, endpoints, DNS, and protocol facts",
async () => {
const root = await createTestTempDirectory("rea-pcap-x-");
const capturePath = join(root, "capture.pcap");
const captureBytes = "cross-platform-pcap-fixture";
await writeFile(capturePath, captureBytes);
const result = await evidenceResult(providerOver(), {
operation: "inspect_pcap_capture",
input: { path: capturePath },
});
expect(result.target).toMatchObject({
path: capturePath,
bytes: captureBytes.length,
sha256: createHash("sha256").update(captureBytes).digest("hex"),
});
expect(result.file_type).toContain("pcap");
expect(result.packet_count).toBe(3);
expect((result.endpoints as unknown[]).length).toBeGreaterThan(0);
expect((result.protocol_distribution as unknown[]).length).toBeGreaterThan(
0,
);
expect(result.coverage).toBe("complete");
},
);
// Hosts without a native bound refuse before touching the path; that order
// is pinned by the unsupported-boundary test below.
it.runIf(hasNativeBound)(
"rejects a path that is not a readable file",
async () => {
const result = await providerOver().execute({
operation: "inspect_pcap_capture",
input: { path: "/nonexistent/definitely-missing.pcap" },
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
});
},
);
it("reports a missing binary as a capability gap", async () => {
const provider = new PcapProvider({
environment: { REA_TSHARK_COMMAND: "/nonexistent/tshark" },
});
expect(await provider.inspectAvailability()).toMatchObject({
status: "unavailable",
code: "executable_missing",
});
});
it("cancels before spawning anything", async () => {
const controller = new AbortController();
controller.abort();
const result = await providerOver().execute(
{ operation: "inspect_pcap_capture", input: { path: "/any/capture.pcap" } },
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
});
});
it.runIf(!hasNativeBound)(
"reports an unsupported native memory boundary before reading the capture",
async () => {
const provider = providerOver();
expect(await provider.inspectAvailability()).toMatchObject({
status: "unavailable",
code: "unsupported_host",
});
const result = await provider.execute({
operation: "inspect_pcap_capture",
input: { path: "/not-opened/capture.pcap" },
});
expect(result.ok).toBe(false);
if (result.ok) return;
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("capability_unavailable");
// The refusal concerns this host, so it must not suggest another target.
expect(projected.message).toContain(
"Linux with util-linux prlimit, or Windows with owned Job Objects",
);
expect(projected.remediation.action).toBe(projected.message);
},
);
@@ -0,0 +1,196 @@
import { createHash } from "node:crypto";
import { readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
const createPcapToolFixture = async (root: string) => {
const path = join(root, "caller capture.pcap");
const bytes = Buffer.from("recording fixture bytes");
const sha = createHash("sha256").update(bytes).digest("hex");
await writeFile(path, bytes);
const tshark = join(root, "tshark");
const capinfos = join(root, "capinfos");
const marker = join(root, "reads");
const frames = Array.from({ length: 132 }, (_, index) => ({
_source: {
layers: {
"frame.number": [String(index + 1)],
"frame.protocols": ["ip:udp:dns"],
"ip.src": ["192.0.2.1"],
"ip.dst": ["192.0.2.2"],
"dns.qry.name": ["many.example"],
"dns.flags.response": ["True"],
"dns.a": [`198.51.100.${index}`],
"tls.handshake.extensions_server_name": [`host${index}.example`],
"http.request.full_uri": [
"http://user:password@example.invalid/p?q=keep",
],
},
},
}));
await writeFile(
tshark,
`#!/bin/sh\nif [ "$1" = "--version" ]; then printf 'TShark (Wireshark) 4.6.6-emulated\\n'; exit 0; fi\nprintf 'read\\n' >> ${quote(marker)}\nprintf '%s' ${quote(JSON.stringify(frames))}\nprintf 'retained warning' >&2\n`,
{ mode: 0o755 },
);
await writeFile(
capinfos,
`#!/bin/sh\nif [ "$1" = "--version" ]; then printf 'Capinfos (Wireshark) 4.6.6-emulated\\n'; exit 0; fi\nprintf '%s\\n' ${quote(`File type: pcap\nFile encapsulation: Ethernet\nNumber of packets: 132\nSHA256: ${sha}`)}\n`,
{ mode: 0o755 },
);
const environment = {
REA_TSHARK_COMMAND: tshark,
REA_CAPINFOS_COMMAND: capinfos,
};
return { path, marker, environment };
};
// Native tools are emulated here; this proves the production CLI/MCP boundary,
// retention and paging, not Wireshark's real dissector semantics.
it.runIf(process.platform === "linux")(
"retains every fact and pages late DNS/SNI rows after source deletion without another tool launch",
async () => {
const root = await createTestTempDirectory("rea-pcap-view-");
const { path, marker, environment } = await createPcapToolFixture(root);
const complete = await promisify(execFile)(
process.execPath,
[
join(import.meta.dirname, "../../../scripts/rea.mjs"),
"inspect-pcap-capture",
path,
"--json",
],
{ env: { ...process.env, ...environment } },
);
const parent = parseEvidence(JSON.parse(complete.stdout));
expect(parent.normalized_result).toMatchObject({
tls_sni_count: 132,
tls_sni_values: expect.arrayContaining(["host131.example"]),
dns_queries: [{ query: "many.example", response_address_count: 132 }],
});
expect(JSON.stringify(parent)).not.toContain("user:password");
const { call } = await connectLocalToolsMcp(environment);
const response = await call("inspect_pcap_capture", {
path,
detail: "summary",
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const summary = parseEvidence(response.structuredContent).normalized_result;
expect(summary).toMatchObject({
parent_evidence_id: parent.evidence_id,
summary: {
tls_sni_count: 132,
dns_query_count: 1,
retained_counts: { tls_sni_values: 132 },
diagnostics_code_units: { tshark: 16, capinfos: 0 },
},
});
expect(JSON.stringify(summary)).not.toContain("host131.example");
await rm(path);
const source = {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
};
const before = await readFile(marker, "utf8");
const cases = [
[
{ kind: "pcap", facet: "endpoints", limit: 1 },
{ items: [{ address: "192.0.2.1", packet_count: 132 }] },
],
[
{ kind: "pcap", facet: "dns-queries", limit: 1 },
{
items: [
{ query: "many.example", retained_response_address_count: 132 },
],
},
],
[
{
kind: "pcap",
facet: "dns-addresses",
query: "many.example",
offset: 130,
limit: 2,
},
{ items: ["198.51.100.130", "198.51.100.131"] },
],
[
{ kind: "pcap", facet: "tls-sni", offset: 130, limit: 2 },
{ items: ["host130.example", "host131.example"] },
],
[
{ kind: "pcap", facet: "protocols" },
{ items: [{ protocol: "ip:udp:dns", packet_count: 132 }] },
],
[
{ kind: "pcap", facet: "http-uris" },
{ items: ["http://example.invalid/p?q=keep"] },
],
[{ kind: "pcap", facet: "unattributed-addresses" }, { items: [] }],
[
{
kind: "pcap",
facet: "diagnostics",
stream: "tshark",
offset: 9,
limit: 7,
},
{ text: "warning", status: "retained" },
],
] as const;
for (const [view, expected] of cases) {
const response = await call("inspect_analysis_view", { source, view });
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(
parseEvidence(response.structuredContent).normalized_result,
).toMatchObject({ page: expected, source_coverage: "complete" });
}
const workflow = join(root, "portable.json");
const view = {
kind: "pcap",
facet: "dns-addresses",
query: "many.example",
offset: 130,
limit: 2,
};
await writeFile(
workflow,
JSON.stringify({ source: { kind: "inline", evidence: parent }, view }),
);
const portable = await promisify(execFile)(process.execPath, [
join(import.meta.dirname, "../../../scripts/rea.mjs"),
"inspect-analysis-view",
workflow,
"--json",
]);
const retained = parseEvidence(
(await call("inspect_analysis_view", { source, view })).structuredContent,
);
expect(
parseEvidence(JSON.parse(portable.stdout)).normalized_result,
).toEqual(retained.normalized_result);
expect(await readFile(marker, "utf8")).toBe(before);
expect(
parseMcpToolError(
await call("inspect_analysis_view", {
source,
view: {
kind: "pcap",
facet: "dns-addresses",
query: "missing.example",
},
}),
),
).toMatchObject({ error: { code: "invalid_request" } });
},
60_000,
);
@@ -26,6 +26,7 @@ import {
import {
createDarwinProcessRunTokenReader,
DarwinProcessOwnershipInspectionError,
SWIFTC_INTERRUPT,
} from "../../../src/process/DarwinProcessRunTokenReader.js";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import {
@@ -1110,16 +1111,8 @@ it.skipIf(!onDarwin)(
try {
await execFileOutput(
"/usr/bin/xcrun",
[
"swiftc",
"-module-cache-path",
join(root, "modules"),
core,
fixture,
"-o",
executable,
],
{ timeout: 60_000 },
["swiftc", core, fixture, "-o", executable],
{ timeout: 120_000, stopSignal: SWIFTC_INTERRUPT },
);
const { stdout } = await execFileAsync(executable, [], {
encoding: "utf8",
@@ -1179,6 +1172,7 @@ it.skipIf(!onDarwin)(
await rm(root, { recursive: true, force: true });
}
},
150_000,
);
it.skipIf(!onDarwin)(
@@ -1203,16 +1197,8 @@ it.skipIf(!onDarwin)(
try {
await execFileOutput(
"/usr/bin/xcrun",
[
"swiftc",
"-module-cache-path",
join(root, "modules"),
core,
fixture,
"-o",
executable,
],
{ timeout: 60_000 },
["swiftc", core, fixture, "-o", executable],
{ timeout: 120_000, stopSignal: SWIFTC_INTERRUPT },
);
const { stdout } = await execFileAsync(executable, [], {
encoding: "utf8",
@@ -1226,6 +1212,7 @@ it.skipIf(!onDarwin)(
await rm(root, { recursive: true, force: true });
}
},
150_000,
);
it.skipIf(!onDarwin)(
@@ -73,9 +73,9 @@ processTest.for(cases)(
[
"--input-type=module",
"--eval",
`import { resolveJavaScriptSourceMapReference } from "./dist/domain/javascript/javascriptSourceMapPaths.js";
`import { resolveJavaScriptSourceMapReferences } from "./dist/domain/javascript/javascriptSourceMapPaths.js";
const [source, root] = JSON.parse(process.argv[1]);
console.log(JSON.stringify(resolveJavaScriptSourceMapReference(source, root, "maps/main.js.map")));`,
console.log(JSON.stringify(resolveJavaScriptSourceMapReferences([source], root, "maps/main.js.map")[0]));`,
JSON.stringify([scenario.source, sourceRoot]),
],
{ timeoutMs: 10_000 },
@@ -286,7 +286,8 @@ describe.skipIf(process.platform === "win32")(
{
platform: process.platform,
architecture: process.arch,
readText: () => "application.version=12.1.4\n",
readText: () =>
"application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.12",
@@ -84,6 +84,7 @@ describe("Hopper bridge launcher selection", () => {
"private",
"/usr/bin/python3",
"/rea/hopper-demo-x11.py",
"--owner-stdin",
"--strategy",
"user-mount-namespace",
"--mount-private-x11",
@@ -117,6 +118,7 @@ describe("Hopper bridge launcher selection", () => {
command: "/usr/bin/python3",
args: [
"/rea/hopper-demo-x11.py",
"--owner-stdin",
"--strategy",
"direct",
"--hopper",
@@ -202,3 +204,59 @@ it("launches Hopper helpers with the caller-selected environment without restori
await launched.value.releaseLease?.();
}
});
it.skipIf(process.platform !== "linux")(
"gives the demo helper a live owner stream through Node's actual stdio transport",
async () => {
const directory = await createTestTempDirectory("rea-hopper-owner-stdio-");
const launcher = new HopperApplicationLauncher(
{
...options(process.execPath),
launchMode: "verified_linux_demo",
demoHelperPath: fileURLToPath(
new URL("../../../fixtures/hopperLifetimeLaunch.py", import.meta.url),
),
},
{
selectPrivateDisplay: async () => ({
ok: true,
strategy: "direct",
diagnostic: {
component: "hopper_private_display",
operation: "probe",
status: "ready",
failure_code: null,
reason: "ready",
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: "1777",
mount_read_only: false,
effective_socket_directory_mode: "1777",
effective_mount_read_only: false,
wsl: false,
strategy: "direct",
fallback_reason: null,
xvfb_stderr_bytes: 0,
},
}),
},
);
const launched = await launcher.launch({
directory,
socketPath: join(directory, "bridge.sock"),
token: "fixture-token",
runId: randomUUID(),
});
if (!launched.ok) throw launched.error;
const supervisor = new ProviderProcessSupervisor(launched.value);
try {
expect(await supervisor.waitForOutputClose(5_000)).toBe(true);
expect(supervisor.snapshot().exitCode).toBe(0);
expect(JSON.parse(supervisor.snapshot().stdout.text)).toEqual({
owner_alive: true,
});
} finally {
await supervisor.stop();
await launched.value.releaseLease?.();
}
},
);
@@ -31,6 +31,9 @@ const dialogDetectionFixturePath = fileURLToPath(
const cleanupTimeoutFixturePath = fileURLToPath(
new URL("../../../fixtures/hopperCleanupTimeout.py", import.meta.url),
);
const ownerLifetimeFixturePath = fileURLToPath(
new URL("../../../fixtures/hopperOwnerLifetime.py", import.meta.url),
);
type DiagnosticOverrides = Partial<
Omit<HopperStartupDiagnostic, "failure_code" | "status">
@@ -107,6 +110,23 @@ describe("Hopper demo dialog detection", () => {
});
describe("Hopper process cleanup", () => {
it.skipIf(process.platform !== "linux").each(["startup", "ready"])(
"reaps only its own children when the owner pipe closes during %s",
(phase) => {
const result = spawnSync(
"/usr/bin/python3",
[ownerLifetimeFixturePath, helperPath, phase],
{ encoding: "utf8", timeout: 10_000 },
);
expect(result.status, result.stderr).toBe(0);
expect(JSON.parse(result.stdout)).toEqual({
phase,
children_cleaned: true,
sentinel_alive: true,
});
},
);
it.skipIf(process.platform !== "linux")(
"kills a child that ignores SIGTERM after the bounded timeout",
() => {
@@ -1200,6 +1200,138 @@ describe("native DMG command diagnostics", () => {
});
});
describe("native DMG verification resource availability", () => {
const transientFailure = {
stdout: "",
stderr:
'hdiutil: verify: unable to recognize "/tmp/image.dmg" as a disk image. (Resource temporarily unavailable)\nhdiutil: verify failed - Resource temporarily unavailable\n',
exitCode: 1,
};
it("retries the explicit transient refusal before attachment and retains both attempts", async () => {
const { host, state } = createOmittedInventoryHost();
state.inventoryMode = "listed";
state.detachAttempts = 4;
const delays = vi.fn(async () => {});
const timeouts: number[] = [];
let attempts = 0;
const reader = await createAttachedReader(
"/tmp/image.dmg",
process.env,
undefined,
{
...host,
delay: delays,
async run(arguments_, signal, options) {
if (arguments_[0] === "verify") {
attempts += 1;
if (options === undefined)
throw new Error("missing verify deadline");
timeouts.push(options.timeoutMs);
if (attempts === 1) return transientFailure;
}
return host.run(arguments_, signal, options);
},
},
);
onTestFinished(() => reader.close());
expect(attempts).toBe(2);
expect(delays.mock.calls).toEqual([[250]]);
expect(timeouts[0]).toBeLessThanOrEqual(120_000);
expect(timeouts[1]).toBeLessThanOrEqual(timeouts[0]!);
expect(reader.provenance().slice(0, 2)).toMatchObject([
{
arguments: ["verify", "/tmp/image.dmg"],
exit_code: 1,
effects: ["read"],
},
{
arguments: ["verify", "/tmp/image.dmg"],
exit_code: 0,
effects: ["read"],
},
]);
await reader.close();
expect(state.attached).toBe(false);
});
it("bounds repeated transient refusals and never attaches an unverified image", async () => {
const run = vi.fn(async () => transientFailure);
const delay = vi.fn(async () => {});
const reader = new NativeDmgArtifactReader("/tmp/image.dmg", process.env, {
run,
delay,
});
await expect(entryPaths(reader)).rejects.toMatchObject({
reason: "unavailable",
message: expect.stringContaining("Resource temporarily unavailable"),
});
await reader.close();
expect(run.mock.calls).toHaveLength(3);
expect(delay.mock.calls).toEqual([[250], [500]]);
expect(reader.provenance().map(({ exit_code }) => exit_code)).toEqual([
1, 1, 1,
]);
});
it("honors cancellation during the wait without starting another command", async () => {
const controller = new AbortController();
const run = vi.fn(async () => transientFailure);
await expect(
createAttachedReader("/tmp/image.dmg", process.env, controller.signal, {
run,
async delay() {
controller.abort(new Error("cancel verification"));
},
}),
).rejects.toMatchObject({ reason: "cancelled" });
expect(run).toHaveBeenCalledTimes(1);
});
it("does not start another verification after the shared deadline", async () => {
const clock = vi.spyOn(performance, "now").mockReturnValue(0);
const run = vi.fn(async () => transientFailure);
try {
await expect(
createAttachedReader("/tmp/image.dmg", process.env, undefined, {
run,
async delay() {
clock.mockReturnValue(120_001);
},
}),
).rejects.toMatchObject({
reason: "unavailable",
message: expect.stringContaining("Resource temporarily unavailable"),
});
expect(run).toHaveBeenCalledTimes(1);
} finally {
clock.mockRestore();
}
});
it.each([
["image data corrupted", "integrity"],
["image not recognized", "format"],
["Permission denied", "io"],
["an unknown failure", "unavailable"],
])("does not retry %s", async (diagnostic, reason) => {
const run = vi.fn(async () => ({
stdout: "",
stderr: `hdiutil: verify failed - ${diagnostic}\n`,
exitCode: 1,
}));
const delay = vi.fn(async () => {});
await expect(
createAttachedReader("/tmp/image.dmg", process.env, undefined, {
run,
delay,
}),
).rejects.toMatchObject({ reason });
expect(run).toHaveBeenCalledTimes(1);
expect(delay).not.toHaveBeenCalled();
});
});
describe("native DMG real verification diagnostics", () => {
it.skipIf(process.platform !== "darwin")(
"classifies a real hdiutil verify refusal as a format failure with captured output",
@@ -134,6 +134,114 @@ describe("Codex agent release evaluation", () => {
});
});
describe("Codex completed tool call parsing", () => {
it("does not let an unfinished direct event reserve a completed call identity", () => {
const evidence = observation();
const metrics = evaluateCodexEvents(
[
{
type: "mcp_tool_call",
id: "same-call",
status: "in_progress",
server: "rea",
tool: evidence.operation,
arguments: {},
},
{
type: "item.completed",
item: {
id: "same-call",
type: "mcp_tool_call",
status: "completed",
server: "rea",
tool: evidence.operation,
arguments: {},
result: { structuredContent: evidence },
},
},
{
type: "item.completed",
item: {
type: "agent_message",
text: `Observed Evidence ${evidence.evidence_id} supports the artifact claim; runtime behavior remains unknown without runtime authority.`,
},
},
],
evidence.operation,
{ requireEvidence: true },
);
expect(metrics).toMatchObject({
naturalUse: true,
correctFirstTool: true,
reaCalls: [{ id: "same-call" }],
evidenceIds: [evidence.evidence_id],
finalCitesEvidence: true,
answerHeuristicsMet: true,
});
});
it.each([
{ server: "rea", server_name: "other" },
{ tool: "inspect_managed_artifact", name: "other_tool" },
{ server: 42 },
{ arguments: { value: 1 }, input: { value: 2 } },
])(
"rejects completed calls with invalid or conflicting fields: %j",
(aliases) => {
const evidence = observation();
const metrics = evaluateCodexEvents(
[
{
type: "item.completed",
item: {
type: "mcp_tool_call",
status: "completed",
server: "rea",
tool: evidence.operation,
arguments: {},
result: { structuredContent: evidence },
...aliases,
},
},
],
evidence.operation,
{ requiredToolSubsequence: [evidence.operation] },
);
expect(metrics).toMatchObject({
naturalUse: false,
correctFirstTool: false,
requiredToolSubsequenceMet: false,
evidenceIds: [],
});
},
);
it("preserves legacy completed calls with no server field", () => {
const metrics = evaluateCodexEvents(
[
{
type: "item.completed",
item: {
type: "mcp_tool_call",
status: "completed",
tool: "inspect_managed_artifact",
arguments: {},
},
},
],
"inspect_managed_artifact",
);
expect(metrics).toMatchObject({
naturalUse: true,
correctFirstTool: true,
reaCalls: [{ server: null }],
});
});
});
describe("Codex Evidence delivery", () => {
it("rejects diagnostic IDs and failed results as delivered Evidence", () => {
const evidenceId = `ev_${"a".repeat(64)}`;
@@ -524,28 +632,32 @@ describe("Codex agent completion evaluation", () => {
});
});
it("recognizes Codex MCP failed status when the error field is null", () => {
const metrics = evaluateCodexEvents(
[
{
type: "item.completed",
item: {
id: "item-failed",
type: "mcp_tool_call",
server: "rea",
tool: "analyze_javascript_application",
arguments: { input_path: "/tmp/app.asar" },
result: { structured_content: { error: { code: "denied" } } },
error: null,
status: "failed",
},
},
],
"analyze_javascript_application",
);
it.each(["item.completed", "mcp_tool_call"] as const)(
"counts a failed completed invocation from %s without delivering Evidence",
(type) => {
const item = {
id: "item-failed",
type: "mcp_tool_call",
server: "rea",
tool: "analyze_javascript_application",
arguments: { input_path: "/tmp/app.asar" },
result: { structured_content: { error: { code: "denied" } } },
error: null,
status: "failed",
};
const metrics = evaluateCodexEvents(
[type === "item.completed" ? { type, item } : item],
"analyze_javascript_application",
);
expect(metrics.reaCalls[0]?.error).toBe(true);
});
expect(metrics).toMatchObject({
naturalUse: true,
correctFirstTool: true,
evidenceIds: [],
reaCalls: [{ error: true }],
});
},
);
});
describe("Codex agent workflow evaluation", () => {
+6 -2
View File
@@ -1,5 +1,6 @@
import { createHash } from "node:crypto";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import type { EvmInterfaceExecution } from "../../../src/application/evm/EvmInterfacePort.js";
import type { EvmInterface } from "../../../src/domain/evm/evmInterface.js";
/** Source-owned transport seam, independent of real engine verification. */
@@ -27,8 +28,10 @@ export const evmInterfaceFixture = (
});
/** Bind a fixture to its explicit producing seam and carrier identity. */
export const evmInterfaceExecution = (value = evmInterfaceFixture()) =>
createAnalysisExecution(
export const evmInterfaceExecution = (
value = evmInterfaceFixture(),
): EvmInterfaceExecution => {
return createAnalysisExecution(
value,
{ id: "fixture-evm", name: "Source-owned EVM seam", version: "1" },
{
@@ -42,3 +45,4 @@ export const evmInterfaceExecution = (value = evmInterfaceFixture()) =>
locations: [{ kind: "artifact-path", path: value.artifact.path }],
},
);
};
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Inspect the real Node launcher stdio with the production lifetime parser."""
import importlib.util
import json
from pathlib import Path
import sys
spec = importlib.util.spec_from_file_location(
"hopper_demo_x11", Path(__file__).resolve().parents[2] / "scripts/hopper-demo-x11.py"
)
assert spec is not None and spec.loader is not None
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
assert "--owner-stdin" in sys.argv
print(json.dumps({"owner_alive": helper.OwnerLifetime(True).alive()}))
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Exercise the production runner with real children and a simulated X11 surface."""
import argparse
import importlib.util
import json
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
spec = importlib.util.spec_from_file_location("hopper_demo_x11", sys.argv[1])
assert spec is not None and spec.loader is not None
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
def child_command(receipt):
return [
sys.executable,
"-c",
"import os,pathlib,time;"
f"receipt=pathlib.Path({str(receipt)!r});"
"pending=receipt.with_suffix('.pending');"
"pending.write_text(str(os.getpid()));pending.replace(receipt);"
"time.sleep(100)",
]
if len(sys.argv) > 3:
phase, directory = sys.argv[2], Path(sys.argv[3])
def terminate_worker(*_):
raise SystemExit(143)
# Failed assertions in the parent must still unwind run_launch's finally.
signal.signal(signal.SIGTERM, terminate_worker)
class X11:
def XOpenDisplay(self, *_):
return 1
def XDefaultRootWindow(self, *_):
return 1
def XDisplayWidth(self, *_):
return 1280
def XDisplayHeight(self, *_):
return 1024
def XCloseDisplay(self, *_):
return 1
def start_xvfb(*_):
child = subprocess.Popen(
child_command(directory / "xvfb.pid"),
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
)
return child, ":123", directory / "Xauthority", helper.CapturedStderr(child.stderr)
helper.digest = lambda _: next(iter(helper.SUPPORTED_HOPPER_SHA256))
helper.start_xvfb = start_xvfb
helper.ctypes.CDLL = lambda _: X11()
helper.configure_x11 = lambda *_: None
helper.windows = lambda *_: []
socket = directory / "bridge.sock"
if phase == "ready":
socket.touch()
raise SystemExit(helper.run_launch(argparse.Namespace(
owner_stdin=True,
hopper=sys.executable,
socket=str(socket),
command=child_command(directory / "hopper.pid"),
)))
with tempfile.TemporaryDirectory(prefix="rea-owner-lifetime-") as root:
directory = Path(root)
sentinel = subprocess.Popen([sys.executable, "-c", "import time;time.sleep(100)"])
worker = subprocess.Popen(
[sys.executable, __file__, sys.argv[1], sys.argv[2], root],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
deadline = time.monotonic() + 5
receipts = [directory / "hopper.pid", directory / "xvfb.pid"]
while not all(receipt.exists() for receipt in receipts):
assert worker.poll() is None, worker.communicate()
assert time.monotonic() < deadline, "owned children did not start"
time.sleep(0.01)
pids = [int(receipt.read_text()) for receipt in receipts]
assert worker.poll() is None, "live owner did not retain the helper"
assert worker.stdin is not None
worker.stdin.close()
assert worker.wait(timeout=5) == 0, worker.stderr.read()
for pid in pids:
assert not Path(f"/proc/{pid}").exists(), f"owned child {pid} survived EOF"
assert sentinel.poll() is None, "unrelated process was stopped"
print(json.dumps({"phase": sys.argv[2], "children_cleaned": True, "sentinel_alive": True}))
finally:
helper.stop_process(worker)
helper.stop_process(sentinel)
+4 -1
View File
@@ -34,7 +34,9 @@ const compileValidator = (schema: unknown): ValidateFunction<unknown> => {
};
/** Start the built production server without configuring deep binary providers. */
export async function connectLocalToolsMcp() {
export async function connectLocalToolsMcp(
environment: Readonly<Record<string, string>> = {},
) {
const transport = new StdioClientTransport({
command: process.execPath,
args: [
@@ -45,6 +47,7 @@ export async function connectLocalToolsMcp() {
PATH: process.env.PATH ?? "/usr/bin:/bin",
REA_LOG_LEVEL: "silent",
HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper",
...environment,
},
stderr: "pipe",
});
+19
View File
@@ -0,0 +1,19 @@
@echo off
rem capinfos stub for Windows: emulates capinfos --version and metadata output.
if "%~1"=="--version" (
echo Capinfos ^(Wireshark^) 4.6.6-windows-stub
exit /b 0
)
if not "%~1"=="-M" exit /b 2
if not "%~2"=="--" exit /b 2
if "%~3"=="" exit /b 2
echo File name: capture.pcap
echo File type: Wireshark/tcpdump/... - pcap
echo File encapsulation: Ethernet
echo Packet size limit: file hdr: 262144 bytes
echo Number of packets: 3
echo Capture duration: 0.123 seconds
exit /b 0
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# POSIX capinfos stub (mirrors capinfos-stub.cmd for Windows parity).
if [ "$1" = "--version" ]; then printf 'Capinfos (Wireshark) 4.6.6-posix-stub\n'; exit 0; fi
[ "$1" = "-M" ] && [ "$2" = "--" ] && [ "$#" = "3" ] || exit 2
printf '%s\n' 'File name: capture.pcap'
printf '%s\n' 'File type: Wireshark/tcpdump/... - pcap'
printf '%s\n' 'File encapsulation: Ethernet'
printf '%s\n' 'Packet size limit: file hdr: 262144 bytes'
printf '%s\n' 'Number of packets: 3'
printf '%s\n' 'Capture duration: 0.123 seconds'
exit 0
+17
View File
@@ -0,0 +1,17 @@
@echo off
rem Pcap tool stub for Windows: emulates tshark --version and field output.
rem %1 is the first argument; the capture path arrives as %2 for -r/-c.
if "%~1"=="--version" (
echo TShark ^(Wireshark^) 4.6.6-windows-stub
exit /b 0
)
if not "%~1"=="-n" exit /b 2
if not "%~2"=="-r" exit /b 2
if not "%~4"=="-T" exit /b 2
if not "%~5"=="json" exit /b 2
rem Emit the same JSON as the POSIX stub
echo [{"_source":{"layers":{"frame.number":["1"],"frame.protocols":["eth:ethertype:ip:udp:dns"],"ip.src":["192.168.1.100"],"ip.dst":["8.8.8.8"],"dns.qry.name":["api.example.com"],"dns.flags.response":["1"],"dns.a":["93.184.216.34"]}}},{"_source":{"layers":{"frame.number":["2"],"frame.protocols":["eth:ethertype:ip:tcp:tls"],"ip.src":["192.168.1.100"],"ip.dst":["93.184.216.34"],"tls.handshake.extensions_server_name":["api.example.com"]}}},{"_source":{"layers":{"frame.number":["3"],"frame.protocols":["eth:ethertype:ip:tcp:http"],"ip.src":["192.168.1.100"],"ip.dst":["93.184.216.34"],"http.request.full_uri":["http://api.example.com/v1/data"]}}}]
exit /b 0
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# POSIX pcap tool stub (mirrors tshark-stub.cmd for Windows parity).
if [ "$1" = "--version" ]; then printf 'TShark (Wireshark) 4.6.6-posix-stub\n'; exit 0; fi
[ "$1" = "-n" ] && [ "$2" = "-r" ] && [ "$4" = "-T" ] && [ "$5" = "json" ] || exit 2
printf '%s' '[{"_source":{"layers":{"frame.number":["1"],"frame.protocols":["eth:ethertype:ip:udp:dns"],"ip.src":["192.168.1.100"],"ip.dst":["8.8.8.8"],"dns.qry.name":["api.example.com"],"dns.flags.response":["1"],"dns.a":["93.184.216.34"]}}},{"_source":{"layers":{"frame.number":["2"],"frame.protocols":["eth:ethertype:ip:tcp:tls"],"ip.src":["192.168.1.100"],"ip.dst":["93.184.216.34"],"tls.handshake.extensions_server_name":["api.example.com"]}}},{"_source":{"layers":{"frame.number":["3"],"frame.protocols":["eth:ethertype:ip:tcp:http"],"ip.src":["192.168.1.100"],"ip.dst":["93.184.216.34"],"http.request.full_uri":["http://api.example.com/v1/data"]}}}]'
exit 0
+6 -2
View File
@@ -1,5 +1,6 @@
import { createHash } from "node:crypto";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import type { WasmArtifactExecution } from "../../../src/application/wasm/WasmArtifactPort.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 = (
@@ -42,8 +43,10 @@ export const wasmArtifactFixture = (
network_fetch: "not-performed" as const,
limitations: ["Source-owned transport seam."],
});
export const wasmArtifactExecution = (value = wasmArtifactFixture()) =>
createAnalysisExecution(
export const wasmArtifactExecution = (
value = wasmArtifactFixture(),
): WasmArtifactExecution => {
return createAnalysisExecution(
value,
{ id: "fixture-wabt", name: "Source-owned WABT seam", version: "1" },
{
@@ -55,3 +58,4 @@ export const wasmArtifactExecution = (value = wasmArtifactFixture()) =>
limitations: value.limitations,
},
);
};
@@ -261,6 +261,14 @@ it.runIf(supportedHost).each([
if (result.ok) throw new Error("Expected unresolved process ownership");
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("cleanup_incomplete");
expect(projected).toMatchObject({
details: {
resources: expect.arrayContaining([
expect.stringMatching(/^pid:\d+$/u),
expect.stringMatching(/^process-group:\d+$/u),
]),
},
});
if (stage === "debugger")
expect(projected).toMatchObject({
details: {
@@ -0,0 +1,55 @@
import { readFile, symlink } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
vi.mock("node:fs", async (importOriginal) => {
const original = await importOriginal<typeof import("node:fs")>();
return {
...original,
constants: { ...original.constants, O_NOFOLLOW: 0 },
};
});
import { openRegularFile } from "../../src/filesystem/RegularFile.js";
import { ZipArtifactReader } from "../../src/artifacts/ZipArtifactReader.js";
import { writeOrderedZip } from "../fixtures/artifactEntryOrder.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
it("rejects a symlink when O_NOFOLLOW is unavailable and still follows when requested", async () => {
const root = await createTestTempDirectory("rea-no-nofollow-");
const target = join(root, "target.zip");
const link = join(root, "selected.zip");
await writeOrderedZip(target, ["member.bin"]);
await symlink(target, link);
const reader = new ZipArtifactReader(target, "zip");
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
expect(entries.map(({ path }) => path)).toEqual(["member.bin"]);
} finally {
await reader.close();
}
const linkedReader = new ZipArtifactReader(link, "zip");
try {
await expect(async () => {
for await (const _entry of linkedReader.entries()) {
// Consume through the public reader boundary.
}
}).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "format",
});
} finally {
await linkedReader.close();
}
const followed = await openRegularFile(link, { symlinks: "follow" });
try {
await expect(readFile(followed)).resolves.toEqual(await readFile(target));
} finally {
await followed.close();
}
});
@@ -126,6 +126,41 @@ describe("OMP integration maintenance", () => {
});
});
describe("maintenance activation and layered configuration", () => {
it("leaves a natively disabled ZCode registration outside maintenance", async () => {
const configPath = await writeClient(
"zcode",
JSON.stringify({
mcp: {
servers: {
rea: { command: entryPoint, args: ["mcp"], enable: false },
},
},
}),
);
const original = await readFile(configPath, "utf8");
await expect(
existingMaintenanceScope(home, entryPoint, process.env),
).resolves.toMatchObject({ clients: [] });
expect(await readFile(configPath, "utf8")).toBe(original);
});
it("selects an enabled registration inherited through layered OpenCode files", async () => {
const directory = join(home, ".config", "opencode");
await mkdir(directory, { recursive: true });
await writeFile(
join(directory, "opencode.json"),
JSON.stringify({
mcp: { rea: { type: "local", command: [entryPoint, "mcp"] } },
}),
);
await writeClient("opencode", JSON.stringify({ theme: "user-selected" }));
await expect(
existingMaintenanceScope(home, entryPoint, process.env),
).resolves.toMatchObject({ clients: ["opencode"] });
});
});
describe("existing REA integration maintenance", () => {
it("selects owned registrations while preserving unconfigured, foreign, and disabled choices", async () => {
await writeClient("codex", staleCodex);