refactor(tools): remove artificial analysis ceilings

This commit is contained in:
morluto
2026-09-29 16:29:23 +08:00
parent 36aeec9586
commit 2f08c7c932
202 changed files with 2314 additions and 3072 deletions
@@ -94,27 +94,22 @@ async function runInlineEvidenceScenarios(
expect(session.exportEvidenceBundle().records.length).toBeGreaterThan(2);
}
async function runEvidenceIdScenarios(harness: TestHarness): Promise<void> {
const tracedById = await harness.client.callTool({
async function runInlineWorkflowScenarios(harness: TestHarness): Promise<void> {
const tracedInline = await harness.client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application_evidence_id:
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
},
});
expect(tracedById.isError).not.toBe(true);
expect(tracedInline.isError).not.toBe(true);
const comparedById = await harness.client.callTool({
const comparedInline = await harness.client.callTool({
name: "compare_application_versions",
arguments: {
left: JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left
.evidence_id,
right:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
...JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
},
});
expect(comparedById).toMatchObject({
expect(comparedInline).toMatchObject({
structuredContent: {
result: {
evidence_links: expect.arrayContaining([
@@ -125,27 +120,7 @@ async function runEvidenceIdScenarios(harness: TestHarness): Promise<void> {
},
});
const mixedLeftInline = await harness.client.callTool({
name: "compare_application_versions",
arguments: {
left: JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left,
right:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
},
});
expect(mixedLeftInline.isError).not.toBe(true);
const mixedRightInline = await harness.client.callTool({
name: "compare_application_versions",
arguments: {
left: JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left
.evidence_id,
right: JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right,
},
});
expect(mixedRightInline.isError).not.toBe(true);
const legacyAliases = await harness.client.callTool({
const idsRejected = await harness.client.callTool({
name: "compare_application_versions",
arguments: {
left_evidence_id:
@@ -154,14 +129,12 @@ async function runEvidenceIdScenarios(harness: TestHarness): Promise<void> {
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
},
});
expect(legacyAliases.isError).toBe(true);
expect(idsRejected.isError).toBe(true);
const sourceComparedById = await harness.client.callTool({
name: "compare_source_to_bundle",
arguments: {
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
application_evidence_id:
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
},
});
expect(sourceComparedById.isError).not.toBe(true);
@@ -171,17 +144,6 @@ async function assertRejectedEvidenceReferences(
client: Client,
session: BinarySession,
): Promise<void> {
const missing = await client.callTool({
name: "trace_application_feature",
arguments: JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
});
expect(missing).toMatchObject({
isError: true,
structuredContent: {
error: { details: { reason: "missing" } },
},
});
const wrongOperation = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
@@ -199,20 +161,17 @@ async function assertRejectedEvidenceReferences(
);
expect(session.recordEvidence(wrongOperation).ok).toBe(true);
expect(session.recordEvidence(wrongPredicate).ok).toBe(true);
for (const [record, reason] of [
[wrongOperation, "wrong_operation"],
[wrongPredicate, "wrong_predicate"],
] as const) {
for (const record of [wrongOperation, wrongPredicate]) {
const rejected = await client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application_evidence_id: record.evidence_id,
application: record,
},
});
expect(rejected).toMatchObject({
isError: true,
structuredContent: { error: { details: { reason } } },
structuredContent: { error: expect.any(Object) },
});
}
}
@@ -224,9 +183,7 @@ async function assertRejectedInlineEvidence(client: Client): Promise<void> {
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
native_observations: [
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
],
native_observation_evidence_ids: [
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
],
},
});
@@ -261,7 +218,7 @@ describe("application workflow MCP parity", () => {
const harness = await createTestHarness();
try {
await runInlineEvidenceScenarios(harness.client, harness.session);
await runEvidenceIdScenarios(harness);
await runInlineWorkflowScenarios(harness);
await assertRejectedEvidenceReferences(harness.client, harness.session);
await assertRejectedInlineEvidence(harness.client);
} finally {
@@ -9,14 +9,9 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascriptApplicationWorkflowExamples.js";
import {
createEvidenceBundle,
serializeEvidenceBundle,
} from "../../../src/domain/evidenceBundle.js";
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
import { REPLAY_MACHINE_RUN_EXAMPLE } from "../../../src/contracts/replayMachineExample.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
@@ -117,106 +112,24 @@ describe("application workflow CLI parity", () => {
}, 20_000);
});
describe("application workflow CLI Evidence lookup", () => {
it("resolves Evidence IDs from a caller-supplied bundle", async () => {
const root = await createTestTempDirectory("rea-application-bundle-cli-");
temporary.push(root);
const bundlePath = join(root, "evidence.json");
await writeFile(
bundlePath,
serializeEvidenceBundle(
createEvidenceBundle([
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right,
]),
),
);
const environment = {};
const traced = await runCli(
[
"trace-application-feature",
JSON.stringify({
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application_evidence_id:
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application
.evidence_id,
}),
"--evidence-bundle",
bundlePath,
"--json",
],
environment,
);
expect(traced).toMatchObject({
operation: "trace_application_feature",
normalized_result: { source_evidence_id: expect.any(String) },
});
const compared = await runCli(
[
"compare-application-versions",
JSON.stringify({
left: JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left
.evidence_id,
right:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right
.evidence_id,
}),
"--evidence-bundle",
bundlePath,
"--json",
],
environment,
);
expect(compared).toMatchObject({
operation: "compare_application_versions",
normalized_result: { summary: expect.any(Object) },
});
const missingRecord = await runCli(
[
"trace-application-feature",
JSON.stringify(JAVASCRIPT_FEATURE_TRACE_EXAMPLE),
"--evidence-bundle",
bundlePath,
"--json",
],
environment,
);
expect(missingRecord).toMatchObject({
code: "evidence_integrity_mismatch",
details: { reason: "missing" },
});
const outsideRoot = await createTestTempDirectory(
"rea-outside-bundle-cli-",
);
temporary.push(outsideRoot);
const outsideBundlePath = join(outsideRoot, "evidence.json");
await writeFile(
outsideBundlePath,
serializeEvidenceBundle(createEvidenceBundle([])),
);
const outsideBundle = await runCli(
[
"trace-application-feature",
JSON.stringify(JAVASCRIPT_FEATURE_TRACE_EXAMPLE),
"--evidence-bundle",
outsideBundlePath,
"--json",
],
environment,
);
expect(outsideBundle).toMatchObject({
code: "evidence_integrity_mismatch",
details: { reason: "missing" },
});
}, 30_000);
describe("application workflow CLI input", () => {
it("rejects Evidence ID-only workflow inputs", async () => {
const result = await runCli([
"compare-application-versions",
JSON.stringify({
left: JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left
.evidence_id,
right:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
}),
"--json",
]);
expect(result).toMatchObject({ code: "invalid_request" });
});
});
describe("application workflow CLI export Evidence", () => {
it("compares exact export shapes from an authorized Evidence bundle", async () => {
it("compares exact export shapes from inline Evidence", async () => {
const root = await createTestTempDirectory("rea-export-shape-cli-");
temporary.push(root);
const leftRoot = join(root, "left");
@@ -242,23 +155,16 @@ describe("application workflow CLI export Evidence", () => {
]);
if (!left.ok) throw left.error;
if (!right.ok) throw right.error;
const bundlePath = join(root, "evidence.json");
await writeFile(
bundlePath,
serializeEvidenceBundle(createEvidenceBundle([left.value, right.value])),
);
const compared = await runCli([
"compare-javascript-export-shapes",
JSON.stringify({
left: left.value.evidence_id,
right: right.value.evidence_id,
left: left.value,
right: right.value,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
}),
"--evidence-bundle",
bundlePath,
"--json",
]);
expect(compared).toMatchObject({
@@ -22,7 +22,7 @@ describe("local application workflow verifier", () => {
);
});
it("reports bounded two-version and trace claims without source text", async () => {
it("reports two-version and trace results", async () => {
const root = await createTestTempDirectory("rea-application-verifier-");
temporary.push(root);
const fixtures = await writeVersionedJavaScriptApplicationFixtures(root);
@@ -57,10 +57,9 @@ describe("local application workflow verifier", () => {
coverage: { status: expect.any(String) },
trace: { summary: { matched_seeds: expect.any(Number) } },
});
expect(stdout).not.toContain("stableValue");
}, 20_000);
it("verifies the source-owned parser depth return-shape addition", async () => {
it("reports an added parser return field", async () => {
const root = await createTestTempDirectory("rea-shape-verifier-");
temporary.push(root);
const left = join(root, "left");
@@ -110,6 +109,5 @@ describe("local application workflow verifier", () => {
automatically_started: false,
},
});
expect(stdout).not.toContain("value.slice");
}, 20_000);
});
@@ -99,10 +99,6 @@ describe("package installation workflows", () => {
it("verifies the package before publish and runs published canaries outside the checkout", async () => {
const release = await readWorkflow("release.yml");
const canary = await readFile(
new URL("../../../scripts/verify-published-package.mjs", import.meta.url),
"utf8",
);
const publishJob = workflowJob(release, "publish");
const publishSteps = publishJob.steps;
@@ -120,13 +116,9 @@ describe("package installation workflows", () => {
({ name }: { readonly name?: unknown }) =>
name === "Verify published CLI from npm",
);
expect(publishedCanary?.run).toContain('verification_root="$(mktemp -d)"');
expect(publishedCanary?.run).toContain('cd "${verification_root}"');
expect(publishedCanary?.run).not.toContain(
'npm run verify:published -- "${version}"',
expect(publishedCanary?.run).toContain(
"scripts/verify-published-package.mjs",
);
expect(canary).toContain('mkdtemp(join(tmpdir(), "rea-published-canary-")');
expect(canary).toContain("cwd: canaryRoot");
const publisherJob = workflowJob(release, "publish-mcp");
const publisherSteps = publisherJob.steps;
expect(publisherJob).toMatchObject({
@@ -46,7 +46,6 @@ describe("CdpElectronProvider target access", () => {
const inspected = await new CdpElectronProvider().inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
observation_ms: 0,
}),
@@ -56,7 +55,7 @@ describe("CdpElectronProvider target access", () => {
expect(inspected.value.completeness.truncated_sections).toEqual([]);
});
it("returns every approved Electron page target inline", async () => {
it("returns every Electron page target exposed by the endpoint inline", async () => {
const root = await electronFixture();
const index = join(root, "index.html");
const browser = await startFakeCdpBrowser({
@@ -67,7 +66,6 @@ describe("CdpElectronProvider target access", () => {
const listed = await new CdpElectronProvider().listTargets(
listElectronTargetsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
}),
);
if (!listed.ok) throw listed.error;
@@ -78,7 +76,7 @@ describe("CdpElectronProvider target access", () => {
});
describe("CdpElectronProvider target selection", () => {
it("lists and inspects only canonical file targets beneath approved roots", async () => {
it("lists and inspects every canonical local file target", async () => {
const root = await electronFixture();
const index = join(root, "index.html");
const browser = await startFakeCdpBrowser({
@@ -90,7 +88,6 @@ describe("CdpElectronProvider target selection", () => {
const listed = await provider.listTargets(
listElectronTargetsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
}),
);
if (!listed.ok) throw listed.error;
@@ -101,7 +98,6 @@ describe("CdpElectronProvider target selection", () => {
}),
]);
expect(listed.value.excluded).toEqual({
outside_root: 0,
unsupported_url: 3,
non_page: 2,
});
@@ -109,7 +105,6 @@ describe("CdpElectronProvider target selection", () => {
const inspected = await provider.inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
observation_ms: 0,
}),
@@ -144,7 +139,6 @@ describe("CdpElectronProvider target selection", () => {
const missing = await provider.inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "missing",
observation_ms: 0,
}),
@@ -171,7 +165,6 @@ describe("CdpElectronProvider target selection", () => {
const result = await new CdpElectronProvider().inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
observation_ms: 0,
}),
@@ -187,13 +180,11 @@ describe("CdpElectronProvider target selection", () => {
});
it("maps cancelled Electron discovery to the Electron operation", async () => {
const root = await electronFixture();
const controller = new AbortController();
controller.abort();
const result = await new CdpElectronProvider().listTargets(
listElectronTargetsInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_file_roots: [root],
}),
{ signal: controller.signal },
);
@@ -213,14 +204,12 @@ describe("Electron request schemas", () => {
expect(
listElectronTargetsInputSchema.safeParse({
cdp_endpoint: "http://127.0.0.1:9223",
allowed_file_roots: ["/tmp/app"],
allowed_file_root: "/tmp/app",
}).success,
).toBe(false);
expect(
inspectElectronPageInputSchema.safeParse({
cdp_endpoint: "http://127.0.0.1:9223",
allowed_file_roots: ["/tmp/app"],
target_id: "page-1",
observation_ms: 0,
limits: { max_dom_nodes: 20 },
@@ -239,7 +228,6 @@ describe("CdpElectronProvider capture", () => {
const result = await new CdpElectronProvider().inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
observation_ms: 0,
include_script_sources: true,
@@ -265,7 +253,6 @@ describe("CdpElectronProvider capture", () => {
const result = await new CdpElectronProvider().inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
observation_ms: 0,
}),
@@ -296,7 +283,6 @@ describe("CdpElectronProvider capture", () => {
const result = await new CdpElectronProvider().inspectPage(
inspectElectronPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
observation_ms: 0,
}),
@@ -32,15 +32,13 @@ describe("passive V8 Inspector provider", () => {
expect(
observeJavaScriptRuntimeToolInputSchema.safeParse({
inspector_endpoint: "http://127.0.0.1:9229",
allowed_file_roots: ["/tmp/app"],
allowed_origins: [],
target_id: "target-1",
limits: {},
}).success,
).toBe(false);
});
test("returns every approved Inspector target inline", async () => {
test("returns every target exposed by the selected Inspector endpoint inline", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
@@ -49,8 +47,6 @@ describe("passive V8 Inspector provider", () => {
try {
const listed = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
allowed_file_roots: [fixture.root],
allowed_origins: [],
});
expect(listed.ok).toBe(true);
if (!listed.ok) return;
@@ -61,7 +57,7 @@ describe("passive V8 Inspector provider", () => {
}
});
test("filters target locations and never retains the excluded path", async () => {
test("includes targets outside the old caller root filter", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("outside.js");
const fake = await startFakeV8Inspector({
@@ -71,14 +67,13 @@ describe("passive V8 Inspector provider", () => {
try {
const result = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
allowed_file_roots: [fixture.root],
allowed_origins: [],
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.targets).toHaveLength(1);
expect(result.value.excluded.outside_file_roots).toBe(1);
expect(JSON.stringify(result.value)).not.toContain(outside);
expect(result.value.targets).toHaveLength(2);
expect(
result.value.targets.map(({ location }) => location),
).toContainEqual(expect.objectContaining({ file_path: outside }));
} finally {
await fake.close();
}
@@ -97,12 +92,12 @@ describe("passive V8 Inspector provider", () => {
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, fixture.root, "node"),
observeInput(fake.endpoint, fake.targetId, "node"),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.scripts.items).toHaveLength(2);
expect(result.value.scripts.excluded.outside_file_roots).toBe(1);
expect(result.value.scripts.items).toHaveLength(3);
expect(result.value.scripts.excluded.unsupported_location).toBe(0);
expect(result.value.execution_contexts).toEqual([
{
context_key: "1",
@@ -115,7 +110,7 @@ describe("passive V8 Inspector provider", () => {
"Runtime.enable",
"Debugger.enable",
]);
expect(JSON.stringify(result.value)).not.toContain(outside);
expect(JSON.stringify(result.value)).toContain(outside);
expect(result.value.unavailable_without_instrumentation).toContain(
"Electron IPC messages and handlers",
);
@@ -134,24 +129,17 @@ describe("passive V8 Inspector provider", () => {
const provider = new V8InspectorProvider();
const listed = await provider.listTargets({
inspector_endpoint: fake.endpoint,
allowed_file_roots: [fixture.root],
allowed_origins: [],
});
expect(listed.ok).toBe(true);
if (!listed.ok) return;
expect(listed.value.targets).toEqual([]);
const observed = await provider.observe(
observeInput(
fake.endpoint,
fake.targetId,
fixture.root,
"electron-main",
),
observeInput(fake.endpoint, fake.targetId, "electron-main"),
);
expect(observed.ok).toBe(false);
if (observed.ok) return;
expect(observed.error.message).toMatch(/outside_file_roots|target/u);
expect(observed.error.message).toMatch(/target/u);
} finally {
await fake.close();
}
@@ -172,7 +160,7 @@ describe("passive V8 Inspector provider", () => {
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, fixture.root, runtimeKind),
observeInput(fake.endpoint, fake.targetId, runtimeKind),
);
expect(result.ok).toBe(true);
} finally {
@@ -198,7 +186,7 @@ describe("complete Inspector script hashes", () => {
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, fixture.root, "node"),
observeInput(fake.endpoint, fake.targetId, "node"),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
@@ -220,12 +208,7 @@ describe("undeclared V8 runtime role", () => {
targetType: "page",
});
try {
const input = observeInput(
fake.endpoint,
fake.targetId,
fixture.root,
"node",
);
const input = observeInput(fake.endpoint, fake.targetId, "node");
delete input.runtime_kind;
const result = await new V8InspectorProvider().observe(input);
expect(result.ok).toBe(true);
@@ -243,7 +226,6 @@ describe("undeclared V8 runtime role", () => {
describe("passive V8 Inspector evidence", () => {
test("retains authorized script locations longer than the former byte ceiling", async () => {
const fixture = await runtimeFixture();
const longUrl = `https://example.test/${"a".repeat(20_000)}`;
const fake = await startFakeV8Inspector({
targetUrl: longUrl,
@@ -251,8 +233,7 @@ describe("passive V8 Inspector evidence", () => {
});
try {
const input = {
...observeInput(fake.endpoint, fake.targetId, fixture.root, "node"),
allowed_origins: ["https://example.test"],
...observeInput(fake.endpoint, fake.targetId, "node"),
};
const result = await new V8InspectorProvider().observe(input);
expect(result.ok).toBe(true);
@@ -279,12 +260,7 @@ describe("passive V8 Inspector evidence", () => {
scriptUrls,
});
try {
const input = observeInput(
fake.endpoint,
fake.targetId,
fixture.root,
"node",
);
const input = observeInput(fake.endpoint, fake.targetId, "node");
const result = await new V8InspectorProvider().observe(input);
expect(result.ok).toBe(true);
if (!result.ok) return;
@@ -303,13 +279,8 @@ describe("passive V8 Inspector evidence", () => {
targetUrl: pathToFileURL(fixture.entry).href,
});
try {
const input = observeInput(
fake.endpoint,
fake.targetId,
fixture.root,
"node",
);
const authority = await authorityFor(fake.endpoint, fixture.root);
const input = observeInput(fake.endpoint, fake.targetId, "node");
const authority = await authorityFor();
const first = await observeJavaScriptRuntime(
new V8InspectorProvider(),
authority,
@@ -330,8 +301,6 @@ describe("passive V8 Inspector evidence", () => {
authority,
{
inspector_endpoint: fake.endpoint,
allowed_file_roots: [fixture.root],
allowed_origins: [],
},
);
expect(listed.ok).toBe(true);
@@ -350,8 +319,6 @@ describe("passive V8 Inspector evidence", () => {
"observe_javascript_runtime",
{
inspector_endpoint: "http://127.0.0.1:9229",
allowed_file_roots: [root],
allowed_origins: [],
target_id: "example-v8-target",
runtime_kind: "electron-main",
observation_ms: 100,
@@ -391,24 +358,20 @@ const temporaryFile = async (name: string): Promise<string> => {
const observeInput = (
endpoint: string,
targetId: string,
root: string,
runtimeKind: ObserveJavaScriptRuntimeInput["runtime_kind"],
): ObserveJavaScriptRuntimeInput => ({
inspector_endpoint: endpoint,
allowed_file_roots: [root],
allowed_origins: [],
target_id: targetId,
runtime_kind: runtimeKind,
observation_ms: 10,
});
const authorityFor = async (endpoint: string, root: string) => {
const authorityFor = async () => {
const scope: PermissionCeiling = {
capability: "v8_inspector_observe",
roots: [root],
roots: [],
executables: [],
environment_names: [],
origins: [endpoint],
network: "loopback",
mount: false,
};
@@ -464,8 +427,6 @@ const runtimeObservation = (
],
observed_total: 1,
excluded: {
outside_file_roots: 0,
outside_origins: 0,
unsupported_location: 0,
invalid_protocol_value: 0,
},
+1 -3
View File
@@ -31,7 +31,7 @@ afterEach(async () => {
describe("Electron CLI parity", () => {
it(
"returns the same root-confined Electron Evidence contracts",
"returns the same endpoint-scoped Electron Evidence contracts",
async () => {
const root = await createTestTempDirectory("rea-electron-cli-");
temporary.push(root);
@@ -47,8 +47,6 @@ describe("Electron CLI parity", () => {
const environment = {
...process.env,
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
};
const listed = await runCli(
["list-electron-targets", browser.endpoint, "--json"],
@@ -44,8 +44,6 @@ describe("JavaScript runtime observation CLI parity", () => {
const environment = {
...process.env,
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: JSON.stringify([inspector.endpoint]),
REA_V8_INSPECTOR_FILE_ROOTS_JSON: JSON.stringify([root]),
};
const listed = await runCli(
@@ -96,8 +94,6 @@ describe("JavaScript runtime observation CLI parity", () => {
authority.value,
observeJavaScriptRuntimeInputSchema.parse({
inspector_endpoint: inspector.endpoint,
allowed_file_roots: [root],
allowed_origins: [],
target_id: inspector.targetId,
runtime_kind: "node",
observation_ms: 10,
+1 -15
View File
@@ -1,4 +1,4 @@
import { open, rm, writeFile } from "node:fs/promises";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { execFile } from "node:child_process";
@@ -119,20 +119,6 @@ describe("process CLI errors", () => {
});
});
it("rejects oversized process input before parsing", async () => {
const root = await fixture();
const path = join(root, "large.json");
const handle = await open(path, "w");
await handle.truncate(64 * 1024 * 1024 + 1);
await handle.close();
expect(await captureProcessScenarioFile(path)).toEqual({
error: "Process command failed",
category: "truncated",
message:
"Process input file is too large. Reduce it below 64 MiB, then try again.",
});
});
it("rejects unrelated capture evidence", async () => {
const root = await fixture();
const invalidCapture = join(root, "invalid-capture.json");
@@ -58,7 +58,7 @@ describe("dependency install freshness", () => {
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("alpha: installed 0.9.0, expected 1.0.0");
expect(result.stderr.match(/npm ci/gu)).toHaveLength(1);
expect(result.stderr).toContain("npm ci");
});
it("reports a missing direct development dependency", async () => {
@@ -70,7 +70,7 @@ describe("dependency install freshness", () => {
expect(result.stderr).toContain(
"beta: missing from the installed dependency lockfile",
);
expect(result.stderr.match(/npm ci/gu)).toHaveLength(1);
expect(result.stderr).toContain("npm ci");
});
it("runs from a script path containing URL-escaped characters", async () => {
@@ -6,10 +6,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
authorizedElectronFile,
canonicalElectronRoots,
} from "../../../src/browser/ElectronFileScope.js";
import { authorizedElectronFile } from "../../../src/browser/ElectronFileScope.js";
describe("Electron file scope", () => {
it("accepts dot-prefixed child names beneath a canonical root", async () => {
@@ -18,13 +15,10 @@ describe("Electron file scope", () => {
await mkdir(directory);
const path = join(directory, "index.html");
await writeFile(path, "allowed");
const roots = await canonicalElectronRoots([root]);
expect(await authorizedElectronFile(pathToFileURL(path).href, roots)).toBe(
path,
);
expect(await authorizedElectronFile(pathToFileURL(path).href)).toBe(path);
});
it("accepts canonical files within a root and rejects escape forms", async () => {
it("accepts explicit canonical local files and rejects remote or malformed URLs", async () => {
const base = await createTestTempDirectory("rea-electron-scope-");
const root = join(base, "root");
const outside = join(base, "outside");
@@ -35,35 +29,31 @@ describe("Electron file scope", () => {
await writeFile(allowed, "allowed");
await writeFile(denied, "denied");
await symlink(denied, join(root, "escape.html"));
const roots = await canonicalElectronRoots([root]);
expect(
await authorizedElectronFile(pathToFileURL(allowed).href, roots),
).toBe(allowed);
expect(
await authorizedElectronFile(pathToFileURL(denied).href, roots),
).toBeUndefined();
expect(await authorizedElectronFile(pathToFileURL(allowed).href)).toBe(
allowed,
);
expect(await authorizedElectronFile(pathToFileURL(denied).href)).toBe(
denied,
);
expect(
await authorizedElectronFile(
pathToFileURL(join(root, "escape.html")).href,
roots,
),
).toBe(denied);
expect(
await authorizedElectronFile("file://server/share/index.html"),
).toBeUndefined();
expect(
await authorizedElectronFile("file://server/share/index.html", roots),
).toBeUndefined();
expect(
await authorizedElectronFile("file:///tmp/root%2Findex.html", roots),
await authorizedElectronFile("file:///tmp/root%2Findex.html"),
).toBeUndefined();
});
it("accepts file URLs with long query text inside a root", async () => {
it("accepts file URLs with long query text", async () => {
const root = await createTestTempDirectory("rea-electron-long-url-");
const path = join(root, "index.html");
await writeFile(path, "allowed");
const roots = await canonicalElectronRoots([root]);
const value = `${pathToFileURL(path).href}?${"x".repeat(70_000)}`;
await expect(authorizedElectronFile(value, roots)).resolves.toBe(path);
await expect(authorizedElectronFile(value)).resolves.toBe(path);
});
});
@@ -38,6 +38,35 @@ describe("project permission store", () => {
});
});
it("round-trips every operator grant without an arbitrary collection ceiling", async () => {
const project = await createTestTempDirectory("rea-policy-many-grants-");
const path = join(project, ".rea", "permissions.json");
const grants = Array.from({ length: 1_001 }, (_, index) => ({
grant_id: `project:grant-${String(index)}`,
capability: "process_capture" as const,
roots: [project],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
lifetime: "project" as const,
operation_identity: null,
expires_at: null,
}));
const written = await writeProjectPermissionStore(path, project, grants);
expect(written.ok).toBe(true);
if (!written.ok) return;
expect(written.value.grants).toHaveLength(grants.length);
const loaded = await readProjectPermissionStore(path, project);
expect(loaded.ok).toBe(true);
if (!loaded.ok) return;
expect(loaded.value?.grants).toEqual(grants);
});
});
describe("project permission store integrity", () => {
it("rejects stores readable by another user class", async () => {
const project = await createTestTempDirectory("rea-policy-mode-");
const path = join(project, "permissions.json");
+31 -29
View File
@@ -199,8 +199,8 @@ it("records an approved mismatch, preserves verified siblings, and never reports
const compared = await client.callTool({
name: "compare_artifacts",
arguments: {
left_evidence_id: evidence.evidence_id,
right_evidence_id: evidence.evidence_id,
left: evidence,
right: evidence,
},
});
expect(compared.isError).not.toBe(true);
@@ -224,14 +224,12 @@ it("records an approved mismatch, preserves verified siblings, and never reports
}
});
it("rejects altered payloads that reuse session Evidence IDs", async () => {
it("rejects inline artifact Evidence whose content does not match its ID", async () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
session.recordEvidence(ARTIFACT_COMPARISON_EXAMPLE.left);
session.recordEvidence(ARTIFACT_COMPARISON_EXAMPLE.right);
const server = createServer(session, session);
const client = new Client({
name: "artifact-authority-test",
@@ -255,16 +253,16 @@ it("rejects altered payloads that reuse session Evidence IDs", async () => {
expect(result.isError).toBe(true);
expect(
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.left.evidence_id),
).toBeDefined();
).toBeUndefined();
expect(
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.right.evidence_id),
).toBeDefined();
).toBeUndefined();
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
it("rejects comparison Evidence that is not owned by the session", async () => {
it("compares inline inventory Evidence without prior session calls", async () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
@@ -284,13 +282,18 @@ it("rejects comparison Evidence that is not owned by the session", async () => {
name: "compare_artifacts",
arguments: ARTIFACT_COMPARISON_EXAMPLE,
});
expect(result.isError).toBe(true);
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
true,
);
expect(compactResult(result.structuredContent).result).toMatchObject({
status: "changed",
});
expect(
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.left.evidence_id),
).toBeUndefined();
).toBeDefined();
expect(
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.right.evidence_id),
).toBeUndefined();
).toBeDefined();
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
@@ -368,21 +371,18 @@ it("returns full artifact graphs inline and compares changed inventories", async
});
const inventoryInspection = z
.object({
substeps: z.array(
z.object({
evidence: z.object({
normalized_result: z.object({
manifest: z.object({ root_format: z.literal("ipa") }),
occurrences: z.array(z.object({ logical_path: z.string() })),
}),
}),
}),
),
substeps: z.array(z.object({ evidence: z.unknown() })),
})
.parse(inventoryResult.result);
expect(
inventoryInspection.substeps[0]?.evidence.normalized_result.occurrences,
).toEqual(
const inventoryEvidence = z
.object({
normalized_result: z.object({
manifest: z.object({ root_format: z.literal("ipa") }),
occurrences: z.array(z.object({ logical_path: z.string() })),
}),
})
.parse(inventoryInspection.substeps[0]?.evidence);
expect(inventoryEvidence.normalized_result.occurrences).toEqual(
expect.arrayContaining([
expect.objectContaining({
logical_path: "Payload/Fixture.app/main.js",
@@ -399,14 +399,16 @@ it("returns full artifact graphs inline and compares changed inventories", async
arguments: {},
});
const changedResult = compactResult(changedInventory.structuredContent);
const changedEvidence = session.evidenceById(changedResult.evidence_id);
if (changedEvidence === undefined)
throw new Error("missing changed Evidence");
const changedInspection = z
.object({
substeps: z.array(z.object({ evidence: z.unknown() })),
})
.parse(changedResult.result);
const compared = await client.callTool({
name: "compare_artifacts",
arguments: {
left_evidence_id: evidence.evidence_id,
right_evidence_id: changedEvidence.evidence_id,
left: inventoryInspection.substeps[0]?.evidence,
right: changedInspection.substeps[0]?.evidence,
},
});
expect(compared.isError).not.toBe(true);
+20 -21
View File
@@ -1,8 +1,8 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { parseConfig } from "../../../src/config.js";
@@ -111,9 +111,7 @@ it(
name: "reconcile_javascript_runtime",
arguments: {
static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers,
runtime_observations: [
evidenceFor(connected.session, inspected.structuredContent),
],
runtime_observations: [evidenceFor(inspected.structuredContent)],
},
});
expect(reconciled.isError).not.toBe(true);
@@ -222,10 +220,13 @@ const verifySessionAndComparisonTools = async (
expect(visual.structuredContent).toMatchObject({
result: { status: "identical", changed_pixels: 0 },
});
const evidenceId = evidenceIdOf(inspected.structuredContent);
expect(inspected.structuredContent).toMatchObject({
evidence_id: evidenceId,
result: expect.any(Object),
evidence: {
operation: "inspect_web_page",
predicate_type: expect.any(String),
parameters: expect.any(Object),
},
});
};
@@ -285,27 +286,25 @@ const connectBrowser = async (browser: FakeCdpBrowser) => {
return { client, session };
};
const evidenceIdOf = (value: unknown): string => {
if (
typeof value !== "object" ||
value === null ||
!("evidence_id" in value) ||
typeof value.evidence_id !== "string"
)
throw new TypeError("Missing browser evidence ID");
return value.evidence_id;
};
const normalizedResultOf = (value: unknown): unknown => {
if (typeof value !== "object" || value === null || !("result" in value))
throw new TypeError("Missing normalized browser result");
return value.result;
};
const evidenceFor = (session: BinarySession, value: unknown) => {
const evidence = session.evidenceById(evidenceIdOf(value));
if (evidence === undefined) throw new TypeError("Missing session Evidence");
return evidence;
const evidenceFor = (value: unknown) => {
const parsed = z
.object({
evidence_id: z.string(),
result: z.unknown(),
evidence: z.object({}).passthrough(),
})
.parse(value);
return {
...parsed.evidence,
evidence_id: parsed.evidence_id,
normalized_result: parsed.result,
};
};
const artifactOf = (value: unknown): unknown => {
@@ -225,12 +225,12 @@ describe("browser scenario MCP tool", () => {
expect(JSON.stringify(captured.structuredContent)).not.toContain(
"correct horse battery staple",
);
const evidenceId = Reflect.get(
captured.structuredContent ?? {},
"evidence_id",
);
expect(session.evidenceById(String(evidenceId))).toMatchObject({
predicate_type: "rea.browser-scenario-capture",
expect(captured.structuredContent).toMatchObject({
evidence: {
predicate_type: "rea.browser-scenario-capture",
operation: "capture_browser_scenario",
parameters: expect.any(Object),
},
});
const captureResult = Reflect.get(
captured.structuredContent ?? {},
+26 -58
View File
@@ -1,4 +1,4 @@
import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
import { rm, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
@@ -9,7 +9,6 @@ import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import type { ElectronActiveObservationPort } from "../../../src/application/ElectronActiveObservationPort.js";
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
@@ -37,7 +36,7 @@ afterEach(async () => {
);
});
it("exposes root-confined Electron discovery and inspection as Evidence", async () => {
it("exposes endpoint-scoped Electron discovery and inspection as Evidence", async () => {
const root = await createTestTempDirectory("rea-electron-mcp-");
temporary.push(root);
await writeFile(join(root, "index.html"), "<script src='app.js'></script>");
@@ -56,8 +55,6 @@ it("exposes root-confined Electron discovery and inspection as Evidence", async
browsers.push(browser);
const config = parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
@@ -86,7 +83,6 @@ it("exposes root-confined Electron discovery and inspection as Evidence", async
name: "list_electron_targets",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
},
});
expect(listed.isError).not.toBe(true);
@@ -95,11 +91,10 @@ it("exposes root-confined Electron discovery and inspection as Evidence", async
targets: [{ target_id: "electron-page" }],
},
});
const discoveryEvidenceId = evidenceIdFrom(listed.structuredContent);
const inspected = await client.callTool({
name: "inspect_electron_page",
arguments: {
discovery_evidence_id: discoveryEvidenceId,
cdp_endpoint: browser.endpoint,
target_id: "electron-page",
observation_ms: 0,
include_script_sources: true,
@@ -124,10 +119,10 @@ it("exposes root-confined Electron discovery and inspection as Evidence", async
static_layers: [
{
role: "application",
analysis: evidenceFor(session, analyzed.structuredContent),
analysis: evidenceFor(analyzed.structuredContent),
},
],
runtime_observations: [evidenceFor(session, inspected.structuredContent)],
runtime_observations: [evidenceFor(inspected.structuredContent)],
},
});
expect(reconciled.isError).not.toBe(true);
@@ -158,25 +153,6 @@ it("exposes root-confined Electron discovery and inspection as Evidence", async
],
},
});
const outside = join(root, "..", `outside-${Date.now().toString(16)}`);
await mkdir(outside);
temporary.push(outside);
const commandsBeforeDenial = browser.commands.length;
const denied = await client.callTool({
name: "list_electron_targets",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_file_roots: [outside],
},
});
expect(denied.isError).toBe(true);
expect(denied.structuredContent).toMatchObject({
error: {
code: "permission_required",
details: { missing: { roots: [expect.stringMatching(/outside-/u)] } },
},
});
expect(browser.commands).toHaveLength(commandsBeforeDenial);
}, 20_000);
it("exposes active Electron scenarios through the separately granted MCP boundary", async () => {
@@ -266,15 +242,14 @@ it("exposes active Electron scenarios through the separately granted MCP boundar
expect(JSON.stringify(captured.structuredContent)).not.toContain(
"super-secret",
);
const evidenceId = Reflect.get(
captured.structuredContent ?? {},
"evidence_id",
);
expect(session.evidenceById(String(evidenceId))).toMatchObject({
predicate_type: "rea.electron-active-scenario",
parameters: {
args: ["--token", "<redacted>"],
actions: [{ step_id: "submit", kind: "click" }],
expect(captured.structuredContent).toMatchObject({
evidence: {
predicate_type: "rea.electron-active-scenario",
operation: "capture_electron_scenario",
parameters: {
args: ["--token", "<redacted>"],
actions: [{ step_id: "submit", kind: "click" }],
},
},
});
}, 20_000);
@@ -354,24 +329,17 @@ it("exposes the target-free static JavaScript application workflow", async () =>
expect(projected.evidence.operation).toBe("analyze_javascript_application");
});
const evidenceFor = (session: BinarySession, value: unknown) => {
if (
typeof value !== "object" ||
value === null ||
!("evidence_id" in value) ||
typeof value.evidence_id !== "string"
)
throw new TypeError("Missing compact Evidence ID");
const evidence = session.evidenceById(value.evidence_id);
if (evidence === undefined) throw new TypeError("Missing session Evidence");
return evidence;
};
const evidenceIdFrom = (value: unknown): string => {
if (typeof value !== "object" || value === null)
throw new TypeError("Missing structured result");
const evidenceId = Reflect.get(value, "evidence_id");
if (typeof evidenceId !== "string")
throw new TypeError("Missing Evidence ID");
return evidenceId;
const evidenceFor = (value: unknown) => {
const parsed = z
.object({
evidence_id: z.string(),
result: z.unknown(),
evidence: z.object({}).passthrough(),
})
.parse(value);
return {
...parsed.evidence,
evidence_id: parsed.evidence_id,
normalized_result: parsed.result,
};
};
@@ -172,7 +172,7 @@ describe("enhanced MCP tools", () => {
});
});
it("bounds batch concurrency at the parsed maximum of 20", async () => {
it("dispatches every batch item without an artificial concurrency cap", async () => {
let active = 0;
let maximum = 0;
const analysis: AnalysisOperationPort = {
@@ -190,13 +190,13 @@ describe("enhanced MCP tools", () => {
name: "batch_decompile",
arguments: {
addresses: Array.from(
{ length: 20 },
{ length: 37 },
(_, index) => `0x${String(index)}`,
),
},
});
expect(result.isError).not.toBe(true);
expect(maximum).toBe(20);
expect(maximum).toBe(37);
});
it("returns ordered typed batch failures and zero counts for empty input", async () => {
@@ -33,8 +33,8 @@ describe("function comparison MCP integration", () => {
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_id: FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
left: FUNCTION_COMPARISON_EXAMPLE.left,
right: FUNCTION_COMPARISON_EXAMPLE.right,
},
});
expect(result.isError).not.toBe(true);
@@ -70,7 +70,7 @@ describe("function comparison MCP integration", () => {
}
});
it("rejects dangling Evidence links before recording output", async () => {
it("accepts inline Evidence without prior session registration", async () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
@@ -86,12 +86,14 @@ describe("function comparison MCP integration", () => {
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_id: FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
left: FUNCTION_COMPARISON_EXAMPLE.left,
right: FUNCTION_COMPARISON_EXAMPLE.right,
},
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toEqual([]);
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: { status: expect.any(String) },
});
} finally {
await Promise.allSettled([
client.close(),
@@ -101,7 +103,7 @@ describe("function comparison MCP integration", () => {
}
});
it("rejects Evidence IDs with the wrong operation", async () => {
it("rejects inline Evidence with the wrong operation", async () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
@@ -131,8 +133,8 @@ describe("function comparison MCP integration", () => {
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_id: wrong.evidence_id,
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
left: wrong,
right: FUNCTION_COMPARISON_EXAMPLE.right,
},
});
expect(result.isError).toBe(true);
-1
View File
@@ -111,7 +111,6 @@ const installationHost = (): GhidraInstallationHost => ({
const sessionInfo = (profileDigest: string, targetSha256: string) => ({
name: "REA Ghidra bridge" as const,
bridge_version: 7 as const,
run_id: "11111111-1111-4111-8111-111111111111",
profile_digest: profileDigest,
provider: { id: "ghidra" as const, version: "12.1.2" },
@@ -40,7 +40,7 @@ it("aggregates comparison Evidence and records an approved runtime gap", async (
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
const evidence = inlineEvidence(response.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-changed-behavior" },
normalized_result: { behavior_status: "unknown" },
@@ -67,7 +67,7 @@ it("builds a zero-hop exact-address path with dossier citations", async () => {
arguments: INVESTIGATION_EXAMPLES.build_call_path,
});
expect(response.isError).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
const evidence = inlineEvidence(response.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-call-path" },
normalized_result: {
@@ -152,7 +152,7 @@ it("records an explicit non-causal static/runtime hypothesis", async () => {
arguments: INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
});
expect(response.isError).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
const evidence = inlineEvidence(response.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-static-runtime-correlation" },
confidence: "inferred",
@@ -221,7 +221,7 @@ it("passes only the finite declared reconstruction specification", async () => {
},
});
expect(response.isError).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
const evidence = inlineEvidence(response.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-reconstruction-verifier" },
normalized_result: { status: "pass", summary: { passed: 1 } },
@@ -269,7 +269,7 @@ it("cannot omit a session-owned active unknown from reconstruction input", async
},
});
expect(response.isError).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
const evidence = inlineEvidence(response.structuredContent);
expect(evidence.normalized_result).toMatchObject({
status: "unknown",
summary: { unknown: 1 },
@@ -305,13 +305,19 @@ const connected = async (permissionAuthority?: PermissionAuthority) => {
return { session, server, client };
};
const sessionEvidence = (session: BinarySession, value: unknown) => {
const inlineEvidence = (value: unknown) => {
const parsed = z
.object({ evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u) })
.object({
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
result: z.unknown(),
evidence: z.object({ limitations: z.array(z.string()) }).passthrough(),
})
.parse(value);
const evidence = session.evidenceById(parsed.evidence_id);
if (evidence === undefined) throw new TypeError("Missing session Evidence");
return evidence;
return {
...parsed.evidence,
evidence_id: parsed.evidence_id,
normalized_result: parsed.result,
};
};
const close = async (
@@ -38,8 +38,6 @@ describe("JavaScript runtime observation MCP tools", () => {
Array.from({ length: count }, (_, index) => `item-${index}`);
const scope = {
inspector_endpoint: "http://127.0.0.1:9222",
allowed_file_roots: ["/tmp/rea-runtime"],
allowed_origins: [],
};
expect(
observeJavaScriptRuntimeInputSchema.parse({
@@ -57,8 +55,6 @@ describe("JavaScript runtime observation MCP tools", () => {
},
targets: [],
excluded: {
outside_file_roots: 0,
outside_origins: 0,
unsupported_location: 0,
unconnectable: 0,
},
@@ -96,8 +92,6 @@ describe("JavaScript runtime observation MCP tools", () => {
items: [],
observed_total: 0,
excluded: {
outside_file_roots: 0,
outside_origins: 0,
unsupported_location: 0,
invalid_protocol_value: 0,
},
@@ -114,15 +108,13 @@ describe("JavaScript runtime observation MCP tools", () => {
test("lists and observes one target as retained Evidence", async () => {
const root = await createTestTempDirectory("rea-v8-mcp-");
temporary.push(root);
const { entry, inspector, authority, client, session } =
const { entry, inspector, authority, client } =
await createObservationClient(root, resources);
const listed = await client.callTool({
name: "list_javascript_runtime_targets",
arguments: {
inspector_endpoint: inspector.endpoint,
allowed_file_roots: [root],
allowed_origins: [],
},
});
expect(listed.isError).not.toBe(true);
@@ -131,12 +123,10 @@ describe("JavaScript runtime observation MCP tools", () => {
targets: [{ target_id: inspector.targetId }],
},
});
const discoveryEvidenceId = evidenceIdFrom(listed.structuredContent);
const observedRuntime = await client.callTool({
name: "observe_javascript_runtime",
arguments: {
discovery_evidence_id: discoveryEvidenceId,
inspector_endpoint: inspector.endpoint,
target_id: inspector.targetId,
runtime_kind: "node",
observation_ms: 10,
@@ -160,7 +150,13 @@ describe("JavaScript runtime observation MCP tools", () => {
},
});
const evidenceId = evidenceIdFrom(observedRuntime.structuredContent);
expect(session.evidenceById(evidenceId)).toBeDefined();
expect(observedRuntime.structuredContent).toMatchObject({
evidence: {
evidence_id: evidenceId,
operation: "observe_javascript_runtime",
parameters: expect.any(Object),
},
});
expect(inspector.commands.map(({ method }) => method)).toEqual([
"Runtime.enable",
"Debugger.enable",
@@ -183,8 +179,6 @@ const createObservationClient = async (
resources.push(inspector);
const config = parseConfig({
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: JSON.stringify([inspector.endpoint]),
REA_V8_INSPECTOR_FILE_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
@@ -208,7 +202,7 @@ const createObservationClient = async (
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
return { entry, inspector, authority: authority.value, client, session };
return { entry, inspector, authority: authority.value, client };
};
const observeDirectly = (
@@ -221,8 +215,6 @@ const observeDirectly = (
authority,
observeJavaScriptRuntimeInputSchema.parse({
inspector_endpoint: inspector.endpoint,
allowed_file_roots: [root],
allowed_origins: [],
target_id: inspector.targetId,
runtime_kind: "node",
observation_ms: 10,
-8
View File
@@ -208,15 +208,7 @@ const configure = (
"https://example.test",
]);
env.REA_ELECTRON_OBSERVE_ENABLED = String(enabled);
env.REA_ELECTRON_CDP_ENDPOINTS_JSON = JSON.stringify([
"http://127.0.0.1:9223",
]);
env.REA_ELECTRON_FILE_ROOTS_JSON = JSON.stringify([root]);
env.REA_V8_INSPECTOR_OBSERVE_ENABLED = String(enabled);
env.REA_V8_INSPECTOR_ENDPOINTS_JSON = JSON.stringify([
"http://127.0.0.1:9224",
]);
env.REA_V8_INSPECTOR_FILE_ROOTS_JSON = JSON.stringify([root]);
};
const startRuntime = async (
+35 -47
View File
@@ -76,13 +76,8 @@ it("opens a managed PE and executes the managed static provider through MCP", as
await server.connect(serverTransport);
await client.connect(clientTransport);
await verifyManagedCatalogAndNativeWorkflow(client, session);
const members = await inspectManagedStaticWorkflow(client, session, path);
await verifyManagedComparisonAndReconstruction(
client,
session,
members,
rightPath,
);
const members = await inspectManagedStaticWorkflow(client, path);
await verifyManagedComparisonAndReconstruction(client, members, rightPath);
} finally {
await Promise.all([client.close(), server.close()]);
await session.close();
@@ -114,12 +109,10 @@ const verifyManagedCatalogAndNativeWorkflow = async (
await client.callTool({
name: "verify_managed_native_boundaries",
arguments: {
managed_boundaries_evidence_id:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries.evidence_id,
native_observation_evidence_ids:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations.map(
({ evidence_id: evidenceId }) => evidenceId,
),
managed_boundaries:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
native_observations:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations,
},
}),
);
@@ -135,26 +128,22 @@ const verifyManagedCatalogAndNativeWorkflow = async (
const wrong = await client.callTool({
name: "verify_managed_native_boundaries",
arguments: {
managed_boundaries_evidence_id: native.evidence_id,
native_observation_evidence_ids: [
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries.evidence_id,
managed_boundaries: native,
native_observations: [
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
],
},
});
expect(wrong).toMatchObject({
isError: true,
structuredContent: {
error: {
code: "evidence_integrity_mismatch",
details: { reason: "wrong_operation", actual: "inspect_macho" },
},
error: { code: "evidence_integrity_mismatch" },
},
});
};
const inspectManagedStaticWorkflow = async (
client: Client,
session: BinarySession,
path: string,
): Promise<Record<string, unknown>> => {
const inspected = structured(
@@ -169,8 +158,7 @@ const inspectManagedStaticWorkflow = async (
references: [expect.objectContaining({ name: "System.Runtime" })],
},
});
const members = sessionEvidence(
session,
const members = inlineEvidence(
structured(
await client.callTool({
name: "inspect_managed_members",
@@ -225,7 +213,6 @@ const methodFrom = (members: Record<string, unknown>) =>
const verifyManagedComparisonAndReconstruction = async (
client: Client,
session: BinarySession,
members: Record<string, unknown>,
rightPath: string,
): Promise<void> => {
@@ -233,8 +220,7 @@ const verifyManagedComparisonAndReconstruction = async (
name: "open_binary",
arguments: { path: rightPath },
});
const right = sessionEvidence(
session,
const right = inlineEvidence(
structured(
await client.callTool({
name: "inspect_managed_members",
@@ -242,14 +228,13 @@ const verifyManagedComparisonAndReconstruction = async (
}),
),
);
const compared = sessionEvidence(
session,
const compared = inlineEvidence(
structured(
await client.callTool({
name: "compare_managed_members",
arguments: {
left_evidence_id: members.evidence_id,
right_evidence_id: right.evidence_id,
left: members,
right,
},
}),
),
@@ -266,25 +251,23 @@ const verifyManagedComparisonAndReconstruction = async (
const method = methodFrom(members);
expect(method).toBeDefined();
if (method === undefined) return;
await verifyImport(client, session, members, method);
await verifyRuntimePlan(client, session, members, method);
await verifyImport(client, members, method);
await verifyRuntimePlan(client, members, method);
};
type ManagedMethod = NonNullable<ReturnType<typeof methodFrom>>;
const verifyImport = async (
client: Client,
session: BinarySession,
members: Record<string, unknown>,
method: ManagedMethod,
): Promise<void> => {
const imported = sessionEvidence(
session,
const imported = inlineEvidence(
structured(
await client.callTool({
name: "import_managed_reconstruction",
arguments: {
static_members_evidence_id: members.evidence_id,
static_members: members,
decompiler: {
name: "ilspycmd",
version: "9.1.0.7988",
@@ -328,17 +311,15 @@ const verifyImport = async (
const verifyRuntimePlan = async (
client: Client,
session: BinarySession,
members: Record<string, unknown>,
method: ManagedMethod,
): Promise<void> => {
const planned = sessionEvidence(
session,
const planned = inlineEvidence(
structured(
await client.callTool({
name: "plan_managed_runtime_correlation",
arguments: {
static_members_evidence_id: members.evidence_id,
static_members: members,
method: {
token: method.token,
signature_sha256: method.signature.raw_sha256,
@@ -383,12 +364,19 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
};
const sessionEvidence = (
session: BinarySession,
result: Readonly<Record<string, unknown>>,
const inlineEvidence = (
value: Readonly<Record<string, unknown>>,
): Record<string, unknown> => {
const evidenceId = z.string().parse(result.evidence_id);
const evidence = session.evidenceById(evidenceId);
if (evidence === undefined) throw new Error("missing session Evidence");
return z.record(z.string(), z.unknown()).parse(evidence);
const parsed = z
.object({
evidence_id: z.string(),
result: z.unknown(),
evidence: z.object({}).passthrough(),
})
.parse(value);
return {
...parsed.evidence,
evidence_id: parsed.evidence_id,
normalized_result: parsed.result,
};
};
@@ -138,8 +138,8 @@ describe("declared trace adapter parity", () => {
const response = await client.callTool({
name: "compare_process_captures",
arguments: {
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
left,
right,
trace_spec: traceSpecification,
},
});
@@ -1,4 +1,4 @@
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import WebSocket from "ws";
import { startLoopbackReplay } from "../../../src/application/LoopbackReplay.js";
@@ -91,6 +91,37 @@ it("matches bounded HTTP scripts without persisting request secrets", async () =
}
});
it("keeps long replay delays pending and cancels them when replay closes", async () => {
const scenario = parseProcessScenario({
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
http: [
{
method: "GET",
path: "/later",
status: 200,
body: "ready",
delay_ms: 2_147_483_648,
},
],
},
});
const replay = await startLoopbackReplay(scenario);
const response = fetch(`${replay.httpUrl}/later`);
try {
await vi.waitFor(() => {
expect(
replay.events.some(({ direction }) => direction === "request"),
).toBe(true);
});
await replay.close();
await expect(response).resolves.toMatchObject({ status: 200 });
} finally {
await replay.close();
}
});
it("consumes ordered WebSocket reconnect scripts and reports exhaustion", async () => {
const scenario = parseProcessScenario({
executable: "/bin/sh",
@@ -91,7 +91,6 @@ const clientFor = (
launcher: GhidraLauncher,
options: {
readonly startupTimeoutMs?: number;
readonly requestTimeoutMs?: number;
readonly onDiagnostic?: (event: GhidraDiagnostic) => void;
readonly transport?: GhidraTransportKind;
readonly runId?: string;
@@ -105,7 +104,6 @@ const clientFor = (
providerVersion: PROVIDER_VERSION,
profileDigest: PROFILE_DIGEST,
startupTimeoutMs: options.startupTimeoutMs ?? 1_000,
requestTimeoutMs: options.requestTimeoutMs ?? 100,
...(options.runId === undefined ? {} : { runId: options.runId }),
...(options.onDiagnostic === undefined
? {}
@@ -124,7 +122,8 @@ describe("GhidraClient", () => {
const launcher = new FixtureLauncher("fragmented");
const client = clientFor(launcher);
await expect(client.start()).resolves.toMatchObject({
const started = await client.start();
expect(started).toMatchObject({
ok: true,
value: {
provider: { id: "ghidra", version: PROVIDER_VERSION },
@@ -139,6 +138,7 @@ describe("GhidraClient", () => {
},
},
});
if (started.ok) expect(started.value).not.toHaveProperty("bridge_version");
if (HOST_TRANSPORT === "unix-socket")
expect(Buffer.byteLength(launcher.endpointPaths[0] ?? "")).toBeLessThan(
108,
@@ -155,7 +155,6 @@ describe("GhidraClient", () => {
await expect(client.start()).resolves.toMatchObject({
ok: true,
value: {
bridge_version: 7,
target: { sha256: TARGET_SHA256 },
},
});
@@ -211,10 +210,7 @@ describe("GhidraClient", () => {
["analysis_timeout", "analysis_timeout"],
["exit", "process"],
] as const)("projects %s startup as %s", async (mode, expectedKind) => {
const client = clientFor(
new FixtureLauncher(mode),
mode === "future_id" ? { requestTimeoutMs: 1_000 } : {},
);
const client = clientFor(new FixtureLauncher(mode));
const result = await client.start();
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.kind).toBe(expectedKind);
@@ -260,16 +256,6 @@ describe("GhidraClient startup lifecycle", () => {
});
describe("GhidraClient established requests", () => {
it("times out an established ping without corrupting shutdown", async () => {
const client = clientFor(new FixtureLauncher("hang_after_start"));
await expect(client.start()).resolves.toMatchObject({ ok: true });
await expect(client.ping({ timeoutMs: 5 })).resolves.toMatchObject({
ok: false,
error: { kind: "timeout", timeoutMs: 5 },
});
});
it("fails an established function request when the provider process exits", async () => {
const client = clientFor(new FixtureLauncher("exit_tools"));
await expect(client.start()).resolves.toMatchObject({ ok: true });
@@ -283,9 +269,7 @@ describe("GhidraClient established requests", () => {
});
it("cancels an established queued operation promptly", async () => {
const client = clientFor(new FixtureLauncher("hang_tools"), {
requestTimeoutMs: 10_000,
});
const client = clientFor(new FixtureLauncher("hang_tools"));
await expect(client.start()).resolves.toMatchObject({ ok: true });
const activeController = new AbortController();
const active = client.callTool(
@@ -309,37 +293,6 @@ describe("GhidraClient established requests", () => {
activeController.abort();
await active;
});
it("counts serial queue wait against the request deadline", async () => {
const client = clientFor(new FixtureLauncher("hang_tools"), {
requestTimeoutMs: 10_000,
});
await expect(client.start()).resolves.toMatchObject({ ok: true });
const activeController = new AbortController();
const active = client.callTool(
"procedure_pseudo_code",
{ document: null, procedure: "fixture_main" },
{ signal: activeController.signal },
);
await wait(5);
await expect(
client.callTool(
"procedure_info",
{ document: null, procedure: "fixture_main" },
{ timeoutMs: 5 },
),
).resolves.toMatchObject({
ok: false,
error: {
kind: "timeout",
timeoutMs: 5,
message: expect.stringContaining("serial queue"),
},
});
activeController.abort();
await active;
});
});
describe("GhidraClient cleanup and diagnostics", () => {
@@ -40,7 +40,6 @@ const expectIsolatedEnvironment = (
XDG_CACHE_HOME: join(runtimeRoot, "cache"),
XDG_CONFIG_HOME: join(runtimeRoot, "config"),
XDG_DATA_HOME: join(runtimeRoot, "data"),
GHIDRA_HEADLESS_MAXMEM: "2G",
GHIDRA_JAVA_OPTIONS: "",
JAVA_TOOL_OPTIONS: "",
JDK_JAVA_OPTIONS: "",
@@ -66,7 +65,7 @@ afterEach(async () => {
});
describe("Ghidra headless launcher", () => {
it("builds a bounded read-only import in deterministic order", () => {
it("builds a read-only import in deterministic order", () => {
expect(
ghidraHeadlessArguments({
projectRoot: "/tmp/project",
@@ -83,10 +82,6 @@ describe("Ghidra headless launcher", () => {
"/tmp/target",
"-readOnly",
"-deleteProject",
"-analysisTimeoutPerFile",
"300",
"-max-cpu",
"2",
"-log",
"/tmp/ghidra.log",
"-scriptlog",
@@ -134,7 +134,6 @@ const clients: HopperClient[] = [];
const startClient = async () => {
const client = new HopperClient({
launcher: new FixtureLauncher(),
requestTimeoutMs: 100,
startupTimeoutMs: 1_000,
});
clients.push(client);
@@ -150,18 +149,13 @@ afterEach(async () => {
});
describe("HopperClient cleanup", () => {
it("ignores more than 1,024 late responses without corrupting the session", async () => {
it("waits for an operation reply without a fixed request deadline", async () => {
const client = await startClient();
const timedOut = await Promise.all(
Array.from({ length: 1_025 }, (_, index) =>
client.callTool("echo", { index, delay: 150 }, { timeoutMs: 5 }),
),
);
expect(timedOut.every((result) => !result.ok)).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 200));
await expect(client.callTool("echo", { value: "alive" })).resolves.toEqual({
await expect(
client.callTool("echo", { value: "waited", delay: 150 }),
).resolves.toEqual({
ok: true,
value: { value: "alive" },
value: { value: "waited", delay: 150 },
});
});
@@ -53,7 +53,6 @@ const clients: HopperClient[] = [];
const startClient = async () => {
const client = new HopperClient({
launcher: new FixtureLauncher(),
requestTimeoutMs: 100,
startupTimeoutMs: 1_000,
});
clients.push(client);
@@ -76,7 +75,7 @@ describe("HopperClient progress", () => {
readonly completed: number;
readonly terminal?: boolean;
}> = [];
const result = await client.callTool(
const pending = client.callTool(
"echo",
{ value: "progress" },
{
@@ -88,6 +87,7 @@ describe("HopperClient progress", () => {
},
},
);
const result = await pending;
expect(result).toEqual({ ok: true, value: { value: "progress" } });
expect(updates).toEqual(
@@ -145,27 +145,23 @@ describe("HopperClient progress", () => {
if (!cancelled.ok)
expect(cancelled.error._tag).toBe("HopperCancelledError");
const timedOut = await client.callTool(
"echo",
{ delay: 30 },
{ timeoutMs: 5 },
);
expect(timedOut.ok).toBe(false);
await new Promise((resolve) => setTimeout(resolve, 40));
const waited = await client.callTool("echo", { delay: 30 });
expect(waited).toMatchObject({ ok: true });
await expect(client.callTool("echo", { value: "alive" })).resolves.toEqual({
ok: true,
value: { value: "alive" },
});
});
it("retains timed-out bridge activity until the late reply releases the queue", async () => {
it("retains cancelled bridge activity until the reply releases the queue", async () => {
const client = await startClient();
const progress: string[] = [];
const result = await client.callTool(
const controller = new AbortController();
const pending = client.callTool(
"echo",
{ delay: 60 },
{
timeoutMs: 5,
signal: controller.signal,
progress: {
report: (update) => {
progress.push(update.message);
@@ -174,15 +170,17 @@ describe("HopperClient progress", () => {
},
},
);
await new Promise((resolve) => setTimeout(resolve, 5));
controller.abort();
const result = await pending;
expect(result).toMatchObject({
ok: false,
error: { _tag: "HopperTimeoutError" },
error: { _tag: "HopperCancelledError" },
});
expect(client.requestActivity()).toMatchObject({
operation: "echo",
callerState: "timed_out",
timeoutMs: 5,
callerState: "cancelled",
});
expect(progress).toEqual(
expect.arrayContaining([
@@ -56,7 +56,6 @@ const clients: HopperClient[] = [];
const startClient = async () => {
const client = new HopperClient({
launcher: new FixtureLauncher(),
requestTimeoutMs: 1_000,
startupTimeoutMs: 1_000,
});
clients.push(client);
@@ -147,7 +146,6 @@ describe("HopperClient protocol", () => {
["wrong_event_id", "HopperProtocolError"],
["malformed_event", "HopperProtocolError"],
["remote_error", "HopperRemoteError"],
["hang", "HopperTimeoutError"],
["exit", "HopperProcessError"],
])("projects %s as %s", async (method, expectedTag) => {
const client = await startClient();
@@ -157,12 +155,6 @@ describe("HopperClient protocol", () => {
expect(result.error._tag).toBe(expectedTag);
if (result.error._tag === "HopperRemoteError")
expect(result.error).toMatchObject({ operation: method, requestId: 2 });
if (result.error._tag === "HopperTimeoutError")
expect(result.error).toMatchObject({
operation: method,
requestId: 2,
providerState: "busy",
});
}
});
@@ -170,7 +162,6 @@ describe("HopperClient protocol", () => {
const diagnostics: HopperDiagnostic[] = [];
const client = new HopperClient({
launcher: new FixtureLauncher(),
requestTimeoutMs: 100,
startupTimeoutMs: 1_000,
onDiagnostic: (event) => diagnostics.push(event),
});
@@ -53,7 +53,6 @@ const clients: HopperClient[] = [];
const startClient = async () => {
const client = new HopperClient({
launcher: new FixtureLauncher(),
requestTimeoutMs: 100,
startupTimeoutMs: 1_000,
});
clients.push(client);
@@ -58,6 +58,26 @@ describe("artifact archive inventory", () => {
expect(inspectionEvidence.evidence_links).toEqual(
inspection.evidence_links,
);
const expandedInspection = artifactInspectionResultSchema.parse({
...inspection,
subject: { ...inspection.subject, root_format: "f".repeat(129) },
observations: inspection.observations.map((observation) => ({
...observation,
subject: "s".repeat(4_097),
})),
hypotheses: inspection.hypotheses.map((hypothesis) => ({
...hypothesis,
statement: "s".repeat(4_097),
basis_evidence_ids: Array(9).fill(inspection.evidence_links[0] ?? ""),
})),
next_probes: inspection.next_probes.map((probe) => ({
...probe,
operation: "o".repeat(129),
})),
limitations: Array.from({ length: 1_001 }, (_, index) => `gap-${index}`),
});
expect(expandedInspection.subject.root_format).toHaveLength(129);
expect(expandedInspection.limitations).toHaveLength(1_001);
const cancellation = new AbortController();
cancellation.abort();
await expect(
@@ -29,8 +29,6 @@ describe("artifact Mach-O slices", () => {
stderr: "",
stdoutBytes: 1,
stderrBytes: 0,
stdoutTruncated: false,
stderrTruncated: false,
exitCode: 0,
signal: null,
}),
@@ -34,7 +34,7 @@ describe("native macOS provider discovery and inspection", () => {
: ok({ path: "/usr/bin/true", sha256: "a".repeat(64) }),
);
});
const options = { timeoutMs: 1_000, maxOutputBytes: 1_024 };
const options = {};
expect((await runner.run("file", [], options)).ok).toBe(false);
expect((await runner.run("file", [], options)).ok).toBe(true);
@@ -42,22 +42,40 @@ describe("native macOS provider discovery and inspection", () => {
expect(resolutions).toBe(2);
});
it("fails closed when a native command exceeds its output limit", async () => {
it("retains the complete native command output", async () => {
const runner = new XcrunCommandRunner(() =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
);
const output = "x".repeat(4096);
const captured = await runner.run(
"file",
["-e", "process.stdout.write('x'.repeat(4096))"],
{ timeoutMs: 1_000, maxOutputBytes: 64 },
["-e", `process.stdout.write(${JSON.stringify(output)})`],
{},
);
expect(captured).toMatchObject({
ok: false,
error: { reason: "output-limit" },
});
expect(captured.ok && captured.value.stdout).toBe(output);
});
it("cancels and reaps a running native command without an operation timeout", async () => {
const runner = new XcrunCommandRunner(() =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
);
const controller = new AbortController();
const pending = runner.run("file", ["-e", "setTimeout(() => {}, 10000)"], {
signal: controller.signal,
});
setTimeout(() => controller.abort(), 30);
const result = await pending;
expect(result).toMatchObject({
ok: false,
error: { reason: "cancelled" },
});
});
});
describe("native macOS provider inspection", () => {
it("normalizes comprehensive Mach-O inspection with exact bounded provenance", async () => {
const runner = new FixtureRunner();
const client = new NativeMacOSProvider(runner, "darwin").createClient(
@@ -120,7 +138,7 @@ describe("native macOS provider discovery and inspection", () => {
it("propagates optional vtool failures other than unavailability", async () => {
const client = new NativeMacOSProvider(
new VtoolFailingRunner("timeout"),
new VtoolFailingRunner("io"),
"darwin",
).createClient(machoTarget("/private/fixture"));
@@ -128,7 +146,7 @@ describe("native macOS provider discovery and inspection", () => {
expect(execution).toMatchObject({
ok: false,
error: { _tag: "AnalysisTimeoutError" },
error: { _tag: "ProviderAdapterError" },
});
});
@@ -139,6 +157,8 @@ describe("native macOS provider discovery and inspection", () => {
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await writeFile(executable, "fixture");
await writeFile(join(app, "Contents/Info.plist"), "fixture");
const externalPlist = join(directory, "Outside.plist");
await writeFile(externalPlist, "fixture");
const client = new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
@@ -155,12 +175,16 @@ describe("native macOS provider discovery and inspection", () => {
hardened_runtime: true,
entitlements: { "com.apple.security.app-sandbox": true },
});
const defaultPlist = await client.execute("inspect_plist", {});
expect(defaultPlist.ok && defaultPlist.value.result).toMatchObject({
source_path: join(app, "Contents/Info.plist"),
});
const plist = await client.execute("inspect_plist", {
relative_path: "Contents/Info.plist",
path: externalPlist,
});
expect(plist.ok && plist.value.result).toMatchObject({
bundle: { identifier: "com.example.fixture", version: "42" },
source_path: "Contents/Info.plist",
source_path: externalPlist,
});
const demangled = await client.execute("demangle_swift", {
symbols: ["$s4Test3fooyyF", "plain_symbol"],
@@ -175,7 +199,7 @@ describe("native macOS provider discovery and inspection", () => {
});
describe("native macOS provider failures and parsing", () => {
it("classifies unavailable, malformed, timeout, and cancellation", async () => {
it("classifies unavailable, malformed, command failure, and cancellation", async () => {
const unavailable = new NativeMacOSProvider(
new FailingRunner("unavailable"),
"darwin",
@@ -198,7 +222,7 @@ describe("native macOS provider failures and parsing", () => {
);
for (const [reason, tag] of [
["timeout", "AnalysisTimeoutError"],
["io", "ProviderAdapterError"],
["cancelled", "AnalysisCancelledError"],
] as const) {
const client = new NativeMacOSProvider(
@@ -328,8 +352,6 @@ const capture = (
stderr: tool === "codesign" ? output : "",
stdoutBytes: Buffer.byteLength(tool === "codesign" ? "" : output),
stderrBytes: Buffer.byteLength(tool === "codesign" ? output : ""),
stdoutTruncated: false,
stderrTruncated: false,
exitCode: 0,
signal: null,
});
@@ -133,6 +133,33 @@ describe("Apple application projection", () => {
second.value.normalized_result,
);
expect(left).toEqual(right);
const longPath = `Payload/${"deep/".repeat(1_000)}Fixture.app`;
expect(
appleApplicationProjectionResultSchema.parse({
...left,
application_roots: [longPath],
}).application_roots,
).toEqual([longPath]);
expect(
appleApplicationProjectionResultSchema.parse({
...left,
limitations: ["x".repeat(5_000)],
}).limitations,
).toEqual(["x".repeat(5_000)]);
const [framework, ...otherFrameworks] = left.components.frameworks;
if (framework === undefined) throw new Error("Expected framework fixture");
expect(
appleApplicationProjectionResultSchema.parse({
...left,
components: {
...left.components,
frameworks: [
{ ...framework, format: "x".repeat(500) },
...otherFrameworks,
],
},
}).components.frameworks[0]?.format,
).toBe("x".repeat(500));
expect(left).toMatchObject({
root_format: "ipa",
application_roots: ["Payload/Fixture.app"],
@@ -178,7 +205,9 @@ describe("Apple application projection", () => {
error: { _tag: "AnalysisInputError" },
});
});
});
describe("Apple application projection completeness", () => {
it("returns every component, inventory page, and bridge hypothesis", async () => {
const projection = await createCompleteAppleProjection();
expect(projection.components.frameworks).toHaveLength(1_001);
@@ -193,12 +222,6 @@ describe("Apple application projection", () => {
});
expect(projection).not.toHaveProperty("omitted_components");
expect(projection).not.toHaveProperty("omitted_bridge_candidates");
expect(
appleApplicationProjectionResultSchema.parse({
...projection,
limitations: Array.from({ length: 101 }, (_, index) => `fact ${index}`),
}).limitations,
).toHaveLength(101);
});
it("infers an application root when the IPA omits directory entries", async () => {
@@ -59,23 +59,33 @@ const evidencePages = (
),
);
const changedArtifactComparison = async () => {
const parent = await createTestTempDirectory("rea-artifact-compare-");
const leftPath = join(parent, "left.app");
const rightPath = join(parent, "right.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "main.js"), "old();"),
writeFile(join(leftPath, "same.txt"), "same"),
writeFile(join(rightPath, "main.js"), "newer();"),
writeFile(join(rightPath, "same.txt"), "same"),
writeFile(join(rightPath, "added.txt"), "added"),
]);
const left = await observe(leftPath);
const right = await observe(rightPath);
return {
left,
right,
result: compareArtifacts(left, right),
};
};
describe("artifact comparison", () => {
it("classifies deterministic path changes and cites both inventories", async () => {
const parent = await createTestTempDirectory("rea-artifact-compare-");
const leftPath = join(parent, "left.app");
const rightPath = join(parent, "right.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "main.js"), "old();"),
writeFile(join(leftPath, "same.txt"), "same"),
writeFile(join(rightPath, "main.js"), "newer();"),
writeFile(join(rightPath, "same.txt"), "same"),
writeFile(join(rightPath, "added.txt"), "added"),
]);
const left = await observe(leftPath);
const right = await observe(rightPath);
const first = compareArtifacts(left, right);
const second = compareArtifacts(left, right);
const firstObservation = await changedArtifactComparison();
const secondObservation = await changedArtifactComparison();
const first = firstObservation.result;
const second = secondObservation.result;
expect(first).toEqual(second);
expect(artifactComparisonResultSchema.parse(first)).toMatchObject({
status: "changed",
@@ -85,8 +95,8 @@ describe("artifact comparison", () => {
]),
});
expect(first.changes[0]?.evidence_links).toEqual([
left.evidence_id,
right.evidence_id,
firstObservation.left.evidence_id,
firstObservation.right.evidence_id,
]);
expect(first.changes).toEqual(
expect.arrayContaining([
@@ -103,6 +113,30 @@ describe("artifact comparison", () => {
);
});
it("accepts all reported comparison dimensions", async () => {
const result = (await changedArtifactComparison()).result;
const firstChange = result.changes[0];
if (firstChange === undefined) throw new Error("Expected artifact change");
const dimensions = [
"content",
"kind",
"format",
"size",
"executable",
"relations",
"metadata",
"availability",
"integrity",
] as const;
expect(
artifactComparisonResultSchema.parse({
...result,
changes: [{ ...firstChange, dimensions }, ...result.changes.slice(1)],
}).changes[0]?.dimensions,
).toEqual(dimensions);
});
it("reports incomplete inventory as truncated, never unchanged", async () => {
const root = await createTestTempDirectory("rea-artifact-truncated-");
await writeFile(join(root, "one.txt"), "one");
@@ -138,7 +172,9 @@ describe("artifact comparison", () => {
"Left artifact inventory is incomplete.",
);
});
});
describe("artifact comparison completeness", () => {
it("compares every graph member for inventories larger than 500 entries", async () => {
const root = await createTestTempDirectory("rea-artifact-pages-");
await Promise.all(
@@ -61,8 +61,7 @@ const nonHopperProvider = (operations: string[]): AnalysisProvider => {
requestId: 7,
operation: "analyze_function",
elapsedMs: 31_000,
timeoutMs: 30_000,
callerState: "timed_out",
callerState: "cancelled",
},
queuedRequests: 2,
},
@@ -136,7 +135,7 @@ describe("binary session", () => {
},
},
analysis_activity: {
status: "timed_out_busy",
status: "busy",
providers: [
{
provider: { id: "fixture", name: "Fixture", version: "1" },
@@ -144,8 +143,7 @@ describe("binary session", () => {
request_id: 7,
operation: "analyze_function",
elapsed_ms: 31_000,
timeout_ms: 30_000,
caller_state: "timed_out",
caller_state: "cancelled",
},
queued_requests: 2,
},
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { projectManagedApplicationGraphEvidence } from "../../../src/application/ManagedApplicationGraphService.js";
import { managedApplicationGraphReferenceInputSchema } from "../../../src/contracts/managedWorkflowToolContracts.js";
import { MANAGED_APPLICATION_GRAPH_EXAMPLE } from "../../../src/contracts/managedWorkflowExamples.js";
import { traceApplicationFeatureEvidence } from "../../../src/application/JavaScriptApplicationWorkflowService.js";
import { MANAGED_STATIC_PROVIDER } from "../../../src/application/InvestigationProviders.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
@@ -161,11 +162,11 @@ describe("managed application graph projection", () => {
});
describe("managed application graph request", () => {
it("accepts any nonempty set of sources and rejects duplicate IDs", () => {
const id = `ev_${"a".repeat(64)}`;
it("accepts any nonempty set of inline sources and rejects duplicates", () => {
const evidence = MANAGED_APPLICATION_GRAPH_EXAMPLE.managed_members;
expect(
managedApplicationGraphReferenceInputSchema.safeParse({
managed_members_evidence_id: id,
managed_members: evidence,
}).success,
).toBe(true);
expect(
@@ -173,8 +174,8 @@ describe("managed application graph request", () => {
).toBe(false);
expect(
managedApplicationGraphReferenceInputSchema.safeParse({
managed_members_evidence_id: id,
managed_native_boundaries_evidence_id: id,
managed_members: evidence,
managed_native_boundaries: evidence,
}).success,
).toBe(false);
});
@@ -26,6 +26,15 @@ it("reconstructs package, Electron roles, Webpack/Rspack modules, and cross-laye
expect(Reflect.get(globalThis, "__rea_bundle_executed")).toBeUndefined();
expect(result.input_path).toBe(root);
const longPath = `/${"deep/".repeat(4_000)}application`;
const { electron_summary: summary, ...analysisResult } = result;
expect(
javascriptApplicationAnalysisResultSchema.parse({
...analysisResult,
summary,
input_path: longPath,
}).input_path,
).toBe(longPath);
expect(result.statistics).toMatchObject({
modules: 4,
parse_failures: 0,
@@ -60,17 +60,6 @@ describe("release configuration", () => {
},
);
it("keeps generated metadata compatible with the generic updater", async () => {
const generator = await readFile(
"scripts/generate-package-metadata.mjs",
"utf8",
);
const generated = await readFile("src/generatedPackageMetadata.ts", "utf8");
expect(generator).toContain("x-release-please-version");
expect(generated).toContain("x-release-please-version");
});
it("keeps the npm package and MCP Registry metadata aligned", async () => {
const packageJson = (await readJson("package.json")) as {
name: string;
-1
View File
@@ -174,7 +174,6 @@ const sessionInfo = ({
timedOut,
}) => ({
name: "REA Ghidra bridge",
bridge_version: 7,
run_id: sessionRunId,
profile_digest: digest,
provider: { id: "ghidra", version },