feat: add managed characterization and coverage closure
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFile, realpath } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
@@ -13,6 +14,7 @@ import { observed } from "./fixtures/analysisExecution.js";
|
||||
import { PermissionAuthority } from "../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../src/domain/permissionPolicy.js";
|
||||
import { controlledReplayOutputSchema } from "../src/domain/javascriptReplay.js";
|
||||
import { nodeCharacterizationPreparationOutputSchema } from "../src/domain/nodeRuntimeCharacterization.js";
|
||||
|
||||
describe("application workflow MCP parity", () => {
|
||||
it("traces and compares authenticated graph Evidence in the session", async () => {
|
||||
@@ -227,6 +229,78 @@ describe("application workflow MCP parity", () => {
|
||||
expect.objectContaining({ authority: "controlled-replay" }),
|
||||
]),
|
||||
);
|
||||
const factoryPath = resolve(root, "sanitizer.factory.txt");
|
||||
const factoryBytes = await readFile(factoryPath);
|
||||
const factorySha256 = createHash("sha256")
|
||||
.update(factoryBytes)
|
||||
.digest("hex");
|
||||
const characterizationInput = {
|
||||
preparation_approved: true,
|
||||
selected_alias: "bundle",
|
||||
expected_effect: "pure",
|
||||
instrumentation: {
|
||||
artifact_path: factoryPath,
|
||||
artifact_sha256: factorySha256,
|
||||
selection: {
|
||||
byte_start: 0,
|
||||
byte_end: factoryBytes.byteLength,
|
||||
selected_sha256: factorySha256,
|
||||
export_name: "selected",
|
||||
},
|
||||
},
|
||||
replay: {
|
||||
mode: "plan",
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "bundle",
|
||||
path: factoryPath,
|
||||
format: "commonjs-factory",
|
||||
role: "module",
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "bundle",
|
||||
entry_export: "selected",
|
||||
},
|
||||
cases: [{ case_id: "heading", arguments: ["# Title"] }],
|
||||
approved: false,
|
||||
},
|
||||
};
|
||||
const characterizationPlan = await client.callTool({
|
||||
name: "prepare_node_characterization",
|
||||
arguments: characterizationInput,
|
||||
});
|
||||
expect(characterizationPlan.isError).not.toBe(true);
|
||||
const approvedPlan = nodeCharacterizationPreparationOutputSchema.parse(
|
||||
characterizationPlan.structuredContent,
|
||||
).plan;
|
||||
const characterized = await client.callTool({
|
||||
name: "execute_node_characterization",
|
||||
arguments: {
|
||||
execution_approved: true,
|
||||
approved_plan_sha256: approvedPlan.plan_sha256,
|
||||
preparation: characterizationInput,
|
||||
},
|
||||
});
|
||||
expect(characterized.isError).not.toBe(true);
|
||||
expect(characterized.structuredContent).toMatchObject({
|
||||
phase: "execution",
|
||||
evidence: {
|
||||
authority: "controlled-replay",
|
||||
provider: { id: "rea-node-characterization" },
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
predicate_type: "rea.javascript-export-transformation/v1",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
predicate_type: "rea.runtime-characterization/v1",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
BrowserStartupError,
|
||||
waitForBrowserDevtoolsPort,
|
||||
} from "../src/browser/BrowserProcessStartup.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser process startup", () => {
|
||||
it("returns a delayed valid DevToolsActivePort", async () => {
|
||||
const root = await temporaryRoot();
|
||||
const portPath = join(root, "DevToolsActivePort");
|
||||
const child = spawn(process.execPath, [
|
||||
"-e",
|
||||
`setTimeout(() => require("node:fs").writeFileSync(${JSON.stringify(portPath)}, "43117\\n/browser"), 20); setTimeout(() => {}, 1000)`,
|
||||
]);
|
||||
try {
|
||||
await expect(
|
||||
waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
executable: process.execPath,
|
||||
activePortPath: portPath,
|
||||
stderr: () => "",
|
||||
timeoutMs: 1_000,
|
||||
pollIntervalMs: 5,
|
||||
}),
|
||||
).resolves.toBe(43_117);
|
||||
} finally {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
});
|
||||
|
||||
it("classifies signal termination instead of timing out", async () => {
|
||||
const root = await temporaryRoot();
|
||||
const child = spawn(process.execPath, [
|
||||
"-e",
|
||||
"process.kill(process.pid, 'SIGTERM')",
|
||||
]);
|
||||
|
||||
const failure = await waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
executable: process.execPath,
|
||||
activePortPath: join(root, "DevToolsActivePort"),
|
||||
stderr: () => "signal fixture",
|
||||
timeoutMs: 1_000,
|
||||
pollIntervalMs: 5,
|
||||
}).catch((cause: unknown) => cause);
|
||||
|
||||
expect(failure).toBeInstanceOf(BrowserStartupError);
|
||||
expect(failure).toMatchObject({
|
||||
failure: "signalled",
|
||||
exitCode: null,
|
||||
signalCode: "SIGTERM",
|
||||
stderr: "signal fixture",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports bounded timeout diagnostics", async () => {
|
||||
const root = await temporaryRoot();
|
||||
const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 1000)"]);
|
||||
try {
|
||||
const failure = await waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
executable: process.execPath,
|
||||
activePortPath: join(root, "DevToolsActivePort"),
|
||||
stderr: () => "",
|
||||
timeoutMs: 20,
|
||||
pollIntervalMs: 5,
|
||||
}).catch((cause: unknown) => cause);
|
||||
|
||||
expect(failure).toBeInstanceOf(BrowserStartupError);
|
||||
expect(failure).toMatchObject({
|
||||
failure: "timeout",
|
||||
exitCode: null,
|
||||
signalCode: null,
|
||||
});
|
||||
expect(String(failure)).toContain("stderr=<empty>");
|
||||
} finally {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const temporaryRoot = async (): Promise<string> => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-browser-startup-"));
|
||||
roots.push(root);
|
||||
return root;
|
||||
};
|
||||
@@ -71,7 +71,7 @@ describe("tool contract surface", () => {
|
||||
...ELECTRON_TOOL_CONTRACTS,
|
||||
...APPLICATION_TOOL_CONTRACTS,
|
||||
];
|
||||
expect(contracts).toHaveLength(73);
|
||||
expect(contracts).toHaveLength(77);
|
||||
for (const contract of contracts) {
|
||||
const inputSchema = contractJsonSchema(contract.inputSchema);
|
||||
const outputSchema = contractJsonSchema(contract.outputSchema);
|
||||
|
||||
@@ -348,4 +348,64 @@ describe("doctor", () => {
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.checks.find(({ name }) => name === "hopper")?.ok).toBe(false);
|
||||
});
|
||||
|
||||
it("reports a broken shadowed Node candidate without hiding the healthy launcher", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
runtimeExecutables: () =>
|
||||
Promise.resolve({
|
||||
launcher_node: "/healthy/node",
|
||||
candidates: [
|
||||
{
|
||||
tool: "node",
|
||||
lexical_path: "/healthy/node",
|
||||
canonical_path: "/healthy/node",
|
||||
path_index: null,
|
||||
selection: "rea-launcher",
|
||||
version: "v24.18.0",
|
||||
healthy: true,
|
||||
failure: null,
|
||||
},
|
||||
{
|
||||
tool: "node",
|
||||
lexical_path: "/opt/homebrew/bin/node",
|
||||
canonical_path: "/opt/homebrew/Cellar/node/25.2.1/bin/node",
|
||||
path_index: 2,
|
||||
selection: "path-shadowed",
|
||||
version: null,
|
||||
healthy: false,
|
||||
failure: {
|
||||
code: "runtime_dynamic_library_missing",
|
||||
exit_code: 134,
|
||||
signal: null,
|
||||
dependency:
|
||||
"/opt/homebrew/opt/simdjson/lib/libsimdjson.29.dylib",
|
||||
stderr: "dyld: Library not loaded",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity?.runtime_executables).toMatchObject({
|
||||
launcher_node: "/healthy/node",
|
||||
candidates: [
|
||||
{ healthy: true, selection: "rea-launcher" },
|
||||
{
|
||||
healthy: false,
|
||||
failure: { code: "runtime_dynamic_library_missing" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "node-toolchains"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: expect.stringContaining("Do not create"),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { instrumentJavaScriptExport } from "../src/domain/javascriptExportInstrumentation.js";
|
||||
|
||||
const encode = (value: string): Uint8Array => new TextEncoder().encode(value);
|
||||
const sha256 = (value: Uint8Array): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
describe("JavaScript export instrumentation", () => {
|
||||
it.each([
|
||||
[
|
||||
"plain",
|
||||
"const hidden = (value) => value.trim();",
|
||||
"(value) => value.trim()",
|
||||
],
|
||||
["minified", "const x=a=>a+1,y=2;", "a=>a+1"],
|
||||
[
|
||||
"bundle",
|
||||
"(()=>{const registry={7:(m)=>m.exports=(x)=>x*2};globalThis.r=registry})()",
|
||||
"(x)=>x*2",
|
||||
],
|
||||
])(
|
||||
"deterministically exposes one exact %s expression",
|
||||
(_name, text, selectedText) => {
|
||||
const source = encode(text);
|
||||
const original = source.slice();
|
||||
const start = text.indexOf(selectedText);
|
||||
const selected = encode(selectedText);
|
||||
const input = {
|
||||
artifact_path: "/approved/app.js",
|
||||
artifact_sha256: sha256(source),
|
||||
selection: {
|
||||
byte_start: start,
|
||||
byte_end: start + selected.byteLength,
|
||||
selected_sha256: sha256(selected),
|
||||
export_name: "selected",
|
||||
},
|
||||
};
|
||||
|
||||
const first = instrumentJavaScriptExport(source, input);
|
||||
const second = instrumentJavaScriptExport(source, input);
|
||||
|
||||
expect(first).toEqual(second);
|
||||
expect(source).toEqual(original);
|
||||
expect(first.manifest).toMatchObject({
|
||||
original_sha256: sha256(source),
|
||||
instrumented_sha256: sha256(first.bytes),
|
||||
output_format: "commonjs-factory",
|
||||
inserted_ranges: [
|
||||
{ purpose: "factory-prefix" },
|
||||
{ purpose: "export-binding" },
|
||||
{ purpose: "factory-suffix" },
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects stale artifacts and ambiguous caller-selected bytes", () => {
|
||||
const source = encode("const hidden = () => 1;");
|
||||
const input = {
|
||||
artifact_path: "/approved/app.js",
|
||||
artifact_sha256: "0".repeat(64),
|
||||
selection: {
|
||||
byte_start: 15,
|
||||
byte_end: 22,
|
||||
selected_sha256: "1".repeat(64),
|
||||
export_name: "hidden",
|
||||
},
|
||||
};
|
||||
|
||||
expect(() => instrumentJavaScriptExport(source, input)).toThrow(
|
||||
/artifact digest mismatch/u,
|
||||
);
|
||||
expect(() =>
|
||||
instrumentJavaScriptExport(source, {
|
||||
...input,
|
||||
artifact_sha256: sha256(source),
|
||||
}),
|
||||
).toThrow(/selection digest mismatch/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,290 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
executeNodeCharacterization,
|
||||
prepareNodeCharacterization,
|
||||
} from "../src/application/NodeRuntimeCharacterizationService.js";
|
||||
import type {
|
||||
JavaScriptReplayHost,
|
||||
JavaScriptReplayPolicy,
|
||||
JavaScriptReplayRunner,
|
||||
} from "../src/application/JavaScriptReplayPlanning.js";
|
||||
import { PermissionAuthority } from "../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../src/domain/permissionPolicy.js";
|
||||
import {
|
||||
nodeCharacterizationPreparationInputSchema,
|
||||
nodeCharacterizationPreparationOutputSchema,
|
||||
} from "../src/domain/nodeRuntimeCharacterization.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
const sha256 = (value: Uint8Array): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("Node runtime characterization", () => {
|
||||
it("prepares without execution, then executes only the approved exact plan", async () => {
|
||||
const fixture = await createFixture();
|
||||
let executions = 0;
|
||||
const dependencies = dependenciesFor(fixture.root, () => {
|
||||
executions += 1;
|
||||
});
|
||||
const input = preparationInput(fixture);
|
||||
|
||||
const prepared = await prepareNodeCharacterization(dependencies, input);
|
||||
expect(prepared.ok).toBe(true);
|
||||
expect(executions).toBe(0);
|
||||
if (!prepared.ok) throw prepared.error;
|
||||
const output = nodeCharacterizationPreparationOutputSchema.parse(
|
||||
prepared.value,
|
||||
);
|
||||
expect(output).toMatchObject({
|
||||
phase: "preparation",
|
||||
plan: {
|
||||
preparation_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
runtime: { family: "ecmascript", provider_id: "node-javascript" },
|
||||
authority: {
|
||||
preparation_approved: true,
|
||||
execution_approved: false,
|
||||
},
|
||||
},
|
||||
transformation: {
|
||||
original_sha256: fixture.sha256,
|
||||
output_format: "commonjs-factory",
|
||||
},
|
||||
transformation_evidence: {
|
||||
predicate_type: "rea.javascript-export-transformation/v1",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
replay: { phase: "plan" },
|
||||
});
|
||||
|
||||
const stale = await executeNodeCharacterization(dependencies, {
|
||||
execution_approved: true,
|
||||
approved_plan_sha256: "0".repeat(64),
|
||||
preparation: input,
|
||||
});
|
||||
expect(stale.ok).toBe(false);
|
||||
expect(!stale.ok && stale.error._tag).toBe("ReplayPlanStaleError");
|
||||
expect(executions).toBe(0);
|
||||
|
||||
const executed = await executeNodeCharacterization(dependencies, {
|
||||
execution_approved: true,
|
||||
approved_plan_sha256: output.plan.plan_sha256,
|
||||
preparation: input,
|
||||
});
|
||||
expect(executed.ok && executed.value).toMatchObject({
|
||||
phase: "execution",
|
||||
replay: {
|
||||
phase: "execute",
|
||||
evidence: { authority: "controlled-replay" },
|
||||
},
|
||||
evidence: {
|
||||
predicate_type: "rea.runtime-characterization/v1",
|
||||
authority: "controlled-replay",
|
||||
},
|
||||
});
|
||||
expect(executions).toBe(1);
|
||||
expect(await readFile(fixture.path)).toEqual(Buffer.from(fixture.bytes));
|
||||
});
|
||||
|
||||
it("rejects aliases that cannot fit the provider-neutral plan identity", async () => {
|
||||
const input = preparationInput(await createFixture());
|
||||
expect(() =>
|
||||
nodeCharacterizationPreparationInputSchema.parse({
|
||||
...input,
|
||||
selected_alias: "a".repeat(201),
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("maps replay-only alias syntax to a provider-neutral module identity", async () => {
|
||||
const fixture = await createFixture();
|
||||
const input = preparationInput(fixture);
|
||||
const alias = "@scope/pkg";
|
||||
const prepared = await prepareNodeCharacterization(
|
||||
dependenciesFor(fixture.root, () => undefined),
|
||||
{
|
||||
...input,
|
||||
selected_alias: alias,
|
||||
replay: {
|
||||
...input.replay,
|
||||
left: {
|
||||
...input.replay.left,
|
||||
entry_alias: alias,
|
||||
modules: input.replay.left.modules.map((module) => ({
|
||||
...module,
|
||||
alias,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(prepared.ok && prepared.value).toMatchObject({
|
||||
plan: {
|
||||
callable: {
|
||||
module_id: expect.stringMatching(/^module\/[a-f0-9]{64}$/u),
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const createFixture = async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-characterization-"));
|
||||
roots.push(root);
|
||||
const path = join(root, "bundle.js");
|
||||
const source = "const hidden = (value) => value.trim();";
|
||||
const selected = "(value) => value.trim()";
|
||||
const bytes = new TextEncoder().encode(source);
|
||||
await writeFile(path, bytes);
|
||||
const byteStart = source.indexOf(selected);
|
||||
return {
|
||||
root,
|
||||
path,
|
||||
bytes,
|
||||
sha256: sha256(bytes),
|
||||
byteStart,
|
||||
selectedBytes: new TextEncoder().encode(selected),
|
||||
};
|
||||
};
|
||||
|
||||
const preparationInput = (
|
||||
fixture: Awaited<ReturnType<typeof createFixture>>,
|
||||
) => ({
|
||||
preparation_approved: true,
|
||||
selected_alias: "bundle",
|
||||
expected_effect: "pure" as const,
|
||||
instrumentation: {
|
||||
artifact_path: fixture.path,
|
||||
artifact_sha256: fixture.sha256,
|
||||
selection: {
|
||||
byte_start: fixture.byteStart,
|
||||
byte_end: fixture.byteStart + fixture.selectedBytes.byteLength,
|
||||
selected_sha256: sha256(fixture.selectedBytes),
|
||||
export_name: "selected",
|
||||
},
|
||||
},
|
||||
replay: {
|
||||
mode: "plan" as const,
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "bundle",
|
||||
path: fixture.path,
|
||||
format: "commonjs-factory" as const,
|
||||
role: "module" as const,
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "bundle",
|
||||
entry_export: "selected",
|
||||
},
|
||||
cases: [{ case_id: "trim", arguments: [" value "] }],
|
||||
approved: false,
|
||||
},
|
||||
});
|
||||
|
||||
const dependenciesFor = (root: string, onExecute: () => void) => {
|
||||
const policy: JavaScriptReplayPolicy = {
|
||||
enabled: true,
|
||||
roots: [root],
|
||||
nodePath: process.execPath,
|
||||
bubblewrapPath: process.execPath,
|
||||
systemdRunPath: process.execPath,
|
||||
systemctlPath: process.execPath,
|
||||
shellPath: process.execPath,
|
||||
};
|
||||
const host: JavaScriptReplayHost = {
|
||||
readSource: async (path, maximumBytes) => {
|
||||
const canonicalPath = await realpath(path);
|
||||
const bytes = await readFile(canonicalPath);
|
||||
if (bytes.byteLength > maximumBytes)
|
||||
throw new RangeError("fixture limit");
|
||||
return { canonicalPath, bytes };
|
||||
},
|
||||
identifyExecutable: async (path) => ({
|
||||
path,
|
||||
version: "fixture-node-24",
|
||||
sha256: "1".repeat(64),
|
||||
}),
|
||||
identifyWorker: async () => ({
|
||||
path: "/fixture/worker.js",
|
||||
version: "fixture-worker",
|
||||
sha256: "2".repeat(64),
|
||||
}),
|
||||
identifyRuntimeClosure: async (path) => [
|
||||
{
|
||||
sourcePath: path,
|
||||
destinationPath: "/runtime/node",
|
||||
sha256: "1".repeat(64),
|
||||
},
|
||||
],
|
||||
seccompDigest: () => "3".repeat(64),
|
||||
probe: async () => undefined,
|
||||
};
|
||||
const runner: JavaScriptReplayRunner = {
|
||||
execute: async (prepared) => {
|
||||
onExecute();
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [
|
||||
{
|
||||
case_id: "trim",
|
||||
outcome: "return",
|
||||
value: "value",
|
||||
input_sha256:
|
||||
prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
|
||||
output_sha256: "4".repeat(64),
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
stderr: "",
|
||||
termination: "completed",
|
||||
cleanup: { state: "complete", residual_resources: [] },
|
||||
limitations: ["fixture runner"],
|
||||
reproducer: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
const ceiling = {
|
||||
capability: "javascript_replay" as const,
|
||||
roots: [root],
|
||||
executables: [
|
||||
policy.nodePath,
|
||||
policy.bubblewrapPath,
|
||||
policy.systemdRunPath,
|
||||
policy.systemctlPath,
|
||||
policy.shellPath,
|
||||
],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: true,
|
||||
};
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy(
|
||||
[ceiling],
|
||||
[
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:javascript_replay",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
return { policy, host, runner, authority };
|
||||
};
|
||||
@@ -110,7 +110,11 @@ describe("canonical product catalog", () => {
|
||||
({ id }) => id === JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER.id,
|
||||
)?.capabilities,
|
||||
).toEqual([
|
||||
"commit_reconstruction_coverage",
|
||||
"compare_application_versions",
|
||||
"execute_node_characterization",
|
||||
"prepare_node_characterization",
|
||||
"query_reconstruction_coverage",
|
||||
"run_controlled_replay",
|
||||
"trace_application_feature",
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
readReconstructionCoverageWorkspace,
|
||||
writeReconstructionCoverageWorkspace,
|
||||
} from "../src/application/ReconstructionCoverageWorkspaceStore.js";
|
||||
import {
|
||||
commitReconstructionCoverage,
|
||||
queryReconstructionCoverage,
|
||||
} from "../src/application/ReconstructionCoverageService.js";
|
||||
import type { EvidenceFilePolicy } from "../src/domain/evidenceBundle.js";
|
||||
import {
|
||||
createReconstructionCoverageWorkspace,
|
||||
createReconstructionVerifierContract,
|
||||
evaluateReconstructionClosure,
|
||||
parseReconstructionCoverageWorkspace,
|
||||
} from "../src/domain/reconstructionCoverage.js";
|
||||
import { createEvidence } from "../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
|
||||
|
||||
const digest = (character: string): string => character.repeat(64);
|
||||
const evidenceRecords = ["1", "2", "3", "4", "5"].map((character) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType: "rea.coverage-fixture/v1",
|
||||
operation: `fixture-${character}`,
|
||||
parameters: {},
|
||||
result: { character },
|
||||
},
|
||||
),
|
||||
);
|
||||
const evidence = (character: string): string => {
|
||||
const record = evidenceRecords.find(
|
||||
({ operation }) => operation === `fixture-${character}`,
|
||||
);
|
||||
if (record === undefined) throw new Error("Missing fixture Evidence");
|
||||
return record.evidence_id;
|
||||
};
|
||||
const now = Date.parse("2026-07-16T12:00:00.000Z");
|
||||
|
||||
const completeWorkspace = () => {
|
||||
const contract = createReconstructionVerifierContract({
|
||||
verifier_id: "verify.cli.help",
|
||||
claim_ids: ["claim.cli.help"],
|
||||
dimensions: ["output", "exit"],
|
||||
authority: "controlled-replay",
|
||||
max_age_ms: 86_400_000,
|
||||
minimum_repeats: 2,
|
||||
normalization_sha256: digest("4"),
|
||||
normalization_removes_dimensions: false,
|
||||
});
|
||||
return createReconstructionCoverageWorkspace({
|
||||
name: "fixture",
|
||||
revision: 1,
|
||||
previous_revision_sha256: null,
|
||||
evidence_bundle: createEvidenceBundle(evidenceRecords),
|
||||
artifacts: [
|
||||
{
|
||||
artifact_id: "authority.v1",
|
||||
artifact_sha256: digest("1"),
|
||||
version: "1.0.0",
|
||||
environment_sha256: digest("2"),
|
||||
evidence_ids: [evidence("1")],
|
||||
},
|
||||
],
|
||||
surfaces: [
|
||||
{
|
||||
surface_id: "cli.help",
|
||||
family: "cli-command",
|
||||
artifact_id: "authority.v1",
|
||||
occurrence_id: "occ-help",
|
||||
location: "bin/app --help",
|
||||
authority: "observed",
|
||||
dependency_surface_ids: [],
|
||||
evidence_ids: [evidence("2")],
|
||||
},
|
||||
],
|
||||
owners: [
|
||||
{
|
||||
surface_id: "cli.help",
|
||||
ownership: {
|
||||
disposition: "implemented",
|
||||
owner_path: "src/cli.ts",
|
||||
owner_export: "registerHelp",
|
||||
owner_sha256: digest("3"),
|
||||
path_state: "present",
|
||||
package_state: "distributed",
|
||||
authority_route: "none",
|
||||
},
|
||||
},
|
||||
],
|
||||
claims: [
|
||||
{
|
||||
claim_id: "claim.cli.help",
|
||||
title: "Help output and exit behavior match",
|
||||
kind: "behavioral",
|
||||
surface_ids: ["cli.help"],
|
||||
required_dimensions: ["output", "exit"],
|
||||
required_authority: "controlled-replay",
|
||||
},
|
||||
],
|
||||
verifier_contracts: [contract],
|
||||
verifier_results: [
|
||||
{
|
||||
verifier_id: contract.verifier_id,
|
||||
contract_sha256: contract.contract_sha256,
|
||||
observed_at: "2026-07-16T11:00:00.000Z",
|
||||
status: "pass",
|
||||
covered_claim_ids: ["claim.cli.help"],
|
||||
covered_dimensions: ["output", "exit"],
|
||||
artifact_sha256s: [digest("1")],
|
||||
owner_sha256s: [digest("3")],
|
||||
normalization_sha256: digest("4"),
|
||||
repeats: 2,
|
||||
evidence_ids: [evidence("3")],
|
||||
},
|
||||
],
|
||||
residual_unknown_ids: [],
|
||||
contradictions: [],
|
||||
package_proofs: [
|
||||
{
|
||||
proof_id: "proof.clean-install",
|
||||
kind: "clean-install",
|
||||
status: "pass",
|
||||
artifact_sha256s: [digest("1")],
|
||||
evidence_ids: [evidence("4")],
|
||||
},
|
||||
{
|
||||
proof_id: "proof.authority-independence",
|
||||
kind: "authority-independence",
|
||||
status: "pass",
|
||||
artifact_sha256s: [digest("1")],
|
||||
evidence_ids: [evidence("5")],
|
||||
},
|
||||
],
|
||||
boundaries: [
|
||||
{
|
||||
boundary_id: "replacement.cli",
|
||||
title: "CLI replacement",
|
||||
required_surface_ids: ["cli.help"],
|
||||
required_claim_ids: ["claim.cli.help"],
|
||||
required_package_proof_kinds: [
|
||||
"clean-install",
|
||||
"authority-independence",
|
||||
],
|
||||
allowed_dispositions: [],
|
||||
allowed_unknown_ids: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
describe("reconstruction coverage closure", () => {
|
||||
it("returns ready only when ownership, verification, package, and authority closure pass", () => {
|
||||
const workspace = completeWorkspace();
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(workspace, "replacement.cli", now),
|
||||
).toMatchObject({
|
||||
status: "ready",
|
||||
summary: { required_surfaces: 1, required_claims: 1, reasons: 0 },
|
||||
evidence_ids: [
|
||||
evidence("2"),
|
||||
evidence("3"),
|
||||
evidence("4"),
|
||||
evidence("5"),
|
||||
].sort(),
|
||||
});
|
||||
expect(parseReconstructionCoverageWorkspace(workspace)).toEqual(workspace);
|
||||
});
|
||||
|
||||
it("keeps an incomplete inventory partial despite every registered verifier passing", () => {
|
||||
const workspace = completeWorkspace();
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const boundary = workspace.boundaries[0];
|
||||
if (boundary === undefined) throw new Error("Expected fixture boundary");
|
||||
const incomplete = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
boundaries: [
|
||||
{
|
||||
...boundary,
|
||||
required_surface_ids: ["cli.help", "cli.version"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(incomplete, "replacement.cli", now),
|
||||
).toMatchObject({
|
||||
status: "partial",
|
||||
reasons: [
|
||||
expect.objectContaining({
|
||||
code: "surface-missing",
|
||||
subject_id: "cli.version",
|
||||
}),
|
||||
],
|
||||
recommended_probes: [
|
||||
{
|
||||
operation: "update_authoritative_inventory",
|
||||
subject_id: "cli.version",
|
||||
rationale:
|
||||
"Required surface is absent from the authoritative inventory.",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("invalidates stale verifier contracts and detected authority routing", () => {
|
||||
const workspace = completeWorkspace();
|
||||
const owner = workspace.owners[0];
|
||||
if (owner === undefined || owner.ownership.disposition !== "implemented")
|
||||
throw new Error("Expected implemented fixture owner");
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const changed = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
owners: [
|
||||
{
|
||||
...owner,
|
||||
ownership: {
|
||||
...owner.ownership,
|
||||
owner_sha256: digest("9"),
|
||||
path_state: "present",
|
||||
package_state: "distributed",
|
||||
authority_route: "detected",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = evaluateReconstructionClosure(
|
||||
changed,
|
||||
"replacement.cli",
|
||||
now,
|
||||
);
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.reasons).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "authority-routing-detected" }),
|
||||
expect.objectContaining({ code: "verifier-result-incompatible" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("never lets mock-strength or stale results satisfy stronger current claims", () => {
|
||||
const workspace = completeWorkspace();
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const stale = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
verifier_results: workspace.verifier_results.map((result) => ({
|
||||
...result,
|
||||
observed_at: "2026-07-01T00:00:00.000Z",
|
||||
})),
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(stale, "replacement.cli", now),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
reasons: [expect.objectContaining({ code: "verifier-result-stale" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("orders offset-bearing verifier timestamps chronologically", () => {
|
||||
const workspace = completeWorkspace();
|
||||
const result = workspace.verifier_results[0];
|
||||
if (result === undefined)
|
||||
throw new Error("Expected fixture verifier result");
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const changed = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
verifier_results: [
|
||||
{ ...result, observed_at: "2026-07-16T08:00:00.000Z" },
|
||||
{
|
||||
...result,
|
||||
observed_at: "2026-07-16T04:00:00.000-05:00",
|
||||
status: "fail",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(changed, "replacement.cli", now),
|
||||
).toMatchObject({
|
||||
status: "failed",
|
||||
reasons: [expect.objectContaining({ code: "verifier-failed" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects verifier observations from the future", () => {
|
||||
const workspace = completeWorkspace();
|
||||
const result = workspace.verifier_results[0];
|
||||
if (result === undefined)
|
||||
throw new Error("Expected fixture verifier result");
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const changed = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
verifier_results: [
|
||||
{ ...result, observed_at: "2026-07-17T12:00:00.000Z" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(changed, "replacement.cli", now),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
reasons: [expect.objectContaining({ code: "verifier-result-stale" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects green results and package proofs that omit current commitments", () => {
|
||||
const workspace = completeWorkspace();
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const incomplete = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
verifier_results: workspace.verifier_results.map((result) => ({
|
||||
...result,
|
||||
owner_sha256s: [],
|
||||
})),
|
||||
package_proofs: workspace.package_proofs.map((proof) => ({
|
||||
...proof,
|
||||
artifact_sha256s: [digest("8")],
|
||||
})),
|
||||
});
|
||||
|
||||
const result = evaluateReconstructionClosure(
|
||||
incomplete,
|
||||
"replacement.cli",
|
||||
now,
|
||||
);
|
||||
expect(result.status).toBe("unknown");
|
||||
expect(result.reasons).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "verifier-result-incompatible" }),
|
||||
expect.objectContaining({ code: "package-proof-unknown" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("persists owner-only revisions with CAS and digest-chain enforcement", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-coverage-workspace-"));
|
||||
const path = join(root, "coverage.json");
|
||||
const first = completeWorkspace();
|
||||
const filePolicy: EvidenceFilePolicy = {
|
||||
roots: [root],
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024 * 1024,
|
||||
maxNodes: 1_000_000,
|
||||
};
|
||||
try {
|
||||
const written = await writeReconstructionCoverageWorkspace(
|
||||
first,
|
||||
path,
|
||||
null,
|
||||
filePolicy,
|
||||
);
|
||||
expect(written.ok).toBe(true);
|
||||
expect(
|
||||
await readReconstructionCoverageWorkspace(path, filePolicy),
|
||||
).toEqual({ ok: true, value: first });
|
||||
|
||||
const stale = await writeReconstructionCoverageWorkspace(
|
||||
first,
|
||||
path,
|
||||
null,
|
||||
filePolicy,
|
||||
);
|
||||
expect(stale).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "InvestigationWorkspaceError",
|
||||
reason: "revision-conflict",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("shares commit and fail-closed query behavior across adapters", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-coverage-service-"));
|
||||
const path = join(root, "coverage.json");
|
||||
const workspace = completeWorkspace();
|
||||
const filePolicy: EvidenceFilePolicy = {
|
||||
roots: [root],
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024 * 1024,
|
||||
maxNodes: 1_000_000,
|
||||
};
|
||||
try {
|
||||
const committed = await commitReconstructionCoverage(
|
||||
{
|
||||
approved: true,
|
||||
workspace_path: path,
|
||||
expected_revision: null,
|
||||
workspace,
|
||||
},
|
||||
filePolicy,
|
||||
);
|
||||
expect(committed.ok && committed.value).toMatchObject({
|
||||
revision: 1,
|
||||
revision_sha256: workspace.revision_sha256,
|
||||
evidence_records: 5,
|
||||
});
|
||||
const queried = await queryReconstructionCoverage(
|
||||
{ workspace_path: path, boundary_id: "replacement.cli" },
|
||||
filePolicy,
|
||||
now,
|
||||
);
|
||||
expect(queried.ok && queried.value).toMatchObject({ status: "ready" });
|
||||
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const cancelled = await queryReconstructionCoverage(
|
||||
{ workspace_path: path, boundary_id: "replacement.cli" },
|
||||
filePolicy,
|
||||
now,
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(cancelled).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BinarySession } from "../src/application/BinarySession.js";
|
||||
import { INVESTIGATION_EXAMPLES } from "../src/contracts/investigationExamples.js";
|
||||
import { createEvidence } from "../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
|
||||
import {
|
||||
createReconstructionCoverageWorkspace,
|
||||
createReconstructionVerifierContract,
|
||||
} from "../src/domain/reconstructionCoverage.js";
|
||||
import { createServer } from "../src/server/createServer.js";
|
||||
import { observed } from "./fixtures/analysisExecution.js";
|
||||
import { permissionAuthorityForRoot } from "./fixtures/permissionAuthority.js";
|
||||
|
||||
const digest = (character: string): string => character.repeat(64);
|
||||
|
||||
describe("reconstruction coverage MCP parity", () => {
|
||||
it("commits and queries the same evidence-backed fail-closed workspace", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-coverage-mcp-"));
|
||||
const path = join(root, "coverage.json");
|
||||
const policy = {
|
||||
roots: [root],
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024 * 1024,
|
||||
maxNodes: 1_000_000,
|
||||
};
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_workspace_read", "investigation_workspace_write"],
|
||||
["investigation_workspace_read", "investigation_workspace_write"],
|
||||
);
|
||||
const session = new BinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
evidenceFilePolicy: policy,
|
||||
permissionAuthority: authority,
|
||||
});
|
||||
const client = new Client({ name: "coverage-mcp-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const workspace = fixtureWorkspace();
|
||||
const committed = await client.callTool({
|
||||
name: "commit_reconstruction_coverage",
|
||||
arguments: {
|
||||
approved: true,
|
||||
workspace_path: path,
|
||||
expected_revision: null,
|
||||
workspace,
|
||||
},
|
||||
});
|
||||
expect(committed.isError).not.toBe(true);
|
||||
expect(committed.structuredContent).toMatchObject({
|
||||
revision: 1,
|
||||
revision_sha256: workspace.revision_sha256,
|
||||
});
|
||||
const resourceUri = `rea://reconstruction-coverage/${workspace.workspace_id}/revision/1`;
|
||||
expect(committed.content).toContainEqual(
|
||||
expect.objectContaining({ type: "resource_link", uri: resourceUri }),
|
||||
);
|
||||
const resource = await client.readResource({ uri: resourceUri });
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(workspace.revision_sha256),
|
||||
}),
|
||||
);
|
||||
const queried = await client.callTool({
|
||||
name: "query_reconstruction_coverage",
|
||||
arguments: {
|
||||
workspace_path: path,
|
||||
boundary_id: "replacement.cli",
|
||||
},
|
||||
});
|
||||
expect(queried.isError).not.toBe(true);
|
||||
expect(queried.structuredContent).toMatchObject({
|
||||
status: "ready",
|
||||
summary: { reasons: 0 },
|
||||
});
|
||||
const staleVerification = await client.callTool({
|
||||
name: "verify_reconstruction",
|
||||
arguments: {
|
||||
...INVESTIGATION_EXAMPLES.verify_reconstruction,
|
||||
coverage: {
|
||||
workspace_id: workspace.workspace_id,
|
||||
revision: workspace.revision,
|
||||
revision_sha256: digest("9"),
|
||||
boundary_id: "replacement.cli",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(staleVerification.isError).toBe(true);
|
||||
expect(staleVerification.structuredContent).toMatchObject({
|
||||
error: { code: "evidence_integrity_mismatch" },
|
||||
});
|
||||
const unknownBoundary = await client.callTool({
|
||||
name: "verify_reconstruction",
|
||||
arguments: {
|
||||
...INVESTIGATION_EXAMPLES.verify_reconstruction,
|
||||
coverage: {
|
||||
workspace_id: workspace.workspace_id,
|
||||
revision: workspace.revision,
|
||||
revision_sha256: workspace.revision_sha256,
|
||||
boundary_id: "replacement.unknown",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(unknownBoundary.isError).toBe(true);
|
||||
expect(unknownBoundary.structuredContent).toMatchObject({
|
||||
error: { code: "invalid_request" },
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const fixtureWorkspace = () => {
|
||||
const record = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType: "rea.coverage-fixture/v1",
|
||||
operation: "verify-cli",
|
||||
parameters: {},
|
||||
result: { status: "pass" },
|
||||
authority: "controlled-replay",
|
||||
environment: {
|
||||
id: "fixture",
|
||||
platform: "linux",
|
||||
architecture: "x86_64",
|
||||
isolation: "container",
|
||||
},
|
||||
},
|
||||
);
|
||||
const contract = createReconstructionVerifierContract({
|
||||
verifier_id: "verify.cli",
|
||||
claim_ids: ["claim.cli"],
|
||||
dimensions: ["output"],
|
||||
authority: "controlled-replay",
|
||||
max_age_ms: Number.MAX_SAFE_INTEGER,
|
||||
minimum_repeats: 1,
|
||||
normalization_sha256: digest("4"),
|
||||
normalization_removes_dimensions: false,
|
||||
});
|
||||
return createReconstructionCoverageWorkspace({
|
||||
name: "mcp-fixture",
|
||||
revision: 1,
|
||||
previous_revision_sha256: null,
|
||||
evidence_bundle: createEvidenceBundle([record]),
|
||||
artifacts: [
|
||||
{
|
||||
artifact_id: "authority",
|
||||
artifact_sha256: digest("1"),
|
||||
version: "1",
|
||||
environment_sha256: digest("2"),
|
||||
evidence_ids: [record.evidence_id],
|
||||
},
|
||||
],
|
||||
surfaces: [
|
||||
{
|
||||
surface_id: "cli.help",
|
||||
family: "cli-command",
|
||||
artifact_id: "authority",
|
||||
occurrence_id: null,
|
||||
location: "app --help",
|
||||
authority: "observed",
|
||||
dependency_surface_ids: [],
|
||||
evidence_ids: [record.evidence_id],
|
||||
},
|
||||
],
|
||||
owners: [
|
||||
{
|
||||
surface_id: "cli.help",
|
||||
ownership: {
|
||||
disposition: "implemented",
|
||||
owner_path: "src/cli.ts",
|
||||
owner_export: null,
|
||||
owner_sha256: digest("3"),
|
||||
path_state: "present",
|
||||
package_state: "distributed",
|
||||
authority_route: "none",
|
||||
},
|
||||
},
|
||||
],
|
||||
claims: [
|
||||
{
|
||||
claim_id: "claim.cli",
|
||||
title: "CLI help matches",
|
||||
kind: "behavioral",
|
||||
surface_ids: ["cli.help"],
|
||||
required_dimensions: ["output"],
|
||||
required_authority: "controlled-replay",
|
||||
},
|
||||
],
|
||||
verifier_contracts: [contract],
|
||||
verifier_results: [
|
||||
{
|
||||
verifier_id: contract.verifier_id,
|
||||
contract_sha256: contract.contract_sha256,
|
||||
observed_at: "2026-07-16T00:00:00.000Z",
|
||||
status: "pass",
|
||||
covered_claim_ids: ["claim.cli"],
|
||||
covered_dimensions: ["output"],
|
||||
artifact_sha256s: [digest("1")],
|
||||
owner_sha256s: [digest("3")],
|
||||
normalization_sha256: digest("4"),
|
||||
repeats: 1,
|
||||
evidence_ids: [record.evidence_id],
|
||||
},
|
||||
],
|
||||
residual_unknown_ids: [],
|
||||
contradictions: [],
|
||||
package_proofs: [
|
||||
{
|
||||
proof_id: "proof.install",
|
||||
kind: "clean-install",
|
||||
status: "pass",
|
||||
artifact_sha256s: [digest("1")],
|
||||
evidence_ids: [record.evidence_id],
|
||||
},
|
||||
],
|
||||
boundaries: [
|
||||
{
|
||||
boundary_id: "replacement.cli",
|
||||
title: "CLI replacement",
|
||||
required_surface_ids: ["cli.help"],
|
||||
required_claim_ids: ["claim.cli"],
|
||||
required_package_proof_kinds: ["clean-install"],
|
||||
allowed_dispositions: [],
|
||||
allowed_unknown_ids: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createRuntimeCharacterizationPlan,
|
||||
parseRuntimeCharacterizationPlan,
|
||||
} from "../src/domain/runtimeCharacterization.js";
|
||||
|
||||
const digest = (character: string): string => character.repeat(64);
|
||||
|
||||
describe("provider-neutral runtime characterization plan", () => {
|
||||
it("commits preparation separately from execution approval", () => {
|
||||
const plan = createRuntimeCharacterizationPlan({
|
||||
schema_version: 1,
|
||||
preparation_sha256: digest("5"),
|
||||
artifact: {
|
||||
path: "/approved/app.js",
|
||||
sha256: digest("1"),
|
||||
byte_length: 100,
|
||||
},
|
||||
runtime: {
|
||||
family: "ecmascript",
|
||||
provider_id: "node-javascript",
|
||||
executable_path: "/usr/bin/node",
|
||||
executable_sha256: digest("2"),
|
||||
version: "v24.18.0",
|
||||
profile_sha256: digest("3"),
|
||||
},
|
||||
callable: {
|
||||
callable_id: "bundle.module7.hidden",
|
||||
module_id: "bundle.module7",
|
||||
export_name: "selected",
|
||||
semantic_evidence_id: null,
|
||||
selector_sha256: digest("4"),
|
||||
},
|
||||
working_directory: "/owned/work",
|
||||
isolated_home: "/owned/home",
|
||||
expected_effect: "pure",
|
||||
allowed_boundaries: [],
|
||||
limits: {
|
||||
max_calls: 2,
|
||||
max_processes: 0,
|
||||
max_files: 0,
|
||||
max_bytes: 65_536,
|
||||
max_handles: 32,
|
||||
timeout_ms: 5_000,
|
||||
idle_timeout_ms: 1_000,
|
||||
},
|
||||
determinism: {
|
||||
clock: "fixed",
|
||||
randomness: "seeded",
|
||||
identifiers: "deterministic",
|
||||
seed: 7,
|
||||
},
|
||||
authority: {
|
||||
preparation_approved: true,
|
||||
execution_approved: false,
|
||||
network: "none",
|
||||
provider_owned_process_only: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(parseRuntimeCharacterizationPlan(plan)).toEqual(plan);
|
||||
expect(plan.authority.execution_approved).toBe(false);
|
||||
expect(() =>
|
||||
parseRuntimeCharacterizationPlan({
|
||||
...plan,
|
||||
expected_effect: "bounded-effects",
|
||||
}),
|
||||
).toThrow(/digest is invalid/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import { chmod, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { delimiter, join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectRuntimeExecutables } from "../src/application/RuntimeExecutableDiagnostics.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("runtime executable diagnostics", () => {
|
||||
it("preserves lexical and canonical identities for duplicate healthy runtimes", async () => {
|
||||
const first = await temporaryRoot();
|
||||
const second = await temporaryRoot();
|
||||
await symlink(process.execPath, join(first, "node"));
|
||||
await symlink(process.execPath, join(second, "node"));
|
||||
|
||||
const inventory = await inspectRuntimeExecutables({
|
||||
platform: process.platform,
|
||||
path: [first, second].join(delimiter),
|
||||
launcherNode: process.execPath,
|
||||
});
|
||||
const pathNodes = inventory.candidates.filter(
|
||||
({ tool, path_index: pathIndex }) =>
|
||||
tool === "node" && pathIndex !== null,
|
||||
);
|
||||
|
||||
expect(pathNodes).toHaveLength(2);
|
||||
expect(pathNodes.map(({ selection }) => selection)).toEqual([
|
||||
"path-primary",
|
||||
"path-shadowed",
|
||||
]);
|
||||
expect(new Set(pathNodes.map(({ canonical_path: path }) => path))).toEqual(
|
||||
new Set([process.execPath]),
|
||||
);
|
||||
expect(pathNodes.every(({ healthy }) => healthy)).toBe(true);
|
||||
});
|
||||
|
||||
it("distinguishes a healthy primary runtime from a broken shadowed candidate", async () => {
|
||||
const healthy = await temporaryRoot();
|
||||
const broken = await temporaryRoot();
|
||||
await symlink(process.execPath, join(healthy, "node"));
|
||||
await executable(
|
||||
join(broken, "node"),
|
||||
"#!/bin/sh\necho broken-runtime >&2\nexit 17\n",
|
||||
);
|
||||
|
||||
const inventory = await inspectRuntimeExecutables({
|
||||
platform: process.platform,
|
||||
path: [healthy, broken].join(delimiter),
|
||||
launcherNode: process.execPath,
|
||||
});
|
||||
const pathNodes = inventory.candidates.filter(
|
||||
({ tool, path_index: pathIndex }) =>
|
||||
tool === "node" && pathIndex !== null,
|
||||
);
|
||||
|
||||
expect(pathNodes[0]).toMatchObject({
|
||||
healthy: true,
|
||||
selection: "path-primary",
|
||||
});
|
||||
expect(pathNodes[1]).toMatchObject({
|
||||
healthy: false,
|
||||
selection: "path-shadowed",
|
||||
failure: {
|
||||
code: "runtime_nonzero_exit",
|
||||
exit_code: 17,
|
||||
stderr: "broken-runtime",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies a macOS dynamic-loader failure and names the dependency", async () => {
|
||||
const root = await temporaryRoot();
|
||||
await executable(
|
||||
join(root, "node"),
|
||||
"#!/bin/sh\necho 'dyld: Library not loaded: /opt/homebrew/opt/simdjson/lib/libsimdjson.29.dylib' >&2\nexit 134\n",
|
||||
);
|
||||
|
||||
const inventory = await inspectRuntimeExecutables({
|
||||
platform: "darwin",
|
||||
path: root,
|
||||
launcherNode: process.execPath,
|
||||
});
|
||||
const candidate = inventory.candidates.find(
|
||||
({ tool, path_index: pathIndex }) => tool === "node" && pathIndex === 0,
|
||||
);
|
||||
|
||||
expect(candidate).toMatchObject({
|
||||
healthy: false,
|
||||
failure: {
|
||||
code: "runtime_dynamic_library_missing",
|
||||
dependency: "/opt/homebrew/opt/simdjson/lib/libsimdjson.29.dylib",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("probes env shebangs under the diagnosed PATH", async () => {
|
||||
const root = await temporaryRoot();
|
||||
await symlink(process.execPath, join(root, "node"));
|
||||
await executable(
|
||||
join(root, "npm"),
|
||||
"#!/usr/bin/env node\nconsole.log('npm-under-effective-path')\n",
|
||||
);
|
||||
|
||||
const inventory = await inspectRuntimeExecutables({
|
||||
platform: process.platform,
|
||||
path: root,
|
||||
launcherNode: process.execPath,
|
||||
});
|
||||
const npm = inventory.candidates.find(({ tool }) => tool === "npm");
|
||||
|
||||
expect(npm).toMatchObject({
|
||||
healthy: true,
|
||||
version: "npm-under-effective-path",
|
||||
selection: "path-primary",
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies a bounded probe timeout before its kill signal", async () => {
|
||||
const root = await temporaryRoot();
|
||||
await executable(join(root, "node"), "#!/bin/sh\nwhile :; do :; done\n");
|
||||
|
||||
const inventory = await inspectRuntimeExecutables({
|
||||
platform: process.platform,
|
||||
path: root,
|
||||
launcherNode: process.execPath,
|
||||
timeoutMs: 20,
|
||||
});
|
||||
const candidate = inventory.candidates.find(
|
||||
({ tool, path_index: pathIndex }) => tool === "node" && pathIndex === 0,
|
||||
);
|
||||
|
||||
expect(candidate).toMatchObject({
|
||||
healthy: false,
|
||||
failure: { code: "runtime_timeout", signal: "SIGTERM" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const temporaryRoot = async (): Promise<string> => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-runtime-diagnostics-"));
|
||||
roots.push(root);
|
||||
return root;
|
||||
};
|
||||
|
||||
const executable = async (path: string, source: string): Promise<void> => {
|
||||
await writeFile(path, source);
|
||||
await chmod(path, 0o700);
|
||||
};
|
||||
@@ -25,14 +25,14 @@ describe("server and catalog identity", () => {
|
||||
});
|
||||
expect(PRODUCT_IDENTITY.packageVersion).toBe(packageJson.version);
|
||||
expect(SDK_IDENTITY.server).toBe("2.0.0-beta.4");
|
||||
expect(CLI_COMMAND_NAMES).toHaveLength(51);
|
||||
expect(new Set(CLI_COMMAND_NAMES).size).toBe(51);
|
||||
expect(CLI_COMMAND_NAMES).toHaveLength(55);
|
||||
expect(new Set(CLI_COMMAND_NAMES).size).toBe(55);
|
||||
expect(CATALOG_IDENTITY.counts).toEqual({
|
||||
cli_commands: 51,
|
||||
cli_commands: 55,
|
||||
mcp_tools: TOOL_CONTRACTS.length,
|
||||
mcp_prompts: 6,
|
||||
mcp_resources: 2,
|
||||
mcp_resource_templates: 7,
|
||||
mcp_resource_templates: 8,
|
||||
});
|
||||
expect(CATALOG_IDENTITY.digests.combined_sha256).toMatch(/^[a-f0-9]{64}$/u);
|
||||
});
|
||||
|
||||
@@ -52,6 +52,10 @@ describe("tool contract inventory", () => {
|
||||
"trace_application_feature",
|
||||
"compare_application_versions",
|
||||
"run_controlled_replay",
|
||||
"prepare_node_characterization",
|
||||
"execute_node_characterization",
|
||||
"commit_reconstruction_coverage",
|
||||
"query_reconstruction_coverage",
|
||||
]);
|
||||
expect(SESSION_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
|
||||
"open_binary",
|
||||
|
||||
Reference in New Issue
Block a user